Main.hs 37.2 KB
Newer Older
1
{-# LANGUAGE BangPatterns, CPP, ScopedTypeVariables #-}
2

3 4 5 6 7 8 9 10 11 12
-----------------------------------------------------------------------------
--
-- The register allocator
--
-- (c) The University of Glasgow 2004
--
-----------------------------------------------------------------------------

{-
The algorithm is roughly:
13

14 15 16 17 18 19
  1) Compute strongly connected components of the basic block list.

  2) Compute liveness (mapping from pseudo register to
     point(s) of death?).

  3) Walk instructions in each basic block.  We keep track of
20 21 22 23 24 25
        (a) Free real registers (a bitmap?)
        (b) Current assignment of temporaries to machine registers and/or
            spill slots (call this the "assignment").
        (c) Partial mapping from basic block ids to a virt-to-loc mapping.
            When we first encounter a branch to a basic block,
            we fill in its entry in this table with the current mapping.
26 27

     For each instruction:
28
        (a) For each temporary *read* by the instruction:
29 30 31 32 33 34 35 36 37 38
            If the temporary does not have a real register allocation:
                - Allocate a real register from the free list.  If
                  the list is empty:
                  - Find a temporary to spill.  Pick one that is
                    not used in this instruction (ToDo: not
                    used for a while...)
                  - generate a spill instruction
                - If the temporary was previously spilled,
                  generate an instruction to read the temp from its spill loc.
            (optimisation: if we can see that a real register is going to
39 40
            be used soon, then don't use it for allocation).

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
        (b) For each real register clobbered by this instruction:
            If a temporary resides in it,
                If the temporary is live after this instruction,
                    Move the temporary to another (non-clobbered & free) reg,
                    or spill it to memory.  Mark the temporary as residing
                    in both memory and a register if it was spilled (it might
                    need to be read by this instruction).

            (ToDo: this is wrong for jump instructions?)

            We do this after step (a), because if we start with
               movq v1, %rsi
            which is an instruction that clobbers %rsi, if v1 currently resides
            in %rsi we want to get
               movq %rsi, %freereg
               movq %rsi, %rsi     -- will disappear
            instead of
               movq %rsi, %freereg
               movq %freereg, %rsi

61
        (c) Update the current assignment
62

63 64 65 66 67 68 69
        (d) If the instruction is a branch:
              if the destination block already has a register assignment,
                Generate a new block with fixup code and redirect the
                jump to the new block.
              else,
                Update the block id->assignment mapping with the current
                assignment.
70

71 72
        (e) Delete all register assignments for temps which are read
            (only) and die here.  Update the free register list.
73

74 75 76
        (f) Mark all registers clobbered by this instruction as not free,
            and mark temporaries which have been spilled due to clobbering
            as in memory (step (a) marks then as in both mem & reg).
77

78 79 80 81 82 83
        (g) For each temporary *written* by this instruction:
            Allocate a real register as for (b), spilling something
            else if necessary.
                - except when updating the assignment, drop any memory
                  locations that the temporary was previously in, since
                  they will be no longer valid after this instruction.
84

85 86 87
        (h) Delete all register assignments for temps which are
            written and die here (there should rarely be any).  Update
            the free register list.
88

89
        (i) Rewrite the instruction with the new mapping.
90

91 92
        (j) For each spilled reg known to be now dead, re-add its stack slot
            to the free list.
93 94 95

-}

96
module RegAlloc.Linear.Main (
97 98 99
        regAlloc,
        module  RegAlloc.Linear.Base,
        module  RegAlloc.Linear.Stats
100 101 102 103
  ) where

#include "HsVersions.h"

104

105 106
import GhcPrelude

107 108 109 110 111
import RegAlloc.Linear.State
import RegAlloc.Linear.Base
import RegAlloc.Linear.StackMap
import RegAlloc.Linear.FreeRegs
import RegAlloc.Linear.Stats
112
import RegAlloc.Linear.JoinToTargets
ian@well-typed.com's avatar
ian@well-typed.com committed
113 114 115 116
import qualified RegAlloc.Linear.PPC.FreeRegs    as PPC
import qualified RegAlloc.Linear.SPARC.FreeRegs  as SPARC
import qualified RegAlloc.Linear.X86.FreeRegs    as X86
import qualified RegAlloc.Linear.X86_64.FreeRegs as X86_64
117
import TargetReg
118
import RegAlloc.Liveness
119 120
import Instruction
import Reg
121

122
import BlockId
123
import Hoopl.Collections
124
import Cmm hiding (RegSet)
125 126

import Digraph
127
import DynFlags
128
import Unique
129
import UniqSet
130
import UniqFM
131
import UniqSupply
132
import Outputable
John Ericson's avatar
John Ericson committed
133
import GHC.Platform
134

135 136 137
import Data.Maybe
import Data.List
import Control.Monad
138 139 140 141

-- -----------------------------------------------------------------------------
-- Top level of the register allocator

142
-- Allocate registers
143
regAlloc
Ian Lynagh's avatar
Ian Lynagh committed
144
        :: (Outputable instr, Instruction instr)
145
        => DynFlags
Simon Peyton Jones's avatar
Simon Peyton Jones committed
146
        -> LiveCmmDecl statics instr
147 148 149
        -> UniqSM ( NatCmmDecl statics instr
                  , Maybe Int  -- number of extra stack slots required,
                               -- beyond maxSpillSlots
150 151
                  , Maybe RegAllocStats
                  )
152

153
regAlloc _ (CmmData sec d)
154 155
        = return
                ( CmmData sec d
156
                , Nothing
157 158
                , Nothing )

159 160
regAlloc _ (CmmProc (LiveInfo info _ _ _) lbl live [])
        = return ( CmmProc info lbl live (ListGraph [])
161
                 , Nothing
162 163
                 , Nothing )

164
regAlloc dflags (CmmProc static lbl live sccs)
165
        | LiveInfo info entry_ids@(first_id:_) block_live _ <- static
166 167
        = do
                -- do register allocation on each component.
168
                (final_blocks, stats, stack_use)
169
                        <- linearRegAlloc dflags entry_ids block_live sccs
170 171 172 173 174 175

                -- make sure the block that was first in the input list
                --      stays at the front of the output
                let ((first':_), rest')
                                = partition ((== first_id) . blockId) final_blocks

176 177 178 179 180 181 182
                let max_spill_slots = maxSpillSlots dflags
                    extra_stack
                      | stack_use > max_spill_slots
                      = Just (stack_use - max_spill_slots)
                      | otherwise
                      = Nothing

183
                return  ( CmmProc info lbl live (ListGraph (first' : rest'))
184
                        , extra_stack
185 186
                        , Just stats)

Ben.Lippmeier@anu.edu.au's avatar
Ben.Lippmeier@anu.edu.au committed
187
-- bogus. to make non-exhaustive match warning go away.
188
regAlloc _ (CmmProc _ _ _ _)
189
        = panic "RegAllocLinear.regAlloc: no match"
190

191

192 193 194
-- -----------------------------------------------------------------------------
-- Linear sweep to allocate registers

195 196

-- | Do register allocation on some basic blocks.
197 198
--   But be careful to allocate a block in an SCC only if it has
--   an entry in the block map or it is the first block.
199
--
200
linearRegAlloc
Ian Lynagh's avatar
Ian Lynagh committed
201
        :: (Outputable instr, Instruction instr)
202
        => DynFlags
203 204 205 206 207
        -> [BlockId] -- ^ entry points
        -> BlockMap RegSet
              -- ^ live regs on entry to each basic block
        -> [SCC (LiveBasicBlock instr)]
              -- ^ instructions annotated with "deaths"
208
        -> UniqSM ([NatBasicBlock instr], RegAllocStats, Int)
209

210
linearRegAlloc dflags entry_ids block_live sccs
211 212 213 214
 = case platformArch platform of
      ArchX86        -> go $ (frInitFreeRegs platform :: X86.FreeRegs)
      ArchX86_64     -> go $ (frInitFreeRegs platform :: X86_64.FreeRegs)
      ArchSPARC      -> go $ (frInitFreeRegs platform :: SPARC.FreeRegs)
215
      ArchSPARC64    -> panic "linearRegAlloc ArchSPARC64"
216 217 218
      ArchPPC        -> go $ (frInitFreeRegs platform :: PPC.FreeRegs)
      ArchARM _ _ _  -> panic "linearRegAlloc ArchARM"
      ArchARM64      -> panic "linearRegAlloc ArchARM64"
219
      ArchPPC_64 _   -> go $ (frInitFreeRegs platform :: PPC.FreeRegs)
220 221 222
      ArchAlpha      -> panic "linearRegAlloc ArchAlpha"
      ArchMipseb     -> panic "linearRegAlloc ArchMipseb"
      ArchMipsel     -> panic "linearRegAlloc ArchMipsel"
thoughtpolice's avatar
thoughtpolice committed
223
      ArchJavaScript -> panic "linearRegAlloc ArchJavaScript"
224 225 226 227
      ArchUnknown    -> panic "linearRegAlloc ArchUnknown"
 where
  go f = linearRegAlloc' dflags f entry_ids block_live sccs
  platform = targetPlatform dflags
228 229

linearRegAlloc'
Ian Lynagh's avatar
Ian Lynagh committed
230
        :: (FR freeRegs, Outputable instr, Instruction instr)
231
        => DynFlags
232
        -> freeRegs
233
        -> [BlockId]                    -- ^ entry points
234 235
        -> BlockMap RegSet              -- ^ live regs on entry to each basic block
        -> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths"
236
        -> UniqSM ([NatBasicBlock instr], RegAllocStats, Int)
237

238
linearRegAlloc' dflags initFreeRegs entry_ids block_live sccs
239
 = do   us      <- getUniqueSupplyM
240
        let (_, stack, stats, blocks) =
241
                runR dflags mapEmpty initFreeRegs emptyRegMap (emptyStackMap dflags) us
242
                    $ linearRA_SCCs entry_ids block_live [] sccs
243
        return  (blocks, stats, getStackUse stack)
244

245

Ian Lynagh's avatar
Ian Lynagh committed
246
linearRA_SCCs :: (FR freeRegs, Instruction instr, Outputable instr)
247
              => [BlockId]
248 249 250
              -> BlockMap RegSet
              -> [NatBasicBlock instr]
              -> [SCC (LiveBasicBlock instr)]
251
              -> RegM freeRegs [NatBasicBlock instr]
252

253
linearRA_SCCs _ _ blocksAcc []
254
        = return $ reverse blocksAcc
255

256
linearRA_SCCs entry_ids block_live blocksAcc (AcyclicSCC block : sccs)
257
 = do   blocks' <- processBlock block_live block
258
        linearRA_SCCs entry_ids block_live
259 260
                ((reverse blocks') ++ blocksAcc)
                sccs
261

262
linearRA_SCCs entry_ids block_live blocksAcc (CyclicSCC blocks : sccs)
263
 = do
264 265
        blockss' <- process entry_ids block_live blocks [] (return []) False
        linearRA_SCCs entry_ids block_live
266 267
                (reverse (concat blockss') ++ blocksAcc)
                sccs
268 269 270

{- from John Dias's patch 2008/10/16:
   The linear-scan allocator sometimes allocates a block
271
   before allocating one of its predecessors, which could lead to
272 273 274 275 276
   inconsistent allocations. Make it so a block is only allocated
   if a predecessor has set the "incoming" assignments for the block, or
   if it's the procedure's entry block.

   BL 2009/02: Careful. If the assignment for a block doesn't get set for
277
   some reason then this function will loop. We should probably do some
278 279
   more sanity checking to guard against this eventuality.
-}
280

Ian Lynagh's avatar
Ian Lynagh committed
281
process :: (FR freeRegs, Instruction instr, Outputable instr)
282
        => [BlockId]
283 284 285 286 287
        -> BlockMap RegSet
        -> [GenBasicBlock (LiveInstr instr)]
        -> [GenBasicBlock (LiveInstr instr)]
        -> [[NatBasicBlock instr]]
        -> Bool
288
        -> RegM freeRegs [[NatBasicBlock instr]]
289

290
process _ _ [] []         accum _
291
        = return $ reverse accum
292

293
process entry_ids block_live [] next_round accum madeProgress
294 295 296 297 298 299 300 301 302
        | not madeProgress

          {- BUGS: There are so many unreachable blocks in the code the warnings are overwhelming.
             pprTrace "RegAlloc.Linear.Main.process: no progress made, bailing out."
                (  text "Unreachable blocks:"
                $$ vcat (map ppr next_round)) -}
        = return $ reverse accum

        | otherwise
303
        = process entry_ids block_live
304 305
                  next_round [] accum False

306
process entry_ids block_live (b@(BasicBlock id _) : blocks)
307 308 309 310 311
        next_round accum madeProgress
 = do
        block_assig <- getBlockAssigR

        if isJust (mapLookup id block_assig)
312
             || id `elem` entry_ids
313
         then do
314
                b'  <- processBlock block_live b
315
                process entry_ids block_live blocks
316
                        next_round (b' : accum) True
317

318
         else   process entry_ids block_live blocks
319
                        (b : next_round) accum madeProgress
320

321 322 323 324

-- | Do register allocation on this basic block
--
processBlock
Ian Lynagh's avatar
Ian Lynagh committed
325
        :: (FR freeRegs, Outputable instr, Instruction instr)
326
        => BlockMap RegSet              -- ^ live regs on entry to each basic block
327
        -> LiveBasicBlock instr         -- ^ block to do register allocation on
328
        -> RegM freeRegs [NatBasicBlock instr]   -- ^ block with registers allocated
329

330 331
processBlock block_live (BasicBlock id instrs)
 = do   initBlock id block_live
332
        (instrs', fixups)
333
                <- linearRA block_live [] [] id instrs
334
        return  $ BasicBlock id instrs' : fixups
335 336 337


-- | Load the freeregs and current reg assignment into the RegM state
338
--      for the basic block with this BlockId.
339
initBlock :: FR freeRegs
340 341 342 343 344
          => BlockId -> BlockMap RegSet -> RegM freeRegs ()
initBlock id block_live
 = do   dflags <- getDynFlags
        let platform = targetPlatform dflags
        block_assig     <- getBlockAssigR
345
        case mapLookup id block_assig of
346 347 348 349 350
                -- no prior info about this block: we must consider
                -- any fixed regs to be allocated, but we can ignore
                -- virtual regs (presumably this is part of a loop,
                -- and we'll iterate again).  The assignment begins
                -- empty.
351 352
                Nothing
                 -> do  -- pprTrace "initFreeRegs" (text $ show initFreeRegs) (return ())
353 354
                        case mapLookup id block_live of
                          Nothing ->
355
                            setFreeRegsR    (frInitFreeRegs platform)
356
                          Just live ->
357
                            setFreeRegsR $ foldl' (flip $ frAllocateReg platform) (frInitFreeRegs platform)
David Feuer's avatar
David Feuer committed
358
                                                  [ r | RegReal r <- nonDetEltsUniqSet live ]
niteria's avatar
niteria committed
359
                            -- See Note [Unique Determinism and code generation]
360 361 362 363 364 365
                        setAssigR       emptyRegMap

                -- load info about register assignments leading into this block.
                Just (freeregs, assig)
                 -> do  setFreeRegsR    freeregs
                        setAssigR       assig
366 367


368
-- | Do allocation for a sequence of instructions.
369
linearRA
Ian Lynagh's avatar
Ian Lynagh committed
370
        :: (FR freeRegs, Outputable instr, Instruction instr)
371
        => BlockMap RegSet                      -- ^ map of what vregs are live on entry to each block.
372 373 374 375
        -> [instr]                              -- ^ accumulator for instructions already processed.
        -> [NatBasicBlock instr]                -- ^ accumulator for blocks of fixup code.
        -> BlockId                              -- ^ id of the current block, for debugging.
        -> [LiveInstr instr]                    -- ^ liveness annotated instructions in this block.
376

377
        -> RegM freeRegs
378
                ( [instr]                       --   instructions after register allocation
379
                , [NatBasicBlock instr])        --   fresh blocks of fixup code.
380

381

382
linearRA _          accInstr accFixup _ []
383 384 385
        = return
                ( reverse accInstr              -- instrs need to be returned in the correct order.
                , accFixup)                     -- it doesn't matter what order the fixup blocks are returned in.
386 387


388
linearRA block_live accInstr accFixups id (instr:instrs)
389
 = do
390
        (accInstr', new_fixups) <- raInsn block_live accInstr id instr
391

392
        linearRA block_live accInstr' (new_fixups ++ accFixups) id instrs
393 394


395
-- | Do allocation for a single instruction.
396
raInsn
Ian Lynagh's avatar
Ian Lynagh committed
397
        :: (FR freeRegs, Outputable instr, Instruction instr)
398
        => BlockMap RegSet                      -- ^ map of what vregs are love on entry to each block.
399 400 401
        -> [instr]                              -- ^ accumulator for instructions already processed.
        -> BlockId                              -- ^ the id of the current block, for debugging
        -> LiveInstr instr                      -- ^ the instr to have its regs allocated, with liveness info.
402
        -> RegM freeRegs
403 404
                ( [instr]                       -- new instructions
                , [NatBasicBlock instr])        -- extra fixup blocks
405

406
raInsn _     new_instrs _ (LiveInstr ii Nothing)
407 408 409 410
        | Just n        <- takeDeltaInstr ii
        = do    setDeltaR n
                return (new_instrs, [])

411
raInsn _     new_instrs _ (LiveInstr ii@(Instr i) Nothing)
412
        | isMetaInstr ii
413
        = return (i : new_instrs, [])
414

415

416
raInsn block_live new_instrs id (LiveInstr (Instr instr) (Just live))
417
 = do
418 419 420 421
    assig    <- getAssigR

    -- If we have a reg->reg move between virtual registers, where the
    -- src register is not live after this instruction, and the dst
422 423 424
    -- register does not already have an assignment,
    -- and the source register is assigned to a register, not to a spill slot,
    -- then we can eliminate the instruction.
425
    -- (we can't eliminate it if the source register is on the stack, because
426
    --  we do not want to use one spill slot for different virtual registers)
427
    case takeRegRegMoveInstr instr of
428 429 430
        Just (src,dst)  | src `elementOfUniqSet` (liveDieRead live),
                          isVirtualReg dst,
                          not (dst `elemUFM` assig),
431
                          isRealReg src || isInReg src assig -> do
432 433 434 435 436 437 438 439 440 441 442
           case src of
              (RegReal rr) -> setAssigR (addToUFM assig dst (InReg rr))
                -- if src is a fixed reg, then we just map dest to this
                -- reg in the assignment.  src must be an allocatable reg,
                -- otherwise it wouldn't be in r_dying.
              _virt -> case lookupUFM assig src of
                         Nothing -> panic "raInsn"
                         Just loc ->
                           setAssigR (addToUFM (delFromUFM assig src) dst loc)

           -- we have eliminated this instruction
443
          {-
444 445 446 447
          freeregs <- getFreeRegsR
          assig <- getAssigR
          pprTrace "raInsn" (text "ELIMINATED: " <> docToSDoc (pprInstr instr)
                        $$ ppr r_dying <+> ppr w_dying $$ text (show freeregs) $$ ppr assig) $ do
448
          -}
449
           return (new_instrs, [])
450

451
        _ -> genRaInsn block_live new_instrs id instr
David Feuer's avatar
David Feuer committed
452 453
                        (nonDetEltsUniqSet $ liveDieRead live)
                        (nonDetEltsUniqSet $ liveDieWrite live)
niteria's avatar
niteria committed
454
                        -- See Note [Unique Determinism and code generation]
455

456
raInsn _ _ _ instr
Ian Lynagh's avatar
Ian Lynagh committed
457
        = pprPanic "raInsn" (text "no match for:" <> ppr instr)
458

459 460 461 462 463 464 465 466 467 468 469 470
-- ToDo: what can we do about
--
--     R1 = x
--     jump I64[x] // [R1]
--
-- where x is mapped to the same reg as R1.  We want to coalesce x and
-- R1, but the register allocator doesn't know whether x will be
-- assigned to again later, in which case x and R1 should be in
-- different registers.  Right now we assume the worst, and the
-- assignment to R1 will clobber x, so we'll spill x into another reg,
-- generating another reg->reg move.

471

472 473 474 475 476
isInReg :: Reg -> RegMap Loc -> Bool
isInReg src assig | Just (InReg _) <- lookupUFM assig src = True
                  | otherwise = False


Ian Lynagh's avatar
Ian Lynagh committed
477
genRaInsn :: (FR freeRegs, Instruction instr, Outputable instr)
478
          => BlockMap RegSet
479 480 481 482 483
          -> [instr]
          -> BlockId
          -> instr
          -> [Reg]
          -> [Reg]
484
          -> RegM freeRegs ([instr], [NatBasicBlock instr])
485

486 487 488 489
genRaInsn block_live new_instrs block_id instr r_dying w_dying = do
  dflags <- getDynFlags
  let platform = targetPlatform dflags
  case regUsageOfInstr platform instr of { RU read written ->
490
    do
491 492
    let real_written    = [ rr  | (RegReal     rr) <- written ]
    let virt_written    = [ vr  | (RegVirtual  vr) <- written ]
493

494 495 496
    -- we don't need to do anything with real registers that are
    -- only read by this instr.  (the list is typically ~2 elements,
    -- so using nub isn't a problem).
497
    let virt_read       = nub [ vr      | (RegVirtual vr) <- read ]
498

499
    -- debugging
500
{-    freeregs <- getFreeRegsR
501
    assig    <- getAssigR
Moritz Angermann's avatar
Moritz Angermann committed
502
    pprDebugAndThen (defaultDynFlags Settings{ sTargetPlatform=platform } undefined) trace "genRaInsn"
503 504 505 506 507 508 509 510
        (ppr instr
                $$ text "r_dying      = " <+> ppr r_dying
                $$ text "w_dying      = " <+> ppr w_dying
                $$ text "virt_read    = " <+> ppr virt_read
                $$ text "virt_written = " <+> ppr virt_written
                $$ text "freeregs     = " <+> text (show freeregs)
                $$ text "assig        = " <+> ppr assig)
        $ do
511
-}
512

513
    -- (a), (b) allocate real regs for all regs read by this instruction.
514
    (r_spills, r_allocd) <-
515
        allocateRegsAndSpill True{-reading-} virt_read [] [] virt_read
516

Simon Marlow's avatar
Simon Marlow committed
517
    -- (c) save any temporaries which will be clobbered by this instruction
518
    clobber_saves <- saveClobberedTemps real_written r_dying
519

520 521 522 523 524
    -- (d) Update block map for new destinations
    -- NB. do this before removing dead regs from the assignment, because
    -- these dead regs might in fact be live in the jump targets (they're
    -- only dead in the code that follows in the current basic block).
    (fixup_blocks, adjusted_instr)
525
        <- joinToTargets block_live block_id instr
526

527 528 529 530 531
    -- Debugging - show places where the reg alloc inserted
    -- assignment fixup blocks.
    -- when (not $ null fixup_blocks) $
    --    pprTrace "fixup_blocks" (ppr fixup_blocks) (return ())

532 533
    -- (e) Delete all register assignments for temps which are read
    --     (only) and die here.  Update the free register list.
534
    releaseRegs r_dying
535 536

    -- (f) Mark regs which are clobbered as unallocatable
537
    clobberRegs real_written
538 539

    -- (g) Allocate registers for temporaries *written* (only)
540
    (w_spills, w_allocd) <-
541
        allocateRegsAndSpill False{-writing-} virt_written [] [] virt_written
542 543 544

    -- (h) Release registers for temps which are written here and not
    -- used again.
545
    releaseRegs w_dying
546 547

    let
548 549 550 551 552 553
        -- (i) Patch the instruction
        patch_map
                = listToUFM
                        [ (t, RegReal r)
                                | (t, r) <- zip virt_read    r_allocd
                                         ++ zip virt_written w_allocd ]
554

555 556
        patched_instr
                = patchRegsOfInstr adjusted_instr patchLookup
557

558 559 560 561
        patchLookup x
                = case lookupUFM patch_map x of
                        Nothing -> x
                        Just y  -> y
562 563 564 565 566


    -- (j) free up stack slots for dead spilled regs
    -- TODO (can't be bothered right now)

567
    -- erase reg->reg moves where the source and destination are the same.
568 569 570 571 572 573
    --  If the src temp didn't die in this instr but happened to be allocated
    --  to the same real reg as the destination, then we can erase the move anyway.
    let squashed_instr  = case takeRegRegMoveInstr patched_instr of
                                Just (src, dst)
                                 | src == dst   -> []
                                _               -> [patched_instr]
574

575
    let code = squashed_instr ++ w_spills ++ reverse r_spills
576
                ++ clobber_saves ++ new_instrs
577 578 579 580 581 582

--    pprTrace "patched-code" ((vcat $ map (docToSDoc . pprInstr) code)) $ do
--    pprTrace "pached-fixup" ((ppr fixup_blocks)) $ do

    return (code, fixup_blocks)

583
  }
584 585 586 587

-- -----------------------------------------------------------------------------
-- releaseRegs

588 589 590 591
releaseRegs :: FR freeRegs => [Reg] -> RegM freeRegs ()
releaseRegs regs = do
  dflags <- getDynFlags
  let platform = targetPlatform dflags
592 593
  assig <- getAssigR
  free <- getFreeRegsR
594 595 596
  let loop assig !free [] = do setAssigR assig; setFreeRegsR free; return ()
      loop assig !free (RegReal rr : rs) = loop assig (frReleaseReg platform rr free) rs
      loop assig !free (r:rs) =
597 598 599 600 601 602
         case lookupUFM assig r of
         Just (InBoth real _) -> loop (delFromUFM assig r)
                                      (frReleaseReg platform real free) rs
         Just (InReg real)    -> loop (delFromUFM assig r)
                                      (frReleaseReg platform real free) rs
         _                    -> loop (delFromUFM assig r) free rs
603
  loop assig free regs
604

605

606 607 608
-- -----------------------------------------------------------------------------
-- Clobber real registers

609
-- For each temp in a register that is going to be clobbered:
610 611 612 613 614
--      - if the temp dies after this instruction, do nothing
--      - otherwise, put it somewhere safe (another reg if possible,
--              otherwise spill and record InBoth in the assignment).
--      - for allocateRegs on the temps *read*,
--      - clobbered regs are allocatable.
615
--
616 617
--      for allocateRegs on the temps *written*,
--        - clobbered regs are not allocatable.
618
--
619 620

saveClobberedTemps
621
        :: (Instruction instr, FR freeRegs)
622
        => [RealReg]            -- real registers clobbered by this instruction
623
        -> [Reg]                -- registers which are no longer live after this insn
624
        -> RegM freeRegs [instr]         -- return: instructions to spill any temps that will
625
                                -- be clobbered.
626

627
saveClobberedTemps [] _
628
        = return []
629

630
saveClobberedTemps clobbered dying
631
 = do
632 633 634
        assig   <- getAssigR
        let to_spill
                = [ (temp,reg)
niteria's avatar
niteria committed
635 636 637 638
                        | (temp, InReg reg) <- nonDetUFMToList assig
                        -- This is non-deterministic but we do not
                        -- currently support deterministic code-generation.
                        -- See Note [Unique Determinism and code generation]
639 640
                        , any (realRegsAlias reg) clobbered
                        , temp `notElem` map getUnique dying  ]
641

642 643 644
        (instrs,assig') <- clobber assig [] to_spill
        setAssigR assig'
        return instrs
645 646

   where
647 648 649 650
     clobber assig instrs []
            = return (instrs, assig)

     clobber assig instrs ((temp, reg) : rest)
651 652 653
       = do dflags <- getDynFlags
            let platform = targetPlatform dflags

654 655
            freeRegs <- getFreeRegsR
            let regclass = targetClassOfRealReg platform reg
656
                freeRegs_thisClass = frGetFreeRegs platform regclass freeRegs
657 658 659 660 661 662 663

            case filter (`notElem` clobbered) freeRegs_thisClass of

              -- (1) we have a free reg of the right class that isn't
              -- clobbered by this instruction; use it to save the
              -- clobbered value.
              (my_reg : _) -> do
664
                  setFreeRegsR (frAllocateReg platform my_reg freeRegs)
665 666 667 668 669 670 671 672 673

                  let new_assign = addToUFM assig temp (InReg my_reg)
                  let instr = mkRegRegMoveInstr platform
                                  (RegReal reg) (RegReal my_reg)

                  clobber new_assign (instr : instrs) rest

              -- (2) no free registers: spill the value
              [] -> do
674
                  (spill, slot)   <- spillR (RegReal reg) temp
675

676 677
                  -- record why this reg was spilled for profiling
                  recordSpill (SpillClobber temp)
678

679
                  let new_assign  = addToUFM assig temp (InBoth reg slot)
680

681
                  clobber new_assign (spill : instrs) rest
682 683 684



685
-- | Mark all these real regs as allocated,
686
--      and kick out their vreg assignments.
687
--
688 689
clobberRegs :: FR freeRegs => [RealReg] -> RegM freeRegs ()
clobberRegs []
690
        = return ()
691

692 693 694 695
clobberRegs clobbered
 = do   dflags <- getDynFlags
        let platform = targetPlatform dflags

696
        freeregs        <- getFreeRegsR
697
        setFreeRegsR $! foldl' (flip $ frAllocateReg platform) freeregs clobbered
698

699
        assig           <- getAssigR
niteria's avatar
niteria committed
700 701 702 703
        setAssigR $! clobber assig (nonDetUFMToList assig)
          -- This is non-deterministic but we do not
          -- currently support deterministic code-generation.
          -- See Note [Unique Determinism and code generation]
704 705

   where
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
        -- if the temp was InReg and clobbered, then we will have
        -- saved it in saveClobberedTemps above.  So the only case
        -- we have to worry about here is InBoth.  Note that this
        -- also catches temps which were loaded up during allocation
        -- of read registers, not just those saved in saveClobberedTemps.

        clobber assig []
                = assig

        clobber assig ((temp, InBoth reg slot) : rest)
                | any (realRegsAlias reg) clobbered
                = clobber (addToUFM assig temp (InMem slot)) rest

        clobber assig (_:rest)
                = clobber assig rest
721 722 723 724

-- -----------------------------------------------------------------------------
-- allocateRegsAndSpill

725 726 727 728 729 730 731 732 733 734
-- Why are we performing a spill?
data SpillLoc = ReadMem StackSlot  -- reading from register only in memory
              | WriteNew           -- writing to a new variable
              | WriteMem           -- writing to register only in memory
-- Note that ReadNew is not valid, since you don't want to be reading
-- from an uninitialized register.  We also don't need the location of
-- the register in memory, since that will be invalidated by the write.
-- Technically, we could coalesce WriteNew and WriteMem into a single
-- entry as well. -- EZY

735 736 737 738 739 740 741 742
-- This function does several things:
--   For each temporary referred to by this instruction,
--   we allocate a real register (spilling another temporary if necessary).
--   We load the temporary up from memory if necessary.
--   We also update the register assignment in the process, and
--   the list of free registers and free stack slots.

allocateRegsAndSpill
Ian Lynagh's avatar
Ian Lynagh committed
743
        :: (FR freeRegs, Outputable instr, Instruction instr)
744
        => Bool                 -- True <=> reading (load up spilled regs)
745 746 747 748
        -> [VirtualReg]         -- don't push these out
        -> [instr]              -- spill insns
        -> [RealReg]            -- real registers allocated (accum.)
        -> [VirtualReg]         -- temps to allocate
749
        -> RegM freeRegs ( [instr] , [RealReg])
750

751
allocateRegsAndSpill _       _    spills alloc []
752 753
        = return (spills, reverse alloc)

754
allocateRegsAndSpill reading keep spills alloc (r:rs)
755
 = do   assig <- getAssigR
756
        let doSpill = allocRegsAndSpill_spill reading keep spills alloc r rs assig
757 758 759
        case lookupUFM assig r of
                -- case (1a): already in a register
                Just (InReg my_reg) ->
760
                        allocateRegsAndSpill reading keep spills (my_reg:alloc) rs
761 762 763 764 765 766 767 768

                -- case (1b): already in a register (and memory)
                -- NB1. if we're writing this register, update its assignment to be
                -- InReg, because the memory value is no longer valid.
                -- NB2. This is why we must process written registers here, even if they
                -- are also read by the same instruction.
                Just (InBoth my_reg _)
                 -> do  when (not reading) (setAssigR (addToUFM assig r (InReg my_reg)))
769
                        allocateRegsAndSpill reading keep spills (my_reg:alloc) rs
770 771 772 773

                -- Not already in a register, so we need to find a free one...
                Just (InMem slot) | reading   -> doSpill (ReadMem slot)
                                  | otherwise -> doSpill WriteMem
774
                Nothing | reading   ->
775 776 777 778 779 780 781
                   pprPanic "allocateRegsAndSpill: Cannot read from uninitialized register" (ppr r)
                   -- NOTE: if the input to the NCG contains some
                   -- unreachable blocks with junk code, this panic
                   -- might be triggered.  Make sure you only feed
                   -- sensible code into the NCG.  In CmmPipeline we
                   -- call removeUnreachableBlocks at the end for this
                   -- reason.
782

783 784
                        | otherwise -> doSpill WriteNew

785

786 787
-- reading is redundant with reason, but we keep it around because it's
-- convenient and it maintains the recursive structure of the allocator. -- EZY
Ian Lynagh's avatar
Ian Lynagh committed
788
allocRegsAndSpill_spill :: (FR freeRegs, Instruction instr, Outputable instr)
789
                        => Bool
790 791 792 793 794 795 796
                        -> [VirtualReg]
                        -> [instr]
                        -> [RealReg]
                        -> VirtualReg
                        -> [VirtualReg]
                        -> UniqFM Loc
                        -> SpillLoc
797
                        -> RegM freeRegs ([instr], [RealReg])
798 799 800
allocRegsAndSpill_spill reading keep spills alloc r rs assig spill_loc
 = do   dflags <- getDynFlags
        let platform = targetPlatform dflags
801
        freeRegs                <- getFreeRegsR
802
        let freeRegs_thisClass  = frGetFreeRegs platform (classOfVirtualReg r) freeRegs
803 804 805

        case freeRegs_thisClass of

806 807
         -- case (2): we have a free register
         (my_reg : _) ->
808
           do   spills'   <- loadTemp r spill_loc my_reg spills
809 810

                setAssigR       (addToUFM assig r $! newLocation spill_loc my_reg)
811
                setFreeRegsR $  frAllocateReg platform my_reg freeRegs
812

813
                allocateRegsAndSpill reading keep spills' (my_reg : alloc) rs
814 815 816 817


          -- case (3): we need to push something out to free up a register
         [] ->
818 819 820 821 822 823 824 825 826 827 828
           do   let inRegOrBoth (InReg _) = True
                    inRegOrBoth (InBoth _ _) = True
                    inRegOrBoth _ = False
                let candidates' =
                      flip delListFromUFM keep $
                      filterUFM inRegOrBoth $
                      assig
                      -- This is non-deterministic but we do not
                      -- currently support deterministic code-generation.
                      -- See Note [Unique Determinism and code generation]
                let candidates = nonDetUFMToList candidates'
829 830 831 832

                -- the vregs we could kick out that are already in a slot
                let candidates_inBoth
                        = [ (temp, reg, mem)
833
                          | (temp, InBoth reg mem) <- candidates
niteria's avatar
niteria committed
834
                          , targetClassOfRealReg platform reg == classOfVirtualReg r ]
835 836 837 838 839

                -- the vregs we could kick out that are only in a reg
                --      this would require writing the reg to a new slot before using it.
                let candidates_inReg
                        = [ (temp, reg)
840
                          | (temp, InReg reg) <- candidates
niteria's avatar
niteria committed
841
                          , targetClassOfRealReg platform reg == classOfVirtualReg r ]
842 843 844 845 846 847

                let result

                        -- we have a temporary that is in both register and mem,
                        -- just free up its register for use.
                        | (temp, my_reg, slot) : _      <- candidates_inBoth
848
                        = do    spills' <- loadTemp r spill_loc my_reg spills
849 850 851 852
                                let assig1  = addToUFM assig temp (InMem slot)
                                let assig2  = addToUFM assig1 r $! newLocation spill_loc my_reg

                                setAssigR assig2
853
                                allocateRegsAndSpill reading keep spills' (my_reg:alloc) rs
854 855 856 857 858 859

                        -- otherwise, we need to spill a temporary that currently
                        -- resides in a register.
                        | (temp_to_push_out, (my_reg :: RealReg)) : _
                                        <- candidates_inReg
                        = do
860
                                (spill_insn, slot) <- spillR (RegReal my_reg) temp_to_push_out
861 862 863 864 865 866 867 868 869 870 871 872 873
                                let spill_store  = (if reading then id else reverse)
                                                        [ -- COMMENT (fsLit "spill alloc")
                                                           spill_insn ]

                                -- record that this temp was spilled
                                recordSpill (SpillAlloc temp_to_push_out)

                                -- update the register assignment
                                let assig1  = addToUFM assig temp_to_push_out   (InMem slot)
                                let assig2  = addToUFM assig1 r                 $! newLocation spill_loc my_reg
                                setAssigR assig2

                                -- if need be, load up a spilled temp into the reg we've just freed up.
874
                                spills' <- loadTemp r spill_loc my_reg spills
875

876
                                allocateRegsAndSpill reading keep
877 878 879 880 881 882 883 884 885
                                        (spill_store ++ spills')
                                        (my_reg:alloc) rs


                        -- there wasn't anything to spill, so we're screwed.
                        | otherwise
                        = pprPanic ("RegAllocLinear.allocRegsAndSpill: no spill candidates\n")
                        $ vcat
                                [ text "allocating vreg:  " <> text (show r)
niteria's avatar
niteria committed
886
                                , text "assignment:       " <> ppr assig
887
                                , text "freeRegs:         " <> text (show freeRegs)
888
                                , text "initFreeRegs:     " <> text (show (frInitFreeRegs platform `asTypeOf` freeRegs)) ]
889 890 891

                result

892

893 894 895 896 897 898 899 900
-- | Calculate a new location after a register has been loaded.
newLocation :: SpillLoc -> RealReg -> Loc
-- if the tmp was read from a slot, then now its in a reg as well
newLocation (ReadMem slot) my_reg = InBoth my_reg slot
-- writes will always result in only the register being available
newLocation _ my_reg = InReg my_reg

-- | Load up a spilled temporary if we need to (read from memory).
901
loadTemp
902
        :: (Instruction instr)
903
        => VirtualReg   -- the temp being loaded
904 905 906
        -> SpillLoc     -- the current location of this temp
        -> RealReg      -- the hreg to load the temp into
        -> [instr]
907
        -> RegM freeRegs [instr]
908

909
loadTemp vreg (ReadMem slot) hreg spills
910
 = do
911
        insn <- loadR (RegReal hreg) slot
912 913
        recordSpill (SpillLoad $ getUnique vreg)
        return  $  {- COMMENT (fsLit "spill load") : -} insn : spills
914

915
loadTemp _ _ _ spills =
916 917
   return spills