Generalize CmmUnwind and pass unwind information through NCG
[ghc.git] / compiler / cmm / CmmLayoutStack.hs
1 {-# LANGUAGE CPP, RecordWildCards, GADTs #-}
2 module CmmLayoutStack (
3 cmmLayoutStack, setInfoTableStackMap
4 ) where
5
6 import StgCmmUtils ( callerSaveVolatileRegs ) -- XXX layering violation
7 import StgCmmForeign ( saveThreadState, loadThreadState ) -- XXX layering violation
8
9 import BasicTypes
10 import Cmm
11 import CmmInfo
12 import BlockId
13 import CLabel
14 import CmmUtils
15 import MkGraph
16 import ForeignCall
17 import CmmLive
18 import CmmProcPoint
19 import SMRep
20 import Hoopl
21 import UniqSupply
22 import StgCmmUtils ( newTemp )
23 import Maybes
24 import UniqFM
25 import Util
26
27 import DynFlags
28 import FastString
29 import Outputable hiding ( isEmpty )
30 import qualified Data.Set as Set
31 import Control.Monad.Fix
32 import Data.Array as Array
33 import Data.Bits
34 import Data.List (nub)
35
36 import Prelude hiding ((<*>))
37
38 #include "HsVersions.h"
39
40 {- Note [Stack Layout]
41
42 The job of this pass is to
43
44 - replace references to abstract stack Areas with fixed offsets from Sp.
45
46 - replace the CmmHighStackMark constant used in the stack check with
47 the maximum stack usage of the proc.
48
49 - save any variables that are live across a call, and reload them as
50 necessary.
51
52 Before stack allocation, local variables remain live across native
53 calls (CmmCall{ cmm_cont = Just _ }), and after stack allocation local
54 variables are clobbered by native calls.
55
56 We want to do stack allocation so that as far as possible
57 - stack use is minimized, and
58 - unnecessary stack saves and loads are avoided.
59
60 The algorithm we use is a variant of linear-scan register allocation,
61 where the stack is our register file.
62
63 - First, we do a liveness analysis, which annotates every block with
64 the variables live on entry to the block.
65
66 - We traverse blocks in reverse postorder DFS; that is, we visit at
67 least one predecessor of a block before the block itself. The
68 stack layout flowing from the predecessor of the block will
69 determine the stack layout on entry to the block.
70
71 - We maintain a data structure
72
73 Map Label StackMap
74
75 which describes the contents of the stack and the stack pointer on
76 entry to each block that is a successor of a block that we have
77 visited.
78
79 - For each block we visit:
80
81 - Look up the StackMap for this block.
82
83 - If this block is a proc point (or a call continuation, if we
84 aren't splitting proc points), emit instructions to reload all
85 the live variables from the stack, according to the StackMap.
86
87 - Walk forwards through the instructions:
88 - At an assignment x = Sp[loc]
89 - Record the fact that Sp[loc] contains x, so that we won't
90 need to save x if it ever needs to be spilled.
91 - At an assignment x = E
92 - If x was previously on the stack, it isn't any more
93 - At the last node, if it is a call or a jump to a proc point
94 - Lay out the stack frame for the call (see setupStackFrame)
95 - emit instructions to save all the live variables
96 - Remember the StackMaps for all the successors
97 - emit an instruction to adjust Sp
98 - If the last node is a branch, then the current StackMap is the
99 StackMap for the successors.
100
101 - Manifest Sp: replace references to stack areas in this block
102 with real Sp offsets. We cannot do this until we have laid out
103 the stack area for the successors above.
104
105 In this phase we also eliminate redundant stores to the stack;
106 see elimStackStores.
107
108 - There is one important gotcha: sometimes we'll encounter a control
109 transfer to a block that we've already processed (a join point),
110 and in that case we might need to rearrange the stack to match
111 what the block is expecting. (exactly the same as in linear-scan
112 register allocation, except here we have the luxury of an infinite
113 supply of temporary variables).
114
115 - Finally, we update the magic CmmHighStackMark constant with the
116 stack usage of the function, and eliminate the whole stack check
117 if there was no stack use. (in fact this is done as part of the
118 main traversal, by feeding the high-water-mark output back in as
119 an input. I hate cyclic programming, but it's just too convenient
120 sometimes.)
121
122 There are plenty of tricky details: update frames, proc points, return
123 addresses, foreign calls, and some ad-hoc optimisations that are
124 convenient to do here and effective in common cases. Comments in the
125 code below explain these.
126
127 -}
128
129
130 -- All stack locations are expressed as positive byte offsets from the
131 -- "base", which is defined to be the address above the return address
132 -- on the stack on entry to this CmmProc.
133 --
134 -- Lower addresses have higher StackLocs.
135 --
136 type StackLoc = ByteOff
137
138 {-
139 A StackMap describes the stack at any given point. At a continuation
140 it has a particular layout, like this:
141
142 | | <- base
143 |-------------|
144 | ret0 | <- base + 8
145 |-------------|
146 . upd frame . <- base + sm_ret_off
147 |-------------|
148 | |
149 . vars .
150 . (live/dead) .
151 | | <- base + sm_sp - sm_args
152 |-------------|
153 | ret1 |
154 . ret vals . <- base + sm_sp (<--- Sp points here)
155 |-------------|
156
157 Why do we include the final return address (ret0) in our stack map? I
158 have absolutely no idea, but it seems to be done that way consistently
159 in the rest of the code generator, so I played along here. --SDM
160
161 Note that we will be constructing an info table for the continuation
162 (ret1), which needs to describe the stack down to, but not including,
163 the update frame (or ret0, if there is no update frame).
164 -}
165
166 data StackMap = StackMap
167 { sm_sp :: StackLoc
168 -- ^ the offset of Sp relative to the base on entry
169 -- to this block.
170 , sm_args :: ByteOff
171 -- ^ the number of bytes of arguments in the area for this block
172 -- Defn: the offset of young(L) relative to the base is given by
173 -- (sm_sp - sm_args) of the StackMap for block L.
174 , sm_ret_off :: ByteOff
175 -- ^ Number of words of stack that we do not describe with an info
176 -- table, because it contains an update frame.
177 , sm_regs :: UniqFM (LocalReg,StackLoc)
178 -- ^ regs on the stack
179 }
180
181 instance Outputable StackMap where
182 ppr StackMap{..} =
183 text "Sp = " <> int sm_sp $$
184 text "sm_args = " <> int sm_args $$
185 text "sm_ret_off = " <> int sm_ret_off $$
186 text "sm_regs = " <> pprUFM sm_regs ppr
187
188
189 cmmLayoutStack :: DynFlags -> ProcPointSet -> ByteOff -> CmmGraph
190 -> UniqSM (CmmGraph, LabelMap StackMap)
191 cmmLayoutStack dflags procpoints entry_args
192 graph@(CmmGraph { g_entry = entry })
193 = do
194 -- We need liveness info. Dead assignments are removed later
195 -- by the sinking pass.
196 let liveness = cmmLocalLiveness dflags graph
197 blocks = postorderDfs graph
198
199 (final_stackmaps, _final_high_sp, new_blocks) <-
200 mfix $ \ ~(rec_stackmaps, rec_high_sp, _new_blocks) ->
201 layout dflags procpoints liveness entry entry_args
202 rec_stackmaps rec_high_sp blocks
203
204 new_blocks' <- mapM (lowerSafeForeignCall dflags) new_blocks
205 return (ofBlockList entry new_blocks', final_stackmaps)
206
207
208 layout :: DynFlags
209 -> LabelSet -- proc points
210 -> LabelMap CmmLocalLive -- liveness
211 -> BlockId -- entry
212 -> ByteOff -- stack args on entry
213
214 -> LabelMap StackMap -- [final] stack maps
215 -> ByteOff -- [final] Sp high water mark
216
217 -> [CmmBlock] -- [in] blocks
218
219 -> UniqSM
220 ( LabelMap StackMap -- [out] stack maps
221 , ByteOff -- [out] Sp high water mark
222 , [CmmBlock] -- [out] new blocks
223 )
224
225 layout dflags procpoints liveness entry entry_args final_stackmaps final_sp_high blocks
226 = go blocks init_stackmap entry_args []
227 where
228 (updfr, cont_info) = collectContInfo blocks
229
230 init_stackmap = mapSingleton entry StackMap{ sm_sp = entry_args
231 , sm_args = entry_args
232 , sm_ret_off = updfr
233 , sm_regs = emptyUFM
234 }
235
236 go [] acc_stackmaps acc_hwm acc_blocks
237 = return (acc_stackmaps, acc_hwm, acc_blocks)
238
239 go (b0 : bs) acc_stackmaps acc_hwm acc_blocks
240 = do
241 let (entry0@(CmmEntry entry_lbl tscope), middle0, last0) = blockSplit b0
242
243 let stack0@StackMap { sm_sp = sp0 }
244 = mapFindWithDefault
245 (pprPanic "no stack map for" (ppr entry_lbl))
246 entry_lbl acc_stackmaps
247
248 -- (a) Update the stack map to include the effects of
249 -- assignments in this block
250 let stack1 = foldBlockNodesF (procMiddle acc_stackmaps) middle0 stack0
251
252 -- (b) Insert assignments to reload all the live variables if this
253 -- block is a proc point
254 let middle1 = if entry_lbl `setMember` procpoints
255 then foldr blockCons middle0 (insertReloads stack0)
256 else middle0
257
258 -- (c) Look at the last node and if we are making a call or
259 -- jumping to a proc point, we must save the live
260 -- variables, adjust Sp, and construct the StackMaps for
261 -- each of the successor blocks. See handleLastNode for
262 -- details.
263 (middle2, sp_off, last1, fixup_blocks, out)
264 <- handleLastNode dflags procpoints liveness cont_info
265 acc_stackmaps stack1 tscope middle0 last0
266
267 -- (d) Manifest Sp: run over the nodes in the block and replace
268 -- CmmStackSlot with CmmLoad from Sp with a concrete offset.
269 --
270 -- our block:
271 -- middle1 -- the original middle nodes
272 -- middle2 -- live variable saves from handleLastNode
273 -- Sp = Sp + sp_off -- Sp adjustment goes here
274 -- last1 -- the last node
275 --
276 let middle_pre = blockToList $ foldl blockSnoc middle1 middle2
277
278 let final_blocks =
279 manifestSp dflags final_stackmaps stack0 sp0 final_sp_high
280 entry0 middle_pre sp_off last1 fixup_blocks
281
282 let acc_stackmaps' = mapUnion acc_stackmaps out
283
284 -- If this block jumps to the GC, then we do not take its
285 -- stack usage into account for the high-water mark.
286 -- Otherwise, if the only stack usage is in the stack-check
287 -- failure block itself, we will do a redundant stack
288 -- check. The stack has a buffer designed to accommodate
289 -- the largest amount of stack needed for calling the GC.
290 --
291 this_sp_hwm | isGcJump last0 = 0
292 | otherwise = sp0 - sp_off
293
294 hwm' = maximum (acc_hwm : this_sp_hwm : map sm_sp (mapElems out))
295
296 go bs acc_stackmaps' hwm' (final_blocks ++ acc_blocks)
297
298
299 -- -----------------------------------------------------------------------------
300
301 -- Not foolproof, but GCFun is the culprit we most want to catch
302 isGcJump :: CmmNode O C -> Bool
303 isGcJump (CmmCall { cml_target = CmmReg (CmmGlobal l) })
304 = l == GCFun || l == GCEnter1
305 isGcJump _something_else = False
306
307 -- -----------------------------------------------------------------------------
308
309 -- This doesn't seem right somehow. We need to find out whether this
310 -- proc will push some update frame material at some point, so that we
311 -- can avoid using that area of the stack for spilling. The
312 -- updfr_space field of the CmmProc *should* tell us, but it doesn't
313 -- (I think maybe it gets filled in later when we do proc-point
314 -- splitting).
315 --
316 -- So we'll just take the max of all the cml_ret_offs. This could be
317 -- unnecessarily pessimistic, but probably not in the code we
318 -- generate.
319
320 collectContInfo :: [CmmBlock] -> (ByteOff, LabelMap ByteOff)
321 collectContInfo blocks
322 = (maximum ret_offs, mapFromList (catMaybes mb_argss))
323 where
324 (mb_argss, ret_offs) = mapAndUnzip get_cont blocks
325
326 get_cont :: Block CmmNode x C -> (Maybe (Label, ByteOff), ByteOff)
327 get_cont b =
328 case lastNode b of
329 CmmCall { cml_cont = Just l, .. }
330 -> (Just (l, cml_ret_args), cml_ret_off)
331 CmmForeignCall { .. }
332 -> (Just (succ, ret_args), ret_off)
333 _other -> (Nothing, 0)
334
335
336 -- -----------------------------------------------------------------------------
337 -- Updating the StackMap from middle nodes
338
339 -- Look for loads from stack slots, and update the StackMap. This is
340 -- purely for optimisation reasons, so that we can avoid saving a
341 -- variable back to a different stack slot if it is already on the
342 -- stack.
343 --
344 -- This happens a lot: for example when function arguments are passed
345 -- on the stack and need to be immediately saved across a call, we
346 -- want to just leave them where they are on the stack.
347 --
348 procMiddle :: LabelMap StackMap -> CmmNode e x -> StackMap -> StackMap
349 procMiddle stackmaps node sm
350 = case node of
351 CmmAssign (CmmLocal r) (CmmLoad (CmmStackSlot area off) _)
352 -> sm { sm_regs = addToUFM (sm_regs sm) r (r,loc) }
353 where loc = getStackLoc area off stackmaps
354 CmmAssign (CmmLocal r) _other
355 -> sm { sm_regs = delFromUFM (sm_regs sm) r }
356 _other
357 -> sm
358
359 getStackLoc :: Area -> ByteOff -> LabelMap StackMap -> StackLoc
360 getStackLoc Old n _ = n
361 getStackLoc (Young l) n stackmaps =
362 case mapLookup l stackmaps of
363 Nothing -> pprPanic "getStackLoc" (ppr l)
364 Just sm -> sm_sp sm - sm_args sm + n
365
366
367 -- -----------------------------------------------------------------------------
368 -- Handling stack allocation for a last node
369
370 -- We take a single last node and turn it into:
371 --
372 -- C1 (some statements)
373 -- Sp = Sp + N
374 -- C2 (some more statements)
375 -- call f() -- the actual last node
376 --
377 -- plus possibly some more blocks (we may have to add some fixup code
378 -- between the last node and the continuation).
379 --
380 -- C1: is the code for saving the variables across this last node onto
381 -- the stack, if the continuation is a call or jumps to a proc point.
382 --
383 -- C2: if the last node is a safe foreign call, we have to inject some
384 -- extra code that goes *after* the Sp adjustment.
385
386 handleLastNode
387 :: DynFlags -> ProcPointSet -> LabelMap CmmLocalLive -> LabelMap ByteOff
388 -> LabelMap StackMap -> StackMap -> CmmTickScope
389 -> Block CmmNode O O
390 -> CmmNode O C
391 -> UniqSM
392 ( [CmmNode O O] -- nodes to go *before* the Sp adjustment
393 , ByteOff -- amount to adjust Sp
394 , CmmNode O C -- new last node
395 , [CmmBlock] -- new blocks
396 , LabelMap StackMap -- stackmaps for the continuations
397 )
398
399 handleLastNode dflags procpoints liveness cont_info stackmaps
400 stack0@StackMap { sm_sp = sp0 } tscp middle last
401 = case last of
402 -- At each return / tail call,
403 -- adjust Sp to point to the last argument pushed, which
404 -- is cml_args, after popping any other junk from the stack.
405 CmmCall{ cml_cont = Nothing, .. } -> do
406 let sp_off = sp0 - cml_args
407 return ([], sp_off, last, [], mapEmpty)
408
409 -- At each CmmCall with a continuation:
410 CmmCall{ cml_cont = Just cont_lbl, .. } ->
411 return $ lastCall cont_lbl cml_args cml_ret_args cml_ret_off
412
413 CmmForeignCall{ succ = cont_lbl, .. } -> do
414 return $ lastCall cont_lbl (wORD_SIZE dflags) ret_args ret_off
415 -- one word of args: the return address
416
417 CmmBranch {} -> handleBranches
418 CmmCondBranch {} -> handleBranches
419 CmmSwitch {} -> handleBranches
420
421 where
422 -- Calls and ForeignCalls are handled the same way:
423 lastCall :: BlockId -> ByteOff -> ByteOff -> ByteOff
424 -> ( [CmmNode O O]
425 , ByteOff
426 , CmmNode O C
427 , [CmmBlock]
428 , LabelMap StackMap
429 )
430 lastCall lbl cml_args cml_ret_args cml_ret_off
431 = ( assignments
432 , spOffsetForCall sp0 cont_stack cml_args
433 , last
434 , [] -- no new blocks
435 , mapSingleton lbl cont_stack )
436 where
437 (assignments, cont_stack) = prepareStack lbl cml_ret_args cml_ret_off
438
439
440 prepareStack lbl cml_ret_args cml_ret_off
441 | Just cont_stack <- mapLookup lbl stackmaps
442 -- If we have already seen this continuation before, then
443 -- we just have to make the stack look the same:
444 = (fixupStack stack0 cont_stack, cont_stack)
445 -- Otherwise, we have to allocate the stack frame
446 | otherwise
447 = (save_assignments, new_cont_stack)
448 where
449 (new_cont_stack, save_assignments)
450 = setupStackFrame dflags lbl liveness cml_ret_off cml_ret_args stack0
451
452
453 -- For other last nodes (branches), if any of the targets is a
454 -- proc point, we have to set up the stack to match what the proc
455 -- point is expecting.
456 --
457 handleBranches :: UniqSM ( [CmmNode O O]
458 , ByteOff
459 , CmmNode O C
460 , [CmmBlock]
461 , LabelMap StackMap )
462
463 handleBranches
464 -- Note [diamond proc point]
465 | Just l <- futureContinuation middle
466 , (nub $ filter (`setMember` procpoints) $ successors last) == [l]
467 = do
468 let cont_args = mapFindWithDefault 0 l cont_info
469 (assigs, cont_stack) = prepareStack l cont_args (sm_ret_off stack0)
470 out = mapFromList [ (l', cont_stack)
471 | l' <- successors last ]
472 return ( assigs
473 , spOffsetForCall sp0 cont_stack (wORD_SIZE dflags)
474 , last
475 , []
476 , out)
477
478 | otherwise = do
479 pps <- mapM handleBranch (successors last)
480 let lbl_map :: LabelMap Label
481 lbl_map = mapFromList [ (l,tmp) | (l,tmp,_,_) <- pps ]
482 fix_lbl l = mapFindWithDefault l l lbl_map
483 return ( []
484 , 0
485 , mapSuccessors fix_lbl last
486 , concat [ blk | (_,_,_,blk) <- pps ]
487 , mapFromList [ (l, sm) | (l,_,sm,_) <- pps ] )
488
489 -- For each successor of this block
490 handleBranch :: BlockId -> UniqSM (BlockId, BlockId, StackMap, [CmmBlock])
491 handleBranch l
492 -- (a) if the successor already has a stackmap, we need to
493 -- shuffle the current stack to make it look the same.
494 -- We have to insert a new block to make this happen.
495 | Just stack2 <- mapLookup l stackmaps
496 = do
497 let assigs = fixupStack stack0 stack2
498 (tmp_lbl, block) <- makeFixupBlock dflags sp0 l stack2 tscp assigs
499 return (l, tmp_lbl, stack2, block)
500
501 -- (b) if the successor is a proc point, save everything
502 -- on the stack.
503 | l `setMember` procpoints
504 = do
505 let cont_args = mapFindWithDefault 0 l cont_info
506 (stack2, assigs) =
507 setupStackFrame dflags l liveness (sm_ret_off stack0)
508 cont_args stack0
509 (tmp_lbl, block) <- makeFixupBlock dflags sp0 l stack2 tscp assigs
510 return (l, tmp_lbl, stack2, block)
511
512 -- (c) otherwise, the current StackMap is the StackMap for
513 -- the continuation. But we must remember to remove any
514 -- variables from the StackMap that are *not* live at
515 -- the destination, because this StackMap might be used
516 -- by fixupStack if this is a join point.
517 | otherwise = return (l, l, stack1, [])
518 where live = mapFindWithDefault (panic "handleBranch") l liveness
519 stack1 = stack0 { sm_regs = filterUFM is_live (sm_regs stack0) }
520 is_live (r,_) = r `elemRegSet` live
521
522
523 makeFixupBlock :: DynFlags -> ByteOff -> Label -> StackMap
524 -> CmmTickScope -> [CmmNode O O]
525 -> UniqSM (Label, [CmmBlock])
526 makeFixupBlock dflags sp0 l stack tscope assigs
527 | null assigs && sp0 == sm_sp stack = return (l, [])
528 | otherwise = do
529 tmp_lbl <- newBlockId
530 let sp_off = sp0 - sm_sp stack
531 block = blockJoin (CmmEntry tmp_lbl tscope)
532 (maybeAddSpAdj dflags sp_off (blockFromList assigs))
533 (CmmBranch l)
534 return (tmp_lbl, [block])
535
536
537 -- Sp is currently pointing to current_sp,
538 -- we want it to point to
539 -- (sm_sp cont_stack - sm_args cont_stack + args)
540 -- so the difference is
541 -- sp0 - (sm_sp cont_stack - sm_args cont_stack + args)
542 spOffsetForCall :: ByteOff -> StackMap -> ByteOff -> ByteOff
543 spOffsetForCall current_sp cont_stack args
544 = current_sp - (sm_sp cont_stack - sm_args cont_stack + args)
545
546
547 -- | create a sequence of assignments to establish the new StackMap,
548 -- given the old StackMap.
549 fixupStack :: StackMap -> StackMap -> [CmmNode O O]
550 fixupStack old_stack new_stack = concatMap move new_locs
551 where
552 old_map = sm_regs old_stack
553 new_locs = stackSlotRegs new_stack
554
555 move (r,n)
556 | Just (_,m) <- lookupUFM old_map r, n == m = []
557 | otherwise = [CmmStore (CmmStackSlot Old n)
558 (CmmReg (CmmLocal r))]
559
560
561
562 setupStackFrame
563 :: DynFlags
564 -> BlockId -- label of continuation
565 -> LabelMap CmmLocalLive -- liveness
566 -> ByteOff -- updfr
567 -> ByteOff -- bytes of return values on stack
568 -> StackMap -- current StackMap
569 -> (StackMap, [CmmNode O O])
570
571 setupStackFrame dflags lbl liveness updfr_off ret_args stack0
572 = (cont_stack, assignments)
573 where
574 -- get the set of LocalRegs live in the continuation
575 live = mapFindWithDefault Set.empty lbl liveness
576
577 -- the stack from the base to updfr_off is off-limits.
578 -- our new stack frame contains:
579 -- * saved live variables
580 -- * the return address [young(C) + 8]
581 -- * the args for the call,
582 -- which are replaced by the return values at the return
583 -- point.
584
585 -- everything up to updfr_off is off-limits
586 -- stack1 contains updfr_off, plus everything we need to save
587 (stack1, assignments) = allocate dflags updfr_off live stack0
588
589 -- And the Sp at the continuation is:
590 -- sm_sp stack1 + ret_args
591 cont_stack = stack1{ sm_sp = sm_sp stack1 + ret_args
592 , sm_args = ret_args
593 , sm_ret_off = updfr_off
594 }
595
596
597 -- -----------------------------------------------------------------------------
598 -- Note [diamond proc point]
599 --
600 -- This special case looks for the pattern we get from a typical
601 -- tagged case expression:
602 --
603 -- Sp[young(L1)] = L1
604 -- if (R1 & 7) != 0 goto L1 else goto L2
605 -- L2:
606 -- call [R1] returns to L1
607 -- L1: live: {y}
608 -- x = R1
609 --
610 -- If we let the generic case handle this, we get
611 --
612 -- Sp[-16] = L1
613 -- if (R1 & 7) != 0 goto L1a else goto L2
614 -- L2:
615 -- Sp[-8] = y
616 -- Sp = Sp - 16
617 -- call [R1] returns to L1
618 -- L1a:
619 -- Sp[-8] = y
620 -- Sp = Sp - 16
621 -- goto L1
622 -- L1:
623 -- x = R1
624 --
625 -- The code for saving the live vars is duplicated in each branch, and
626 -- furthermore there is an extra jump in the fast path (assuming L1 is
627 -- a proc point, which it probably is if there is a heap check).
628 --
629 -- So to fix this we want to set up the stack frame before the
630 -- conditional jump. How do we know when to do this, and when it is
631 -- safe? The basic idea is, when we see the assignment
632 --
633 -- Sp[young(L)] = L
634 --
635 -- we know that
636 -- * we are definitely heading for L
637 -- * there can be no more reads from another stack area, because young(L)
638 -- overlaps with it.
639 --
640 -- We don't necessarily know that everything live at L is live now
641 -- (some might be assigned between here and the jump to L). So we
642 -- simplify and only do the optimisation when we see
643 --
644 -- (1) a block containing an assignment of a return address L
645 -- (2) ending in a branch where one (and only) continuation goes to L,
646 -- and no other continuations go to proc points.
647 --
648 -- then we allocate the stack frame for L at the end of the block,
649 -- before the branch.
650 --
651 -- We could generalise (2), but that would make it a bit more
652 -- complicated to handle, and this currently catches the common case.
653
654 futureContinuation :: Block CmmNode O O -> Maybe BlockId
655 futureContinuation middle = foldBlockNodesB f middle Nothing
656 where f :: CmmNode a b -> Maybe BlockId -> Maybe BlockId
657 f (CmmStore (CmmStackSlot (Young l) _) (CmmLit (CmmBlock _))) _
658 = Just l
659 f _ r = r
660
661 -- -----------------------------------------------------------------------------
662 -- Saving live registers
663
664 -- | Given a set of live registers and a StackMap, save all the registers
665 -- on the stack and return the new StackMap and the assignments to do
666 -- the saving.
667 --
668 allocate :: DynFlags -> ByteOff -> LocalRegSet -> StackMap
669 -> (StackMap, [CmmNode O O])
670 allocate dflags ret_off live stackmap@StackMap{ sm_sp = sp0
671 , sm_regs = regs0 }
672 =
673 -- we only have to save regs that are not already in a slot
674 let to_save = filter (not . (`elemUFM` regs0)) (Set.elems live)
675 regs1 = filterUFM (\(r,_) -> elemRegSet r live) regs0
676 in
677
678 -- make a map of the stack
679 let stack = reverse $ Array.elems $
680 accumArray (\_ x -> x) Empty (1, toWords dflags (max sp0 ret_off)) $
681 ret_words ++ live_words
682 where ret_words =
683 [ (x, Occupied)
684 | x <- [ 1 .. toWords dflags ret_off] ]
685 live_words =
686 [ (toWords dflags x, Occupied)
687 | (r,off) <- nonDetEltsUFM regs1,
688 -- See Note [Unique Determinism and code generation]
689 let w = localRegBytes dflags r,
690 x <- [ off, off - wORD_SIZE dflags .. off - w + 1] ]
691 in
692
693 -- Pass over the stack: find slots to save all the new live variables,
694 -- choosing the oldest slots first (hence a foldr).
695 let
696 save slot ([], stack, n, assigs, regs) -- no more regs to save
697 = ([], slot:stack, plusW dflags n 1, assigs, regs)
698 save slot (to_save, stack, n, assigs, regs)
699 = case slot of
700 Occupied -> (to_save, Occupied:stack, plusW dflags n 1, assigs, regs)
701 Empty
702 | Just (stack', r, to_save') <-
703 select_save to_save (slot:stack)
704 -> let assig = CmmStore (CmmStackSlot Old n')
705 (CmmReg (CmmLocal r))
706 n' = plusW dflags n 1
707 in
708 (to_save', stack', n', assig : assigs, (r,(r,n')):regs)
709
710 | otherwise
711 -> (to_save, slot:stack, plusW dflags n 1, assigs, regs)
712
713 -- we should do better here: right now we'll fit the smallest first,
714 -- but it would make more sense to fit the biggest first.
715 select_save :: [LocalReg] -> [StackSlot]
716 -> Maybe ([StackSlot], LocalReg, [LocalReg])
717 select_save regs stack = go regs []
718 where go [] _no_fit = Nothing
719 go (r:rs) no_fit
720 | Just rest <- dropEmpty words stack
721 = Just (replicate words Occupied ++ rest, r, rs++no_fit)
722 | otherwise
723 = go rs (r:no_fit)
724 where words = localRegWords dflags r
725
726 -- fill in empty slots as much as possible
727 (still_to_save, save_stack, n, save_assigs, save_regs)
728 = foldr save (to_save, [], 0, [], []) stack
729
730 -- push any remaining live vars on the stack
731 (push_sp, push_assigs, push_regs)
732 = foldr push (n, [], []) still_to_save
733 where
734 push r (n, assigs, regs)
735 = (n', assig : assigs, (r,(r,n')) : regs)
736 where
737 n' = n + localRegBytes dflags r
738 assig = CmmStore (CmmStackSlot Old n')
739 (CmmReg (CmmLocal r))
740
741 trim_sp
742 | not (null push_regs) = push_sp
743 | otherwise
744 = plusW dflags n (- length (takeWhile isEmpty save_stack))
745
746 final_regs = regs1 `addListToUFM` push_regs
747 `addListToUFM` save_regs
748
749 in
750 -- XXX should be an assert
751 if ( n /= max sp0 ret_off ) then pprPanic "allocate" (ppr n <+> ppr sp0 <+> ppr ret_off) else
752
753 if (trim_sp .&. (wORD_SIZE dflags - 1)) /= 0 then pprPanic "allocate2" (ppr trim_sp <+> ppr final_regs <+> ppr push_sp) else
754
755 ( stackmap { sm_regs = final_regs , sm_sp = trim_sp }
756 , push_assigs ++ save_assigs )
757
758
759 -- -----------------------------------------------------------------------------
760 -- Manifesting Sp
761
762 -- | Manifest Sp: turn all the CmmStackSlots into CmmLoads from Sp. The
763 -- block looks like this:
764 --
765 -- middle_pre -- the middle nodes
766 -- Sp = Sp + sp_off -- Sp adjustment goes here
767 -- last -- the last node
768 --
769 -- And we have some extra blocks too (that don't contain Sp adjustments)
770 --
771 -- The adjustment for middle_pre will be different from that for
772 -- middle_post, because the Sp adjustment intervenes.
773 --
774 manifestSp
775 :: DynFlags
776 -> LabelMap StackMap -- StackMaps for other blocks
777 -> StackMap -- StackMap for this block
778 -> ByteOff -- Sp on entry to the block
779 -> ByteOff -- SpHigh
780 -> CmmNode C O -- first node
781 -> [CmmNode O O] -- middle
782 -> ByteOff -- sp_off
783 -> CmmNode O C -- last node
784 -> [CmmBlock] -- new blocks
785 -> [CmmBlock] -- final blocks with Sp manifest
786
787 manifestSp dflags stackmaps stack0 sp0 sp_high
788 first middle_pre sp_off last fixup_blocks
789 = final_block : fixup_blocks'
790 where
791 area_off = getAreaOff stackmaps
792
793 adj_pre_sp, adj_post_sp :: CmmNode e x -> CmmNode e x
794 adj_pre_sp = mapExpDeep (areaToSp dflags sp0 sp_high area_off)
795 adj_post_sp = mapExpDeep (areaToSp dflags (sp0 - sp_off) sp_high area_off)
796
797 -- Add unwind pseudo-instructions at the beginning of each block to
798 -- document Sp level for debugging
799 add_unwind_info block
800 | debugLevel dflags > 0 =
801 CmmUnwind [(Sp, sp_unwind)] : block
802 | otherwise = block
803 sp_unwind = CmmRegOff (CmmGlobal Sp) (sp0 - wORD_SIZE dflags)
804
805 final_middle = maybeAddSpAdj dflags sp_off
806 . blockFromList
807 . add_unwind_info
808 . map adj_pre_sp
809 . elimStackStores stack0 stackmaps area_off
810 $ middle_pre
811 final_last = optStackCheck (adj_post_sp last)
812
813 final_block = blockJoin first final_middle final_last
814
815 fixup_blocks' = map (mapBlock3' (id, adj_post_sp, id)) fixup_blocks
816
817
818 getAreaOff :: LabelMap StackMap -> (Area -> StackLoc)
819 getAreaOff _ Old = 0
820 getAreaOff stackmaps (Young l) =
821 case mapLookup l stackmaps of
822 Just sm -> sm_sp sm - sm_args sm
823 Nothing -> pprPanic "getAreaOff" (ppr l)
824
825
826 maybeAddSpAdj :: DynFlags -> ByteOff -> Block CmmNode O O -> Block CmmNode O O
827 maybeAddSpAdj _ 0 block = block
828 maybeAddSpAdj dflags sp_off block = block `blockSnoc` adj
829 where
830 adj = CmmAssign spReg (cmmOffset dflags (CmmReg spReg) sp_off)
831
832 {-
833 Sp(L) is the Sp offset on entry to block L relative to the base of the
834 OLD area.
835
836 SpArgs(L) is the size of the young area for L, i.e. the number of
837 arguments.
838
839 - in block L, each reference to [old + N] turns into
840 [Sp + Sp(L) - N]
841
842 - in block L, each reference to [young(L') + N] turns into
843 [Sp + Sp(L) - Sp(L') + SpArgs(L') - N]
844
845 - be careful with the last node of each block: Sp has already been adjusted
846 to be Sp + Sp(L) - Sp(L')
847 -}
848
849 areaToSp :: DynFlags -> ByteOff -> ByteOff -> (Area -> StackLoc) -> CmmExpr -> CmmExpr
850
851 areaToSp dflags sp_old _sp_hwm area_off (CmmStackSlot area n)
852 = cmmOffset dflags (CmmReg spReg) (sp_old - area_off area - n)
853 -- Replace (CmmStackSlot area n) with an offset from Sp
854
855 areaToSp dflags _ sp_hwm _ (CmmLit CmmHighStackMark)
856 = mkIntExpr dflags sp_hwm
857 -- Replace CmmHighStackMark with the number of bytes of stack used,
858 -- the sp_hwm. See Note [Stack usage] in StgCmmHeap
859
860 areaToSp dflags _ _ _ (CmmMachOp (MO_U_Lt _) args)
861 | falseStackCheck args
862 = zeroExpr dflags
863 areaToSp dflags _ _ _ (CmmMachOp (MO_U_Ge _) args)
864 | falseStackCheck args
865 = mkIntExpr dflags 1
866 -- Replace a stack-overflow test that cannot fail with a no-op
867 -- See Note [Always false stack check]
868
869 areaToSp _ _ _ _ other = other
870
871 -- | Determine whether a stack check cannot fail.
872 falseStackCheck :: [CmmExpr] -> Bool
873 falseStackCheck [ CmmMachOp (MO_Sub _)
874 [ CmmRegOff (CmmGlobal Sp) x_off
875 , CmmLit (CmmInt y_lit _)]
876 , CmmReg (CmmGlobal SpLim)]
877 = fromIntegral x_off >= y_lit
878 falseStackCheck _ = False
879
880 -- Note [Always false stack check]
881 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
882 -- We can optimise stack checks of the form
883 --
884 -- if ((Sp + x) - y < SpLim) then .. else ..
885 --
886 -- where are non-negative integer byte offsets. Since we know that
887 -- SpLim <= Sp (remember the stack grows downwards), this test must
888 -- yield False if (x >= y), so we can rewrite the comparison to False.
889 -- A subsequent sinking pass will later drop the dead code.
890 -- Optimising this away depends on knowing that SpLim <= Sp, so it is
891 -- really the job of the stack layout algorithm, hence we do it now.
892 --
893 -- The control flow optimiser may negate a conditional to increase
894 -- the likelihood of a fallthrough if the branch is not taken. But
895 -- not every conditional is inverted as the control flow optimiser
896 -- places some requirements on the predecessors of both branch targets.
897 -- So we better look for the inverted comparison too.
898
899 optStackCheck :: CmmNode O C -> CmmNode O C
900 optStackCheck n = -- Note [Always false stack check]
901 case n of
902 CmmCondBranch (CmmLit (CmmInt 0 _)) _true false _ -> CmmBranch false
903 CmmCondBranch (CmmLit (CmmInt _ _)) true _false _ -> CmmBranch true
904 other -> other
905
906
907 -- -----------------------------------------------------------------------------
908
909 -- | Eliminate stores of the form
910 --
911 -- Sp[area+n] = r
912 --
913 -- when we know that r is already in the same slot as Sp[area+n]. We
914 -- could do this in a later optimisation pass, but that would involve
915 -- a separate analysis and we already have the information to hand
916 -- here. It helps clean up some extra stack stores in common cases.
917 --
918 -- Note that we may have to modify the StackMap as we walk through the
919 -- code using procMiddle, since an assignment to a variable in the
920 -- StackMap will invalidate its mapping there.
921 --
922 elimStackStores :: StackMap
923 -> LabelMap StackMap
924 -> (Area -> ByteOff)
925 -> [CmmNode O O]
926 -> [CmmNode O O]
927 elimStackStores stackmap stackmaps area_off nodes
928 = go stackmap nodes
929 where
930 go _stackmap [] = []
931 go stackmap (n:ns)
932 = case n of
933 CmmStore (CmmStackSlot area m) (CmmReg (CmmLocal r))
934 | Just (_,off) <- lookupUFM (sm_regs stackmap) r
935 , area_off area + m == off
936 -> go stackmap ns
937 _otherwise
938 -> n : go (procMiddle stackmaps n stackmap) ns
939
940
941 -- -----------------------------------------------------------------------------
942 -- Update info tables to include stack liveness
943
944
945 setInfoTableStackMap :: DynFlags -> LabelMap StackMap -> CmmDecl -> CmmDecl
946 setInfoTableStackMap dflags stackmaps (CmmProc top_info@TopInfo{..} l v g)
947 = CmmProc top_info{ info_tbls = mapMapWithKey fix_info info_tbls } l v g
948 where
949 fix_info lbl info_tbl@CmmInfoTable{ cit_rep = StackRep _ } =
950 info_tbl { cit_rep = StackRep (get_liveness lbl) }
951 fix_info _ other = other
952
953 get_liveness :: BlockId -> Liveness
954 get_liveness lbl
955 = case mapLookup lbl stackmaps of
956 Nothing -> pprPanic "setInfoTableStackMap" (ppr lbl <+> ppr info_tbls)
957 Just sm -> stackMapToLiveness dflags sm
958
959 setInfoTableStackMap _ _ d = d
960
961
962 stackMapToLiveness :: DynFlags -> StackMap -> Liveness
963 stackMapToLiveness dflags StackMap{..} =
964 reverse $ Array.elems $
965 accumArray (\_ x -> x) True (toWords dflags sm_ret_off + 1,
966 toWords dflags (sm_sp - sm_args)) live_words
967 where
968 live_words = [ (toWords dflags off, False)
969 | (r,off) <- nonDetEltsUFM sm_regs
970 , isGcPtrType (localRegType r) ]
971 -- See Note [Unique Determinism and code generation]
972
973
974 -- -----------------------------------------------------------------------------
975 -- Lowering safe foreign calls
976
977 {-
978 Note [Lower safe foreign calls]
979
980 We start with
981
982 Sp[young(L1)] = L1
983 ,-----------------------
984 | r1 = foo(x,y,z) returns to L1
985 '-----------------------
986 L1:
987 R1 = r1 -- copyIn, inserted by mkSafeCall
988 ...
989
990 the stack layout algorithm will arrange to save and reload everything
991 live across the call. Our job now is to expand the call so we get
992
993 Sp[young(L1)] = L1
994 ,-----------------------
995 | SAVE_THREAD_STATE()
996 | token = suspendThread(BaseReg, interruptible)
997 | r = foo(x,y,z)
998 | BaseReg = resumeThread(token)
999 | LOAD_THREAD_STATE()
1000 | R1 = r -- copyOut
1001 | jump Sp[0]
1002 '-----------------------
1003 L1:
1004 r = R1 -- copyIn, inserted by mkSafeCall
1005 ...
1006
1007 Note the copyOut, which saves the results in the places that L1 is
1008 expecting them (see Note [safe foreign call convention]). Note also
1009 that safe foreign call is replace by an unsafe one in the Cmm graph.
1010 -}
1011
1012 lowerSafeForeignCall :: DynFlags -> CmmBlock -> UniqSM CmmBlock
1013 lowerSafeForeignCall dflags block
1014 | (entry@(CmmEntry _ tscp), middle, CmmForeignCall { .. }) <- blockSplit block
1015 = do
1016 -- Both 'id' and 'new_base' are KindNonPtr because they're
1017 -- RTS-only objects and are not subject to garbage collection
1018 id <- newTemp (bWord dflags)
1019 new_base <- newTemp (cmmRegType dflags (CmmGlobal BaseReg))
1020 let (caller_save, caller_load) = callerSaveVolatileRegs dflags
1021 save_state_code <- saveThreadState dflags
1022 load_state_code <- loadThreadState dflags
1023 let suspend = save_state_code <*>
1024 caller_save <*>
1025 mkMiddle (callSuspendThread dflags id intrbl)
1026 midCall = mkUnsafeCall tgt res args
1027 resume = mkMiddle (callResumeThread new_base id) <*>
1028 -- Assign the result to BaseReg: we
1029 -- might now have a different Capability!
1030 mkAssign (CmmGlobal BaseReg) (CmmReg (CmmLocal new_base)) <*>
1031 caller_load <*>
1032 load_state_code
1033
1034 (_, regs, copyout) =
1035 copyOutOflow dflags NativeReturn Jump (Young succ)
1036 (map (CmmReg . CmmLocal) res)
1037 ret_off []
1038
1039 -- NB. after resumeThread returns, the top-of-stack probably contains
1040 -- the stack frame for succ, but it might not: if the current thread
1041 -- received an exception during the call, then the stack might be
1042 -- different. Hence we continue by jumping to the top stack frame,
1043 -- not by jumping to succ.
1044 jump = CmmCall { cml_target = entryCode dflags $
1045 CmmLoad (CmmReg spReg) (bWord dflags)
1046 , cml_cont = Just succ
1047 , cml_args_regs = regs
1048 , cml_args = widthInBytes (wordWidth dflags)
1049 , cml_ret_args = ret_args
1050 , cml_ret_off = ret_off }
1051
1052 graph' <- lgraphOfAGraph ( suspend <*>
1053 midCall <*>
1054 resume <*>
1055 copyout <*>
1056 mkLast jump, tscp)
1057
1058 case toBlockList graph' of
1059 [one] -> let (_, middle', last) = blockSplit one
1060 in return (blockJoin entry (middle `blockAppend` middle') last)
1061 _ -> panic "lowerSafeForeignCall0"
1062
1063 -- Block doesn't end in a safe foreign call:
1064 | otherwise = return block
1065
1066
1067 foreignLbl :: FastString -> CmmExpr
1068 foreignLbl name = CmmLit (CmmLabel (mkForeignLabel name Nothing ForeignLabelInExternalPackage IsFunction))
1069
1070 callSuspendThread :: DynFlags -> LocalReg -> Bool -> CmmNode O O
1071 callSuspendThread dflags id intrbl =
1072 CmmUnsafeForeignCall
1073 (ForeignTarget (foreignLbl (fsLit "suspendThread"))
1074 (ForeignConvention CCallConv [AddrHint, NoHint] [AddrHint] CmmMayReturn))
1075 [id] [CmmReg (CmmGlobal BaseReg), mkIntExpr dflags (fromEnum intrbl)]
1076
1077 callResumeThread :: LocalReg -> LocalReg -> CmmNode O O
1078 callResumeThread new_base id =
1079 CmmUnsafeForeignCall
1080 (ForeignTarget (foreignLbl (fsLit "resumeThread"))
1081 (ForeignConvention CCallConv [AddrHint] [AddrHint] CmmMayReturn))
1082 [new_base] [CmmReg (CmmLocal id)]
1083
1084 -- -----------------------------------------------------------------------------
1085
1086 plusW :: DynFlags -> ByteOff -> WordOff -> ByteOff
1087 plusW dflags b w = b + w * wORD_SIZE dflags
1088
1089 data StackSlot = Occupied | Empty
1090 -- Occupied: a return address or part of an update frame
1091
1092 instance Outputable StackSlot where
1093 ppr Occupied = text "XXX"
1094 ppr Empty = text "---"
1095
1096 dropEmpty :: WordOff -> [StackSlot] -> Maybe [StackSlot]
1097 dropEmpty 0 ss = Just ss
1098 dropEmpty n (Empty : ss) = dropEmpty (n-1) ss
1099 dropEmpty _ _ = Nothing
1100
1101 isEmpty :: StackSlot -> Bool
1102 isEmpty Empty = True
1103 isEmpty _ = False
1104
1105 localRegBytes :: DynFlags -> LocalReg -> ByteOff
1106 localRegBytes dflags r
1107 = roundUpToWords dflags (widthInBytes (typeWidth (localRegType r)))
1108
1109 localRegWords :: DynFlags -> LocalReg -> WordOff
1110 localRegWords dflags = toWords dflags . localRegBytes dflags
1111
1112 toWords :: DynFlags -> ByteOff -> WordOff
1113 toWords dflags x = x `quot` wORD_SIZE dflags
1114
1115
1116 insertReloads :: StackMap -> [CmmNode O O]
1117 insertReloads stackmap =
1118 [ CmmAssign (CmmLocal r) (CmmLoad (CmmStackSlot Old sp)
1119 (localRegType r))
1120 | (r,sp) <- stackSlotRegs stackmap
1121 ]
1122
1123
1124 stackSlotRegs :: StackMap -> [(LocalReg, StackLoc)]
1125 stackSlotRegs sm = nonDetEltsUFM (sm_regs sm)
1126 -- See Note [Unique Determinism and code generation]