Fix #11407.
[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 import Control.Monad (liftM)
36
37 import Prelude hiding ((<*>))
38
39 #include "HsVersions.h"
40
41 {- Note [Stack Layout]
42
43 The job of this pass is to
44
45 - replace references to abstract stack Areas with fixed offsets from Sp.
46
47 - replace the CmmHighStackMark constant used in the stack check with
48 the maximum stack usage of the proc.
49
50 - save any variables that are live across a call, and reload them as
51 necessary.
52
53 Before stack allocation, local variables remain live across native
54 calls (CmmCall{ cmm_cont = Just _ }), and after stack allocation local
55 variables are clobbered by native calls.
56
57 We want to do stack allocation so that as far as possible
58 - stack use is minimized, and
59 - unnecessary stack saves and loads are avoided.
60
61 The algorithm we use is a variant of linear-scan register allocation,
62 where the stack is our register file.
63
64 - First, we do a liveness analysis, which annotates every block with
65 the variables live on entry to the block.
66
67 - We traverse blocks in reverse postorder DFS; that is, we visit at
68 least one predecessor of a block before the block itself. The
69 stack layout flowing from the predecessor of the block will
70 determine the stack layout on entry to the block.
71
72 - We maintain a data structure
73
74 Map Label StackMap
75
76 which describes the contents of the stack and the stack pointer on
77 entry to each block that is a successor of a block that we have
78 visited.
79
80 - For each block we visit:
81
82 - Look up the StackMap for this block.
83
84 - If this block is a proc point (or a call continuation, if we
85 aren't splitting proc points), emit instructions to reload all
86 the live variables from the stack, according to the StackMap.
87
88 - Walk forwards through the instructions:
89 - At an assignment x = Sp[loc]
90 - Record the fact that Sp[loc] contains x, so that we won't
91 need to save x if it ever needs to be spilled.
92 - At an assignment x = E
93 - If x was previously on the stack, it isn't any more
94 - At the last node, if it is a call or a jump to a proc point
95 - Lay out the stack frame for the call (see setupStackFrame)
96 - emit instructions to save all the live variables
97 - Remember the StackMaps for all the successors
98 - emit an instruction to adjust Sp
99 - If the last node is a branch, then the current StackMap is the
100 StackMap for the successors.
101
102 - Manifest Sp: replace references to stack areas in this block
103 with real Sp offsets. We cannot do this until we have laid out
104 the stack area for the successors above.
105
106 In this phase we also eliminate redundant stores to the stack;
107 see elimStackStores.
108
109 - There is one important gotcha: sometimes we'll encounter a control
110 transfer to a block that we've already processed (a join point),
111 and in that case we might need to rearrange the stack to match
112 what the block is expecting. (exactly the same as in linear-scan
113 register allocation, except here we have the luxury of an infinite
114 supply of temporary variables).
115
116 - Finally, we update the magic CmmHighStackMark constant with the
117 stack usage of the function, and eliminate the whole stack check
118 if there was no stack use. (in fact this is done as part of the
119 main traversal, by feeding the high-water-mark output back in as
120 an input. I hate cyclic programming, but it's just too convenient
121 sometimes.)
122
123 There are plenty of tricky details: update frames, proc points, return
124 addresses, foreign calls, and some ad-hoc optimisations that are
125 convenient to do here and effective in common cases. Comments in the
126 code below explain these.
127
128 -}
129
130
131 -- All stack locations are expressed as positive byte offsets from the
132 -- "base", which is defined to be the address above the return address
133 -- on the stack on entry to this CmmProc.
134 --
135 -- Lower addresses have higher StackLocs.
136 --
137 type StackLoc = ByteOff
138
139 {-
140 A StackMap describes the stack at any given point. At a continuation
141 it has a particular layout, like this:
142
143 | | <- base
144 |-------------|
145 | ret0 | <- base + 8
146 |-------------|
147 . upd frame . <- base + sm_ret_off
148 |-------------|
149 | |
150 . vars .
151 . (live/dead) .
152 | | <- base + sm_sp - sm_args
153 |-------------|
154 | ret1 |
155 . ret vals . <- base + sm_sp (<--- Sp points here)
156 |-------------|
157
158 Why do we include the final return address (ret0) in our stack map? I
159 have absolutely no idea, but it seems to be done that way consistently
160 in the rest of the code generator, so I played along here. --SDM
161
162 Note that we will be constructing an info table for the continuation
163 (ret1), which needs to describe the stack down to, but not including,
164 the update frame (or ret0, if there is no update frame).
165 -}
166
167 data StackMap = StackMap
168 { sm_sp :: StackLoc
169 -- ^ the offset of Sp relative to the base on entry
170 -- to this block.
171 , sm_args :: ByteOff
172 -- ^ the number of bytes of arguments in the area for this block
173 -- Defn: the offset of young(L) relative to the base is given by
174 -- (sm_sp - sm_args) of the StackMap for block L.
175 , sm_ret_off :: ByteOff
176 -- ^ Number of words of stack that we do not describe with an info
177 -- table, because it contains an update frame.
178 , sm_regs :: UniqFM (LocalReg,StackLoc)
179 -- ^ regs on the stack
180 }
181
182 instance Outputable StackMap where
183 ppr StackMap{..} =
184 text "Sp = " <> int sm_sp $$
185 text "sm_args = " <> int sm_args $$
186 text "sm_ret_off = " <> int sm_ret_off $$
187 text "sm_regs = " <> ppr (eltsUFM sm_regs)
188
189
190 cmmLayoutStack :: DynFlags -> ProcPointSet -> ByteOff -> CmmGraph
191 -> UniqSM (CmmGraph, BlockEnv StackMap)
192 cmmLayoutStack dflags procpoints entry_args
193 graph0@(CmmGraph { g_entry = entry })
194 = do
195 -- We need liveness info. Dead assignments are removed later
196 -- by the sinking pass.
197 let (graph, liveness) = (graph0, cmmLocalLiveness dflags graph0)
198 blocks = postorderDfs graph
199
200 (final_stackmaps, _final_high_sp, new_blocks) <-
201 mfix $ \ ~(rec_stackmaps, rec_high_sp, _new_blocks) ->
202 layout dflags procpoints liveness entry entry_args
203 rec_stackmaps rec_high_sp blocks
204
205 new_blocks' <- mapM (lowerSafeForeignCall dflags) new_blocks
206 return (ofBlockList entry new_blocks', final_stackmaps)
207
208
209 layout :: DynFlags
210 -> BlockSet -- proc points
211 -> BlockEnv CmmLocalLive -- liveness
212 -> BlockId -- entry
213 -> ByteOff -- stack args on entry
214
215 -> BlockEnv StackMap -- [final] stack maps
216 -> ByteOff -- [final] Sp high water mark
217
218 -> [CmmBlock] -- [in] blocks
219
220 -> UniqSM
221 ( BlockEnv StackMap -- [out] stack maps
222 , ByteOff -- [out] Sp high water mark
223 , [CmmBlock] -- [out] new blocks
224 )
225
226 layout dflags procpoints liveness entry entry_args final_stackmaps final_sp_high blocks
227 = go blocks init_stackmap entry_args []
228 where
229 (updfr, cont_info) = collectContInfo blocks
230
231 init_stackmap = mapSingleton entry StackMap{ sm_sp = entry_args
232 , sm_args = entry_args
233 , sm_ret_off = updfr
234 , sm_regs = emptyUFM
235 }
236
237 go [] acc_stackmaps acc_hwm acc_blocks
238 = return (acc_stackmaps, acc_hwm, acc_blocks)
239
240 go (b0 : bs) acc_stackmaps acc_hwm acc_blocks
241 = do
242 let (entry0@(CmmEntry entry_lbl tscope), middle0, last0) = blockSplit b0
243
244 let stack0@StackMap { sm_sp = sp0 }
245 = mapFindWithDefault
246 (pprPanic "no stack map for" (ppr entry_lbl))
247 entry_lbl acc_stackmaps
248
249 -- (a) Update the stack map to include the effects of
250 -- assignments in this block
251 let stack1 = foldBlockNodesF (procMiddle acc_stackmaps) middle0 stack0
252
253 -- (b) Insert assignments to reload all the live variables if this
254 -- block is a proc point
255 let middle1 = if entry_lbl `setMember` procpoints
256 then foldr blockCons middle0 (insertReloads stack0)
257 else middle0
258
259 -- (c) Look at the last node and if we are making a call or
260 -- jumping to a proc point, we must save the live
261 -- variables, adjust Sp, and construct the StackMaps for
262 -- each of the successor blocks. See handleLastNode for
263 -- details.
264 (middle2, sp_off, last1, fixup_blocks, out)
265 <- handleLastNode dflags procpoints liveness cont_info
266 acc_stackmaps stack1 tscope middle0 last0
267
268 -- (d) Manifest Sp: run over the nodes in the block and replace
269 -- CmmStackSlot with CmmLoad from Sp with a concrete offset.
270 --
271 -- our block:
272 -- middle1 -- the original middle nodes
273 -- middle2 -- live variable saves from handleLastNode
274 -- Sp = Sp + sp_off -- Sp adjustment goes here
275 -- last1 -- the last node
276 --
277 let middle_pre = blockToList $ foldl blockSnoc middle1 middle2
278
279 final_blocks = manifestSp dflags final_stackmaps stack0 sp0 final_sp_high entry0
280 middle_pre sp_off last1 fixup_blocks
281
282 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, BlockEnv 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 :: BlockEnv 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 -> BlockEnv 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 -> BlockEnv CmmLocalLive -> BlockEnv ByteOff
388 -> BlockEnv 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 , BlockEnv 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 , BlockEnv 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 , BlockEnv 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 <- liftM mkBlockId $ getUniqueM
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 -> BlockEnv 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) <- eltsUFM regs1,
688 let w = localRegBytes dflags r,
689 x <- [ off, off - wORD_SIZE dflags .. off - w + 1] ]
690 in
691
692 -- Pass over the stack: find slots to save all the new live variables,
693 -- choosing the oldest slots first (hence a foldr).
694 let
695 save slot ([], stack, n, assigs, regs) -- no more regs to save
696 = ([], slot:stack, plusW dflags n 1, assigs, regs)
697 save slot (to_save, stack, n, assigs, regs)
698 = case slot of
699 Occupied -> (to_save, Occupied:stack, plusW dflags n 1, assigs, regs)
700 Empty
701 | Just (stack', r, to_save') <-
702 select_save to_save (slot:stack)
703 -> let assig = CmmStore (CmmStackSlot Old n')
704 (CmmReg (CmmLocal r))
705 n' = plusW dflags n 1
706 in
707 (to_save', stack', n', assig : assigs, (r,(r,n')):regs)
708
709 | otherwise
710 -> (to_save, slot:stack, plusW dflags n 1, assigs, regs)
711
712 -- we should do better here: right now we'll fit the smallest first,
713 -- but it would make more sense to fit the biggest first.
714 select_save :: [LocalReg] -> [StackSlot]
715 -> Maybe ([StackSlot], LocalReg, [LocalReg])
716 select_save regs stack = go regs []
717 where go [] _no_fit = Nothing
718 go (r:rs) no_fit
719 | Just rest <- dropEmpty words stack
720 = Just (replicate words Occupied ++ rest, r, rs++no_fit)
721 | otherwise
722 = go rs (r:no_fit)
723 where words = localRegWords dflags r
724
725 -- fill in empty slots as much as possible
726 (still_to_save, save_stack, n, save_assigs, save_regs)
727 = foldr save (to_save, [], 0, [], []) stack
728
729 -- push any remaining live vars on the stack
730 (push_sp, push_assigs, push_regs)
731 = foldr push (n, [], []) still_to_save
732 where
733 push r (n, assigs, regs)
734 = (n', assig : assigs, (r,(r,n')) : regs)
735 where
736 n' = n + localRegBytes dflags r
737 assig = CmmStore (CmmStackSlot Old n')
738 (CmmReg (CmmLocal r))
739
740 trim_sp
741 | not (null push_regs) = push_sp
742 | otherwise
743 = plusW dflags n (- length (takeWhile isEmpty save_stack))
744
745 final_regs = regs1 `addListToUFM` push_regs
746 `addListToUFM` save_regs
747
748 in
749 -- XXX should be an assert
750 if ( n /= max sp0 ret_off ) then pprPanic "allocate" (ppr n <+> ppr sp0 <+> ppr ret_off) else
751
752 if (trim_sp .&. (wORD_SIZE dflags - 1)) /= 0 then pprPanic "allocate2" (ppr trim_sp <+> ppr final_regs <+> ppr push_sp) else
753
754 ( stackmap { sm_regs = final_regs , sm_sp = trim_sp }
755 , push_assigs ++ save_assigs )
756
757
758 -- -----------------------------------------------------------------------------
759 -- Manifesting Sp
760
761 -- | Manifest Sp: turn all the CmmStackSlots into CmmLoads from Sp. The
762 -- block looks like this:
763 --
764 -- middle_pre -- the middle nodes
765 -- Sp = Sp + sp_off -- Sp adjustment goes here
766 -- last -- the last node
767 --
768 -- And we have some extra blocks too (that don't contain Sp adjustments)
769 --
770 -- The adjustment for middle_pre will be different from that for
771 -- middle_post, because the Sp adjustment intervenes.
772 --
773 manifestSp
774 :: DynFlags
775 -> BlockEnv StackMap -- StackMaps for other blocks
776 -> StackMap -- StackMap for this block
777 -> ByteOff -- Sp on entry to the block
778 -> ByteOff -- SpHigh
779 -> CmmNode C O -- first node
780 -> [CmmNode O O] -- middle
781 -> ByteOff -- sp_off
782 -> CmmNode O C -- last node
783 -> [CmmBlock] -- new blocks
784 -> [CmmBlock] -- final blocks with Sp manifest
785
786 manifestSp dflags stackmaps stack0 sp0 sp_high
787 first middle_pre sp_off last fixup_blocks
788 = final_block : fixup_blocks'
789 where
790 area_off = getAreaOff stackmaps
791
792 adj_pre_sp, adj_post_sp :: CmmNode e x -> CmmNode e x
793 adj_pre_sp = mapExpDeep (areaToSp dflags sp0 sp_high area_off)
794 adj_post_sp = mapExpDeep (areaToSp dflags (sp0 - sp_off) sp_high area_off)
795
796 -- Add unwind pseudo-instructions to document Sp level for debugging
797 add_unwind_info block
798 | debugLevel dflags > 0 = CmmUnwind Sp sp_unwind : block
799 | otherwise = block
800 sp_unwind = CmmRegOff (CmmGlobal Sp) (sp0 - wORD_SIZE dflags)
801
802 final_middle = maybeAddSpAdj dflags sp_off $
803 blockFromList $
804 add_unwind_info $
805 map adj_pre_sp $
806 elimStackStores stack0 stackmaps area_off $
807 middle_pre
808
809 final_last = optStackCheck (adj_post_sp last)
810
811 final_block = blockJoin first final_middle final_last
812
813 fixup_blocks' = map (mapBlock3' (id, adj_post_sp, id)) fixup_blocks
814
815
816 getAreaOff :: BlockEnv StackMap -> (Area -> StackLoc)
817 getAreaOff _ Old = 0
818 getAreaOff stackmaps (Young l) =
819 case mapLookup l stackmaps of
820 Just sm -> sm_sp sm - sm_args sm
821 Nothing -> pprPanic "getAreaOff" (ppr l)
822
823
824 maybeAddSpAdj :: DynFlags -> ByteOff -> Block CmmNode O O -> Block CmmNode O O
825 maybeAddSpAdj _ 0 block = block
826 maybeAddSpAdj dflags sp_off block
827 = block `blockSnoc` CmmAssign spReg (cmmOffset dflags (CmmReg spReg) sp_off)
828
829
830 {-
831 Sp(L) is the Sp offset on entry to block L relative to the base of the
832 OLD area.
833
834 SpArgs(L) is the size of the young area for L, i.e. the number of
835 arguments.
836
837 - in block L, each reference to [old + N] turns into
838 [Sp + Sp(L) - N]
839
840 - in block L, each reference to [young(L') + N] turns into
841 [Sp + Sp(L) - Sp(L') + SpArgs(L') - N]
842
843 - be careful with the last node of each block: Sp has already been adjusted
844 to be Sp + Sp(L) - Sp(L')
845 -}
846
847 areaToSp :: DynFlags -> ByteOff -> ByteOff -> (Area -> StackLoc) -> CmmExpr -> CmmExpr
848
849 areaToSp dflags sp_old _sp_hwm area_off (CmmStackSlot area n)
850 = cmmOffset dflags (CmmReg spReg) (sp_old - area_off area - n)
851 -- Replace (CmmStackSlot area n) with an offset from Sp
852
853 areaToSp dflags _ sp_hwm _ (CmmLit CmmHighStackMark)
854 = mkIntExpr dflags sp_hwm
855 -- Replace CmmHighStackMark with the number of bytes of stack used,
856 -- the sp_hwm. See Note [Stack usage] in StgCmmHeap
857
858 areaToSp dflags _ _ _ (CmmMachOp (MO_U_Lt _) args)
859 | falseStackCheck args
860 = zeroExpr dflags
861 areaToSp dflags _ _ _ (CmmMachOp (MO_U_Ge _) args)
862 | falseStackCheck args
863 = mkIntExpr dflags 1
864 -- Replace a stack-overflow test that cannot fail with a no-op
865 -- See Note [Always false stack check]
866
867 areaToSp _ _ _ _ other = other
868
869 -- | Determine whether a stack check cannot fail.
870 falseStackCheck :: [CmmExpr] -> Bool
871 falseStackCheck [ CmmMachOp (MO_Sub _)
872 [ CmmRegOff (CmmGlobal Sp) x_off
873 , CmmLit (CmmInt y_lit _)]
874 , CmmReg (CmmGlobal SpLim)]
875 = fromIntegral x_off >= y_lit
876 falseStackCheck _ = False
877
878 -- Note [Always false stack check]
879 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
880 -- We can optimise stack checks of the form
881 --
882 -- if ((Sp + x) - y < SpLim) then .. else ..
883 --
884 -- where are non-negative integer byte offsets. Since we know that
885 -- SpLim <= Sp (remember the stack grows downwards), this test must
886 -- yield False if (x >= y), so we can rewrite the comparison to False.
887 -- A subsequent sinking pass will later drop the dead code.
888 -- Optimising this away depends on knowing that SpLim <= Sp, so it is
889 -- really the job of the stack layout algorithm, hence we do it now.
890 --
891 -- The control flow optimiser may negate a conditional to increase
892 -- the likelihood of a fallthrough if the branch is not taken. But
893 -- not every conditional is inverted as the control flow optimiser
894 -- places some requirements on the predecessors of both branch targets.
895 -- So we better look for the inverted comparison too.
896
897 optStackCheck :: CmmNode O C -> CmmNode O C
898 optStackCheck n = -- Note [Always false stack check]
899 case n of
900 CmmCondBranch (CmmLit (CmmInt 0 _)) _true false _ -> CmmBranch false
901 CmmCondBranch (CmmLit (CmmInt _ _)) true _false _ -> CmmBranch true
902 other -> other
903
904
905 -- -----------------------------------------------------------------------------
906
907 -- | Eliminate stores of the form
908 --
909 -- Sp[area+n] = r
910 --
911 -- when we know that r is already in the same slot as Sp[area+n]. We
912 -- could do this in a later optimisation pass, but that would involve
913 -- a separate analysis and we already have the information to hand
914 -- here. It helps clean up some extra stack stores in common cases.
915 --
916 -- Note that we may have to modify the StackMap as we walk through the
917 -- code using procMiddle, since an assignment to a variable in the
918 -- StackMap will invalidate its mapping there.
919 --
920 elimStackStores :: StackMap
921 -> BlockEnv StackMap
922 -> (Area -> ByteOff)
923 -> [CmmNode O O]
924 -> [CmmNode O O]
925 elimStackStores stackmap stackmaps area_off nodes
926 = go stackmap nodes
927 where
928 go _stackmap [] = []
929 go stackmap (n:ns)
930 = case n of
931 CmmStore (CmmStackSlot area m) (CmmReg (CmmLocal r))
932 | Just (_,off) <- lookupUFM (sm_regs stackmap) r
933 , area_off area + m == off
934 -> go stackmap ns
935 _otherwise
936 -> n : go (procMiddle stackmaps n stackmap) ns
937
938
939 -- -----------------------------------------------------------------------------
940 -- Update info tables to include stack liveness
941
942
943 setInfoTableStackMap :: DynFlags -> BlockEnv StackMap -> CmmDecl -> CmmDecl
944 setInfoTableStackMap dflags stackmaps (CmmProc top_info@TopInfo{..} l v g)
945 = CmmProc top_info{ info_tbls = mapMapWithKey fix_info info_tbls } l v g
946 where
947 fix_info lbl info_tbl@CmmInfoTable{ cit_rep = StackRep _ } =
948 info_tbl { cit_rep = StackRep (get_liveness lbl) }
949 fix_info _ other = other
950
951 get_liveness :: BlockId -> Liveness
952 get_liveness lbl
953 = case mapLookup lbl stackmaps of
954 Nothing -> pprPanic "setInfoTableStackMap" (ppr lbl <+> ppr info_tbls)
955 Just sm -> stackMapToLiveness dflags sm
956
957 setInfoTableStackMap _ _ d = d
958
959
960 stackMapToLiveness :: DynFlags -> StackMap -> Liveness
961 stackMapToLiveness dflags StackMap{..} =
962 reverse $ Array.elems $
963 accumArray (\_ x -> x) True (toWords dflags sm_ret_off + 1,
964 toWords dflags (sm_sp - sm_args)) live_words
965 where
966 live_words = [ (toWords dflags off, False)
967 | (r,off) <- eltsUFM sm_regs, isGcPtrType (localRegType r) ]
968
969
970 -- -----------------------------------------------------------------------------
971 -- Lowering safe foreign calls
972
973 {-
974 Note [Lower safe foreign calls]
975
976 We start with
977
978 Sp[young(L1)] = L1
979 ,-----------------------
980 | r1 = foo(x,y,z) returns to L1
981 '-----------------------
982 L1:
983 R1 = r1 -- copyIn, inserted by mkSafeCall
984 ...
985
986 the stack layout algorithm will arrange to save and reload everything
987 live across the call. Our job now is to expand the call so we get
988
989 Sp[young(L1)] = L1
990 ,-----------------------
991 | SAVE_THREAD_STATE()
992 | token = suspendThread(BaseReg, interruptible)
993 | r = foo(x,y,z)
994 | BaseReg = resumeThread(token)
995 | LOAD_THREAD_STATE()
996 | R1 = r -- copyOut
997 | jump Sp[0]
998 '-----------------------
999 L1:
1000 r = R1 -- copyIn, inserted by mkSafeCall
1001 ...
1002
1003 Note the copyOut, which saves the results in the places that L1 is
1004 expecting them (see Note {safe foreign call convention]). Note also
1005 that safe foreign call is replace by an unsafe one in the Cmm graph.
1006 -}
1007
1008 lowerSafeForeignCall :: DynFlags -> CmmBlock -> UniqSM CmmBlock
1009 lowerSafeForeignCall dflags block
1010 | (entry@(CmmEntry _ tscp), middle, CmmForeignCall { .. }) <- blockSplit block
1011 = do
1012 -- Both 'id' and 'new_base' are KindNonPtr because they're
1013 -- RTS-only objects and are not subject to garbage collection
1014 id <- newTemp (bWord dflags)
1015 new_base <- newTemp (cmmRegType dflags (CmmGlobal BaseReg))
1016 let (caller_save, caller_load) = callerSaveVolatileRegs dflags
1017 save_state_code <- saveThreadState dflags
1018 load_state_code <- loadThreadState dflags
1019 let suspend = save_state_code <*>
1020 caller_save <*>
1021 mkMiddle (callSuspendThread dflags id intrbl)
1022 midCall = mkUnsafeCall tgt res args
1023 resume = mkMiddle (callResumeThread new_base id) <*>
1024 -- Assign the result to BaseReg: we
1025 -- might now have a different Capability!
1026 mkAssign (CmmGlobal BaseReg) (CmmReg (CmmLocal new_base)) <*>
1027 caller_load <*>
1028 load_state_code
1029
1030 (_, regs, copyout) =
1031 copyOutOflow dflags NativeReturn Jump (Young succ)
1032 (map (CmmReg . CmmLocal) res)
1033 ret_off []
1034
1035 -- NB. after resumeThread returns, the top-of-stack probably contains
1036 -- the stack frame for succ, but it might not: if the current thread
1037 -- received an exception during the call, then the stack might be
1038 -- different. Hence we continue by jumping to the top stack frame,
1039 -- not by jumping to succ.
1040 jump = CmmCall { cml_target = entryCode dflags $
1041 CmmLoad (CmmReg spReg) (bWord dflags)
1042 , cml_cont = Just succ
1043 , cml_args_regs = regs
1044 , cml_args = widthInBytes (wordWidth dflags)
1045 , cml_ret_args = ret_args
1046 , cml_ret_off = ret_off }
1047
1048 graph' <- lgraphOfAGraph ( suspend <*>
1049 midCall <*>
1050 resume <*>
1051 copyout <*>
1052 mkLast jump, tscp)
1053
1054 case toBlockList graph' of
1055 [one] -> let (_, middle', last) = blockSplit one
1056 in return (blockJoin entry (middle `blockAppend` middle') last)
1057 _ -> panic "lowerSafeForeignCall0"
1058
1059 -- Block doesn't end in a safe foreign call:
1060 | otherwise = return block
1061
1062
1063 foreignLbl :: FastString -> CmmExpr
1064 foreignLbl name = CmmLit (CmmLabel (mkForeignLabel name Nothing ForeignLabelInExternalPackage IsFunction))
1065
1066 callSuspendThread :: DynFlags -> LocalReg -> Bool -> CmmNode O O
1067 callSuspendThread dflags id intrbl =
1068 CmmUnsafeForeignCall
1069 (ForeignTarget (foreignLbl (fsLit "suspendThread"))
1070 (ForeignConvention CCallConv [AddrHint, NoHint] [AddrHint] CmmMayReturn))
1071 [id] [CmmReg (CmmGlobal BaseReg), mkIntExpr dflags (fromEnum intrbl)]
1072
1073 callResumeThread :: LocalReg -> LocalReg -> CmmNode O O
1074 callResumeThread new_base id =
1075 CmmUnsafeForeignCall
1076 (ForeignTarget (foreignLbl (fsLit "resumeThread"))
1077 (ForeignConvention CCallConv [AddrHint] [AddrHint] CmmMayReturn))
1078 [new_base] [CmmReg (CmmLocal id)]
1079
1080 -- -----------------------------------------------------------------------------
1081
1082 plusW :: DynFlags -> ByteOff -> WordOff -> ByteOff
1083 plusW dflags b w = b + w * wORD_SIZE dflags
1084
1085 data StackSlot = Occupied | Empty
1086 -- Occupied: a return address or part of an update frame
1087
1088 instance Outputable StackSlot where
1089 ppr Occupied = text "XXX"
1090 ppr Empty = text "---"
1091
1092 dropEmpty :: WordOff -> [StackSlot] -> Maybe [StackSlot]
1093 dropEmpty 0 ss = Just ss
1094 dropEmpty n (Empty : ss) = dropEmpty (n-1) ss
1095 dropEmpty _ _ = Nothing
1096
1097 isEmpty :: StackSlot -> Bool
1098 isEmpty Empty = True
1099 isEmpty _ = False
1100
1101 localRegBytes :: DynFlags -> LocalReg -> ByteOff
1102 localRegBytes dflags r
1103 = roundUpToWords dflags (widthInBytes (typeWidth (localRegType r)))
1104
1105 localRegWords :: DynFlags -> LocalReg -> WordOff
1106 localRegWords dflags = toWords dflags . localRegBytes dflags
1107
1108 toWords :: DynFlags -> ByteOff -> WordOff
1109 toWords dflags x = x `quot` wORD_SIZE dflags
1110
1111
1112 insertReloads :: StackMap -> [CmmNode O O]
1113 insertReloads stackmap =
1114 [ CmmAssign (CmmLocal r) (CmmLoad (CmmStackSlot Old sp)
1115 (localRegType r))
1116 | (r,sp) <- stackSlotRegs stackmap
1117 ]
1118
1119
1120 stackSlotRegs :: StackMap -> [(LocalReg, StackLoc)]
1121 stackSlotRegs sm = eltsUFM (sm_regs sm)