CgBindery.lhs 18.4 KB
Newer Older
1
%
2
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 4 5 6 7
%
\section[CgBindery]{Utility functions related to doing @CgBindings@}

\begin{code}
module CgBindery (
8
	CgBindings, CgIdInfo,
9
	StableLoc, VolatileLoc,
10 11 12 13

	stableAmodeIdInfo, heapIdInfo, newTempAmodeAndIdInfo,
	letNoEscapeIdInfo, idInfoToAmode,

14 15
	addBindC, addBindsC,

16
	nukeVolatileBinds,
17
	nukeDeadBindings,
18

19
	bindNewToStack,  rebindToStack,
20 21
	bindNewToNode, bindNewToReg, bindArgsToRegs,
	bindNewToTemp, bindNewPrimToAmode,
22
	getArgAmode, getArgAmodes,
23 24
	getCAddrModeAndInfo, getCAddrMode,
	getCAddrModeIfVolatile, getVolatileRegs,
25

26
	buildContLivenessMask
27 28
    ) where

29
#include "HsVersions.h"
30

31 32 33
import AbsCSyn
import CgMonad

34
import CgUsages		( getHpRelOffset, getSpRelOffset, getRealSp )
35
import CgStackery	( freeStackSlots, getStackFrame )
36
import CLabel		( mkClosureLabel,
37
			  mkBitmapLabel, pprCLabel )
38
import ClosureInfo	( mkLFImported, mkLFArgument, LambdaFormInfo )
39
import BitSet
40
import PrimRep		( isFollowableRep, getPrimRepSize )
41
import Id		( Id, idPrimRep, idType )
42 43 44
import Type		( typePrimRep )
import VarEnv
import VarSet		( varSetElems )
45
import Literal		( Literal )
46
import Maybes		( catMaybes, maybeToBool, seqMaybe )
47
import Name		( Name, isInternalName, NamedThing(..) )
48
#ifdef DEBUG
49
import PprAbsC		( pprAmode )
50
#endif
51
import PrimRep          ( PrimRep(..) )
52
import StgSyn		( StgArg, StgLiveVars, GenStgArg(..), isStgTypeArg )
53
import Unique           ( Unique, Uniquable(..) )
54
import UniqSet		( elementOfUniqSet )
55
import Util		( zipWithEqual, sortLt )
56
import Outputable
57 58 59 60 61 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
\end{code}


%************************************************************************
%*									*
\subsection[Bindery-datatypes]{Data types}
%*									*
%************************************************************************

@(CgBinding a b)@ is a type of finite maps from a to b.

The assumption used to be that @lookupCgBind@ must get exactly one
match.  This is {\em completely wrong} in the case of compiling
letrecs (where knot-tying is used).  An initial binding is fed in (and
never evaluated); eventually, a correct binding is put into the
environment.  So there can be two bindings for a given name.

\begin{code}
type CgBindings = IdEnv CgIdInfo

data CgIdInfo
  = MkCgIdInfo	Id	-- Id that this is the info for
		VolatileLoc
		StableLoc
		LambdaFormInfo

data VolatileLoc
  = NoVolatileLoc
  | TempVarLoc	Unique

  | RegLoc	MagicId			-- in one of the magic registers
88
					-- (probably {Int,Float,Char,etc}Reg)
89 90 91 92 93

  | VirHpLoc	VirtualHeapOffset	-- Hp+offset (address of closure)

  | VirNodeLoc	VirtualHeapOffset	-- Cts of offset indirect from Node
					-- ie *(Node+offset)
94 95 96 97 98 99 100 101
\end{code}

@StableLoc@ encodes where an Id can be found, used by
the @CgBindings@ environment in @CgBindery@.

\begin{code}
data StableLoc
  = NoStableLoc
102
  | VirStkLoc		VirtualSpOffset
103 104 105 106 107
  | LitLoc		Literal
  | StableAmodeLoc	CAddrMode

-- these are so StableLoc can be abstract:

108 109
maybeStkLoc (VirStkLoc offset) = Just offset
maybeStkLoc _		       = Nothing
110 111 112 113 114 115 116 117 118 119 120 121 122
\end{code}

%************************************************************************
%*									*
\subsection[Bindery-idInfo]{Manipulating IdInfo}
%*									*
%************************************************************************

\begin{code}
stableAmodeIdInfo i amode lf_info = MkCgIdInfo i NoVolatileLoc (StableAmodeLoc amode) lf_info
heapIdInfo i offset       lf_info = MkCgIdInfo i (VirHpLoc offset) NoStableLoc lf_info
tempIdInfo i uniq         lf_info = MkCgIdInfo i (TempVarLoc uniq) NoStableLoc lf_info

123 124
letNoEscapeIdInfo i sp lf_info
  = MkCgIdInfo i NoVolatileLoc (StableAmodeLoc (CJoinPoint sp)) lf_info
125 126 127 128 129 130

newTempAmodeAndIdInfo :: Id -> LambdaFormInfo -> (CAddrMode, CgIdInfo)

newTempAmodeAndIdInfo name lf_info
  = (temp_amode, temp_idinfo)
  where
131
    uniq       	= getUnique name
132
    temp_amode	= CTemp uniq (idPrimRep name)
133 134
    temp_idinfo = tempIdInfo name uniq lf_info

135
idInfoToAmode :: PrimRep -> CgIdInfo -> FCode CAddrMode
136 137
idInfoToAmode kind (MkCgIdInfo _ vol stab _) = idInfoPiecesToAmode kind vol stab

138
idInfoPiecesToAmode :: PrimRep -> VolatileLoc -> StableLoc -> FCode CAddrMode
139 140 141 142 143 144 145 146

idInfoPiecesToAmode kind (TempVarLoc uniq) stable_loc   = returnFC (CTemp uniq kind)
idInfoPiecesToAmode kind (RegLoc magic_id) stable_loc   = returnFC (CReg magic_id)

idInfoPiecesToAmode kind NoVolatileLoc (LitLoc lit)           = returnFC (CLit lit)
idInfoPiecesToAmode kind NoVolatileLoc (StableAmodeLoc amode) = returnFC amode

idInfoPiecesToAmode kind (VirNodeLoc nd_off) stable_loc
147
  = returnFC (CVal (nodeRel nd_off) kind)
148 149 150 151 152 153 154 155
    -- Virtual offsets from Node increase into the closures,
    -- and so do Node-relative offsets (which we want in the CVal),
    -- so there is no mucking about to do to the offset.

idInfoPiecesToAmode kind (VirHpLoc hp_off) stable_loc
  = getHpRelOffset hp_off `thenFC` \ rel_hp ->
    returnFC (CAddr rel_hp)

156 157 158
idInfoPiecesToAmode kind NoVolatileLoc (VirStkLoc i)
  = getSpRelOffset i `thenFC` \ rel_sp ->
    returnFC (CVal rel_sp kind)
159

160
#ifdef DEBUG
161
idInfoPiecesToAmode kind NoVolatileLoc NoStableLoc = panic "idInfoPiecesToAmode: no loc"
162
#endif
163 164
\end{code}

165 166 167 168 169 170 171 172 173 174 175 176 177 178
%************************************************************************
%*									*
\subsection[CgMonad-bindery]{Monad things for fiddling with @CgBindings@}
%*									*
%************************************************************************

There are three basic routines, for adding (@addBindC@), modifying
(@modifyBindC@) and looking up (@lookupBindC@) bindings.

A @Id@ is bound to a @(VolatileLoc, StableLoc)@ triple.
The name should not already be bound. (nice ASSERT, eh?)

\begin{code}
addBindC :: Id -> CgIdInfo -> Code
rje's avatar
rje committed
179 180 181
addBindC name stuff_to_bind = do
	binds <- getBinds
	setBinds $ extendVarEnv binds name stuff_to_bind
182 183

addBindsC :: [(Id, CgIdInfo)] -> Code
rje's avatar
rje committed
184 185 186 187 188 189
addBindsC new_bindings = do
	binds <- getBinds
	let new_binds = foldl (\ binds (name,info) -> extendVarEnv binds name info)
		binds
		new_bindings
	setBinds new_binds
190 191

modifyBindC :: Id -> (CgIdInfo -> CgIdInfo) -> Code
rje's avatar
rje committed
192 193 194
modifyBindC name mangle_fn = do
	binds <- getBinds
	setBinds $ modifyVarEnv mangle_fn binds name
195 196

lookupBindC :: Id -> FCode CgIdInfo
197 198 199 200 201 202 203 204 205 206 207 208
lookupBindC id = do maybe_info <- lookupBindC_maybe id
		    case maybe_info of
		      Just info -> return info
		      Nothing   -> cgLookupPanic id

lookupBindC_maybe :: Id -> FCode (Maybe CgIdInfo)
lookupBindC_maybe id
  = do	static_binds <- getStaticBinds
	local_binds  <- getBinds
	return (lookupVarEnv local_binds id
			`seqMaybe`
		lookupVarEnv static_binds id)
rje's avatar
rje committed
209
			
210 211 212
cgLookupPanic :: Id -> FCode a
cgLookupPanic id
  = do	static_binds <- getStaticBinds
rje's avatar
rje committed
213 214 215
	local_binds <- getBinds
	srt <- getSRTLabel
	pprPanic "cgPanic"
216
		(vcat [ppr id,
217 218 219 220 221 222 223 224
		ptext SLIT("static binds for:"),
		vcat [ ppr i | (MkCgIdInfo i _ _ _) <- rngVarEnv static_binds ],
		ptext SLIT("local binds for:"),
		vcat [ ppr i | (MkCgIdInfo i _ _ _) <- rngVarEnv local_binds ],
	        ptext SLIT("SRT label") <+> pprCLabel srt
	      ])
\end{code}

225 226 227 228 229 230 231 232 233 234 235 236
%************************************************************************
%*									*
\subsection[Bindery-nuke-volatile]{Nuking volatile bindings}
%*									*
%************************************************************************

We sometimes want to nuke all the volatile bindings; we must be sure
we don't leave any (NoVolatile, NoStable) binds around...

\begin{code}
nukeVolatileBinds :: CgBindings -> CgBindings
nukeVolatileBinds binds
237
  = mkVarEnv (foldr keep_if_stable [] (rngVarEnv binds))
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
  where
    keep_if_stable (MkCgIdInfo i _ NoStableLoc entry_info) acc = acc
    keep_if_stable (MkCgIdInfo i _ stable_loc  entry_info) acc
      = (i, MkCgIdInfo i NoVolatileLoc stable_loc entry_info) : acc
\end{code}


%************************************************************************
%*									*
\subsection[lookup-interface]{Interface functions to looking up bindings}
%*									*
%************************************************************************

I {\em think} all looking-up is done through @getCAddrMode(s)@.

\begin{code}
254
getCAddrModeAndInfo :: Id -> FCode (Id, CAddrMode, LambdaFormInfo)
255

256
getCAddrModeAndInfo id
257 258 259 260 261
  = do
	maybe_cg_id_info <- lookupBindC_maybe id
	case maybe_cg_id_info of

		-- Nothing => not in the environment, so should be imported
262
	  Nothing | isInternalName name -> cgLookupPanic id
263 264 265 266 267
		  | otherwise	     -> returnFC (id, global_amode, mkLFImported id)

	  Just (MkCgIdInfo id' volatile_loc stable_loc lf_info)
		  -> do amode <- idInfoPiecesToAmode kind volatile_loc stable_loc
			return (id', amode, lf_info)
268
  where
269
    name = getName id
270
    global_amode = CLbl (mkClosureLabel name) kind
271
    kind = idPrimRep id
272 273

getCAddrMode :: Id -> FCode CAddrMode
rje's avatar
rje committed
274 275 276
getCAddrMode name = do
	(_, amode, _) <- getCAddrModeAndInfo name
	return amode
277 278 279 280 281
\end{code}

\begin{code}
getCAddrModeIfVolatile :: Id -> FCode (Maybe CAddrMode)
getCAddrModeIfVolatile name
282 283
--  | toplevelishId name = returnFC Nothing
--  | otherwise
rje's avatar
rje committed
284 285 286 287 288 289 290
	= do
	(MkCgIdInfo _ volatile_loc stable_loc lf_info) <- lookupBindC name
	case stable_loc of
		NoStableLoc -> do -- Aha!  So it is volatile!
			amode <- idInfoPiecesToAmode (idPrimRep name) volatile_loc NoStableLoc
			return $ Just amode
		a_stable_loc -> return Nothing
291 292 293 294 295 296 297 298 299 300
\end{code}

@getVolatileRegs@ gets a set of live variables, and returns a list of
all registers on which these variables depend.  These are the regs
which must be saved and restored across any C calls.  If a variable is
both in a volatile location (depending on a register) {\em and} a
stable one (notably, on the stack), we modify the current bindings to
forget the volatile one.

\begin{code}
301
getVolatileRegs :: StgLiveVars -> FCode [MagicId]
302

rje's avatar
rje committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
getVolatileRegs vars = do
	stuff <- mapFCs snaffle_it (varSetElems vars)
	returnFC $ catMaybes stuff
	where
	snaffle_it var = do
		(MkCgIdInfo _ volatile_loc stable_loc lf_info) <- lookupBindC var 
		let
		-- commoned-up code...
			consider_reg reg =
				if not (isVolatileReg reg) then
				-- Potentially dies across C calls
				-- For now, that's everything; we leave
				-- it to the save-macros to decide which
				-- regs *really* need to be saved.
					returnFC Nothing
				else
					case stable_loc of
						NoStableLoc -> returnFC (Just reg) -- got one!
						is_a_stable_loc -> do
							-- has both volatile & stable locations;
							-- force it to rely on the stable location
							modifyBindC var nuke_vol_bind 
							return Nothing
			in
			case volatile_loc of
				RegLoc reg   -> consider_reg reg
				VirNodeLoc _ -> consider_reg node
				non_reg_loc  -> returnFC Nothing

	nuke_vol_bind (MkCgIdInfo i _ stable_loc lf_info)
		= MkCgIdInfo i NoVolatileLoc stable_loc lf_info
334 335 336
\end{code}

\begin{code}
337 338 339
getArgAmodes :: [StgArg] -> FCode [CAddrMode]
getArgAmodes [] = returnFC []
getArgAmodes (atom:atoms)
rje's avatar
rje committed
340 341 342 343 344 345
	| isStgTypeArg atom 
	= getArgAmodes atoms
	| otherwise = do
		amode <- getArgAmode  atom 
		amodes <- getArgAmodes atoms
		return ( amode : amodes )
346

347
getArgAmode :: StgArg -> FCode CAddrMode
348

349
getArgAmode (StgVarArg var) = getCAddrMode var		-- The common case
350
getArgAmode (StgLitArg lit) = returnFC (CLit lit)
351 352 353 354 355 356 357 358 359
\end{code}

%************************************************************************
%*									*
\subsection[binding-and-rebinding-interface]{Interface functions for binding and re-binding names}
%*									*
%************************************************************************

\begin{code}
360 361
bindNewToStack :: (Id, VirtualSpOffset) -> Code
bindNewToStack (name, offset)
362 363
  = addBindC name info
  where
364
    info = MkCgIdInfo name NoVolatileLoc (VirStkLoc offset) (mkLFArgument name)
365 366 367 368 369 370 371 372 373 374 375 376

bindNewToNode :: Id -> VirtualHeapOffset -> LambdaFormInfo -> Code
bindNewToNode name offset lf_info
  = addBindC name info
  where
    info = MkCgIdInfo name (VirNodeLoc offset) NoStableLoc lf_info

-- Create a new temporary whose unique is that in the id,
-- bind the id to it, and return the addressing mode for the
-- temporary.
bindNewToTemp :: Id -> FCode CAddrMode
bindNewToTemp name
377
  = let (temp_amode, id_info) = newTempAmodeAndIdInfo name (mkLFArgument name)
378 379 380
		-- This is used only for things we don't know
		-- anything about; values returned by a case statement,
		-- for example.
rje's avatar
rje committed
381 382 383
    in do
		addBindC name id_info
		return temp_amode
384 385 386 387 388 389 390 391 392

bindNewToReg :: Id -> MagicId -> LambdaFormInfo -> Code
bindNewToReg name magic_id lf_info
  = addBindC name info
  where
    info = MkCgIdInfo name (RegLoc magic_id) NoStableLoc lf_info

bindArgsToRegs :: [Id] -> [MagicId] -> Code
bindArgsToRegs args regs
393
  = listCs (zipWithEqual "bindArgsToRegs" bind args regs)
394
  where
395
    arg `bind` reg = bindNewToReg arg reg (mkLFArgument arg)
396 397
\end{code}

398 399 400
@bindNewPrimToAmode@ works only for certain addressing modes.  Making
this work for stack offsets is non-trivial (virt vs. real stack offset
difficulties).
401 402 403

\begin{code}
bindNewPrimToAmode :: Id -> CAddrMode -> Code
404 405 406
bindNewPrimToAmode name (CReg reg) 
  = bindNewToReg name reg (panic "bindNewPrimToAmode")

407 408 409 410 411
bindNewPrimToAmode name (CTemp uniq kind)
  = addBindC name (tempIdInfo name uniq (panic "bindNewPrimToAmode"))

#ifdef DEBUG
bindNewPrimToAmode name amode
412
  = pprPanic "bindNew...:" (pprAmode amode)
413 414 415 416
#endif
\end{code}

\begin{code}
417 418
rebindToStack :: Id -> VirtualSpOffset -> Code
rebindToStack name offset
419 420 421
  = modifyBindC name replace_stable_fn
  where
    replace_stable_fn (MkCgIdInfo i vol stab einfo)
422 423
      = MkCgIdInfo i vol (VirStkLoc offset) einfo
\end{code}
424

425 426 427 428 429 430
%************************************************************************
%*									*
\subsection[CgBindery-liveness]{Build a liveness mask for the current stack}
%*									*
%************************************************************************

431
There are four kinds of things on the stack:
432

433 434 435 436
	- pointer variables (bound in the environment)
	- non-pointer variables (boudn in the environment)
	- free slots (recorded in the stack free list)
	- non-pointer data slots (recorded in the stack free list)
437

438 439 440
We build up a bitmap of non-pointer slots by looking down the
environment for all the non-pointer variables, and merging this with
the slots recorded in the stack free list.
441

442 443 444 445 446 447 448
There's a bit of a hack here to do with update frames: since nothing
is recorded in either the environment or the stack free list for an
update frame, the code below defaults to assuming the slots taken up
by an update frame contain pointers.  Furthermore, update frames are
always in slots 0-2 at the bottom of the stack.  The bitmap will
therefore end at slot 3, which is what we want (the update frame info
pointer has its own bitmap to describe the update frame).
449 450 451

\begin{code}
buildLivenessMask 
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 478 479 480 481 482 483 484 485
	:: VirtualSpOffset	-- offset from which the bitmap should start
	-> FCode LivenessMask	-- mask for free/unlifted slots

buildLivenessMask sp = do {

    -- find all unboxed stack-resident ids
    binds <- getBinds;
    ((vsp, _, free, _, _), heap_usage) <- getUsage;
    
    let { 
	unboxed_slots = 
    	    [ (ofs, size) | 
    	    (MkCgIdInfo id _ (VirStkLoc ofs) _) <- rngVarEnv binds,
    	    let rep = idPrimRep id; size = getPrimRepSize rep,
    	    not (isFollowableRep rep),
    	    size > 0
    	    ];
      
    -- flatten this list into a list of unboxed stack slots
        flatten_slots = sortLt (<) 
    	    (foldr (\(ofs,size) r -> [ofs-size+1 .. ofs] ++ r) []
    		  unboxed_slots);
    
    -- merge in the free slots
	all_slots = mergeSlots flatten_slots (map fst free) ++ 
		    if vsp < sp then [vsp+1 .. sp] else [];

    -- recalibrate the list to be sp-relative
	rel_slots = reverse (map (sp-) all_slots);
    };

    ASSERT(all (>=0) rel_slots && rel_slots == sortLt (<) rel_slots)
     return (listToLivenessMask rel_slots)
  }
486 487


488 489 490 491 492 493 494 495 496 497 498
mergeSlots :: [Int] -> [Int] -> [Int]
mergeSlots cs [] = cs
mergeSlots [] ns = ns
mergeSlots (c:cs) (n:ns)
 = if c < n then
	c : mergeSlots cs (n:ns)
   else if c > n then
	n : mergeSlots (c:cs) ns
   else
	panic ("mergeSlots: equal slots: " ++ show (c:cs) ++ show (n:ns))

499 500 501 502 503
listToLivenessMask :: [Int] -> LivenessMask
listToLivenessMask []    = []
listToLivenessMask slots = 
   mkBS this : listToLivenessMask (map (\x -> x-32) rest)
   where (this,rest) = span (<32) slots
504 505
\end{code}

506 507 508 509
In a continuation, we want a liveness mask that starts from just after
the return address, which is on the stack at realSp.

\begin{code}
510 511
buildContLivenessMask :: Name -> FCode Liveness
buildContLivenessMask name = do
rje's avatar
rje committed
512
	realSp <- getRealSp
513 514 515 516 517 518 519 520 521 522 523 524
	mask <- buildLivenessMask (realSp-1)

        let lbl = mkBitmapLabel name

	-- realSp points to the frame-header for the current stack frame,
	-- and the end of this frame is frame_sp.  The size is therefore
	-- realSp - frame_sp - 1 (subtract one for the frame-header).
	frame_sp <- getStackFrame
	let liveness = Liveness lbl (realSp-1-frame_sp) mask

	absC (CBitmap liveness)
	return liveness
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
\end{code}

%************************************************************************
%*									*
\subsection[CgMonad-deadslots]{Finding dead stack slots}
%*									*
%************************************************************************

nukeDeadBindings does the following:

      -	Removes all bindings from the environment other than those
	for variables in the argument to nukeDeadBindings.
      -	Collects any stack slots so freed, and returns them to the  stack free
	list.
      -	Moves the virtual stack pointer to point to the topmost used
	stack locations.

You can have multi-word slots on the stack (where a Double# used to
be, for instance); if dead, such a slot will be reported as *several*
offsets (one per word).

Probably *naughty* to look inside monad...

\begin{code}
nukeDeadBindings :: StgLiveVars  -- All the *live* variables
		 -> Code
rje's avatar
rje committed
551 552 553 554 555 556 557
nukeDeadBindings live_vars = do
	binds <- getBinds
	let (dead_stk_slots, bs') =
		dead_slots live_vars 
			[] []
			[ (i, b) | b@(MkCgIdInfo i _ _ _) <- rngVarEnv binds ]
	setBinds $ mkVarEnv bs'
558
	freeStackSlots dead_stk_slots
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
\end{code}

Several boring auxiliary functions to do the dirty work.

\begin{code}
dead_slots :: StgLiveVars
	   -> [(Id,CgIdInfo)]
	   -> [VirtualSpOffset]
	   -> [(Id,CgIdInfo)]
	   -> ([VirtualSpOffset], [(Id,CgIdInfo)])

-- dead_slots carries accumulating parameters for
--	filtered bindings, dead slots
dead_slots live_vars fbs ds []
  = (ds, reverse fbs) -- Finished; rm the dups, if any

dead_slots live_vars fbs ds ((v,i):bs)
  | v `elementOfUniqSet` live_vars
    = dead_slots live_vars ((v,i):fbs) ds bs
	  -- Live, so don't record it in dead slots
	  -- Instead keep it in the filtered bindings

  | otherwise
    = case i of
	MkCgIdInfo _ _ stable_loc _
584
	 | is_stk_loc && size > 0 ->
585 586 587 588 589 590 591 592 593 594 595 596 597
	   dead_slots live_vars fbs ([offset-size+1 .. offset] ++ ds) bs
 	 where
 	  maybe_stk_loc = maybeStkLoc stable_loc
 	  is_stk_loc	= maybeToBool maybe_stk_loc
 	  (Just offset) = maybe_stk_loc

	_ -> dead_slots live_vars fbs ds bs
  where

    size :: Int
    size = (getPrimRepSize . typePrimRep . idType) v

\end{code}