Instr.hs 40.7 KB
Newer Older
1 2
{-# LANGUAGE CPP, TypeFamilies #-}

3 4 5 6 7 8 9 10
-----------------------------------------------------------------------------
--
-- Machine-dependent assembly language
--
-- (c) The University of Glasgow 1993-2004
--
-----------------------------------------------------------------------------

11
module X86.Instr (Instr(..), Operand(..), PrefetchVariant(..), JumpDest(..),
12
                  getJumpDestBlockId, canShortcut, shortcutStatics,
13
                  shortcutJump, allocMoreStack,
14
                  maxSpillSlots, archWordFormat )
15 16
where

17 18 19
#include "HsVersions.h"
#include "nativeGen/NCG.h"

20 21
import GhcPrelude

22
import X86.Cond
23
import X86.Regs
24
import Instruction
25
import Format
26 27
import RegClass
import Reg
28
import TargetReg
29 30

import BlockId
31 32
import Hoopl.Collections
import Hoopl.Label
33
import CodeGen.Platform
34
import Cmm
35
import FastString
36
import Outputable
John Ericson's avatar
John Ericson committed
37
import GHC.Platform
38

39
import BasicTypes       (Alignment)
Ben.Lippmeier@anu.edu.au's avatar
Ben.Lippmeier@anu.edu.au committed
40
import CLabel
41
import DynFlags
42 43
import UniqSet
import Unique
44
import UniqSupply
45
import Debug (UnwindTable)
46 47

import Control.Monad
48
import Data.Maybe       (fromMaybe)
Ben.Lippmeier@anu.edu.au's avatar
Ben.Lippmeier@anu.edu.au committed
49

50
-- Format of an x86/x86_64 memory address, in bytes.
51
--
52 53
archWordFormat :: Bool -> Format
archWordFormat is32Bit
Ian Lynagh's avatar
Ian Lynagh committed
54 55
 | is32Bit   = II32
 | otherwise = II64
56 57 58

-- | Instruction instance for x86 instruction set.
instance Instruction Instr where
Ian Lynagh's avatar
Ian Lynagh committed
59 60 61 62 63 64 65 66 67 68 69 70
        regUsageOfInstr         = x86_regUsageOfInstr
        patchRegsOfInstr        = x86_patchRegsOfInstr
        isJumpishInstr          = x86_isJumpishInstr
        jumpDestsOfInstr        = x86_jumpDestsOfInstr
        patchJumpInstr          = x86_patchJumpInstr
        mkSpillInstr            = x86_mkSpillInstr
        mkLoadInstr             = x86_mkLoadInstr
        takeDeltaInstr          = x86_takeDeltaInstr
        isMetaInstr             = x86_isMetaInstr
        mkRegRegMoveInstr       = x86_mkRegRegMoveInstr
        takeRegRegMoveInstr     = x86_takeRegRegMoveInstr
        mkJumpInstr             = x86_mkJumpInstr
71 72
        mkStackAllocInstr       = x86_mkStackAllocInstr
        mkStackDeallocInstr     = x86_mkStackDeallocInstr
73 74 75 76 77 78 79 80 81 82 83 84 85 86


-- -----------------------------------------------------------------------------
-- Intel x86 instructions

{-
Intel, in their infinite wisdom, selected a stack model for floating
point registers on x86.  That might have made sense back in 1979 --
nowadays we can see it for the nonsense it really is.  A stack model
fits poorly with the existing nativeGen infrastructure, which assumes
flat integer and FP register sets.  Prior to this commit, nativeGen
could not generate correct x86 FP code -- to do so would have meant
somehow working the register-stack paradigm into the register
allocator and spiller, which sounds very difficult.
Ian Lynagh's avatar
Ian Lynagh committed
87

88 89 90 91 92 93 94 95 96
We have decided to cheat, and go for a simple fix which requires no
infrastructure modifications, at the expense of generating ropey but
correct FP code.  All notions of the x86 FP stack and its insns have
been removed.  Instead, we pretend (to the instruction selector and
register allocator) that x86 has six floating point registers, %fake0
.. %fake5, which can be used in the usual flat manner.  We further
claim that x86 has floating point instructions very similar to SPARC
and Alpha, that is, a simple 3-operand register-register arrangement.
Code generation and register allocation proceed on this basis.
Ian Lynagh's avatar
Ian Lynagh committed
97

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
When we come to print out the final assembly, our convenient fiction
is converted to dismal reality.  Each fake instruction is
independently converted to a series of real x86 instructions.
%fake0 .. %fake5 are mapped to %st(0) .. %st(5).  To do reg-reg
arithmetic operations, the two operands are pushed onto the top of the
FP stack, the operation done, and the result copied back into the
relevant register.  There are only six %fake registers because 2 are
needed for the translation, and x86 has 8 in total.

The translation is inefficient but is simple and it works.  A cleverer
translation would handle a sequence of insns, simulating the FP stack
contents, would not impose a fixed mapping from %fake to %st regs, and
hopefully could avoid most of the redundant reg-reg moves of the
current translation.

We might as well make use of whatever unique FP facilities Intel have
chosen to bless us with (let's not be churlish, after all).
Hence GLDZ and GLD1.  Bwahahahahahahaha!
-}

{-
Simon Marlow's avatar
Simon Marlow committed
119
Note [x86 Floating point precision]
120 121 122 123 124 125 126 127 128 129 130 131 132

Intel's internal floating point registers are by default 80 bit
extended precision.  This means that all operations done on values in
registers are done at 80 bits, and unless the intermediate values are
truncated to the appropriate size (32 or 64 bits) by storing in
memory, calculations in registers will give different results from
calculations which pass intermediate values in memory (eg. via
function calls).

One solution is to set the FPU into 64 bit precision mode.  Some OSs
do this (eg. FreeBSD) and some don't (eg. Linux).  The problem here is
that this will only affect 64-bit precision arithmetic; 32-bit
calculations will still be done at 64-bit precision in registers.  So
Ian Lynagh's avatar
Ian Lynagh committed
133
it doesn't solve the whole problem.
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

There's also the issue of what the C library is expecting in terms of
precision.  It seems to be the case that glibc on Linux expects the
FPU to be set to 80 bit precision, so setting it to 64 bit could have
unexpected effects.  Changing the default could have undesirable
effects on other 3rd-party library code too, so the right thing would
be to save/restore the FPU control word across Haskell code if we were
to do this.

gcc's -ffloat-store gives consistent results by always storing the
results of floating-point calculations in memory, which works for both
32 and 64-bit precision.  However, it only affects the values of
user-declared floating point variables in C, not intermediate results.
GHC in -fvia-C mode uses -ffloat-store (see the -fexcess-precision
flag).

Another problem is how to spill floating point registers in the
register allocator.  Should we spill the whole 80 bits, or just 64?
On an OS which is set to 64 bit precision, spilling 64 is fine.  On
Linux, spilling 64 bits will round the results of some operations.
This is what gcc does.  Spilling at 80 bits requires taking up a full
128 bit slot (so we get alignment).  We spill at 80-bits and ignore
the alignment problems.

Simon Marlow's avatar
Simon Marlow committed
158 159 160 161 162 163
In the future [edit: now available in GHC 7.0.1, with the -msse2
flag], we'll use the SSE registers for floating point.  This requires
a CPU that supports SSE2 (ordinary SSE only supports 32 bit precision
float ops), which means P4 or Xeon and above.  Using SSE will solve
all these problems, because the SSE registers use fixed 32 bit or 64
bit precision.
164 165 166 167 168

--SDM 1/2003
-}

data Instr
Ian Lynagh's avatar
Ian Lynagh committed
169 170
        -- comment pseudo-op
        = COMMENT FastString
171

172 173 174
        -- location pseudo-op (file, line, col, name)
        | LOCATION Int Int Int String

Ian Lynagh's avatar
Ian Lynagh committed
175 176 177 178
        -- some static data spat out during code
        -- generation.  Will be extracted before
        -- pretty-printing.
        | LDATA   Section (Alignment, CmmStatics)
179

Ian Lynagh's avatar
Ian Lynagh committed
180 181 182 183 184
        -- start a new basic block.  Useful during
        -- codegen, removed later.  Preceding
        -- instruction should be a jump, as per the
        -- invariants for a BasicBlock (see Cmm).
        | NEWBLOCK BlockId
185

186 187
        -- unwinding information
        -- See Note [Unwinding information in the NCG].
188
        | UNWIND CLabel UnwindTable
189 190 191 192

        -- specify current stack offset for benefit of subsequent passes.
        -- This carries a BlockId so it can be used in unwinding information.
        | DELTA  Int
Ian Lynagh's avatar
Ian Lynagh committed
193 194

        -- Moves.
195 196 197 198
        | MOV         Format Operand Operand
        | CMOV   Cond Format Operand Reg
        | MOVZxL      Format Operand Operand -- format is the size of operand 1
        | MOVSxL      Format Operand Operand -- format is the size of operand 1
Ian Lynagh's avatar
Ian Lynagh committed
199 200 201 202 203
        -- x86_64 note: plain mov into a 32-bit register always zero-extends
        -- into the 64-bit reg, in contrast to the 8 and 16-bit movs which
        -- don't affect the high bits of the register.

        -- Load effective address (also a very useful three-operand add instruction :-)
204
        | LEA         Format Operand Operand
Ian Lynagh's avatar
Ian Lynagh committed
205 206

        -- Int Arithmetic.
207 208 209 210
        | ADD         Format Operand Operand
        | ADC         Format Operand Operand
        | SUB         Format Operand Operand
        | SBB         Format Operand Operand
Ian Lynagh's avatar
Ian Lynagh committed
211

212 213 214 215
        | MUL         Format Operand Operand
        | MUL2        Format Operand         -- %edx:%eax = operand * %rax
        | IMUL        Format Operand Operand -- signed int mul
        | IMUL2       Format Operand         -- %edx:%eax = operand * %eax
Ian Lynagh's avatar
Ian Lynagh committed
216

217 218
        | DIV         Format Operand         -- eax := eax:edx/op, edx := eax:edx%op
        | IDIV        Format Operand         -- ditto, but signed
Ian Lynagh's avatar
Ian Lynagh committed
219

220 221 222 223
        -- Int Arithmetic, where the effects on the condition register
        -- are important. Used in specialized sequences such as MO_Add2.
        -- Do not rewrite these instructions to "equivalent" ones that
        -- have different effect on the condition register! (See #9013.)
224 225
        | ADD_CC      Format Operand Operand
        | SUB_CC      Format Operand Operand
226

Ian Lynagh's avatar
Ian Lynagh committed
227
        -- Simple bit-twiddling.
228 229 230 231 232 233
        | AND         Format Operand Operand
        | OR          Format Operand Operand
        | XOR         Format Operand Operand
        | NOT         Format Operand
        | NEGI        Format Operand         -- NEG instruction (name clash with Cond)
        | BSWAP       Format Reg
Ian Lynagh's avatar
Ian Lynagh committed
234 235

        -- Shifts (amount may be immediate or %cl only)
236 237 238
        | SHL         Format Operand{-amount-} Operand
        | SAR         Format Operand{-amount-} Operand
        | SHR         Format Operand{-amount-} Operand
239

240
        | BT          Format Imm Operand
Ian Lynagh's avatar
Ian Lynagh committed
241
        | NOP
242

Ian Lynagh's avatar
Ian Lynagh committed
243

244 245 246 247 248 249 250
        -- We need to support the FSTP (x87 store and pop) instruction
        -- so that we can correctly read off the return value of an
        -- x86 CDECL C function call when its floating point.
        -- so we dont include a register argument, and just use st(0)
        -- this instruction is used ONLY for return values of C ffi calls
        -- in x86_32 abi
        | X87Store         Format  AddrMode -- st(0), dst
251 252


Ian Lynagh's avatar
Ian Lynagh committed
253 254 255
        -- SSE2 floating point: we use a restricted set of the available SSE2
        -- instructions for floating-point.
        -- use MOV for moving (either movss or movsd (movlpd better?))
256 257 258 259 260 261
        | CVTSS2SD      Reg Reg            -- F32 to F64
        | CVTSD2SS      Reg Reg            -- F64 to F32
        | CVTTSS2SIQ    Format Operand Reg -- F32 to I32/I64 (with truncation)
        | CVTTSD2SIQ    Format Operand Reg -- F64 to I32/I64 (with truncation)
        | CVTSI2SS      Format Operand Reg -- I32/I64 to F32
        | CVTSI2SD      Format Operand Reg -- I32/I64 to F64
Ian Lynagh's avatar
Ian Lynagh committed
262

263
        -- use ADD, SUB, and SQRT for arithmetic.  In both cases, operands
Ian Lynagh's avatar
Ian Lynagh committed
264 265 266
        -- are  Operand Reg.

        -- SSE2 floating-point division:
267
        | FDIV          Format Operand Operand   -- divisor, dividend(dst)
Ian Lynagh's avatar
Ian Lynagh committed
268 269 270 271

        -- use CMP for comparisons.  ucomiss and ucomisd instructions
        -- compare single/double prec floating point respectively.

272
        | SQRT          Format Operand Reg      -- src, dst
Ian Lynagh's avatar
Ian Lynagh committed
273 274 275


        -- Comparison
276 277
        | TEST          Format Operand Operand
        | CMP           Format Operand Operand
Ian Lynagh's avatar
Ian Lynagh committed
278 279 280
        | SETCC         Cond Operand

        -- Stack Operations.
281 282
        | PUSH          Format Operand
        | POP           Format Operand
Ian Lynagh's avatar
Ian Lynagh committed
283 284 285 286 287
        -- both unused (SDM):
        --  | PUSHA
        --  | POPA

        -- Jumping around.
288
        | JMP         Operand [Reg] -- including live Regs at the call
Ian Lynagh's avatar
Ian Lynagh committed
289 290 291 292
        | JXX         Cond BlockId  -- includes unconditional branches
        | JXX_GBL     Cond Imm      -- non-local version of JXX
        -- Table jump
        | JMP_TBL     Operand   -- Address to jump to
293
                      [Maybe JumpDest] -- Targets of the jump table
Ian Lynagh's avatar
Ian Lynagh committed
294 295 296 297 298
                      Section   -- Data section jump table should be put in
                      CLabel    -- Label of jump table
        | CALL        (Either Imm Reg) [Reg]

        -- Other things.
299
        | CLTD Format            -- sign extend %eax into %edx:%eax
Ian Lynagh's avatar
Ian Lynagh committed
300 301 302 303 304 305 306 307 308 309 310

        | FETCHGOT    Reg        -- pseudo-insn for ELF position-independent code
                                 -- pretty-prints as
                                 --       call 1f
                                 -- 1:    popl %reg
                                 --       addl __GLOBAL_OFFSET_TABLE__+.-1b, %reg
        | FETCHPC     Reg        -- pseudo-insn for Darwin position-independent code
                                 -- pretty-prints as
                                 --       call 1f
                                 -- 1:    popl %reg

311
    -- bit counting instructions
312
        | POPCNT      Format Operand Reg -- [SSE4.2] count number of bits set to 1
313 314
        | LZCNT       Format Operand Reg -- [BMI2] count number of leading zeros
        | TZCNT       Format Operand Reg -- [BMI2] count number of trailing zeros
315 316
        | BSF         Format Operand Reg -- bit scan forward
        | BSR         Format Operand Reg -- bit scan reverse
317

318 319 320 321
    -- bit manipulation instructions
        | PDEP        Format Operand Operand Reg -- [BMI2] deposit bits to   the specified mask
        | PEXT        Format Operand Operand Reg -- [BMI2] extract bits from the specified mask

322
    -- prefetch
323
        | PREFETCH  PrefetchVariant Format Operand -- prefetch Variant, addr size, address to prefetch
324 325
                                        -- variant can be NTA, Lvl0, Lvl1, or Lvl2

326
        | LOCK        Instr -- lock prefix
327 328
        | XADD        Format Operand Operand -- src (r), dst (r/m)
        | CMPXCHG     Format Operand Operand -- src (r), dst (r/m), eax implicit
329
        | MFENCE
330

331 332
data PrefetchVariant = NTA | Lvl0 | Lvl1 | Lvl2

333 334

data Operand
Ian Lynagh's avatar
Ian Lynagh committed
335 336 337
        = OpReg  Reg            -- register
        | OpImm  Imm            -- immediate value
        | OpAddr AddrMode       -- memory reference
338 339


340

341 342
-- | Returns which registers are read and written as a (read, written)
-- pair.
343 344
x86_regUsageOfInstr :: Platform -> Instr -> RegUsage
x86_regUsageOfInstr platform instr
345
 = case instr of
Ian Lynagh's avatar
Ian Lynagh committed
346
    MOV    _ src dst    -> usageRW src dst
347
    CMOV _ _ src dst    -> mkRU (use_R src [dst]) [dst]
Ian Lynagh's avatar
Ian Lynagh committed
348 349 350 351 352 353
    MOVZxL _ src dst    -> usageRW src dst
    MOVSxL _ src dst    -> usageRW src dst
    LEA    _ src dst    -> usageRW src dst
    ADD    _ src dst    -> usageRM src dst
    ADC    _ src dst    -> usageRM src dst
    SUB    _ src dst    -> usageRM src dst
354
    SBB    _ src dst    -> usageRM src dst
Ian Lynagh's avatar
Ian Lynagh committed
355
    IMUL   _ src dst    -> usageRM src dst
Michal Terepeta's avatar
Michal Terepeta committed
356 357 358 359 360 361 362

    -- Result of IMULB will be in just in %ax
    IMUL2  II8 src       -> mkRU (eax:use_R src []) [eax]
    -- Result of IMUL for wider values, will be split between %dx/%edx/%rdx and
    -- %ax/%eax/%rax.
    IMUL2  _ src        -> mkRU (eax:use_R src []) [eax,edx]

Ian Lynagh's avatar
Ian Lynagh committed
363
    MUL    _ src dst    -> usageRM src dst
364
    MUL2   _ src        -> mkRU (eax:use_R src []) [eax,edx]
Simon Marlow's avatar
Simon Marlow committed
365 366
    DIV    _ op -> mkRU (eax:edx:use_R op []) [eax,edx]
    IDIV   _ op -> mkRU (eax:edx:use_R op []) [eax,edx]
367
    ADD_CC _ src dst    -> usageRM src dst
368
    SUB_CC _ src dst    -> usageRM src dst
Ian Lynagh's avatar
Ian Lynagh committed
369 370
    AND    _ src dst    -> usageRM src dst
    OR     _ src dst    -> usageRM src dst
371 372 373 374

    XOR    _ (OpReg src) (OpReg dst)
        | src == dst    -> mkRU [] [dst]

Ian Lynagh's avatar
Ian Lynagh committed
375 376
    XOR    _ src dst    -> usageRM src dst
    NOT    _ op         -> usageM op
377
    BSWAP  _ reg        -> mkRU [reg] [reg]
Ian Lynagh's avatar
Ian Lynagh committed
378 379 380 381
    NEGI   _ op         -> usageM op
    SHL    _ imm dst    -> usageRM imm dst
    SAR    _ imm dst    -> usageRM imm dst
    SHR    _ imm dst    -> usageRM imm dst
Simon Marlow's avatar
Simon Marlow committed
382
    BT     _ _   src    -> mkRUR (use_R src [])
Ian Lynagh's avatar
Ian Lynagh committed
383

Simon Marlow's avatar
Simon Marlow committed
384
    PUSH   _ op         -> mkRUR (use_R op [])
Ian Lynagh's avatar
Ian Lynagh committed
385
    POP    _ op         -> mkRU [] (def_W op)
Simon Marlow's avatar
Simon Marlow committed
386 387
    TEST   _ src dst    -> mkRUR (use_R src $! use_R dst [])
    CMP    _ src dst    -> mkRUR (use_R src $! use_R dst [])
Ian Lynagh's avatar
Ian Lynagh committed
388 389 390
    SETCC  _ op         -> mkRU [] (def_W op)
    JXX    _ _          -> mkRU [] []
    JXX_GBL _ _         -> mkRU [] []
391
    JMP     op regs     -> mkRUR (use_R op regs)
Simon Marlow's avatar
Simon Marlow committed
392
    JMP_TBL op _ _ _    -> mkRUR (use_R op [])
393 394
    CALL (Left _)  params   -> mkRU params (callClobberedRegs platform)
    CALL (Right reg) params -> mkRU (reg:params) (callClobberedRegs platform)
Ian Lynagh's avatar
Ian Lynagh committed
395 396
    CLTD   _            -> mkRU [eax] [edx]
    NOP                 -> mkRU [] []
397

398
    X87Store    _  dst    -> mkRUR ( use_EA dst [])
399

Ian Lynagh's avatar
Ian Lynagh committed
400 401
    CVTSS2SD   src dst  -> mkRU [src] [dst]
    CVTSD2SS   src dst  -> mkRU [src] [dst]
Simon Marlow's avatar
Simon Marlow committed
402 403 404 405
    CVTTSS2SIQ _ src dst -> mkRU (use_R src []) [dst]
    CVTTSD2SIQ _ src dst -> mkRU (use_R src []) [dst]
    CVTSI2SS   _ src dst -> mkRU (use_R src []) [dst]
    CVTSI2SD   _ src dst -> mkRU (use_R src []) [dst]
Ian Lynagh's avatar
Ian Lynagh committed
406
    FDIV _     src dst  -> usageRM src dst
407
    SQRT _ src dst      -> mkRU (use_R src []) [dst]
408 409 410 411

    FETCHGOT reg        -> mkRU [] [reg]
    FETCHPC  reg        -> mkRU [] [reg]

Ian Lynagh's avatar
Ian Lynagh committed
412
    COMMENT _           -> noUsage
413
    LOCATION{}          -> noUsage
414
    UNWIND{}            -> noUsage
415 416
    DELTA   _           -> noUsage

Simon Marlow's avatar
Simon Marlow committed
417
    POPCNT _ src dst -> mkRU (use_R src []) [dst]
418 419
    LZCNT  _ src dst -> mkRU (use_R src []) [dst]
    TZCNT  _ src dst -> mkRU (use_R src []) [dst]
420 421
    BSF    _ src dst -> mkRU (use_R src []) [dst]
    BSR    _ src dst -> mkRU (use_R src []) [dst]
tibbe's avatar
tibbe committed
422

423 424 425
    PDEP   _ src mask dst -> mkRU (use_R src $ use_R mask []) [dst]
    PEXT   _ src mask dst -> mkRU (use_R src $ use_R mask []) [dst]

426 427
    -- note: might be a better way to do this
    PREFETCH _  _ src -> mkRU (use_R src []) []
428
    LOCK i              -> x86_regUsageOfInstr platform i
429 430
    XADD _ src dst      -> usageMM src dst
    CMPXCHG _ src dst   -> usageRMM src dst (OpReg eax)
431
    MFENCE -> noUsage
432

Ian Lynagh's avatar
Ian Lynagh committed
433
    _other              -> panic "regUsage: unrecognised instr"
434
 where
435 436 437 438 439 440 441 442 443
    -- # Definitions
    --
    -- Written: If the operand is a register, it's written. If it's an
    -- address, registers mentioned in the address are read.
    --
    -- Modified: If the operand is a register, it's both read and
    -- written. If it's an address, registers mentioned in the address
    -- are read.

444 445
    -- 2 operand form; first operand Read; second Written
    usageRW :: Operand -> Operand -> RegUsage
Simon Marlow's avatar
Simon Marlow committed
446 447
    usageRW op (OpReg reg)      = mkRU (use_R op []) [reg]
    usageRW op (OpAddr ea)      = mkRUR (use_R op $! use_EA ea [])
Ian Lynagh's avatar
Ian Lynagh committed
448
    usageRW _ _                 = panic "X86.RegInfo.usageRW: no match"
449 450 451

    -- 2 operand form; first operand Read; second Modified
    usageRM :: Operand -> Operand -> RegUsage
Simon Marlow's avatar
Simon Marlow committed
452 453
    usageRM op (OpReg reg)      = mkRU (use_R op [reg]) [reg]
    usageRM op (OpAddr ea)      = mkRUR (use_R op $! use_EA ea [])
Ian Lynagh's avatar
Ian Lynagh committed
454
    usageRM _ _                 = panic "X86.RegInfo.usageRM: no match"
455

456 457 458 459 460 461 462 463 464 465 466 467
    -- 2 operand form; first operand Modified; second Modified
    usageMM :: Operand -> Operand -> RegUsage
    usageMM (OpReg src) (OpReg dst) = mkRU [src, dst] [src, dst]
    usageMM (OpReg src) (OpAddr ea) = mkRU (use_EA ea [src]) [src]
    usageMM _ _                     = panic "X86.RegInfo.usageMM: no match"

    -- 3 operand form; first operand Read; second Modified; third Modified
    usageRMM :: Operand -> Operand -> Operand -> RegUsage
    usageRMM (OpReg src) (OpReg dst) (OpReg reg) = mkRU [src, dst, reg] [dst, reg]
    usageRMM (OpReg src) (OpAddr ea) (OpReg reg) = mkRU (use_EA ea [src, reg]) [reg]
    usageRMM _ _ _                               = panic "X86.RegInfo.usageRMM: no match"

468 469
    -- 1 operand form; operand Modified
    usageM :: Operand -> RegUsage
Ian Lynagh's avatar
Ian Lynagh committed
470
    usageM (OpReg reg)          = mkRU [reg] [reg]
Simon Marlow's avatar
Simon Marlow committed
471
    usageM (OpAddr ea)          = mkRUR (use_EA ea [])
Ian Lynagh's avatar
Ian Lynagh committed
472
    usageM _                    = panic "X86.RegInfo.usageM: no match"
473 474

    -- Registers defd when an operand is written.
Ian Lynagh's avatar
Ian Lynagh committed
475 476 477
    def_W (OpReg reg)           = [reg]
    def_W (OpAddr _ )           = []
    def_W _                     = panic "X86.RegInfo.def_W: no match"
478 479

    -- Registers used when an operand is read.
Simon Marlow's avatar
Simon Marlow committed
480 481 482
    use_R (OpReg reg)  tl = reg : tl
    use_R (OpImm _)    tl = tl
    use_R (OpAddr ea)  tl = use_EA ea tl
483 484

    -- Registers used to compute an effective address.
Simon Marlow's avatar
Simon Marlow committed
485 486 487 488 489 490 491
    use_EA (ImmAddr _ _) tl = tl
    use_EA (AddrBaseIndex base index _) tl =
        use_base base $! use_index index tl
        where use_base (EABaseReg r)  tl = r : tl
              use_base _              tl = tl
              use_index EAIndexNone   tl = tl
              use_index (EAIndex i _) tl = i : tl
492 493

    mkRUR src = src' `seq` RU src' []
494
        where src' = filter (interesting platform) src
495 496

    mkRU src dst = src' `seq` dst' `seq` RU src' dst'
497 498
        where src' = filter (interesting platform) src
              dst' = filter (interesting platform) dst
499

500
-- | Is this register interesting for the register allocator?
501 502
interesting :: Platform -> Reg -> Bool
interesting _        (RegVirtual _)              = True
thomie's avatar
thomie committed
503
interesting platform (RegReal (RealRegSingle i)) = freeReg platform i
504
interesting _        (RegReal (RealRegPair{}))   = panic "X86.interesting: no reg pairs on this arch"
505 506 507



508 509
-- | Applies the supplied function to all registers in instructions.
-- Typically used to change virtual registers to real registers.
510
x86_patchRegsOfInstr :: Instr -> (Reg -> Reg) -> Instr
Ian Lynagh's avatar
Ian Lynagh committed
511
x86_patchRegsOfInstr instr env
512
 = case instr of
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
    MOV  fmt src dst     -> patch2 (MOV  fmt) src dst
    CMOV cc fmt src dst  -> CMOV cc fmt (patchOp src) (env dst)
    MOVZxL fmt src dst   -> patch2 (MOVZxL fmt) src dst
    MOVSxL fmt src dst   -> patch2 (MOVSxL fmt) src dst
    LEA  fmt src dst     -> patch2 (LEA  fmt) src dst
    ADD  fmt src dst     -> patch2 (ADD  fmt) src dst
    ADC  fmt src dst     -> patch2 (ADC  fmt) src dst
    SUB  fmt src dst     -> patch2 (SUB  fmt) src dst
    SBB  fmt src dst     -> patch2 (SBB  fmt) src dst
    IMUL fmt src dst     -> patch2 (IMUL fmt) src dst
    IMUL2 fmt src        -> patch1 (IMUL2 fmt) src
    MUL fmt src dst      -> patch2 (MUL fmt) src dst
    MUL2 fmt src         -> patch1 (MUL2 fmt) src
    IDIV fmt op          -> patch1 (IDIV fmt) op
    DIV fmt op           -> patch1 (DIV fmt) op
    ADD_CC fmt src dst   -> patch2 (ADD_CC fmt) src dst
    SUB_CC fmt src dst   -> patch2 (SUB_CC fmt) src dst
    AND  fmt src dst     -> patch2 (AND  fmt) src dst
    OR   fmt src dst     -> patch2 (OR   fmt) src dst
    XOR  fmt src dst     -> patch2 (XOR  fmt) src dst
    NOT  fmt op          -> patch1 (NOT  fmt) op
    BSWAP fmt reg        -> BSWAP fmt (env reg)
    NEGI fmt op          -> patch1 (NEGI fmt) op
    SHL  fmt imm dst     -> patch1 (SHL fmt imm) dst
    SAR  fmt imm dst     -> patch1 (SAR fmt imm) dst
    SHR  fmt imm dst     -> patch1 (SHR fmt imm) dst
    BT   fmt imm src     -> patch1 (BT  fmt imm) src
    TEST fmt src dst     -> patch2 (TEST fmt) src dst
    CMP  fmt src dst     -> patch2 (CMP  fmt) src dst
    PUSH fmt op          -> patch1 (PUSH fmt) op
    POP  fmt op          -> patch1 (POP  fmt) op
    SETCC cond op        -> patch1 (SETCC cond) op
    JMP op regs          -> JMP (patchOp op) regs
    JMP_TBL op ids s lbl -> JMP_TBL (patchOp op) ids s lbl

548 549
    -- literally only support storing the top x87 stack value st(0)
    X87Store  fmt  dst     -> X87Store fmt  (lookupAddr dst)
550

Ian Lynagh's avatar
Ian Lynagh committed
551 552
    CVTSS2SD src dst    -> CVTSS2SD (env src) (env dst)
    CVTSD2SS src dst    -> CVTSD2SS (env src) (env dst)
553 554 555 556 557
    CVTTSS2SIQ fmt src dst -> CVTTSS2SIQ fmt (patchOp src) (env dst)
    CVTTSD2SIQ fmt src dst -> CVTTSD2SIQ fmt (patchOp src) (env dst)
    CVTSI2SS fmt src dst -> CVTSI2SS fmt (patchOp src) (env dst)
    CVTSI2SD fmt src dst -> CVTSI2SD fmt (patchOp src) (env dst)
    FDIV fmt src dst     -> FDIV fmt (patchOp src) (patchOp dst)
558
    SQRT fmt src dst    -> SQRT fmt (patchOp src) (env dst)
Ian Lynagh's avatar
Ian Lynagh committed
559 560 561

    CALL (Left _)  _    -> instr
    CALL (Right reg) p  -> CALL (Right (env reg)) p
562 563 564 565

    FETCHGOT reg        -> FETCHGOT (env reg)
    FETCHPC  reg        -> FETCHPC  (env reg)

Ian Lynagh's avatar
Ian Lynagh committed
566 567
    NOP                 -> instr
    COMMENT _           -> instr
568
    LOCATION {}         -> instr
569
    UNWIND {}           -> instr
Ian Lynagh's avatar
Ian Lynagh committed
570 571 572 573 574
    DELTA _             -> instr

    JXX _ _             -> instr
    JXX_GBL _ _         -> instr
    CLTD _              -> instr
575

576
    POPCNT fmt src dst -> POPCNT fmt (patchOp src) (env dst)
577 578
    LZCNT  fmt src dst -> LZCNT  fmt (patchOp src) (env dst)
    TZCNT  fmt src dst -> TZCNT  fmt (patchOp src) (env dst)
579 580
    PDEP   fmt src mask dst -> PDEP   fmt (patchOp src) (patchOp mask) (env dst)
    PEXT   fmt src mask dst -> PEXT   fmt (patchOp src) (patchOp mask) (env dst)
581 582
    BSF    fmt src dst -> BSF    fmt (patchOp src) (env dst)
    BSR    fmt src dst -> BSR    fmt (patchOp src) (env dst)
tibbe's avatar
tibbe committed
583

584
    PREFETCH lvl format src -> PREFETCH lvl format (patchOp src)
585

586 587 588 589
    LOCK i               -> LOCK (x86_patchRegsOfInstr i env)
    XADD fmt src dst     -> patch2 (XADD fmt) src dst
    CMPXCHG fmt src dst  -> patch2 (CMPXCHG fmt) src dst
    MFENCE               -> instr
590

Ian Lynagh's avatar
Ian Lynagh committed
591
    _other              -> panic "patchRegs: unrecognised instr"
592 593

  where
594
    patch1 :: (Operand -> a) -> Operand -> a
595
    patch1 insn op      = insn $! patchOp op
596
    patch2 :: (Operand -> Operand -> a) -> Operand -> Operand -> a
597 598 599 600 601 602 603 604 605 606
    patch2 insn src dst = (insn $! patchOp src) $! patchOp dst

    patchOp (OpReg  reg) = OpReg $! env reg
    patchOp (OpImm  imm) = OpImm imm
    patchOp (OpAddr ea)  = OpAddr $! lookupAddr ea

    lookupAddr (ImmAddr imm off) = ImmAddr imm off
    lookupAddr (AddrBaseIndex base index disp)
      = ((AddrBaseIndex $! lookupBase base) $! lookupIndex index) disp
      where
Ian Lynagh's avatar
Ian Lynagh committed
607 608
        lookupBase EABaseNone       = EABaseNone
        lookupBase EABaseRip        = EABaseRip
Simon Marlow's avatar
Simon Marlow committed
609
        lookupBase (EABaseReg r)    = EABaseReg $! env r
Ian Lynagh's avatar
Ian Lynagh committed
610 611

        lookupIndex EAIndexNone     = EAIndexNone
Simon Marlow's avatar
Simon Marlow committed
612
        lookupIndex (EAIndex r i)   = (EAIndex $! env r) i
613 614 615


--------------------------------------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
616 617
x86_isJumpishInstr
        :: Instr -> Bool
618 619 620

x86_isJumpishInstr instr
 = case instr of
Ian Lynagh's avatar
Ian Lynagh committed
621 622 623 624 625 626
        JMP{}           -> True
        JXX{}           -> True
        JXX_GBL{}       -> True
        JMP_TBL{}       -> True
        CALL{}          -> True
        _               -> False
627 628 629


x86_jumpDestsOfInstr
Ian Lynagh's avatar
Ian Lynagh committed
630 631
        :: Instr
        -> [BlockId]
632

Ian Lynagh's avatar
Ian Lynagh committed
633
x86_jumpDestsOfInstr insn
634
  = case insn of
Ian Lynagh's avatar
Ian Lynagh committed
635
        JXX _ id        -> [id]
636
        JMP_TBL _ ids _ _ -> [id | Just (DestBlockId id) <- ids]
Ian Lynagh's avatar
Ian Lynagh committed
637
        _               -> []
638 639


Ian Lynagh's avatar
Ian Lynagh committed
640 641
x86_patchJumpInstr
        :: Instr -> (BlockId -> BlockId) -> Instr
642 643 644

x86_patchJumpInstr insn patchF
  = case insn of
Ian Lynagh's avatar
Ian Lynagh committed
645 646
        JXX cc id       -> JXX cc (patchF id)
        JMP_TBL op ids section lbl
647
          -> JMP_TBL op (map (fmap (patchJumpDest patchF)) ids) section lbl
Ian Lynagh's avatar
Ian Lynagh committed
648
        _               -> insn
649 650 651 652
    where
        patchJumpDest f (DestBlockId id) = DestBlockId (f id)
        patchJumpDest _ dest             = dest

653 654 655 656 657 658 659




-- -----------------------------------------------------------------------------
-- | Make a spill instruction.
x86_mkSpillInstr
660
    :: DynFlags
661 662 663 664
    -> Reg      -- register to spill
    -> Int      -- current stack delta
    -> Int      -- spill slot to use
    -> Instr
665

666
x86_mkSpillInstr dflags reg delta slot
667
  = let off     = spillSlotToOffset platform slot - delta
668
    in
669
    case targetClassOfReg platform reg of
670
           RcInteger   -> MOV (archWordFormat is32Bit)
671
                              (OpReg reg) (OpAddr (spRel dflags off))
672
           RcDouble    -> MOV FF64 (OpReg reg) (OpAddr (spRel dflags off))
673
           _         -> panic "X86.mkSpillInstr: no match"
674 675
    where platform = targetPlatform dflags
          is32Bit = target32Bit platform
676 677 678

-- | Make a spill reload instruction.
x86_mkLoadInstr
679
    :: DynFlags
680 681 682 683
    -> Reg      -- register to load
    -> Int      -- current stack delta
    -> Int      -- spill slot to use
    -> Instr
684

685
x86_mkLoadInstr dflags reg delta slot
686
  = let off     = spillSlotToOffset platform slot - delta
687
    in
688
        case targetClassOfReg platform reg of
689
              RcInteger -> MOV (archWordFormat is32Bit)
690
                               (OpAddr (spRel dflags off)) (OpReg reg)
691
              RcDouble  -> MOV FF64 (OpAddr (spRel dflags off)) (OpReg reg)
692
              _           -> panic "X86.x86_mkLoadInstr"
693 694
    where platform = targetPlatform dflags
          is32Bit = target32Bit platform
695

696
spillSlotSize :: Platform -> Int
697
spillSlotSize dflags = if is32Bit then 12 else 8
698
    where is32Bit = target32Bit dflags
699

700 701
maxSpillSlots :: DynFlags -> Int
maxSpillSlots dflags
702 703 704 705 706 707
    = ((rESERVED_C_STACK_BYTES dflags - 64) `div` spillSlotSize (targetPlatform dflags)) - 1
--     = 0 -- useful for testing allocMoreStack

-- number of bytes that the stack pointer should be aligned to
stackAlign :: Int
stackAlign = 16
708 709 710 711

-- convert a spill slot number to a *byte* offset, with no sign:
-- decide on a per arch basis whether you are spilling above or below
-- the C stack pointer.
712 713 714
spillSlotToOffset :: Platform -> Int -> Int
spillSlotToOffset platform slot
   = 64 + spillSlotSize platform * slot
715 716 717 718 719

--------------------------------------------------------------------------------

-- | See if this instruction is telling us the current C stack delta
x86_takeDeltaInstr
Ian Lynagh's avatar
Ian Lynagh committed
720 721 722
        :: Instr
        -> Maybe Int

723 724
x86_takeDeltaInstr instr
 = case instr of
Ian Lynagh's avatar
Ian Lynagh committed
725 726
        DELTA i         -> Just i
        _               -> Nothing
727 728 729


x86_isMetaInstr
Ian Lynagh's avatar
Ian Lynagh committed
730 731 732
        :: Instr
        -> Bool

733 734
x86_isMetaInstr instr
 = case instr of
Ian Lynagh's avatar
Ian Lynagh committed
735
        COMMENT{}       -> True
736
        LOCATION{}      -> True
Ian Lynagh's avatar
Ian Lynagh committed
737 738
        LDATA{}         -> True
        NEWBLOCK{}      -> True
739
        UNWIND{}        -> True
Ian Lynagh's avatar
Ian Lynagh committed
740 741
        DELTA{}         -> True
        _               -> False
742 743 744



745
---  TODO: why is there
746
-- | Make a reg-reg move instruction.
Ian Lynagh's avatar
Ian Lynagh committed
747 748 749
--      On SPARC v8 there are no instructions to move directly between
--      floating point and integer regs. If we need to do that then we
--      have to go via memory.
750 751
--
x86_mkRegRegMoveInstr
752 753 754 755
    :: Platform
    -> Reg
    -> Reg
    -> Instr
756

757 758
x86_mkRegRegMoveInstr platform src dst
 = case targetClassOfReg platform src of
759 760 761 762
        RcInteger -> case platformArch platform of
                     ArchX86    -> MOV II32 (OpReg src) (OpReg dst)
                     ArchX86_64 -> MOV II64 (OpReg src) (OpReg dst)
                     _          -> panic "x86_mkRegRegMoveInstr: Bad arch"
763 764 765 766
        RcDouble    ->  MOV FF64 (OpReg src) (OpReg dst)
        -- this code is the lie we tell ourselves because both float and double
        -- use the same register class.on x86_64 and x86 32bit with SSE2,
        -- more plainly, both use the XMM registers
Ian Lynagh's avatar
Ian Lynagh committed
767
        _     -> panic "X86.RegInfo.mkRegRegMoveInstr: no match"
768 769

-- | Check whether an instruction represents a reg-reg move.
Ian Lynagh's avatar
Ian Lynagh committed
770 771
--      The register allocator attempts to eliminate reg->reg moves whenever it can,
--      by assigning the src and dest temporaries to the same real register.
772 773
--
x86_takeRegRegMoveInstr
Ian Lynagh's avatar
Ian Lynagh committed
774 775
        :: Instr
        -> Maybe (Reg,Reg)
776

Ian Lynagh's avatar
Ian Lynagh committed
777 778
x86_takeRegRegMoveInstr (MOV _ (OpReg r1) (OpReg r2))
        = Just (r1,r2)
779 780 781 782 783 784

x86_takeRegRegMoveInstr _  = Nothing


-- | Make an unconditional branch instruction.
x86_mkJumpInstr
Ian Lynagh's avatar
Ian Lynagh committed
785 786
        :: BlockId
        -> [Instr]
787

Ian Lynagh's avatar
Ian Lynagh committed
788 789
x86_mkJumpInstr id
        = [JXX ALWAYS id]
790

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
-- Note [Windows stack layout]
-- | On most OSes the kernel will place a guard page after the current stack
--   page.  If you allocate larger than a page worth you may jump over this
--   guard page.  Not only is this a security issue, but on certain OSes such
--   as Windows a new page won't be allocated if you don't hit the guard.  This
--   will cause a segfault or access fault.
--
--   This function defines if the current allocation amount requires a probe.
--   On Windows (for now) we emit a call to _chkstk for this.  For other OSes
--   this is not yet implemented.
--   See https://docs.microsoft.com/en-us/windows/desktop/DevNotes/-win32-chkstk
--   The Windows stack looks like this:
--
--                         +-------------------+
--                         |        SP         |
--                         +-------------------+
--                         |                   |
--                         |    GUARD PAGE     |
--                         |                   |
--                         +-------------------+
--                         |                   |
--                         |                   |
--                         |     UNMAPPED      |
--                         |                   |
--                         |                   |
--                         +-------------------+
--
--   In essense each allocation larger than a page size needs to be chunked and
--   a probe emitted after each page allocation.  You have to hit the guard
--   page so the kernel can map in the next page, otherwise you'll segfault.
--
needs_probe_call :: Platform -> Int -> Bool
needs_probe_call platform amount
  = case platformOS platform of
     OSMinGW32 -> case platformArch platform of
                    ArchX86    -> amount > (4 * 1024)
                    ArchX86_64 -> amount > (8 * 1024)
                    _          -> False
     _         -> False
830

831 832 833
x86_mkStackAllocInstr
        :: Platform
        -> Int
834
        -> [Instr]
835
x86_mkStackAllocInstr platform amount
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
  = case platformOS platform of
      OSMinGW32 ->
        -- These will clobber AX but this should be ok because
        --
        -- 1. It is the first thing we do when entering the closure and AX is
        --    a caller saved registers on Windows both on x86_64 and x86.
        --
        -- 2. The closures are only entered via a call or longjmp in which case
        --    there are no expectations for volatile registers.
        --
        -- 3. When the target is a local branch point it is re-targeted
        --    after the dealloc, preserving #2.  See note [extra spill slots].
        --
        -- We emit a call because the stack probes are quite involved and
        -- would bloat code size a lot.  GHC doesn't really have an -Os.
        -- __chkstk is guaranteed to leave all nonvolatile registers and AX
        -- untouched.  It's part of the standard prologue code for any Windows
        -- function dropping the stack more than a page.
        -- See Note [Windows stack layout]
        case platformArch platform of
            ArchX86    | needs_probe_call platform amount ->
                           [ MOV II32 (OpImm (ImmInt amount)) (OpReg eax)
                           , CALL (Left $ strImmLit "___chkstk_ms") [eax]
                           , SUB II32 (OpReg eax) (OpReg esp)
                           ]
                       | otherwise ->
                           [ SUB II32 (OpImm (ImmInt amount)) (OpReg esp)
                           , TEST II32 (OpReg esp) (OpReg esp)
                           ]
            ArchX86_64 | needs_probe_call platform amount ->
                           [ MOV II64 (OpImm (ImmInt amount)) (OpReg rax)
Tamar Christina's avatar
Tamar Christina committed
867
                           , CALL (Left $ strImmLit "___chkstk_ms") [rax]
868 869 870 871 872 873 874 875 876 877 878 879
                           , SUB II64 (OpReg rax) (OpReg rsp)
                           ]
                       | otherwise ->
                           [ SUB II64 (OpImm (ImmInt amount)) (OpReg rsp)
                           , TEST II64 (OpReg rsp) (OpReg rsp)
                           ]
            _ -> panic "x86_mkStackAllocInstr"
      _       ->
        case platformArch platform of
          ArchX86    -> [ SUB II32 (OpImm (ImmInt amount)) (OpReg esp) ]
          ArchX86_64 -> [ SUB II64 (OpImm (ImmInt amount)) (OpReg rsp) ]
          _ -> panic "x86_mkStackAllocInstr"
880 881 882 883

x86_mkStackDeallocInstr
        :: Platform
        -> Int
884
        -> [Instr]
885 886
x86_mkStackDeallocInstr platform amount
  = case platformArch platform of
887 888
      ArchX86    -> [ADD II32 (OpImm (ImmInt amount)) (OpReg esp)]
      ArchX86_64 -> [ADD II64 (OpImm (ImmInt amount)) (OpReg rsp)]
889
      _ -> panic "x86_mkStackDeallocInstr"
890

891

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
--
-- Note [extra spill slots]
--
-- If the register allocator used more spill slots than we have
-- pre-allocated (rESERVED_C_STACK_BYTES), then we must allocate more
-- C stack space on entry and exit from this proc.  Therefore we
-- insert a "sub $N, %rsp" at every entry point, and an "add $N, %rsp"
-- before every non-local jump.
--
-- This became necessary when the new codegen started bundling entire
-- functions together into one proc, because the register allocator
-- assigns a different stack slot to each virtual reg within a proc.
-- To avoid using so many slots we could also:
--
--   - split up the proc into connected components before code generator
--
--   - rename the virtual regs, so that we re-use vreg names and hence
--     stack slots for non-overlapping vregs.
--
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
-- Note that when a block is both a non-local entry point (with an
-- info table) and a local branch target, we have to split it into
-- two, like so:
--
--    <info table>
--    L:
--       <code>
--
-- becomes
--
--    <info table>
--    L:
--       subl $rsp, N
--       jmp Lnew
--    Lnew:
--       <code>
--
-- and all branches pointing to L are retargetted to point to Lnew.
-- Otherwise, we would repeat the $rsp adjustment for each branch to
-- L.
--
932 933
-- Returns a list of (L,Lnew) pairs.
--
934 935 936 937
allocMoreStack
  :: Platform
  -> Int
  -> NatCmmDecl statics X86.Instr.Instr
938
  -> UniqSM (NatCmmDecl statics X86.Instr.Instr, [(BlockId,BlockId)])
939

940
allocMoreStack _ _ top@(CmmData _ _) = return (top,[])
941 942
allocMoreStack platform slots proc@(CmmProc info lbl live (ListGraph code)) = do
    let entries = entryBlocks proc
943

944
    uniqs <- replicateM (length entries) getUniqueM
945 946 947 948 949 950 951

    let
      delta = ((x + stackAlign - 1) `quot` stackAlign) * stackAlign -- round up
        where x = slots * spillSlotSize platform -- sp delta

      alloc   = mkStackAllocInstr   platform delta
      dealloc = mkStackDeallocInstr platform delta
952

953 954
      retargetList = (zip entries (map mkBlockId uniqs))

955
      new_blockmap :: LabelMap BlockId
956
      new_blockmap = mapFromList retargetList
957

958 959
      insert_stack_insns (BasicBlock id insns)
         | Just new_blockid <- mapLookup id new_blockmap
960
         = [ BasicBlock id $ alloc ++ [JXX ALWAYS new_blockid]
961 962 963 964 965 966 967
           , BasicBlock new_blockid block' ]
         | otherwise
         = [ BasicBlock id block' ]
         where
           block' = foldr insert_dealloc [] insns

      insert_dealloc insn r = case insn of
968
         JMP _ _     -> dealloc ++ (insn : r)
969
         JXX_GBL _ _ -> panic "insert_dealloc: cannot handle JXX_GBL"
970 971
         _other      -> x86_patchJumpInstr insn retarget : r
           where retarget b = fromMaybe b (mapLookup b new_blockmap)
972 973 974

      new_code = concatMap insert_stack_insns code
    -- in
975
    return (CmmProc info lbl live (ListGraph new_code), retargetList)
976

977 978
data JumpDest = DestBlockId BlockId | DestImm Imm

979 980 981 982 983 984
-- Debug Instance
instance Outputable JumpDest where
  ppr (DestBlockId bid) = text "jd<blk>:" <> ppr bid
  ppr (DestImm _imm)    = text "jd<imm>:noShow"


985 986 987
getJumpDestBlockId :: JumpDest -> Maybe BlockId
getJumpDestBlockId (DestBlockId bid) = Just bid
getJumpDestBlockId _                 = Nothing
988 989

canShortcut :: Instr -> Maybe JumpDest
990 991 992
canShortcut (JXX ALWAYS id)      = Just (DestBlockId id)
canShortcut (JMP (OpImm imm) _)  = Just (DestImm imm)
canShortcut _                    = Nothing
993 994


995 996
-- This helper shortcuts a sequence of branches.
-- The blockset helps avoid following cycles.
997
shortcutJump :: (BlockId -> Maybe JumpDest) -> Instr -> Instr
998
shortcutJump fn insn = shortcutJump' fn (setEmpty :: LabelSet) insn
999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  where
    shortcutJump' :: (BlockId -> Maybe JumpDest) -> LabelSet -> Instr -> Instr
    shortcutJump' fn seen insn@(JXX cc id) =
        if setMember id seen then insn
        else case fn id of
            Nothing                -> insn
            Just (DestBlockId id') -> shortcutJump' fn seen' (JXX cc id')
            Just (DestImm imm)     -> shortcutJump' fn seen' (JXX_GBL cc imm)
        where seen' = setInsert id seen
    shortcutJump' fn _ (JMP_TBL addr blocks section tblId) =
1009
        let updateBlock (Just (DestBlockId bid))  =
1010
                case fn bid of
1011 1012 1013
                    Nothing   -> Just (DestBlockId bid )
                    Just dest -> Just dest
            updateBlock dest = dest
1014 1015 1016
            blocks' = map updateBlock blocks
        in  JMP_TBL addr blocks' section tblId
    shortcutJump' _ _ other = other
1017 1018

-- Here because it knows about JumpDest
1019 1020 1021 1022 1023 1024 1025 1026
shortcutStatics :: (BlockId -> Maybe JumpDest) -> (Alignment, CmmStatics) -> (Alignment, CmmStatics)
shortcutStatics fn (align, Statics lbl statics)
  = (align, Statics lbl $ map (shortcutStatic fn) statics)
  -- we need to get the jump tables, so apply the mapping to the entries
  -- of a CmmData too.

shortcutLabel :: (BlockId -> Maybe JumpDest) -> CLabel -> CLabel
shortcutLabel fn lab
1027 1028
  | Just blkId <- maybeLocalBlockLabel lab = shortBlockId fn emptyUniqSet blkId
  | otherwise                              = lab
1029

1030 1031
shortcutStatic :: (BlockId -> Maybe JumpDest) -> CmmStatic -> CmmStatic
shortcutStatic fn (CmmStaticLit (CmmLabel lab))
1032
  = CmmStaticLit (CmmLabel (shortcutLabel fn lab))
1033 1034
shortcutStatic fn (CmmStaticLit (CmmLabelDiffOff lbl1 lbl2 off w))
  = CmmStaticLit (CmmLabelDiffOff (shortcutLabel fn lbl1) lbl2 off w)
1035 1036 1037 1038 1039
        -- slightly dodgy, we're ignoring the second label, but this
        -- works with the way we use CmmLabelDiffOff for jump tables now.
shortcutStatic _ other_static
        = other_static

Ian Lynagh's avatar
Ian Lynagh committed
1040 1041 1042 1043 1044
shortBlockId
        :: (BlockId -> Maybe JumpDest)
        -> UniqSet Unique
        -> BlockId
        -> CLabel
1045

1046
shortBlockId fn seen blockid =
1047
  case (elementOfUniqSet uq seen, fn blockid) of
1048 1049
    (True, _)    -> blockLbl blockid
    (_, Nothing) -> blockLbl blockid
1050 1051 1052
    (_, Just (DestBlockId blockid'))  -> shortBlockId fn (addOneToUniqSet seen uq) blockid'
    (_, Just (DestImm (ImmCLbl lbl))) -> lbl
    (_, _other) -> panic "shortBlockId"
1053
  where uq = getUnique blockid