StgCmmLayout.hs 23.4 KB
Newer Older
1
2
3
4
5
6
7
8
-----------------------------------------------------------------------------
--
-- Building info tables.
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------

Ian Lynagh's avatar
Ian Lynagh committed
9
10
11
12
13
14
15
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details

16
17
module StgCmmLayout (
	mkArgDescr, 
Simon Marlow's avatar
Simon Marlow committed
18
        emitCall, emitReturn, adjustHpBackwards,
19

20
21
	emitClosureProcAndInfoTable,
	emitClosureAndInfoTable,
22
23
24

	slowCall, directCall, 

25
	mkVirtHeapOffsets, mkVirtConstrOffsets, getHpRelOffset, hpRel,
26
27
28
29
30
31
32

	stdInfoTableSizeB,
	entryCode, closureInfoPtr,
	getConstrTag,
        cmmGetClosureType,
	infoTable, infoTableClosureType,
	infoTablePtrs, infoTableNonPtrs,
33
	funInfoTable
34
35
36
37
38
39
40
41
42
  ) where


#include "HsVersions.h"

import StgCmmClosure
import StgCmmEnv
import StgCmmTicky
import StgCmmMonad
43
import StgCmmUtils
Simon Marlow's avatar
Simon Marlow committed
44
import StgCmmProf
45

46
import MkGraph
47
import SMRep
48
import Cmm
Simon Marlow's avatar
Simon Marlow committed
49
import CmmUtils
50
51
52
53
54
import CLabel
import StgSyn
import Id
import Name
import TyCon		( PrimRep(..) )
55
import BasicTypes	( RepArity )
56
import DynFlags
Simon Marlow's avatar
Simon Marlow committed
57
import Module
58
59
60
61
62

import Constants
import Util
import Data.List
import Outputable
Ian Lynagh's avatar
Ian Lynagh committed
63
import FastString
64
65
66
67
68

------------------------------------------------------------------------
--		Call and return sequences
------------------------------------------------------------------------

69
70
71
72
73
-- | Return multiple values to the sequel
--
-- If the sequel is @Return@
--
-- >     return (x,y)
74
--
75
76
77
78
-- If the sequel is @AssignTo [p,q]@
--
-- >    p=x; q=y;
--
79
emitReturn :: [CmmExpr] -> FCode ReturnKind
80
emitReturn results
81
82
  = do { dflags    <- getDynFlags
       ; sequel    <- getSequel
83
84
85
86
       ; updfr_off <- getUpdFrameOff
       ; case sequel of
           Return _ ->
             do { adjustHpBackwards
87
                ; emit (mkReturnSimple dflags results updfr_off) }
88
89
           AssignTo regs adjust ->
             do { if adjust then adjustHpBackwards else return ()
90
                ; emitMultiAssign  regs results }
91
       ; return AssignedDirectly
92
       }
93

94
95
96
97
98

-- | @emitCall conv fun args@ makes a call to the entry-code of @fun@,
-- using the call/return convention @conv@, passing @args@, and
-- returning the results to the current sequel.
--
99
emitCall :: (Convention, Convention) -> CmmExpr -> [CmmExpr] -> FCode ReturnKind
100
101
emitCall convs fun args
  = emitCallWithExtraStack convs fun args noExtraStack
102

103
104
105
106
107
108

-- | @emitCallWithExtraStack conv fun args stack@ makes a call to the
-- entry-code of @fun@, using the call/return convention @conv@,
-- passing @args@, pushing some extra stack frames described by
-- @stack@, and returning the results to the current sequel.
--
Simon Marlow's avatar
Simon Marlow committed
109
110
emitCallWithExtraStack
   :: (Convention, Convention) -> CmmExpr -> [CmmExpr]
111
112
   -> (ByteOff, [(CmmExpr,ByteOff)]) -> FCode ReturnKind
emitCallWithExtraStack (callConv, retConv) fun args extra_stack
113
114
  = do	{ dflags <- getDynFlags
        ; adjustHpBackwards
Simon Marlow's avatar
Simon Marlow committed
115
116
117
	; sequel <- getSequel
	; updfr_off <- getUpdFrameOff
        ; case sequel of
118
            Return _ -> do
119
              emit $ mkForeignJumpExtra dflags callConv fun args updfr_off extra_stack
120
              return AssignedDirectly
Simon Marlow's avatar
Simon Marlow committed
121
            AssignTo res_regs _ -> do
122
123
              k <- newLabelC
              let area = Young k
124
125
                  (off, copyin) = copyInOflow dflags retConv area res_regs
                  copyout = mkCallReturnsTo dflags fun callConv args k off updfr_off
126
127
128
                                   extra_stack
              emit (copyout <*> mkLabel k <*> copyin)
              return (ReturnedTo k off)
Simon Marlow's avatar
Simon Marlow committed
129
130
131
      }


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
adjustHpBackwards :: FCode ()
-- This function adjusts and heap pointers just before a tail call or
-- return.  At a call or return, the virtual heap pointer may be less 
-- than the real Hp, because the latter was advanced to deal with 
-- the worst-case branch of the code, and we may be in a better-case 
-- branch.  In that case, move the real Hp *back* and retract some 
-- ticky allocation count.
--
-- It *does not* deal with high-water-mark adjustment.
-- That's done by functions which allocate heap.
adjustHpBackwards
  = do	{ hp_usg <- getHpUsage
	; let rHp = realHp hp_usg
	      vHp = virtHp hp_usg
	      adjust_words = vHp -rHp
	; new_hp <- getHpRelOffset vHp

	; emit (if adjust_words == 0
		then mkNop
		else mkAssign hpReg new_hp)	-- Generates nothing when vHp==rHp

	; tickyAllocHeap adjust_words		-- ...ditto

	; setRealHp vHp
	}


-------------------------------------------------------------------------
--	Making calls: directCall and slowCall
-------------------------------------------------------------------------

Simon Marlow's avatar
Simon Marlow committed
163
164
165
166
167
168
169
170
171
172
173
174
175
-- General plan is:
--   - we'll make *one* fast call, either to the function itself
--     (directCall) or to stg_ap_<pat>_fast (slowCall)
--     Any left-over arguments will be pushed on the stack,
--
--     e.g. Sp[old+8]  = arg1
--          Sp[old+16] = arg2
--          Sp[old+32] = stg_ap_pp_info
--          R2 = arg3
--          R3 = arg4
--          call f() return to Nothing updfr_off: 32


176
directCall :: Convention -> CLabel -> RepArity -> [StgArg] -> FCode ReturnKind
177
178
179
180
-- (directCall f n args)
-- calls f(arg1, ..., argn), and applies the result to the remaining args
-- The function f has arity n, and there are guaranteed at least n args
-- Both arity and args include void args
181
directCall conv lbl arity stg_args
182
  = do  { argreps <- getArgRepsAmodes stg_args
183
        ; direct_call "directCall" conv lbl arity argreps }
184

185

186
slowCall :: CmmExpr -> [StgArg] -> FCode ReturnKind
187
188
-- (slowCall fun args) applies fun to args, returning the results to Sequel
slowCall fun stg_args 
Simon Marlow's avatar
Simon Marlow committed
189
  = do  { dflags <- getDynFlags
190
191
        ; argsreps <- getArgRepsAmodes stg_args
        ; let (rts_fun, arity) = slowCallPattern (map fst argsreps)
192
        ; r <- direct_call "slow_call" NativeNodeCall
193
                 (mkRtsApFastLabel rts_fun) arity ((P,Just fun):argsreps)
Simon Marlow's avatar
Simon Marlow committed
194
        ; emitComment $ mkFastString ("slow_call for " ++
195
196
                                      showSDoc dflags (ppr fun) ++
                                      " with pat " ++ unpackFS rts_fun)
197
        ; return r
Simon Marlow's avatar
Simon Marlow committed
198
        }
199

200
201

--------------
202
203
204
direct_call :: String
            -> Convention     -- e.g. NativeNodeCall or NativeDirectCall
            -> CLabel -> RepArity
205
            -> [(ArgRep,Maybe CmmExpr)] -> FCode ReturnKind
206
207
direct_call caller call_conv lbl arity args
  | debugIsOn && real_arity > length args  -- Too few args
208
  = do -- Caller should ensure that there enough args!
209
210
       pprPanic "direct_call" $
            text caller <+> ppr arity <+>
211
212
            ppr lbl <+> ppr (length args) <+>
            ppr (map snd args) <+> ppr (map fst args)
213

214
  | null rest_args  -- Precisely the right number of arguments
215
  = emitCall (call_conv, NativeReturn) target (nonVArgs args)
216

Simon Marlow's avatar
Simon Marlow committed
217
  | otherwise       -- Note [over-saturated calls]
218
219
220
221
222
  = do dflags <- getDynFlags
       emitCallWithExtraStack (call_conv, NativeReturn)
                              target
                              (nonVArgs fast_args)
                              (mkStkOffsets (stack_args dflags))
223
224
  where
    target = CmmLit (CmmLabel lbl)
225
    (fast_args, rest_args) = splitAt real_arity args
226
    stack_args dflags = slowArgs dflags rest_args
227
228
229
    real_arity = case call_conv of
                   NativeNodeCall -> arity+1
                   _              -> arity
230

Simon Marlow's avatar
Simon Marlow committed
231

232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
-- When constructing calls, it is easier to keep the ArgReps and the
-- CmmExprs zipped together.  However, a void argument has no
-- representation, so we need to use Maybe CmmExpr (the alternative of
-- using zeroCLit or even undefined would work, but would be ugly).
--
getArgRepsAmodes :: [StgArg] -> FCode [(ArgRep, Maybe CmmExpr)]
getArgRepsAmodes = mapM getArgRepAmode
  where getArgRepAmode arg
           | V <- rep  = return (V, Nothing)
           | otherwise = do expr <- getArgAmode (NonVoid arg)
                            return (rep, Just expr)
           where rep = toArgRep (argPrimRep arg)

nonVArgs :: [(ArgRep, Maybe CmmExpr)] -> [CmmExpr]
nonVArgs [] = []
nonVArgs ((_,Nothing)  : args) = nonVArgs args
nonVArgs ((_,Just arg) : args) = arg : nonVArgs args
Simon Marlow's avatar
Simon Marlow committed
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287

{-
Note [over-saturated calls]

The natural thing to do for an over-saturated call would be to call
the function with the correct number of arguments, and then apply the
remaining arguments to the value returned, e.g.

  f a b c d   (where f has arity 2)
  -->
  r = call f(a,b)
  call r(c,d)

but this entails
  - saving c and d on the stack
  - making a continuation info table
  - at the continuation, loading c and d off the stack into regs
  - finally, call r

Note that since there are a fixed number of different r's
(e.g.  stg_ap_pp_fast), we can also pre-compile continuations
that correspond to each of them, rather than generating a fresh
one for each over-saturated call.

Not only does this generate much less code, it is faster too.  We will
generate something like:

Sp[old+16] = c
Sp[old+24] = d
Sp[old+32] = stg_ap_pp_info
call f(a,b) -- usual calling convention

For the purposes of the CmmCall node, we count this extra stack as
just more arguments that we are passing on the stack (cml_args).
-}

-- | 'slowArgs' takes a list of function arguments and prepares them for
-- pushing on the stack for "extra" arguments to a function which requires
-- fewer arguments than we currently have.
288
289
290
291
292
293
slowArgs :: DynFlags -> [(ArgRep, Maybe CmmExpr)] -> [(ArgRep, Maybe CmmExpr)]
slowArgs _ [] = []
slowArgs dflags args -- careful: reps contains voids (V), but args does not
  | dopt Opt_SccProfilingOn dflags
              = save_cccs ++ this_pat ++ slowArgs dflags rest_args
  | otherwise =              this_pat ++ slowArgs dflags rest_args
294
  where
295
296
297
    (arg_pat, n)            = slowCallPattern (map fst args)
    (call_args, rest_args)  = splitAt n args

Simon Marlow's avatar
Simon Marlow committed
298
    stg_ap_pat = mkCmmRetInfoLabel rtsPackageId arg_pat
299
300
    this_pat   = (N, Just (mkLblExpr stg_ap_pat)) : call_args
    save_cccs  = [(N, Just (mkLblExpr save_cccs_lbl)), (N, Just curCCS)]
Simon Marlow's avatar
Simon Marlow committed
301
302
    save_cccs_lbl = mkCmmRetInfoLabel rtsPackageId (fsLit "stg_restore_cccs")

303

304
305

-- These cases were found to cover about 99% of all slow calls:
306
slowCallPattern :: [ArgRep] -> (FastString, RepArity)
307
-- Returns the generic apply function and arity
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
slowCallPattern (P: P: P: P: P: P: _) = (fsLit "stg_ap_pppppp", 6)
slowCallPattern (P: P: P: P: P: _)    = (fsLit "stg_ap_ppppp", 5)
slowCallPattern (P: P: P: P: _)       = (fsLit "stg_ap_pppp", 4)
slowCallPattern (P: P: P: V: _)       = (fsLit "stg_ap_pppv", 4)
slowCallPattern (P: P: P: _)          = (fsLit "stg_ap_ppp", 3)
slowCallPattern (P: P: V: _)          = (fsLit "stg_ap_ppv", 3)
slowCallPattern (P: P: _)	      = (fsLit "stg_ap_pp", 2)
slowCallPattern (P: V: _)	      = (fsLit "stg_ap_pv", 2)
slowCallPattern (P: _)		      = (fsLit "stg_ap_p", 1)
slowCallPattern (V: _)		      = (fsLit "stg_ap_v", 1)
slowCallPattern (N: _)		      = (fsLit "stg_ap_n", 1)
slowCallPattern (F: _)		      = (fsLit "stg_ap_f", 1)
slowCallPattern (D: _)		      = (fsLit "stg_ap_d", 1)
slowCallPattern (L: _)		      = (fsLit "stg_ap_l", 1)
slowCallPattern []		      = (fsLit "stg_ap_0", 0)
323
324


Simon Marlow's avatar
Simon Marlow committed
325
326
327
328
329
330
331
-------------------------------------------------------------------------
-- Fix the byte-offsets of a bunch of things to push on the stack

-- This is used for pushing slow-call continuations.
-- See Note [over-saturated calls].

mkStkOffsets
332
  :: [(ArgRep, Maybe CmmExpr)]    -- things to make offsets for
Simon Marlow's avatar
Simon Marlow committed
333
334
335
336
337
338
  -> ( ByteOff                    -- OUTPUTS: Topmost allocated word
     , [(CmmExpr, ByteOff)] )     -- things with offsets (voids filtered out)
mkStkOffsets things
    = loop 0 [] (reverse things)
  where
    loop offset offs [] = (offset,offs)
339
    loop offset offs ((_,Nothing):things) = loop offset offs things
Simon Marlow's avatar
Simon Marlow committed
340
	-- ignore Void arguments
341
    loop offset offs ((rep,Just thing):things)
Simon Marlow's avatar
Simon Marlow committed
342
343
344
345
346
347
348
        = loop thing_off ((thing, thing_off):offs) things
	where
          thing_off = offset + argRepSizeW rep * wORD_SIZE
	    -- offset of thing is offset+size, because we're 
	    -- growing the stack *downwards* as the offsets increase.


349
-------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
350
--	Classifying arguments: ArgRep
351
352
-------------------------------------------------------------------------

Simon Marlow's avatar
Simon Marlow committed
353
-- ArgRep is not exported (even abstractly)
354
355
-- It's a local helper type for classification

Simon Marlow's avatar
Simon Marlow committed
356
data ArgRep = P 	-- GC Ptr
357
358
359
360
361
	  | N   -- One-word non-ptr
	  | L	-- Two-word non-ptr (long)
	  | V	-- Void
	  | F	-- Float
	  | D	-- Double
Simon Marlow's avatar
Simon Marlow committed
362
instance Outputable ArgRep where
363
364
365
366
367
368
  ppr P = text "P"
  ppr N = text "N"
  ppr L = text "L"
  ppr V = text "V"
  ppr F = text "F"
  ppr D = text "D"
369

Simon Marlow's avatar
Simon Marlow committed
370
371
372
373
374
375
376
377
378
379
380
381
toArgRep :: PrimRep -> ArgRep
toArgRep VoidRep   = V
toArgRep PtrRep    = P
toArgRep IntRep    = N
toArgRep WordRep   = N
toArgRep AddrRep   = N
toArgRep Int64Rep  = L
toArgRep Word64Rep = L
toArgRep FloatRep  = F
toArgRep DoubleRep = D

isNonV :: ArgRep -> Bool
382
383
384
isNonV V = False
isNonV _ = True

385
argRepSizeW :: ArgRep -> WordOff                -- Size in words
Simon Marlow's avatar
Simon Marlow committed
386
387
388
389
390
391
argRepSizeW N = 1
argRepSizeW P = 1
argRepSizeW F = 1
argRepSizeW L = wORD64_SIZE `quot` wORD_SIZE
argRepSizeW D = dOUBLE_SIZE `quot` wORD_SIZE
argRepSizeW V = 0
392

Simon Marlow's avatar
Simon Marlow committed
393
394
idArgRep :: Id -> ArgRep
idArgRep = toArgRep . idPrimRep
Simon Peyton Jones's avatar
Simon Peyton Jones committed
395

396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
-------------------------------------------------------------------------
----	Laying out objects on the heap and stack
-------------------------------------------------------------------------

-- The heap always grows upwards, so hpRel is easy
hpRel :: VirtualHpOffset 	-- virtual offset of Hp
      -> VirtualHpOffset 	-- virtual offset of The Thing
      -> WordOff		-- integer word offset
hpRel hp off = off - hp

getHpRelOffset :: VirtualHpOffset -> FCode CmmExpr
getHpRelOffset virtual_offset
  = do	{ hp_usg <- getHpUsage
	; return (cmmRegOffW hpReg (hpRel (realHp hp_usg) virtual_offset)) }

mkVirtHeapOffsets
412
413
  :: DynFlags
  -> Bool		-- True <=> is a thunk
414
415
416
  -> [(PrimRep,a)]	-- Things to make offsets for
  -> (WordOff,		-- _Total_ number of words allocated
      WordOff,		-- Number of words allocated for *pointers*
417
      [(NonVoid a, VirtualHpOffset)])
418
419
420
421
422
423
424
425
426
427
428

-- Things with their offsets from start of object in order of
-- increasing offset; BUT THIS MAY BE DIFFERENT TO INPUT ORDER
-- First in list gets lowest offset, which is initial offset + 1.
--
-- Void arguments are removed, so output list may be shorter than
-- input list
--
-- mkVirtHeapOffsets always returns boxed things with smaller offsets
-- than the unboxed things

429
mkVirtHeapOffsets dflags is_thunk things
430
431
432
433
434
435
436
  = let non_void_things		      = filterOut (isVoidRep . fst)  things
	(ptrs, non_ptrs)    	      = partition (isGcPtrRep . fst) non_void_things
    	(wds_of_ptrs, ptrs_w_offsets) = mapAccumL computeOffset 0 ptrs
	(tot_wds, non_ptrs_w_offsets) = mapAccumL computeOffset wds_of_ptrs non_ptrs
    in
    (tot_wds, wds_of_ptrs, ptrs_w_offsets ++ non_ptrs_w_offsets)
  where
437
438
    hdr_size | is_thunk   = thunkHdrSize dflags
             | otherwise  = fixedHdrSize dflags
439
440

    computeOffset wds_so_far (rep, thing)
Simon Marlow's avatar
Simon Marlow committed
441
      = (wds_so_far + argRepSizeW (toArgRep rep), 
442
	 (NonVoid thing, hdr_size + wds_so_far))
443

444
mkVirtConstrOffsets :: DynFlags -> [(PrimRep,a)] -> (WordOff, WordOff, [(NonVoid a, VirtualHpOffset)])
445
-- Just like mkVirtHeapOffsets, but for constructors
446
mkVirtConstrOffsets dflags = mkVirtHeapOffsets dflags False
447

448
449
450
451
452
453
454
455
456
457
458
459
460
461

-------------------------------------------------------------------------
--
--	Making argument descriptors
--
--  An argument descriptor describes the layout of args on the stack,
--  both for 	* GC (stack-layout) purposes, and 
--		* saving/restoring registers when a heap-check fails
--
-- Void arguments aren't important, therefore (contrast constructSlowCall)
--
-------------------------------------------------------------------------

-- bring in ARG_P, ARG_N, etc.
Simon Marlow's avatar
Simon Marlow committed
462
#include "../includes/rts/storage/FunTypes.h"
463
464

mkArgDescr :: Name -> [Id] -> FCode ArgDescr
465
mkArgDescr _nm args 
466
467
  = case stdPattern arg_reps of
	Just spec_id -> return (ArgSpec spec_id)
468
	Nothing      -> return (ArgGen arg_bits)
469
  where
470
    arg_bits = argBits arg_reps
Simon Marlow's avatar
Simon Marlow committed
471
    arg_reps = filter isNonV (map idArgRep args)
472
473
	-- Getting rid of voids eases matching of standard patterns

Simon Marlow's avatar
Simon Marlow committed
474
argBits :: [ArgRep] -> [Bool]	-- True for non-ptr, False for ptr
475
476
argBits [] 		= []
argBits (P   : args) = False : argBits args
Simon Marlow's avatar
Simon Marlow committed
477
argBits (arg : args) = take (argRepSizeW arg) (repeat True) ++ argBits args
478
479

----------------------
Simon Marlow's avatar
Simon Marlow committed
480
stdPattern :: [ArgRep] -> Maybe StgHalfWord
481
482
483
484
stdPattern reps 
  = case reps of
	[]  -> Just ARG_NONE	-- just void args, probably
	[N] -> Just ARG_N
485
	[P] -> Just ARG_P
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
	[F] -> Just ARG_F
	[D] -> Just ARG_D
	[L] -> Just ARG_L

	[N,N] -> Just ARG_NN
	[N,P] -> Just ARG_NP
	[P,N] -> Just ARG_PN
	[P,P] -> Just ARG_PP

	[N,N,N] -> Just ARG_NNN
	[N,N,P] -> Just ARG_NNP
	[N,P,N] -> Just ARG_NPN
	[N,P,P] -> Just ARG_NPP
	[P,N,N] -> Just ARG_PNN
	[P,N,P] -> Just ARG_PNP
	[P,P,N] -> Just ARG_PPN
	[P,P,P] -> Just ARG_PPP

	[P,P,P,P]     -> Just ARG_PPPP
	[P,P,P,P,P]   -> Just ARG_PPPPP
	[P,P,P,P,P,P] -> Just ARG_PPPPPP
	
	_ -> Nothing

-------------------------------------------------------------------------
--
--	Generating the info table and code for a closure
--
-------------------------------------------------------------------------

-- Here we make an info table of type 'CmmInfo'.  The concrete
-- representation as a list of 'CmmAddr' is handled later
-- in the pipeline by 'cmmToRawCmm'.
519
520
521
522
523
-- When loading the free variables, a function closure pointer may be tagged,
-- so we must take it into account.

emitClosureProcAndInfoTable :: Bool                    -- top-level? 
                            -> Id                      -- name of the closure
524
525
                            -> LambdaFormInfo
                            -> CmmInfoTable
526
                            -> [NonVoid Id]            -- incoming arguments
527
                            -> ((Int, LocalReg, [LocalReg]) -> FCode ()) -- function body
528
                            -> FCode ()
529
530
emitClosureProcAndInfoTable top_lvl bndr lf_info info_tbl args body
 = do   {
531
        -- Bind the binder itself, but only if it's not a top-level
532
533
534
535
        -- binding. We need non-top let-bindings to refer to the
        -- top-level binding, which this binding would incorrectly shadow.
        ; node <- if top_lvl then return $ idToReg (NonVoid bndr)
                  else bindToReg (NonVoid bndr) lf_info
536
537
        ; dflags <- getDynFlags
        ; let node_points = nodeMustPointToIt dflags lf_info
538
        ; arg_regs <- bindArgsToRegs args
539
        ; let args' = if node_points then (node : arg_regs) else arg_regs
540
541
              conv  = if nodeMustPointToIt dflags lf_info then NativeNodeCall
                                                          else NativeDirectCall
542
              (offset, _) = mkCallEntry dflags conv args'
543
        ; emitClosureAndInfoTable info_tbl conv args' $ body (offset, node, arg_regs)
544
545
546
547
        }

-- Data constructors need closures, but not with all the argument handling
-- needed for functions. The shared part goes here.
548
emitClosureAndInfoTable ::
549
550
  CmmInfoTable -> Convention -> [LocalReg] -> FCode () -> FCode ()
emitClosureAndInfoTable info_tbl conv args body
551
552
  = do { blks <- getCode body
       ; let entry_lbl = toEntryLbl (cit_lbl info_tbl)
553
       ; emitProcWithConvention conv (Just info_tbl) entry_lbl args blks
554
       }
555
556
557
558
559
560
561

-----------------------------------------------------------------------------
--
--	Info table offsets
--
-----------------------------------------------------------------------------
	
562
stdInfoTableSizeW :: DynFlags -> WordOff
563
564
565
-- The size of a standard info table varies with profiling/ticky etc,
-- so we can't get it from Constants
-- It must vary in sync with mkStdInfoTable
566
stdInfoTableSizeW dflags
567
568
569
  = size_fixed + size_prof
  where
    size_fixed = 2	-- layout, type
570
    size_prof | dopt Opt_SccProfilingOn dflags = 2
571
572
	      | otherwise	   = 0

573
574
stdInfoTableSizeB  :: DynFlags -> ByteOff
stdInfoTableSizeB dflags = stdInfoTableSizeW dflags * wORD_SIZE :: ByteOff
575

576
stdSrtBitmapOffset :: DynFlags -> ByteOff
577
578
-- Byte offset of the SRT bitmap half-word which is 
-- in the *higher-addressed* part of the type_lit
579
stdSrtBitmapOffset dflags = stdInfoTableSizeB dflags - hALF_WORD_SIZE
580

581
stdClosureTypeOffset :: DynFlags -> ByteOff
582
-- Byte offset of the closure type half-word 
583
stdClosureTypeOffset dflags = stdInfoTableSizeB dflags - wORD_SIZE
584

585
586
587
stdPtrsOffset, stdNonPtrsOffset :: DynFlags -> ByteOff
stdPtrsOffset    dflags = stdInfoTableSizeB dflags - 2*wORD_SIZE
stdNonPtrsOffset dflags = stdInfoTableSizeB dflags - 2*wORD_SIZE + hALF_WORD_SIZE
588
589
590
591
592
593
594
595
596
597
598

-------------------------------------------------------------------------
--
--	Accessing fields of an info table
--
-------------------------------------------------------------------------

closureInfoPtr :: CmmExpr -> CmmExpr
-- Takes a closure pointer and returns the info table pointer
closureInfoPtr e = CmmLoad e bWord

599
entryCode :: DynFlags -> CmmExpr -> CmmExpr
600
601
-- Takes an info pointer (the first word of a closure)
-- and returns its entry code
602
603
604
entryCode dflags e
 | tablesNextToCode dflags = e
 | otherwise               = CmmLoad e bWord
605

606
getConstrTag :: DynFlags -> CmmExpr -> CmmExpr
607
608
609
610
-- Takes a closure pointer, and return the *zero-indexed*
-- constructor tag obtained from the info table
-- This lives in the SRT field of the info table
-- (constructors don't need SRTs).
611
612
getConstrTag dflags closure_ptr
  = CmmMachOp (MO_UU_Conv halfWordWidth wordWidth) [infoTableConstrTag dflags info_table]
613
  where
614
    info_table = infoTable dflags (closureInfoPtr closure_ptr)
615

616
cmmGetClosureType :: DynFlags -> CmmExpr -> CmmExpr
617
618
-- Takes a closure pointer, and return the closure type
-- obtained from the info table
619
620
cmmGetClosureType dflags closure_ptr
  = CmmMachOp (MO_UU_Conv halfWordWidth wordWidth) [infoTableClosureType dflags info_table]
621
  where
622
    info_table = infoTable dflags (closureInfoPtr closure_ptr)
623

624
infoTable :: DynFlags -> CmmExpr -> CmmExpr
625
626
627
-- Takes an info pointer (the first word of a closure)
-- and returns a pointer to the first word of the standard-form
-- info table, excluding the entry-code word (if present)
628
infoTable dflags info_ptr
629
630
  | tablesNextToCode dflags = cmmOffsetB info_ptr (- stdInfoTableSizeB dflags)
  | otherwise               = cmmOffsetW info_ptr 1 -- Past the entry code pointer
631

632
infoTableConstrTag :: DynFlags -> CmmExpr -> CmmExpr
633
634
635
636
-- Takes an info table pointer (from infoTable) and returns the constr tag
-- field of the info table (same as the srt_bitmap field)
infoTableConstrTag = infoTableSrtBitmap

637
infoTableSrtBitmap :: DynFlags -> CmmExpr -> CmmExpr
638
639
-- Takes an info table pointer (from infoTable) and returns the srt_bitmap
-- field of the info table
640
641
infoTableSrtBitmap dflags info_tbl
  = CmmLoad (cmmOffsetB info_tbl (stdSrtBitmapOffset dflags)) bHalfWord
642

643
infoTableClosureType :: DynFlags -> CmmExpr -> CmmExpr
644
645
-- Takes an info table pointer (from infoTable) and returns the closure type
-- field of the info table.
646
647
infoTableClosureType dflags info_tbl
  = CmmLoad (cmmOffsetB info_tbl (stdClosureTypeOffset dflags)) bHalfWord
648

649
650
651
infoTablePtrs :: DynFlags -> CmmExpr -> CmmExpr
infoTablePtrs dflags info_tbl
  = CmmLoad (cmmOffsetB info_tbl (stdPtrsOffset dflags)) bHalfWord
652

653
654
655
infoTableNonPtrs :: DynFlags -> CmmExpr -> CmmExpr
infoTableNonPtrs dflags info_tbl
  = CmmLoad (cmmOffsetB info_tbl (stdNonPtrsOffset dflags)) bHalfWord
656

657
funInfoTable :: DynFlags -> CmmExpr -> CmmExpr
658
659
660
-- Takes the info pointer of a function,
-- and returns a pointer to the first word of the StgFunInfoExtra struct
-- in the info table.
661
funInfoTable dflags info_ptr
662
  | tablesNextToCode dflags
663
  = cmmOffsetB info_ptr (- stdInfoTableSizeB dflags - sIZEOF_StgFunInfoExtraRev)
664
  | otherwise
665
  = cmmOffsetW info_ptr (1 + stdInfoTableSizeW dflags)
666
667
				-- Past the entry code pointer