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

\begin{code}
#include "HsVersions.h"

module SimplMonad (
10
	SYN_IE(SmplM),
11 12
	initSmpl, returnSmpl, thenSmpl, thenSmpl_,
	mapSmpl, mapAndUnzipSmpl,
13

14
	-- Counting
sof's avatar
sof committed
15
	SimplCount{-abstract-}, TickType(..), tick, tickN, tickUnfold,
16 17 18 19
	simplCount, detailedSimplCount,
	zeroSimplCount, showSimplCount, combineSimplCounts,

	-- Cloning
20
	cloneId, cloneIds, cloneTyVarSmpl, newIds, newId
21 22
    ) where

23
IMP_Ubiq(){-uitous-}
24
IMPORT_1_3(Ix)
25

26
IMPORT_DELOOPER(SmplLoop)		-- well, cheating sort of
27

sof's avatar
sof committed
28
import Id		( GenId, mkSysLocal, mkIdWithNewUniq, SYN_IE(Id) )
29
import CoreUnfold	( SimpleUnfolding )
30
import SimplEnv
31
import SrcLoc		( noSrcLoc )
sof's avatar
sof committed
32 33
import TyVar		( cloneTyVar, SYN_IE(TyVar) )
import Type             ( SYN_IE(Type) )
34 35 36
import UniqSupply	( getUnique, getUniques, splitUniqSupply,
			  UniqSupply
			)
sof's avatar
sof committed
37 38
import Util		( zipWithEqual, panic, SYN_IE(Eager), appEager, pprTrace )
import Pretty
sof's avatar
sof committed
39
import Outputable	( PprStyle(..), Outputable(..) )
40 41 42 43 44 45

infixr 9  `thenSmpl`, `thenSmpl_`
\end{code}

%************************************************************************
%*									*
46
\subsection{Monad plumbing}
47 48 49 50 51 52 53 54
%*									*
%************************************************************************

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}
type SmplM result
55
  = UniqSupply
56 57 58 59 60
  -> SimplCount    -- things being threaded
  -> (result, SimplCount)
\end{code}

\begin{code}
61
initSmpl :: UniqSupply -- no init count; set to 0
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 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 103 104 105
	  -> SmplM a
	  -> (a, SimplCount)

initSmpl us m = m us zeroSimplCount

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

returnSmpl :: a -> SmplM a
returnSmpl e us sc = (e, sc)

thenSmpl  :: SmplM a -> (a -> SmplM b) -> SmplM b
thenSmpl_ :: SmplM a -> SmplM b -> SmplM b

thenSmpl m k us sc0
  = case splitUniqSupply us of { (s1, s2) ->
    case (m s1 sc0)	    of { (m_result, sc1) ->
    k m_result s2 sc1 }}

thenSmpl_ m k us sc0
  = case splitUniqSupply us of { (s1, s2) ->
    case (m s1 sc0) 	    of { (_, sc1) ->
    k s2 sc1 }}

mapSmpl	    	:: (a -> SmplM b) -> [a] -> SmplM [b]
mapAndUnzipSmpl :: (a -> SmplM (b, c)) -> [a] -> SmplM ([b],[c])

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)
\end{code}


%************************************************************************
%*									*
106
\subsection{Counting up what we've done}
107 108 109 110 111 112 113 114 115 116 117 118 119
%*									*
%************************************************************************

The assoc list isn't particularly costly, because we only use
the number of ticks in ``real life.''

The right thing to do, if you want that to go fast, is thread
a mutable array through @SimplM@.

\begin{code}
data SimplCount
  = SimplCount	FAST_INT	    -- number of ticks
		[(TickType, Int)]   -- assoc list of all diff kinds of ticks
sof's avatar
sof committed
120 121 122 123 124
		UnfoldingHistory

type UnfoldingHistory = (Int,		-- N
		         [(Id,Int)], 	-- Last N unfoldings
		         [(Id,Int)])	-- The MaxUnfoldHistory unfoldings before that
125 126

data TickType
127 128 129 130 131
  = UnfoldingDone    | MagicUnfold	| ConReused
  | CaseFloatFromLet | CaseOfCase
  | LetFloatFromLet  | LetFloatFromCase
  | KnownBranch	     | Let2Case
  | CaseMerge	     | CaseElim
132 133
  | CaseIdentity
  | AtomicRhs	-- Rhs of a let-expression was an atom
134 135
  | EtaExpansion
  | CaseOfError
136 137
  | TyBetaReduction
  | BetaReduction
138
  | SpecialisationDone
139 140
  {- BEGIN F/B ENTRIES -}
  -- the 8 rules
141 142 143 144
  | FoldrBuild	     	-- foldr f z (build g) ==>
  | FoldrAugment	-- foldr f z (augment g z) ==>
  | Foldr_Nil		-- foldr f z [] ==>
  | Foldr_List		-- foldr f z (x:...) ==>
145

146 147 148 149
  | FoldlBuild	        -- foldl f z (build g) ==>
  | FoldlAugment	-- foldl f z (augment g z) ==>
  | Foldl_Nil		-- foldl f z [] ==>
  | Foldl_List		-- foldl f z (x:...) ==>
150 151 152 153

  | Foldr_Cons_Nil	-- foldr (:) [] => id
  | Foldr_Cons		-- foldr (:) => flip (++)

154 155 156
  | Str_FoldrStr	-- foldr f z "hello" => unpackFoldrPS__ f z "hello"
  | Str_UnpackCons	-- unpackFoldrPS# (:) z "hello" => unpackAppendPS__ z "hello"
  | Str_UnpackNil	-- unpackAppendPS__ [] "hello" => "hello"
157
  {- END F/B ENTRIES -}
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  deriving (Eq, Ord, Ix)

instance Text TickType where
    showsPrec p UnfoldingDone	= showString "UnfoldingDone    "
    showsPrec p MagicUnfold	= showString "MagicUnfold      "
    showsPrec p ConReused	= showString "ConReused        "
    showsPrec p CaseFloatFromLet= showString "CaseFloatFromLet "
    showsPrec p CaseOfCase	= showString "CaseOfCase       "
    showsPrec p LetFloatFromLet	= showString "LetFloatFromLet  "
    showsPrec p LetFloatFromCase= showString "LetFloatFromCase "
    showsPrec p KnownBranch	= showString "KnownBranch      "
    showsPrec p Let2Case	= showString "Let2Case         "
    showsPrec p CaseMerge	= showString "CaseMerge        "
    showsPrec p CaseElim	= showString "CaseElim         "
    showsPrec p CaseIdentity	= showString "CaseIdentity     "
    showsPrec p AtomicRhs	= showString "AtomicRhs        "
    showsPrec p EtaExpansion	= showString "EtaExpansion     "
    showsPrec p CaseOfError	= showString "CaseOfError      "
    showsPrec p TyBetaReduction	= showString "TyBetaReduction  "
    showsPrec p BetaReduction	= showString "BetaReduction    "
178 179 180
    showsPrec p SpecialisationDone 
				= showString "Specialisation   "

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
	-- Foldr/Build Stuff:
    showsPrec p FoldrBuild	= showString "FoldrBuild       "
    showsPrec p FoldrAugment	= showString "FoldrAugment     "
    showsPrec p Foldr_Nil	= showString "Foldr_Nil        "
    showsPrec p Foldr_List	= showString "Foldr_List       "

    showsPrec p FoldlBuild	= showString "FoldlBuild       "
    showsPrec p FoldlAugment	= showString "FoldlAugment     "
    showsPrec p Foldl_Nil	= showString "Foldl_Nil        "
    showsPrec p Foldl_List	= showString "Foldl_List       "

    showsPrec p Foldr_Cons_Nil	= showString "Foldr_Cons_Nil   "
    showsPrec p Foldr_Cons	= showString "Foldr_Cons       "

    showsPrec p Str_FoldrStr	= showString "Str_FoldrStr     "
    showsPrec p Str_UnpackCons  = showString "Str_UnpackCons   "
    showsPrec p Str_UnpackNil   = showString "Str_UnpackNil    "
198 199 200

showSimplCount :: SimplCount -> String

sof's avatar
sof committed
201 202
showSimplCount (SimplCount _ stuff (_, unf1, unf2))
  = shw stuff ++ "\nMost recent unfoldings: " ++ show (ppr PprDebug (reverse unf2 ++ reverse unf1))
203 204 205 206 207
  where
    shw []	    = ""
    shw ((t,n):tns) | n /= 0	= show t ++ ('\t' : show n) ++ ('\n' : shw tns)
		    | otherwise = shw tns

sof's avatar
sof committed
208 209 210 211
	-- ToDo: move to Outputable
instance Outputable Int where
   ppr sty n = int n

212 213
zeroSimplCount :: SimplCount
zeroSimplCount
sof's avatar
sof committed
214 215 216
  = SimplCount ILIT(0) stuff (0, [], [])
  where
    stuff =
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
      [ (UnfoldingDone, 0),
	(MagicUnfold, 0),
	(ConReused, 0),
	(CaseFloatFromLet, 0),
	(CaseOfCase, 0),
	(LetFloatFromLet, 0),
	(LetFloatFromCase, 0),
	(KnownBranch, 0),
	(Let2Case, 0),
	(CaseMerge, 0),
	(CaseElim, 0),
	(CaseIdentity, 0),
	(AtomicRhs, 0),
	(EtaExpansion, 0),
	(CaseOfError, 0),
	(TyBetaReduction,0),
	(BetaReduction,0),
234
	(SpecialisationDone,0),
235 236 237 238 239 240 241 242 243 244 245 246
	-- Foldr/Build Stuff:
	(FoldrBuild, 0),
	(FoldrAugment, 0),
	(Foldr_Nil, 0),
	(Foldr_List, 0),
	(FoldlBuild, 0),
	(FoldlAugment, 0),
	(Foldl_Nil, 0),
	(Foldl_List, 0),
	(Foldr_Cons_Nil, 0),
	(Foldr_Cons, 0),

247 248 249
	(Str_FoldrStr, 0),
	(Str_UnpackCons, 0),
	(Str_UnpackNil, 0) ]
250
--
251
--= array (con2tag_TickType UnfoldingDone, con2tag_TickType FoldrInline)
252 253 254 255 256 257 258
--        [ i := 0 | i <- indices zeroSimplCount ]
\end{code}

Counting-related monad functions:
\begin{code}
tick :: TickType -> SmplM ()

sof's avatar
sof committed
259 260
tick tick_type us (SimplCount n stuff unf)
  = -- pprTrace "Tick: " (text (show tick_type)) $
261
#ifdef OMIT_SIMPL_COUNTS
sof's avatar
sof committed
262
    ((), SimplCount (n _ADD_ ILIT(1) stuff unf))		    stuff -- don't change anything
263
#else
sof's avatar
sof committed
264 265
    new_stuff `seqL`
    ((), SimplCount (n _ADD_ ILIT(1)) new_stuff unf)
266
  where
sof's avatar
sof committed
267
    new_stuff = inc_tick tick_type ILIT(1) stuff
268
#endif
269

sof's avatar
sof committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
maxUnfoldHistory :: Int
maxUnfoldHistory = 20

tickUnfold :: Id -> SmplM ()
tickUnfold id us (SimplCount n stuff (n_unf, unf1, unf2))
  = -- pprTrace "Unfolding: " (ppr PprDebug id) $
    new_stuff `seqL`
    new_unf   `seqTriple`
    ((), SimplCount (n _ADD_ ILIT(1)) new_stuff new_unf)
  where
     new_stuff = inc_tick UnfoldingDone ILIT(1) stuff

     new_unf | n_unf >= maxUnfoldHistory = (1, [unf_item], unf1)
	     | otherwise 		 = (n_unf+1, unf_item:unf1, unf2)
	     
     unf_item = (id, IBOX(n))


    -- force list to avoid getting a chain of @inc_tick@ applications
    -- building up on the heap. (Only true when not dumping stats).
seqL []    y = y
seqL (_:_) y = y

seqTriple (_,_,_) y = y

295 296
tickN :: TickType -> Int -> SmplM ()

297 298
tickN tick_type 0 us counts 
  = ((), counts)
sof's avatar
sof committed
299 300
tickN tick_type IBOX(increment) us (SimplCount n stuff unf)
  = -- pprTrace "Tick: " (text (show tick_type)) $
301
#ifdef OMIT_SIMPL_COUNTS
sof's avatar
sof committed
302
    ((), SimplCount (n _ADD_ increment) stuff) -- don't change anything
303
#else
sof's avatar
sof committed
304 305 306 307 308 309 310 311 312 313 314 315 316
    new_stuff	`seqL`
    ((), SimplCount (n _ADD_ increment) new_stuff unf)
  where   
    new_stuff = inc_tick tick_type increment stuff


inc_tick tick_type n [] = panic "couldn't inc_tick!"

inc_tick tick_type n (x@(ttype, I# cnt#) : xs)
  | ttype == tick_type = case cnt# +# n of
		              incd -> (ttype,IBOX(incd)) : xs

  | otherwise	       = case inc_tick tick_type n xs of { [] -> [x]; ls -> x:ls }
317
#endif
318 319

simplCount :: SmplM Int
sof's avatar
sof committed
320
simplCount us sc@(SimplCount n _ _) = (IBOX(n), sc)
321 322 323 324 325 326 327

detailedSimplCount :: SmplM SimplCount
detailedSimplCount us sc = (sc, sc)

combineSimplCounts :: SimplCount -> SimplCount -> SimplCount

#ifdef OMIT_SIMPL_COUNTS
sof's avatar
sof committed
328
combineSimplCounts (SimplCount n1 stuff1 unf1) (SimplCount n2 stuff2 unf2)
329
  = SimplCount (n1 _ADD_ n2)
sof's avatar
sof committed
330 331
	       stuff2 -- just pick one
	       unf2
332
#else
sof's avatar
sof committed
333 334 335 336 337
combineSimplCounts (SimplCount n1 stuff1 unf1) (SimplCount n2 stuff2 unf2)
  = new_stuff `seqL`
    SimplCount (n1 _ADD_ n2) new_stuff unf2	-- Just pick the second for unfold history
  where
    new_stuff = zipWithEqual "combineSimplCounts" (\ (t1,c1) (t2,c2) -> (t1,c1+c2)) stuff1 stuff2
338 339 340 341 342 343 344 345 346 347
#endif
\end{code}

%************************************************************************
%*									*
\subsection{Monad primitives}
%*									*
%************************************************************************

\begin{code}
348
newId :: Type -> SmplM Id
349
newId ty us sc
350
  = (mkSysLocal SLIT("s") uniq ty noSrcLoc, sc)
351
  where
352
    uniq = getUnique us
353

354
newIds :: [Type] -> SmplM [Id]
355
newIds tys us sc
356
  = (zipWithEqual "newIds" mk_id tys uniqs, sc)
357
  where
358
    uniqs  = getUniques (length tys) us
359
    mk_id ty uniq = mkSysLocal SLIT("s") uniq ty noSrcLoc
360 361 362 363 364 365

cloneTyVarSmpl :: TyVar -> SmplM TyVar

cloneTyVarSmpl tyvar us sc
  = (new_tyvar, sc)
  where
366
   uniq = getUnique us
367 368 369 370
   new_tyvar = cloneTyVar tyvar uniq

cloneId :: SimplEnv -> InBinder -> SmplM OutId
cloneId env (id,_) us sc
sof's avatar
sof committed
371 372
  = simplTyInId env id	`appEager` \ id_with_new_ty ->
    (mkIdWithNewUniq id_with_new_ty uniq, sc)
373
  where
374
    uniq = getUnique us
375 376 377 378

cloneIds :: SimplEnv -> [InBinder] -> SmplM [OutId]
cloneIds env binders = mapSmpl (cloneId env) binders
\end{code}