Use the most complex form of addressing modes on x86
[ghc-hetmet.git] / compiler / nativeGen / MachCodeGen.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Generating machine code (instruction selection)
4 --
5 -- (c) The University of Glasgow 1996-2004
6 --
7 -----------------------------------------------------------------------------
8
9 -- This is a big module, but, if you pay attention to
10 -- (a) the sectioning, (b) the type signatures, and
11 -- (c) the #if blah_TARGET_ARCH} things, the
12 -- structure should not be too overwhelming.
13
14 module MachCodeGen ( cmmTopCodeGen, InstrBlock ) where
15
16 #include "HsVersions.h"
17 #include "nativeGen/NCG.h"
18 #include "MachDeps.h"
19
20 -- NCG stuff:
21 import MachInstrs
22 import MachRegs
23 import NCGMonad
24 import PositionIndependentCode
25 import RegAllocInfo ( mkBranchInstr )
26
27 -- Our intermediate code:
28 import PprCmm           ( pprExpr )
29 import Cmm
30 import MachOp
31 import CLabel
32
33 -- The rest:
34 import StaticFlags      ( opt_PIC )
35 import ForeignCall      ( CCallConv(..) )
36 import OrdList
37 import Pretty
38 import Outputable
39 import FastString
40 import FastTypes        ( isFastTrue )
41 import Constants        ( wORD_SIZE )
42
43 #ifdef DEBUG
44 import Outputable       ( assertPanic )
45 import Debug.Trace      ( trace )
46 #endif
47
48 import Control.Monad    ( mapAndUnzipM )
49 import Data.Maybe       ( fromJust )
50 import Data.Bits
51 import Data.Word
52 import Data.Int
53
54 -- -----------------------------------------------------------------------------
55 -- Top-level of the instruction selector
56
57 -- | 'InstrBlock's are the insn sequences generated by the insn selectors.
58 -- They are really trees of insns to facilitate fast appending, where a
59 -- left-to-right traversal (pre-order?) yields the insns in the correct
60 -- order.
61
62 type InstrBlock = OrdList Instr
63
64 cmmTopCodeGen :: CmmTop -> NatM [NatCmmTop]
65 cmmTopCodeGen (CmmProc info lab params blocks) = do
66   (nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
67   picBaseMb <- getPicBaseMaybeNat
68   let proc = CmmProc info lab params (concat nat_blocks)
69       tops = proc : concat statics
70   case picBaseMb of
71       Just picBase -> initializePicBase picBase tops
72       Nothing -> return tops
73   
74 cmmTopCodeGen (CmmData sec dat) = do
75   return [CmmData sec dat]  -- no translation, we just use CmmStatic
76
77 basicBlockCodeGen :: CmmBasicBlock -> NatM ([NatBasicBlock],[NatCmmTop])
78 basicBlockCodeGen (BasicBlock id stmts) = do
79   instrs <- stmtsToInstrs stmts
80   -- code generation may introduce new basic block boundaries, which
81   -- are indicated by the NEWBLOCK instruction.  We must split up the
82   -- instruction stream into basic blocks again.  Also, we extract
83   -- LDATAs here too.
84   let
85         (top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs
86         
87         mkBlocks (NEWBLOCK id) (instrs,blocks,statics) 
88           = ([], BasicBlock id instrs : blocks, statics)
89         mkBlocks (LDATA sec dat) (instrs,blocks,statics) 
90           = (instrs, blocks, CmmData sec dat:statics)
91         mkBlocks instr (instrs,blocks,statics)
92           = (instr:instrs, blocks, statics)
93   -- in
94   return (BasicBlock id top : other_blocks, statics)
95
96 stmtsToInstrs :: [CmmStmt] -> NatM InstrBlock
97 stmtsToInstrs stmts
98    = do instrss <- mapM stmtToInstrs stmts
99         return (concatOL instrss)
100
101 stmtToInstrs :: CmmStmt -> NatM InstrBlock
102 stmtToInstrs stmt = case stmt of
103     CmmNop         -> return nilOL
104     CmmComment s   -> return (unitOL (COMMENT s))
105
106     CmmAssign reg src
107       | isFloatingRep kind -> assignReg_FltCode kind reg src
108 #if WORD_SIZE_IN_BITS==32
109       | kind == I64        -> assignReg_I64Code      reg src
110 #endif
111       | otherwise          -> assignReg_IntCode kind reg src
112         where kind = cmmRegRep reg
113
114     CmmStore addr src
115       | isFloatingRep kind -> assignMem_FltCode kind addr src
116 #if WORD_SIZE_IN_BITS==32
117       | kind == I64      -> assignMem_I64Code      addr src
118 #endif
119       | otherwise        -> assignMem_IntCode kind addr src
120         where kind = cmmExprRep src
121
122     CmmCall target result_regs args vols
123        -> genCCall target result_regs args vols
124
125     CmmBranch id          -> genBranch id
126     CmmCondBranch arg id  -> genCondJump id arg
127     CmmSwitch arg ids     -> genSwitch arg ids
128     CmmJump arg params    -> genJump arg
129
130 -- -----------------------------------------------------------------------------
131 -- General things for putting together code sequences
132
133 -- Expand CmmRegOff.  ToDo: should we do it this way around, or convert
134 -- CmmExprs into CmmRegOff?
135 mangleIndexTree :: CmmExpr -> CmmExpr
136 mangleIndexTree (CmmRegOff reg off)
137   = CmmMachOp (MO_Add rep) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) rep)]
138   where rep = cmmRegRep reg
139
140 -- -----------------------------------------------------------------------------
141 --  Code gen for 64-bit arithmetic on 32-bit platforms
142
143 {-
144 Simple support for generating 64-bit code (ie, 64 bit values and 64
145 bit assignments) on 32-bit platforms.  Unlike the main code generator
146 we merely shoot for generating working code as simply as possible, and
147 pay little attention to code quality.  Specifically, there is no
148 attempt to deal cleverly with the fixed-vs-floating register
149 distinction; all values are generated into (pairs of) floating
150 registers, even if this would mean some redundant reg-reg moves as a
151 result.  Only one of the VRegUniques is returned, since it will be
152 of the VRegUniqueLo form, and the upper-half VReg can be determined
153 by applying getHiVRegFromLo to it.
154 -}
155
156 data ChildCode64        -- a.k.a "Register64"
157    = ChildCode64 
158         InstrBlock      -- code
159         Reg             -- the lower 32-bit temporary which contains the
160                         -- result; use getHiVRegFromLo to find the other
161                         -- VRegUnique.  Rules of this simplified insn
162                         -- selection game are therefore that the returned
163                         -- Reg may be modified
164
165 #if WORD_SIZE_IN_BITS==32
166 assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
167 assignReg_I64Code :: CmmReg  -> CmmExpr -> NatM InstrBlock
168 #endif
169
170 #ifndef x86_64_TARGET_ARCH
171 iselExpr64        :: CmmExpr -> NatM ChildCode64
172 #endif
173
174 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
175
176 #if i386_TARGET_ARCH
177
178 assignMem_I64Code addrTree valueTree = do
179   Amode addr addr_code <- getAmode addrTree
180   ChildCode64 vcode rlo <- iselExpr64 valueTree
181   let 
182         rhi = getHiVRegFromLo rlo
183
184         -- Little-endian store
185         mov_lo = MOV I32 (OpReg rlo) (OpAddr addr)
186         mov_hi = MOV I32 (OpReg rhi) (OpAddr (fromJust (addrOffset addr 4)))
187   -- in
188   return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
189
190
191 assignReg_I64Code (CmmLocal (LocalReg u_dst pk)) valueTree = do
192    ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
193    let 
194          r_dst_lo = mkVReg u_dst I32
195          r_dst_hi = getHiVRegFromLo r_dst_lo
196          r_src_hi = getHiVRegFromLo r_src_lo
197          mov_lo = MOV I32 (OpReg r_src_lo) (OpReg r_dst_lo)
198          mov_hi = MOV I32 (OpReg r_src_hi) (OpReg r_dst_hi)
199    -- in
200    return (
201         vcode `snocOL` mov_lo `snocOL` mov_hi
202      )
203
204 assignReg_I64Code lvalue valueTree
205    = panic "assignReg_I64Code(i386): invalid lvalue"
206
207 ------------
208
209 iselExpr64 (CmmLit (CmmInt i _)) = do
210   (rlo,rhi) <- getNewRegPairNat I32
211   let
212         r = fromIntegral (fromIntegral i :: Word32)
213         q = fromIntegral ((fromIntegral i `shiftR` 32) :: Word32)
214         code = toOL [
215                 MOV I32 (OpImm (ImmInteger r)) (OpReg rlo),
216                 MOV I32 (OpImm (ImmInteger q)) (OpReg rhi)
217                 ]
218   -- in
219   return (ChildCode64 code rlo)
220
221 iselExpr64 (CmmLoad addrTree I64) = do
222    Amode addr addr_code <- getAmode addrTree
223    (rlo,rhi) <- getNewRegPairNat I32
224    let 
225         mov_lo = MOV I32 (OpAddr addr) (OpReg rlo)
226         mov_hi = MOV I32 (OpAddr (fromJust (addrOffset addr 4))) (OpReg rhi)
227    -- in
228    return (
229             ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi) 
230                         rlo
231      )
232
233 iselExpr64 (CmmReg (CmmLocal (LocalReg vu I64)))
234    = return (ChildCode64 nilOL (mkVReg vu I32))
235          
236 -- we handle addition, but rather badly
237 iselExpr64 (CmmMachOp (MO_Add _) [e1, CmmLit (CmmInt i _)]) = do
238    ChildCode64 code1 r1lo <- iselExpr64 e1
239    (rlo,rhi) <- getNewRegPairNat I32
240    let
241         r = fromIntegral (fromIntegral i :: Word32)
242         q = fromIntegral ((fromIntegral i `shiftR` 32) :: Word32)
243         r1hi = getHiVRegFromLo r1lo
244         code =  code1 `appOL`
245                 toOL [ MOV I32 (OpReg r1lo) (OpReg rlo),
246                        ADD I32 (OpImm (ImmInteger r)) (OpReg rlo),
247                        MOV I32 (OpReg r1hi) (OpReg rhi),
248                        ADC I32 (OpImm (ImmInteger q)) (OpReg rhi) ]
249    -- in
250    return (ChildCode64 code rlo)
251
252 iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
253    ChildCode64 code1 r1lo <- iselExpr64 e1
254    ChildCode64 code2 r2lo <- iselExpr64 e2
255    (rlo,rhi) <- getNewRegPairNat I32
256    let
257         r1hi = getHiVRegFromLo r1lo
258         r2hi = getHiVRegFromLo r2lo
259         code =  code1 `appOL`
260                 code2 `appOL`
261                 toOL [ MOV I32 (OpReg r1lo) (OpReg rlo),
262                        ADD I32 (OpReg r2lo) (OpReg rlo),
263                        MOV I32 (OpReg r1hi) (OpReg rhi),
264                        ADC I32 (OpReg r2hi) (OpReg rhi) ]
265    -- in
266    return (ChildCode64 code rlo)
267
268 iselExpr64 expr
269    = pprPanic "iselExpr64(i386)" (ppr expr)
270
271 #endif /* i386_TARGET_ARCH */
272
273 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
274
275 #if sparc_TARGET_ARCH
276
277 assignMem_I64Code addrTree valueTree = do
278      Amode addr addr_code <- getAmode addrTree
279      ChildCode64 vcode rlo <- iselExpr64 valueTree  
280      (src, code) <- getSomeReg addrTree
281      let 
282          rhi = getHiVRegFromLo rlo
283          -- Big-endian store
284          mov_hi = ST I32 rhi (AddrRegImm src (ImmInt 0))
285          mov_lo = ST I32 rlo (AddrRegImm src (ImmInt 4))
286      return (vcode `appOL` code `snocOL` mov_hi `snocOL` mov_lo)
287
288 assignReg_I64Code (CmmLocal (LocalReg u_dst pk)) valueTree = do
289      ChildCode64 vcode r_src_lo <- iselExpr64 valueTree    
290      let 
291          r_dst_lo = mkVReg u_dst pk
292          r_dst_hi = getHiVRegFromLo r_dst_lo
293          r_src_hi = getHiVRegFromLo r_src_lo
294          mov_lo = mkMOV r_src_lo r_dst_lo
295          mov_hi = mkMOV r_src_hi r_dst_hi
296          mkMOV sreg dreg = OR False g0 (RIReg sreg) dreg
297      return (vcode `snocOL` mov_hi `snocOL` mov_lo)
298 assignReg_I64Code lvalue valueTree
299    = panic "assignReg_I64Code(sparc): invalid lvalue"
300
301
302 -- Don't delete this -- it's very handy for debugging.
303 --iselExpr64 expr 
304 --   | trace ("iselExpr64: " ++ showSDoc (ppr expr)) False
305 --   = panic "iselExpr64(???)"
306
307 iselExpr64 (CmmLoad addrTree I64) = do
308      Amode (AddrRegReg r1 r2) addr_code <- getAmode addrTree
309      rlo <- getNewRegNat I32
310      let rhi = getHiVRegFromLo rlo
311          mov_hi = LD I32 (AddrRegImm r1 (ImmInt 0)) rhi
312          mov_lo = LD I32 (AddrRegImm r1 (ImmInt 4)) rlo
313      return (
314             ChildCode64 (addr_code `snocOL` mov_hi `snocOL` mov_lo) 
315                          rlo
316           )
317
318 iselExpr64 (CmmReg (CmmLocal (LocalReg uq I64))) = do
319      r_dst_lo <-  getNewRegNat I32
320      let r_dst_hi = getHiVRegFromLo r_dst_lo
321          r_src_lo = mkVReg uq I32
322          r_src_hi = getHiVRegFromLo r_src_lo
323          mov_lo = mkMOV r_src_lo r_dst_lo
324          mov_hi = mkMOV r_src_hi r_dst_hi
325          mkMOV sreg dreg = OR False g0 (RIReg sreg) dreg
326      return (
327             ChildCode64 (toOL [mov_hi, mov_lo]) r_dst_lo
328          )
329
330 iselExpr64 expr
331    = pprPanic "iselExpr64(sparc)" (ppr expr)
332
333 #endif /* sparc_TARGET_ARCH */
334
335 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
336
337 #if powerpc_TARGET_ARCH
338
339 getI64Amodes :: CmmExpr -> NatM (AddrMode, AddrMode, InstrBlock)
340 getI64Amodes addrTree = do
341     Amode hi_addr addr_code <- getAmode addrTree
342     case addrOffset hi_addr 4 of
343         Just lo_addr -> return (hi_addr, lo_addr, addr_code)
344         Nothing      -> do (hi_ptr, code) <- getSomeReg addrTree
345                            return (AddrRegImm hi_ptr (ImmInt 0),
346                                    AddrRegImm hi_ptr (ImmInt 4),
347                                    code)
348
349 assignMem_I64Code addrTree valueTree = do
350         (hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
351         ChildCode64 vcode rlo <- iselExpr64 valueTree
352         let 
353                 rhi = getHiVRegFromLo rlo
354
355                 -- Big-endian store
356                 mov_hi = ST I32 rhi hi_addr
357                 mov_lo = ST I32 rlo lo_addr
358         -- in
359         return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
360
361 assignReg_I64Code (CmmLocal (LocalReg u_dst pk)) valueTree = do
362    ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
363    let 
364          r_dst_lo = mkVReg u_dst I32
365          r_dst_hi = getHiVRegFromLo r_dst_lo
366          r_src_hi = getHiVRegFromLo r_src_lo
367          mov_lo = MR r_dst_lo r_src_lo
368          mov_hi = MR r_dst_hi r_src_hi
369    -- in
370    return (
371         vcode `snocOL` mov_lo `snocOL` mov_hi
372      )
373
374 assignReg_I64Code lvalue valueTree
375    = panic "assignReg_I64Code(powerpc): invalid lvalue"
376
377
378 -- Don't delete this -- it's very handy for debugging.
379 --iselExpr64 expr 
380 --   | trace ("iselExpr64: " ++ showSDoc (pprCmmExpr expr)) False
381 --   = panic "iselExpr64(???)"
382
383 iselExpr64 (CmmLoad addrTree I64) = do
384     (hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
385     (rlo, rhi) <- getNewRegPairNat I32
386     let mov_hi = LD I32 rhi hi_addr
387         mov_lo = LD I32 rlo lo_addr
388     return $ ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi) 
389                          rlo
390
391 iselExpr64 (CmmReg (CmmLocal (LocalReg vu I64)))
392    = return (ChildCode64 nilOL (mkVReg vu I32))
393
394 iselExpr64 (CmmLit (CmmInt i _)) = do
395   (rlo,rhi) <- getNewRegPairNat I32
396   let
397         half0 = fromIntegral (fromIntegral i :: Word16)
398         half1 = fromIntegral ((fromIntegral i `shiftR` 16) :: Word16)
399         half2 = fromIntegral ((fromIntegral i `shiftR` 32) :: Word16)
400         half3 = fromIntegral ((fromIntegral i `shiftR` 48) :: Word16)
401         
402         code = toOL [
403                 LIS rlo (ImmInt half1),
404                 OR rlo rlo (RIImm $ ImmInt half0),
405                 LIS rhi (ImmInt half3),
406                 OR rlo rlo (RIImm $ ImmInt half2)
407                 ]
408   -- in
409   return (ChildCode64 code rlo)
410
411 iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
412    ChildCode64 code1 r1lo <- iselExpr64 e1
413    ChildCode64 code2 r2lo <- iselExpr64 e2
414    (rlo,rhi) <- getNewRegPairNat I32
415    let
416         r1hi = getHiVRegFromLo r1lo
417         r2hi = getHiVRegFromLo r2lo
418         code =  code1 `appOL`
419                 code2 `appOL`
420                 toOL [ ADDC rlo r1lo r2lo,
421                        ADDE rhi r1hi r2hi ]
422    -- in
423    return (ChildCode64 code rlo)
424
425 iselExpr64 expr
426    = pprPanic "iselExpr64(powerpc)" (ppr expr)
427
428 #endif /* powerpc_TARGET_ARCH */
429
430
431 -- -----------------------------------------------------------------------------
432 -- The 'Register' type
433
434 -- 'Register's passed up the tree.  If the stix code forces the register
435 -- to live in a pre-decided machine register, it comes out as @Fixed@;
436 -- otherwise, it comes out as @Any@, and the parent can decide which
437 -- register to put it in.
438
439 data Register
440   = Fixed   MachRep Reg InstrBlock
441   | Any     MachRep (Reg -> InstrBlock)
442
443 swizzleRegisterRep :: Register -> MachRep -> Register
444 swizzleRegisterRep (Fixed _ reg code) rep = Fixed rep reg code
445 swizzleRegisterRep (Any _ codefn)     rep = Any rep codefn
446
447
448 -- -----------------------------------------------------------------------------
449 -- Utils based on getRegister, below
450
451 -- The dual to getAnyReg: compute an expression into a register, but
452 -- we don't mind which one it is.
453 getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
454 getSomeReg expr = do
455   r <- getRegister expr
456   case r of
457     Any rep code -> do
458         tmp <- getNewRegNat rep
459         return (tmp, code tmp)
460     Fixed _ reg code -> 
461         return (reg, code)
462
463 -- -----------------------------------------------------------------------------
464 -- Grab the Reg for a CmmReg
465
466 getRegisterReg :: CmmReg -> Reg
467
468 getRegisterReg (CmmLocal (LocalReg u pk))
469   = mkVReg u pk
470
471 getRegisterReg (CmmGlobal mid)
472   = case get_GlobalReg_reg_or_addr mid of
473        Left (RealReg rrno) -> RealReg rrno
474        _other -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
475           -- By this stage, the only MagicIds remaining should be the
476           -- ones which map to a real machine register on this
477           -- platform.  Hence ...
478
479
480 -- -----------------------------------------------------------------------------
481 -- Generate code to get a subtree into a Register
482
483 -- Don't delete this -- it's very handy for debugging.
484 --getRegister expr 
485 --   | trace ("getRegister: " ++ showSDoc (pprCmmExpr expr)) False
486 --   = panic "getRegister(???)"
487
488 getRegister :: CmmExpr -> NatM Register
489
490 #if !x86_64_TARGET_ARCH
491     -- on x86_64, we have %rip for PicBaseReg, but it's not a full-featured
492     -- register, it can only be used for rip-relative addressing.
493 getRegister (CmmReg (CmmGlobal PicBaseReg))
494   = do
495       reg <- getPicBaseNat wordRep
496       return (Fixed wordRep reg nilOL)
497 #endif
498
499 getRegister (CmmReg reg) 
500   = return (Fixed (cmmRegRep reg) (getRegisterReg reg) nilOL)
501
502 getRegister tree@(CmmRegOff _ _) 
503   = getRegister (mangleIndexTree tree)
504
505
506 #if WORD_SIZE_IN_BITS==32
507     -- for 32-bit architectuers, support some 64 -> 32 bit conversions:
508     -- TO_W_(x), TO_W_(x >> 32)
509
510 getRegister (CmmMachOp (MO_U_Conv I64 I32)
511              [CmmMachOp (MO_U_Shr I64) [x,CmmLit (CmmInt 32 _)]]) = do
512   ChildCode64 code rlo <- iselExpr64 x
513   return $ Fixed I32 (getHiVRegFromLo rlo) code
514
515 getRegister (CmmMachOp (MO_S_Conv I64 I32)
516              [CmmMachOp (MO_U_Shr I64) [x,CmmLit (CmmInt 32 _)]]) = do
517   ChildCode64 code rlo <- iselExpr64 x
518   return $ Fixed I32 (getHiVRegFromLo rlo) code
519
520 getRegister (CmmMachOp (MO_U_Conv I64 I32) [x]) = do
521   ChildCode64 code rlo <- iselExpr64 x
522   return $ Fixed I32 rlo code
523
524 getRegister (CmmMachOp (MO_S_Conv I64 I32) [x]) = do
525   ChildCode64 code rlo <- iselExpr64 x
526   return $ Fixed I32 rlo code       
527
528 #endif
529
530 -- end of machine-"independent" bit; here we go on the rest...
531
532 #if alpha_TARGET_ARCH
533
534 getRegister (StDouble d)
535   = getBlockIdNat                   `thenNat` \ lbl ->
536     getNewRegNat PtrRep             `thenNat` \ tmp ->
537     let code dst = mkSeqInstrs [
538             LDATA RoDataSegment lbl [
539                     DATA TF [ImmLab (rational d)]
540                 ],
541             LDA tmp (AddrImm (ImmCLbl lbl)),
542             LD TF dst (AddrReg tmp)]
543     in
544         return (Any F64 code)
545
546 getRegister (StPrim primop [x]) -- unary PrimOps
547   = case primop of
548       IntNegOp -> trivialUCode (NEG Q False) x
549
550       NotOp    -> trivialUCode NOT x
551
552       FloatNegOp  -> trivialUFCode FloatRep  (FNEG TF) x
553       DoubleNegOp -> trivialUFCode F64 (FNEG TF) x
554
555       OrdOp -> coerceIntCode IntRep x
556       ChrOp -> chrCode x
557
558       Float2IntOp  -> coerceFP2Int    x
559       Int2FloatOp  -> coerceInt2FP pr x
560       Double2IntOp -> coerceFP2Int    x
561       Int2DoubleOp -> coerceInt2FP pr x
562
563       Double2FloatOp -> coerceFltCode x
564       Float2DoubleOp -> coerceFltCode x
565
566       other_op -> getRegister (StCall fn CCallConv F64 [x])
567         where
568           fn = case other_op of
569                  FloatExpOp    -> FSLIT("exp")
570                  FloatLogOp    -> FSLIT("log")
571                  FloatSqrtOp   -> FSLIT("sqrt")
572                  FloatSinOp    -> FSLIT("sin")
573                  FloatCosOp    -> FSLIT("cos")
574                  FloatTanOp    -> FSLIT("tan")
575                  FloatAsinOp   -> FSLIT("asin")
576                  FloatAcosOp   -> FSLIT("acos")
577                  FloatAtanOp   -> FSLIT("atan")
578                  FloatSinhOp   -> FSLIT("sinh")
579                  FloatCoshOp   -> FSLIT("cosh")
580                  FloatTanhOp   -> FSLIT("tanh")
581                  DoubleExpOp   -> FSLIT("exp")
582                  DoubleLogOp   -> FSLIT("log")
583                  DoubleSqrtOp  -> FSLIT("sqrt")
584                  DoubleSinOp   -> FSLIT("sin")
585                  DoubleCosOp   -> FSLIT("cos")
586                  DoubleTanOp   -> FSLIT("tan")
587                  DoubleAsinOp  -> FSLIT("asin")
588                  DoubleAcosOp  -> FSLIT("acos")
589                  DoubleAtanOp  -> FSLIT("atan")
590                  DoubleSinhOp  -> FSLIT("sinh")
591                  DoubleCoshOp  -> FSLIT("cosh")
592                  DoubleTanhOp  -> FSLIT("tanh")
593   where
594     pr = panic "MachCode.getRegister: no primrep needed for Alpha"
595
596 getRegister (StPrim primop [x, y]) -- dyadic PrimOps
597   = case primop of
598       CharGtOp -> trivialCode (CMP LTT) y x
599       CharGeOp -> trivialCode (CMP LE) y x
600       CharEqOp -> trivialCode (CMP EQQ) x y
601       CharNeOp -> int_NE_code x y
602       CharLtOp -> trivialCode (CMP LTT) x y
603       CharLeOp -> trivialCode (CMP LE) x y
604
605       IntGtOp  -> trivialCode (CMP LTT) y x
606       IntGeOp  -> trivialCode (CMP LE) y x
607       IntEqOp  -> trivialCode (CMP EQQ) x y
608       IntNeOp  -> int_NE_code x y
609       IntLtOp  -> trivialCode (CMP LTT) x y
610       IntLeOp  -> trivialCode (CMP LE) x y
611
612       WordGtOp -> trivialCode (CMP ULT) y x
613       WordGeOp -> trivialCode (CMP ULE) x y
614       WordEqOp -> trivialCode (CMP EQQ)  x y
615       WordNeOp -> int_NE_code x y
616       WordLtOp -> trivialCode (CMP ULT) x y
617       WordLeOp -> trivialCode (CMP ULE) x y
618
619       AddrGtOp -> trivialCode (CMP ULT) y x
620       AddrGeOp -> trivialCode (CMP ULE) y x
621       AddrEqOp -> trivialCode (CMP EQQ)  x y
622       AddrNeOp -> int_NE_code x y
623       AddrLtOp -> trivialCode (CMP ULT) x y
624       AddrLeOp -> trivialCode (CMP ULE) x y
625         
626       FloatGtOp -> cmpF_code (FCMP TF LE) EQQ x y
627       FloatGeOp -> cmpF_code (FCMP TF LTT) EQQ x y
628       FloatEqOp -> cmpF_code (FCMP TF EQQ) NE x y
629       FloatNeOp -> cmpF_code (FCMP TF EQQ) EQQ x y
630       FloatLtOp -> cmpF_code (FCMP TF LTT) NE x y
631       FloatLeOp -> cmpF_code (FCMP TF LE) NE x y
632
633       DoubleGtOp -> cmpF_code (FCMP TF LE) EQQ x y
634       DoubleGeOp -> cmpF_code (FCMP TF LTT) EQQ x y
635       DoubleEqOp -> cmpF_code (FCMP TF EQQ) NE x y
636       DoubleNeOp -> cmpF_code (FCMP TF EQQ) EQQ x y
637       DoubleLtOp -> cmpF_code (FCMP TF LTT) NE x y
638       DoubleLeOp -> cmpF_code (FCMP TF LE) NE x y
639
640       IntAddOp  -> trivialCode (ADD Q False) x y
641       IntSubOp  -> trivialCode (SUB Q False) x y
642       IntMulOp  -> trivialCode (MUL Q False) x y
643       IntQuotOp -> trivialCode (DIV Q False) x y
644       IntRemOp  -> trivialCode (REM Q False) x y
645
646       WordAddOp  -> trivialCode (ADD Q False) x y
647       WordSubOp  -> trivialCode (SUB Q False) x y
648       WordMulOp  -> trivialCode (MUL Q False) x y
649       WordQuotOp -> trivialCode (DIV Q True) x y
650       WordRemOp  -> trivialCode (REM Q True) x y
651
652       FloatAddOp -> trivialFCode  FloatRep (FADD TF) x y
653       FloatSubOp -> trivialFCode  FloatRep (FSUB TF) x y
654       FloatMulOp -> trivialFCode  FloatRep (FMUL TF) x y
655       FloatDivOp -> trivialFCode  FloatRep (FDIV TF) x y
656
657       DoubleAddOp -> trivialFCode  F64 (FADD TF) x y
658       DoubleSubOp -> trivialFCode  F64 (FSUB TF) x y
659       DoubleMulOp -> trivialFCode  F64 (FMUL TF) x y
660       DoubleDivOp -> trivialFCode  F64 (FDIV TF) x y
661
662       AddrAddOp  -> trivialCode (ADD Q False) x y
663       AddrSubOp  -> trivialCode (SUB Q False) x y
664       AddrRemOp  -> trivialCode (REM Q True) x y
665
666       AndOp  -> trivialCode AND x y
667       OrOp   -> trivialCode OR  x y
668       XorOp  -> trivialCode XOR x y
669       SllOp  -> trivialCode SLL x y
670       SrlOp  -> trivialCode SRL x y
671
672       ISllOp -> trivialCode SLL x y -- was: panic "AlphaGen:isll"
673       ISraOp -> trivialCode SRA x y -- was: panic "AlphaGen:isra"
674       ISrlOp -> trivialCode SRL x y -- was: panic "AlphaGen:isrl"
675
676       FloatPowerOp  -> getRegister (StCall FSLIT("pow") CCallConv F64 [x,y])
677       DoublePowerOp -> getRegister (StCall FSLIT("pow") CCallConv F64 [x,y])
678   where
679     {- ------------------------------------------------------------
680         Some bizarre special code for getting condition codes into
681         registers.  Integer non-equality is a test for equality
682         followed by an XOR with 1.  (Integer comparisons always set
683         the result register to 0 or 1.)  Floating point comparisons of
684         any kind leave the result in a floating point register, so we
685         need to wrangle an integer register out of things.
686     -}
687     int_NE_code :: StixTree -> StixTree -> NatM Register
688
689     int_NE_code x y
690       = trivialCode (CMP EQQ) x y       `thenNat` \ register ->
691         getNewRegNat IntRep             `thenNat` \ tmp ->
692         let
693             code = registerCode register tmp
694             src  = registerName register tmp
695             code__2 dst = code . mkSeqInstr (XOR src (RIImm (ImmInt 1)) dst)
696         in
697         return (Any IntRep code__2)
698
699     {- ------------------------------------------------------------
700         Comments for int_NE_code also apply to cmpF_code
701     -}
702     cmpF_code
703         :: (Reg -> Reg -> Reg -> Instr)
704         -> Cond
705         -> StixTree -> StixTree
706         -> NatM Register
707
708     cmpF_code instr cond x y
709       = trivialFCode pr instr x y       `thenNat` \ register ->
710         getNewRegNat F64                `thenNat` \ tmp ->
711         getBlockIdNat                   `thenNat` \ lbl ->
712         let
713             code = registerCode register tmp
714             result  = registerName register tmp
715
716             code__2 dst = code . mkSeqInstrs [
717                 OR zeroh (RIImm (ImmInt 1)) dst,
718                 BF cond  result (ImmCLbl lbl),
719                 OR zeroh (RIReg zeroh) dst,
720                 NEWBLOCK lbl]
721         in
722         return (Any IntRep code__2)
723       where
724         pr = panic "trivialU?FCode: does not use PrimRep on Alpha"
725       ------------------------------------------------------------
726
727 getRegister (CmmLoad pk mem)
728   = getAmode mem                    `thenNat` \ amode ->
729     let
730         code = amodeCode amode
731         src   = amodeAddr amode
732         size = primRepToSize pk
733         code__2 dst = code . mkSeqInstr (LD size dst src)
734     in
735     return (Any pk code__2)
736
737 getRegister (StInt i)
738   | fits8Bits i
739   = let
740         code dst = mkSeqInstr (OR zeroh (RIImm src) dst)
741     in
742     return (Any IntRep code)
743   | otherwise
744   = let
745         code dst = mkSeqInstr (LDI Q dst src)
746     in
747     return (Any IntRep code)
748   where
749     src = ImmInt (fromInteger i)
750
751 getRegister leaf
752   | isJust imm
753   = let
754         code dst = mkSeqInstr (LDA dst (AddrImm imm__2))
755     in
756     return (Any PtrRep code)
757   where
758     imm = maybeImm leaf
759     imm__2 = case imm of Just x -> x
760
761 #endif /* alpha_TARGET_ARCH */
762
763 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
764
765 #if i386_TARGET_ARCH
766
767 getRegister (CmmLit (CmmFloat f F32)) = do
768     lbl <- getNewLabelNat
769     dynRef <- cmmMakeDynamicReference addImportNat DataReference lbl
770     Amode addr addr_code <- getAmode dynRef
771     let code dst =
772             LDATA ReadOnlyData
773                         [CmmDataLabel lbl,
774                          CmmStaticLit (CmmFloat f F32)]
775             `consOL` (addr_code `snocOL`
776             GLD F32 addr dst)
777     -- in
778     return (Any F32 code)
779
780
781 getRegister (CmmLit (CmmFloat d F64))
782   | d == 0.0
783   = let code dst = unitOL (GLDZ dst)
784     in  return (Any F64 code)
785
786   | d == 1.0
787   = let code dst = unitOL (GLD1 dst)
788     in  return (Any F64 code)
789
790   | otherwise = do
791     lbl <- getNewLabelNat
792     dynRef <- cmmMakeDynamicReference addImportNat DataReference lbl
793     Amode addr addr_code <- getAmode dynRef
794     let code dst =
795             LDATA ReadOnlyData
796                         [CmmDataLabel lbl,
797                          CmmStaticLit (CmmFloat d F64)]
798             `consOL` (addr_code `snocOL`
799             GLD F64 addr dst)
800     -- in
801     return (Any F64 code)
802
803 #endif /* i386_TARGET_ARCH */
804
805 #if x86_64_TARGET_ARCH
806
807 getRegister (CmmLit (CmmFloat 0.0 rep)) = do
808    let code dst = unitOL  (XOR rep (OpReg dst) (OpReg dst))
809         -- I don't know why there are xorpd, xorps, and pxor instructions.
810         -- They all appear to do the same thing --SDM
811    return (Any rep code)
812
813 getRegister (CmmLit (CmmFloat f rep)) = do
814     lbl <- getNewLabelNat
815     let code dst = toOL [
816             LDATA ReadOnlyData
817                         [CmmDataLabel lbl,
818                          CmmStaticLit (CmmFloat f rep)],
819             MOV rep (OpAddr (ripRel (ImmCLbl lbl))) (OpReg dst)
820             ]
821     -- in
822     return (Any rep code)
823
824 #endif /* x86_64_TARGET_ARCH */
825
826 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
827
828 -- catch simple cases of zero- or sign-extended load
829 getRegister (CmmMachOp (MO_U_Conv I8 I32) [CmmLoad addr _]) = do
830   code <- intLoadCode (MOVZxL I8) addr
831   return (Any I32 code)
832
833 getRegister (CmmMachOp (MO_S_Conv I8 I32) [CmmLoad addr _]) = do
834   code <- intLoadCode (MOVSxL I8) addr
835   return (Any I32 code)
836
837 getRegister (CmmMachOp (MO_U_Conv I16 I32) [CmmLoad addr _]) = do
838   code <- intLoadCode (MOVZxL I16) addr
839   return (Any I32 code)
840
841 getRegister (CmmMachOp (MO_S_Conv I16 I32) [CmmLoad addr _]) = do
842   code <- intLoadCode (MOVSxL I16) addr
843   return (Any I32 code)
844
845 #endif
846
847 #if x86_64_TARGET_ARCH
848
849 -- catch simple cases of zero- or sign-extended load
850 getRegister (CmmMachOp (MO_U_Conv I8 I64) [CmmLoad addr _]) = do
851   code <- intLoadCode (MOVZxL I8) addr
852   return (Any I64 code)
853
854 getRegister (CmmMachOp (MO_S_Conv I8 I64) [CmmLoad addr _]) = do
855   code <- intLoadCode (MOVSxL I8) addr
856   return (Any I64 code)
857
858 getRegister (CmmMachOp (MO_U_Conv I16 I64) [CmmLoad addr _]) = do
859   code <- intLoadCode (MOVZxL I16) addr
860   return (Any I64 code)
861
862 getRegister (CmmMachOp (MO_S_Conv I16 I64) [CmmLoad addr _]) = do
863   code <- intLoadCode (MOVSxL I16) addr
864   return (Any I64 code)
865
866 getRegister (CmmMachOp (MO_U_Conv I32 I64) [CmmLoad addr _]) = do
867   code <- intLoadCode (MOV I32) addr -- 32-bit loads zero-extend
868   return (Any I64 code)
869
870 getRegister (CmmMachOp (MO_S_Conv I32 I64) [CmmLoad addr _]) = do
871   code <- intLoadCode (MOVSxL I32) addr
872   return (Any I64 code)
873
874 #endif
875
876 #if x86_64_TARGET_ARCH
877 getRegister (CmmMachOp (MO_Add I64) [CmmReg (CmmGlobal PicBaseReg),
878                                      CmmLit displacement])
879     = return $ Any I64 (\dst -> unitOL $
880         LEA I64 (OpAddr (ripRel (litToImm displacement))) (OpReg dst))
881 #endif
882
883 #if x86_64_TARGET_ARCH
884 getRegister (CmmMachOp (MO_S_Neg F32) [x]) = do
885   x_code <- getAnyReg x
886   lbl <- getNewLabelNat
887   let
888     code dst = x_code dst `appOL` toOL [
889         -- This is how gcc does it, so it can't be that bad:
890         LDATA ReadOnlyData16 [
891                 CmmAlign 16,
892                 CmmDataLabel lbl,
893                 CmmStaticLit (CmmInt 0x80000000 I32),
894                 CmmStaticLit (CmmInt 0 I32),
895                 CmmStaticLit (CmmInt 0 I32),
896                 CmmStaticLit (CmmInt 0 I32)
897         ],
898         XOR F32 (OpAddr (ripRel (ImmCLbl lbl))) (OpReg dst)
899                 -- xorps, so we need the 128-bit constant
900                 -- ToDo: rip-relative
901         ]
902   --
903   return (Any F32 code)
904
905 getRegister (CmmMachOp (MO_S_Neg F64) [x]) = do
906   x_code <- getAnyReg x
907   lbl <- getNewLabelNat
908   let
909         -- This is how gcc does it, so it can't be that bad:
910     code dst = x_code dst `appOL` toOL [
911         LDATA ReadOnlyData16 [
912                 CmmAlign 16,
913                 CmmDataLabel lbl,
914                 CmmStaticLit (CmmInt 0x8000000000000000 I64),
915                 CmmStaticLit (CmmInt 0 I64)
916         ],
917                 -- gcc puts an unpck here.  Wonder if we need it.
918         XOR F64 (OpAddr (ripRel (ImmCLbl lbl))) (OpReg dst)
919                 -- xorpd, so we need the 128-bit constant
920         ]
921   --
922   return (Any F64 code)
923 #endif
924
925 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
926
927 getRegister (CmmMachOp mop [x]) -- unary MachOps
928   = case mop of
929 #if i386_TARGET_ARCH
930       MO_S_Neg F32 -> trivialUFCode F32 (GNEG F32) x
931       MO_S_Neg F64 -> trivialUFCode F64 (GNEG F64) x
932 #endif
933
934       MO_S_Neg rep -> trivialUCode rep (NEGI rep) x
935       MO_Not rep   -> trivialUCode rep (NOT  rep) x
936
937       -- Nop conversions
938       MO_U_Conv I32 I8  -> toI8Reg  I32 x
939       MO_S_Conv I32 I8  -> toI8Reg  I32 x
940       MO_U_Conv I16 I8  -> toI8Reg  I16 x
941       MO_S_Conv I16 I8  -> toI8Reg  I16 x
942       MO_U_Conv I32 I16 -> toI16Reg I32 x
943       MO_S_Conv I32 I16 -> toI16Reg I32 x
944 #if x86_64_TARGET_ARCH
945       MO_U_Conv I64 I32 -> conversionNop I64 x
946       MO_S_Conv I64 I32 -> conversionNop I64 x
947       MO_U_Conv I64 I16 -> toI16Reg I64 x
948       MO_S_Conv I64 I16 -> toI16Reg I64 x
949       MO_U_Conv I64 I8  -> toI8Reg  I64 x
950       MO_S_Conv I64 I8  -> toI8Reg  I64 x
951 #endif
952
953       MO_U_Conv rep1 rep2 | rep1 == rep2 -> conversionNop rep1 x
954       MO_S_Conv rep1 rep2 | rep1 == rep2 -> conversionNop rep1 x
955
956       -- widenings
957       MO_U_Conv I8  I32 -> integerExtend I8  I32 MOVZxL x
958       MO_U_Conv I16 I32 -> integerExtend I16 I32 MOVZxL x
959       MO_U_Conv I8  I16 -> integerExtend I8  I16 MOVZxL x
960
961       MO_S_Conv I8  I32 -> integerExtend I8  I32 MOVSxL x
962       MO_S_Conv I16 I32 -> integerExtend I16 I32 MOVSxL x
963       MO_S_Conv I8  I16 -> integerExtend I8  I16 MOVSxL x
964
965 #if x86_64_TARGET_ARCH
966       MO_U_Conv I8  I64 -> integerExtend I8  I64 MOVZxL x
967       MO_U_Conv I16 I64 -> integerExtend I16 I64 MOVZxL x
968       MO_U_Conv I32 I64 -> integerExtend I32 I64 MOVZxL x
969       MO_S_Conv I8  I64 -> integerExtend I8  I64 MOVSxL x
970       MO_S_Conv I16 I64 -> integerExtend I16 I64 MOVSxL x
971       MO_S_Conv I32 I64 -> integerExtend I32 I64 MOVSxL x
972         -- for 32-to-64 bit zero extension, amd64 uses an ordinary movl.
973         -- However, we don't want the register allocator to throw it
974         -- away as an unnecessary reg-to-reg move, so we keep it in
975         -- the form of a movzl and print it as a movl later.
976 #endif
977
978 #if i386_TARGET_ARCH
979       MO_S_Conv F32 F64 -> conversionNop F64 x
980       MO_S_Conv F64 F32 -> conversionNop F32 x
981 #else
982       MO_S_Conv F32 F64 -> coerceFP2FP F64 x
983       MO_S_Conv F64 F32 -> coerceFP2FP F32 x
984 #endif
985
986       MO_S_Conv from to
987         | isFloatingRep from -> coerceFP2Int from to x
988         | isFloatingRep to   -> coerceInt2FP from to x
989
990       other -> pprPanic "getRegister" (pprMachOp mop)
991    where
992         -- signed or unsigned extension.
993         integerExtend from to instr expr = do
994             (reg,e_code) <- if from == I8 then getByteReg expr
995                                           else getSomeReg expr
996             let 
997                 code dst = 
998                   e_code `snocOL`
999                   instr from (OpReg reg) (OpReg dst)
1000             return (Any to code)
1001
1002         toI8Reg new_rep expr
1003             = do codefn <- getAnyReg expr
1004                  return (Any new_rep codefn)
1005                 -- HACK: use getAnyReg to get a byte-addressable register.
1006                 -- If the source was a Fixed register, this will add the
1007                 -- mov instruction to put it into the desired destination.
1008                 -- We're assuming that the destination won't be a fixed
1009                 -- non-byte-addressable register; it won't be, because all
1010                 -- fixed registers are word-sized.
1011
1012         toI16Reg = toI8Reg -- for now
1013
1014         conversionNop new_rep expr
1015             = do e_code <- getRegister expr
1016                  return (swizzleRegisterRep e_code new_rep)
1017
1018
1019 getRegister e@(CmmMachOp mop [x, y]) -- dyadic MachOps
1020   = ASSERT2(cmmExprRep x /= I8, pprExpr e)
1021     case mop of
1022       MO_Eq F32   -> condFltReg EQQ x y
1023       MO_Ne F32   -> condFltReg NE x y
1024       MO_S_Gt F32 -> condFltReg GTT x y
1025       MO_S_Ge F32 -> condFltReg GE x y
1026       MO_S_Lt F32 -> condFltReg LTT x y
1027       MO_S_Le F32 -> condFltReg LE x y
1028
1029       MO_Eq F64   -> condFltReg EQQ x y
1030       MO_Ne F64   -> condFltReg NE x y
1031       MO_S_Gt F64 -> condFltReg GTT x y
1032       MO_S_Ge F64 -> condFltReg GE x y
1033       MO_S_Lt F64 -> condFltReg LTT x y
1034       MO_S_Le F64 -> condFltReg LE x y
1035
1036       MO_Eq rep   -> condIntReg EQQ x y
1037       MO_Ne rep   -> condIntReg NE x y
1038
1039       MO_S_Gt rep -> condIntReg GTT x y
1040       MO_S_Ge rep -> condIntReg GE x y
1041       MO_S_Lt rep -> condIntReg LTT x y
1042       MO_S_Le rep -> condIntReg LE x y
1043
1044       MO_U_Gt rep -> condIntReg GU  x y
1045       MO_U_Ge rep -> condIntReg GEU x y
1046       MO_U_Lt rep -> condIntReg LU  x y
1047       MO_U_Le rep -> condIntReg LEU x y
1048
1049 #if i386_TARGET_ARCH
1050       MO_Add F32 -> trivialFCode F32 GADD x y
1051       MO_Sub F32 -> trivialFCode F32 GSUB x y
1052
1053       MO_Add F64 -> trivialFCode F64 GADD x y
1054       MO_Sub F64 -> trivialFCode F64 GSUB x y
1055
1056       MO_S_Quot F32 -> trivialFCode F32 GDIV x y
1057       MO_S_Quot F64 -> trivialFCode F64 GDIV x y
1058 #endif
1059
1060 #if x86_64_TARGET_ARCH
1061       MO_Add F32 -> trivialFCode F32 ADD x y
1062       MO_Sub F32 -> trivialFCode F32 SUB x y
1063
1064       MO_Add F64 -> trivialFCode F64 ADD x y
1065       MO_Sub F64 -> trivialFCode F64 SUB x y
1066
1067       MO_S_Quot F32 -> trivialFCode F32 FDIV x y
1068       MO_S_Quot F64 -> trivialFCode F64 FDIV x y
1069 #endif
1070
1071       MO_Add rep -> add_code rep x y
1072       MO_Sub rep -> sub_code rep x y
1073
1074       MO_S_Quot rep -> div_code rep True  True  x y
1075       MO_S_Rem  rep -> div_code rep True  False x y
1076       MO_U_Quot rep -> div_code rep False True  x y
1077       MO_U_Rem  rep -> div_code rep False False x y
1078
1079 #if i386_TARGET_ARCH
1080       MO_Mul   F32 -> trivialFCode F32 GMUL x y
1081       MO_Mul   F64 -> trivialFCode F64 GMUL x y
1082 #endif
1083
1084 #if x86_64_TARGET_ARCH
1085       MO_Mul   F32 -> trivialFCode F32 MUL x y
1086       MO_Mul   F64 -> trivialFCode F64 MUL x y
1087 #endif
1088
1089       MO_Mul   rep -> let op = IMUL rep in 
1090                       trivialCode rep op (Just op) x y
1091
1092       MO_S_MulMayOflo rep -> imulMayOflo rep x y
1093
1094       MO_And rep -> let op = AND rep in 
1095                     trivialCode rep op (Just op) x y
1096       MO_Or  rep -> let op = OR  rep in
1097                     trivialCode rep op (Just op) x y
1098       MO_Xor rep -> let op = XOR rep in
1099                     trivialCode rep op (Just op) x y
1100
1101         {- Shift ops on x86s have constraints on their source, it
1102            either has to be Imm, CL or 1
1103             => trivialCode is not restrictive enough (sigh.)
1104         -}         
1105       MO_Shl rep   -> shift_code rep (SHL rep) x y {-False-}
1106       MO_U_Shr rep -> shift_code rep (SHR rep) x y {-False-}
1107       MO_S_Shr rep -> shift_code rep (SAR rep) x y {-False-}
1108
1109       other -> pprPanic "getRegister(x86) - binary CmmMachOp (1)" (pprMachOp mop)
1110   where
1111     --------------------
1112     imulMayOflo :: MachRep -> CmmExpr -> CmmExpr -> NatM Register
1113     imulMayOflo rep a b = do
1114          (a_reg, a_code) <- getNonClobberedReg a
1115          b_code <- getAnyReg b
1116          let 
1117              shift_amt  = case rep of
1118                            I32 -> 31
1119                            I64 -> 63
1120                            _ -> panic "shift_amt"
1121
1122              code = a_code `appOL` b_code eax `appOL`
1123                         toOL [
1124                            IMUL2 rep (OpReg a_reg),   -- result in %edx:%eax
1125                            SAR rep (OpImm (ImmInt shift_amt)) (OpReg eax),
1126                                 -- sign extend lower part
1127                            SUB rep (OpReg edx) (OpReg eax)
1128                                 -- compare against upper
1129                            -- eax==0 if high part == sign extended low part
1130                         ]
1131          -- in
1132          return (Fixed rep eax code)
1133
1134     --------------------
1135     shift_code :: MachRep
1136                -> (Operand -> Operand -> Instr)
1137                -> CmmExpr
1138                -> CmmExpr
1139                -> NatM Register
1140
1141     {- Case1: shift length as immediate -}
1142     shift_code rep instr x y@(CmmLit lit) = do
1143           x_code <- getAnyReg x
1144           let
1145                code dst
1146                   = x_code dst `snocOL` 
1147                     instr (OpImm (litToImm lit)) (OpReg dst)
1148           -- in
1149           return (Any rep code)
1150         
1151     {- Case2: shift length is complex (non-immediate) -}
1152     shift_code rep instr x y{-amount-} = do
1153         (x_reg, x_code) <- getNonClobberedReg x
1154         y_code <- getAnyReg y
1155         let 
1156            code = x_code `appOL`
1157                   y_code ecx `snocOL`
1158                   instr (OpReg ecx) (OpReg x_reg)
1159         -- in
1160         return (Fixed rep x_reg code)
1161
1162     --------------------
1163     add_code :: MachRep -> CmmExpr -> CmmExpr -> NatM Register
1164     add_code rep x (CmmLit (CmmInt y _))
1165         | not (is64BitInteger y) = add_int rep x y
1166     add_code rep x y = trivialCode rep (ADD rep) (Just (ADD rep)) x y
1167
1168     --------------------
1169     sub_code :: MachRep -> CmmExpr -> CmmExpr -> NatM Register
1170     sub_code rep x (CmmLit (CmmInt y _))
1171         | not (is64BitInteger (-y)) = add_int rep x (-y)
1172     sub_code rep x y = trivialCode rep (SUB rep) Nothing x y
1173
1174     -- our three-operand add instruction:
1175     add_int rep x y = do
1176         (x_reg, x_code) <- getSomeReg x
1177         let
1178             imm = ImmInt (fromInteger y)
1179             code dst
1180                = x_code `snocOL`
1181                  LEA rep
1182                         (OpAddr (AddrBaseIndex (EABaseReg x_reg) EAIndexNone imm))
1183                         (OpReg dst)
1184         -- 
1185         return (Any rep code)
1186
1187     ----------------------
1188     div_code rep signed quotient x y = do
1189            (y_op, y_code) <- getRegOrMem y -- cannot be clobbered
1190            x_code <- getAnyReg x
1191            let
1192              widen | signed    = CLTD rep
1193                    | otherwise = XOR rep (OpReg edx) (OpReg edx)
1194
1195              instr | signed    = IDIV
1196                    | otherwise = DIV
1197
1198              code = y_code `appOL`
1199                     x_code eax `appOL`
1200                     toOL [widen, instr rep y_op]
1201
1202              result | quotient  = eax
1203                     | otherwise = edx
1204
1205            -- in
1206            return (Fixed rep result code)
1207
1208
1209 getRegister (CmmLoad mem pk)
1210   | isFloatingRep pk
1211   = do
1212     Amode src mem_code <- getAmode mem
1213     let
1214         code dst = mem_code `snocOL` 
1215                    IF_ARCH_i386(GLD pk src dst,
1216                                 MOV pk (OpAddr src) (OpReg dst))
1217     --
1218     return (Any pk code)
1219
1220 #if i386_TARGET_ARCH
1221 getRegister (CmmLoad mem pk)
1222   | pk /= I64
1223   = do 
1224     code <- intLoadCode (instr pk) mem
1225     return (Any pk code)
1226   where
1227         instr I8  = MOVZxL pk
1228         instr I16 = MOV I16
1229         instr I32 = MOV I32
1230         -- we always zero-extend 8-bit loads, if we
1231         -- can't think of anything better.  This is because
1232         -- we can't guarantee access to an 8-bit variant of every register
1233         -- (esi and edi don't have 8-bit variants), so to make things
1234         -- simpler we do our 8-bit arithmetic with full 32-bit registers.
1235 #endif
1236
1237 #if x86_64_TARGET_ARCH
1238 -- Simpler memory load code on x86_64
1239 getRegister (CmmLoad mem pk)
1240   = do 
1241     code <- intLoadCode (MOV pk) mem
1242     return (Any pk code)
1243 #endif
1244
1245 getRegister (CmmLit (CmmInt 0 rep))
1246   = let
1247         -- x86_64: 32-bit xor is one byte shorter, and zero-extends to 64 bits
1248         adj_rep = case rep of I64 -> I32; _ -> rep
1249         rep1 = IF_ARCH_i386( rep, adj_rep ) 
1250         code dst 
1251            = unitOL (XOR rep1 (OpReg dst) (OpReg dst))
1252     in
1253         return (Any rep code)
1254
1255 #if x86_64_TARGET_ARCH
1256   -- optimisation for loading small literals on x86_64: take advantage
1257   -- of the automatic zero-extension from 32 to 64 bits, because the 32-bit
1258   -- instruction forms are shorter.
1259 getRegister (CmmLit lit) 
1260   | I64 <- cmmLitRep lit, not (isBigLit lit)
1261   = let 
1262         imm = litToImm lit
1263         code dst = unitOL (MOV I32 (OpImm imm) (OpReg dst))
1264     in
1265         return (Any I64 code)
1266   where
1267    isBigLit (CmmInt i I64) = i < 0 || i > 0xffffffff
1268    isBigLit _ = False
1269         -- note1: not the same as is64BitLit, because that checks for
1270         -- signed literals that fit in 32 bits, but we want unsigned
1271         -- literals here.
1272         -- note2: all labels are small, because we're assuming the
1273         -- small memory model (see gcc docs, -mcmodel=small).
1274 #endif
1275
1276 getRegister (CmmLit lit)
1277   = let 
1278         rep = cmmLitRep lit
1279         imm = litToImm lit
1280         code dst = unitOL (MOV rep (OpImm imm) (OpReg dst))
1281     in
1282         return (Any rep code)
1283
1284 getRegister other = pprPanic "getRegister(x86)" (ppr other)
1285
1286
1287 intLoadCode :: (Operand -> Operand -> Instr) -> CmmExpr
1288    -> NatM (Reg -> InstrBlock)
1289 intLoadCode instr mem = do
1290   Amode src mem_code <- getAmode mem
1291   return (\dst -> mem_code `snocOL` instr (OpAddr src) (OpReg dst))
1292
1293 -- Compute an expression into *any* register, adding the appropriate
1294 -- move instruction if necessary.
1295 getAnyReg :: CmmExpr -> NatM (Reg -> InstrBlock)
1296 getAnyReg expr = do
1297   r <- getRegister expr
1298   anyReg r
1299
1300 anyReg :: Register -> NatM (Reg -> InstrBlock)
1301 anyReg (Any _ code)          = return code
1302 anyReg (Fixed rep reg fcode) = return (\dst -> fcode `snocOL` reg2reg rep reg dst)
1303
1304 -- A bit like getSomeReg, but we want a reg that can be byte-addressed.
1305 -- Fixed registers might not be byte-addressable, so we make sure we've
1306 -- got a temporary, inserting an extra reg copy if necessary.
1307 getByteReg :: CmmExpr -> NatM (Reg, InstrBlock)
1308 #if x86_64_TARGET_ARCH
1309 getByteReg = getSomeReg -- all regs are byte-addressable on x86_64
1310 #else
1311 getByteReg expr = do
1312   r <- getRegister expr
1313   case r of
1314     Any rep code -> do
1315         tmp <- getNewRegNat rep
1316         return (tmp, code tmp)
1317     Fixed rep reg code 
1318         | isVirtualReg reg -> return (reg,code)
1319         | otherwise -> do
1320             tmp <- getNewRegNat rep
1321             return (tmp, code `snocOL` reg2reg rep reg tmp)
1322         -- ToDo: could optimise slightly by checking for byte-addressable
1323         -- real registers, but that will happen very rarely if at all.
1324 #endif
1325
1326 -- Another variant: this time we want the result in a register that cannot
1327 -- be modified by code to evaluate an arbitrary expression.
1328 getNonClobberedReg :: CmmExpr -> NatM (Reg, InstrBlock)
1329 getNonClobberedReg expr = do
1330   r <- getRegister expr
1331   case r of
1332     Any rep code -> do
1333         tmp <- getNewRegNat rep
1334         return (tmp, code tmp)
1335     Fixed rep reg code
1336         -- only free regs can be clobbered
1337         | RealReg rr <- reg, isFastTrue (freeReg rr) -> do
1338                 tmp <- getNewRegNat rep
1339                 return (tmp, code `snocOL` reg2reg rep reg tmp)
1340         | otherwise -> 
1341                 return (reg, code)
1342
1343 reg2reg :: MachRep -> Reg -> Reg -> Instr
1344 reg2reg rep src dst 
1345 #if i386_TARGET_ARCH
1346   | isFloatingRep rep = GMOV src dst
1347 #endif
1348   | otherwise         = MOV rep (OpReg src) (OpReg dst)
1349
1350 #endif /* i386_TARGET_ARCH || x86_64_TARGET_ARCH */
1351
1352 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1353
1354 #if sparc_TARGET_ARCH
1355
1356 getRegister (CmmLit (CmmFloat f F32)) = do
1357     lbl <- getNewLabelNat
1358     let code dst = toOL [
1359             LDATA ReadOnlyData
1360                         [CmmDataLabel lbl,
1361                          CmmStaticLit (CmmFloat f F32)],
1362             SETHI (HI (ImmCLbl lbl)) dst,
1363             LD F32 (AddrRegImm dst (LO (ImmCLbl lbl))) dst] 
1364     return (Any F32 code)
1365
1366 getRegister (CmmLit (CmmFloat d F64)) = do
1367     lbl <- getNewLabelNat
1368     let code dst = toOL [
1369             LDATA ReadOnlyData
1370                         [CmmDataLabel lbl,
1371                          CmmStaticLit (CmmFloat d F64)],
1372             SETHI (HI (ImmCLbl lbl)) dst,
1373             LD F64 (AddrRegImm dst (LO (ImmCLbl lbl))) dst] 
1374     return (Any F64 code)
1375
1376 getRegister (CmmMachOp mop [x]) -- unary MachOps
1377   = case mop of
1378       MO_S_Neg F32     -> trivialUFCode F32 (FNEG F32) x
1379       MO_S_Neg F64     -> trivialUFCode F64 (FNEG F64) x
1380
1381       MO_S_Neg rep     -> trivialUCode rep (SUB False False g0) x
1382       MO_Not rep       -> trivialUCode rep (XNOR False g0) x
1383
1384       MO_U_Conv I32 I8 -> trivialCode I8 (AND False) x (CmmLit (CmmInt 255 I8))
1385
1386       MO_U_Conv F64 F32-> coerceDbl2Flt x
1387       MO_U_Conv F32 F64-> coerceFlt2Dbl x
1388
1389       MO_S_Conv F32 I32-> coerceFP2Int F32 I32 x
1390       MO_S_Conv I32 F32-> coerceInt2FP I32 F32 x
1391       MO_S_Conv F64 I32-> coerceFP2Int F64 I32 x
1392       MO_S_Conv I32 F64-> coerceInt2FP I32 F64 x
1393
1394       -- Conversions which are a nop on sparc
1395       MO_U_Conv from to
1396         | from == to   -> conversionNop to   x
1397       MO_U_Conv I32 to -> conversionNop to   x
1398       MO_S_Conv I32 to -> conversionNop to   x
1399
1400       -- widenings
1401       MO_U_Conv I8 I32  -> integerExtend False I8 I32  x
1402       MO_U_Conv I16 I32 -> integerExtend False I16 I32 x
1403       MO_U_Conv I8 I16  -> integerExtend False I8 I16  x
1404       MO_S_Conv I16 I32 -> integerExtend True I16 I32  x
1405
1406       other_op -> panic "Unknown unary mach op"
1407     where
1408         -- XXX SLL/SRL?
1409         integerExtend signed from to expr = do
1410            (reg, e_code) <- getSomeReg expr
1411            let
1412                code dst =
1413                    e_code `snocOL` 
1414                    ((if signed then SRA else SRL)
1415                           reg (RIImm (ImmInt 0)) dst)
1416            return (Any to code)
1417         conversionNop new_rep expr
1418             = do e_code <- getRegister expr
1419                  return (swizzleRegisterRep e_code new_rep)
1420
1421 getRegister (CmmMachOp mop [x, y]) -- dyadic PrimOps
1422   = case mop of
1423       MO_Eq F32 -> condFltReg EQQ x y
1424       MO_Ne F32 -> condFltReg NE x y
1425
1426       MO_S_Gt F32 -> condFltReg GTT x y
1427       MO_S_Ge F32 -> condFltReg GE x y 
1428       MO_S_Lt F32 -> condFltReg LTT x y
1429       MO_S_Le F32 -> condFltReg LE x y
1430
1431       MO_Eq F64 -> condFltReg EQQ x y
1432       MO_Ne F64 -> condFltReg NE x y
1433
1434       MO_S_Gt F64 -> condFltReg GTT x y
1435       MO_S_Ge F64 -> condFltReg GE x y
1436       MO_S_Lt F64 -> condFltReg LTT x y
1437       MO_S_Le F64 -> condFltReg LE x y
1438
1439       MO_Eq rep -> condIntReg EQQ x y
1440       MO_Ne rep -> condIntReg NE x y
1441
1442       MO_S_Gt rep -> condIntReg GTT x y
1443       MO_S_Ge rep -> condIntReg GE x y
1444       MO_S_Lt rep -> condIntReg LTT x y
1445       MO_S_Le rep -> condIntReg LE x y
1446               
1447       MO_U_Gt I32  -> condIntReg GTT x y
1448       MO_U_Ge I32  -> condIntReg GE x y
1449       MO_U_Lt I32  -> condIntReg LTT x y
1450       MO_U_Le I32  -> condIntReg LE x y
1451
1452       MO_U_Gt I16 -> condIntReg GU  x y
1453       MO_U_Ge I16 -> condIntReg GEU x y
1454       MO_U_Lt I16 -> condIntReg LU  x y
1455       MO_U_Le I16 -> condIntReg LEU x y
1456
1457       MO_Add I32 -> trivialCode I32 (ADD False False) x y
1458       MO_Sub I32 -> trivialCode I32 (SUB False False) x y
1459
1460       MO_S_MulMayOflo rep -> imulMayOflo rep x y
1461 {-
1462       -- ToDo: teach about V8+ SPARC div instructions
1463       MO_S_Quot I32 -> idiv FSLIT(".div")  x y
1464       MO_S_Rem I32  -> idiv FSLIT(".rem")  x y
1465       MO_U_Quot I32 -> idiv FSLIT(".udiv")  x y
1466       MO_U_Rem I32  -> idiv FSLIT(".urem")  x y
1467 -}
1468       MO_Add F32  -> trivialFCode F32 FADD  x y
1469       MO_Sub F32   -> trivialFCode F32  FSUB x y
1470       MO_Mul F32   -> trivialFCode F32  FMUL  x y
1471       MO_S_Quot F32   -> trivialFCode F32  FDIV x y
1472
1473       MO_Add F64   -> trivialFCode F64 FADD  x y
1474       MO_Sub F64   -> trivialFCode F64  FSUB x y
1475       MO_Mul F64   -> trivialFCode F64  FMUL x y
1476       MO_S_Quot F64   -> trivialFCode F64  FDIV x y
1477
1478       MO_And rep   -> trivialCode rep (AND False) x y
1479       MO_Or rep    -> trivialCode rep (OR  False) x y
1480       MO_Xor rep   -> trivialCode rep (XOR False) x y
1481
1482       MO_Mul rep -> trivialCode rep (SMUL False) x y
1483
1484       MO_Shl rep   -> trivialCode rep SLL  x y
1485       MO_U_Shr rep   -> trivialCode rep SRL x y
1486       MO_S_Shr rep   -> trivialCode rep SRA x y
1487
1488 {-
1489       MO_F32_Pwr  -> getRegister (StCall (Left FSLIT("pow")) CCallConv F64 
1490                                          [promote x, promote y])
1491                        where promote x = CmmMachOp MO_F32_to_Dbl [x]
1492       MO_F64_Pwr -> getRegister (StCall (Left FSLIT("pow")) CCallConv F64 
1493                                         [x, y])
1494 -}
1495       other -> pprPanic "getRegister(sparc) - binary CmmMachOp (1)" (pprMachOp mop)
1496   where
1497     --idiv fn x y = getRegister (StCall (Left fn) CCallConv I32 [x, y])
1498
1499     --------------------
1500     imulMayOflo :: MachRep -> CmmExpr -> CmmExpr -> NatM Register
1501     imulMayOflo rep a b = do
1502          (a_reg, a_code) <- getSomeReg a
1503          (b_reg, b_code) <- getSomeReg b
1504          res_lo <- getNewRegNat I32
1505          res_hi <- getNewRegNat I32
1506          let
1507             shift_amt  = case rep of
1508                           I32 -> 31
1509                           I64 -> 63
1510                           _ -> panic "shift_amt"
1511             code dst = a_code `appOL` b_code `appOL`
1512                        toOL [
1513                            SMUL False a_reg (RIReg b_reg) res_lo,
1514                            RDY res_hi,
1515                            SRA res_lo (RIImm (ImmInt shift_amt)) res_lo,
1516                            SUB False False res_lo (RIReg res_hi) dst
1517                         ]
1518          return (Any I32 code)
1519
1520 getRegister (CmmLoad mem pk) = do
1521     Amode src code <- getAmode mem
1522     let
1523         code__2 dst = code `snocOL` LD pk src dst
1524     return (Any pk code__2)
1525
1526 getRegister (CmmLit (CmmInt i _))
1527   | fits13Bits i
1528   = let
1529         src = ImmInt (fromInteger i)
1530         code dst = unitOL (OR False g0 (RIImm src) dst)
1531     in
1532         return (Any I32 code)
1533
1534 getRegister (CmmLit lit)
1535   = let rep = cmmLitRep lit
1536         imm = litToImm lit
1537         code dst = toOL [
1538             SETHI (HI imm) dst,
1539             OR False dst (RIImm (LO imm)) dst]
1540     in return (Any I32 code)
1541
1542 #endif /* sparc_TARGET_ARCH */
1543
1544 #if powerpc_TARGET_ARCH
1545 getRegister (CmmLoad mem pk)
1546   | pk /= I64
1547   = do
1548         Amode addr addr_code <- getAmode mem
1549         let code dst = ASSERT((regClass dst == RcDouble) == isFloatingRep pk)
1550                        addr_code `snocOL` LD pk dst addr
1551         return (Any pk code)
1552
1553 -- catch simple cases of zero- or sign-extended load
1554 getRegister (CmmMachOp (MO_U_Conv I8 I32) [CmmLoad mem _]) = do
1555     Amode addr addr_code <- getAmode mem
1556     return (Any I32 (\dst -> addr_code `snocOL` LD I8 dst addr))
1557
1558 -- Note: there is no Load Byte Arithmetic instruction, so no signed case here
1559
1560 getRegister (CmmMachOp (MO_U_Conv I16 I32) [CmmLoad mem _]) = do
1561     Amode addr addr_code <- getAmode mem
1562     return (Any I32 (\dst -> addr_code `snocOL` LD I16 dst addr))
1563
1564 getRegister (CmmMachOp (MO_S_Conv I16 I32) [CmmLoad mem _]) = do
1565     Amode addr addr_code <- getAmode mem
1566     return (Any I32 (\dst -> addr_code `snocOL` LA I16 dst addr))
1567
1568 getRegister (CmmMachOp mop [x]) -- unary MachOps
1569   = case mop of
1570       MO_Not rep   -> trivialUCode rep NOT x
1571
1572       MO_S_Conv F64 F32 -> trivialUCode F32 FRSP x
1573       MO_S_Conv F32 F64 -> conversionNop F64 x
1574
1575       MO_S_Conv from to
1576         | from == to         -> conversionNop to x
1577         | isFloatingRep from -> coerceFP2Int from to x
1578         | isFloatingRep to   -> coerceInt2FP from to x
1579
1580         -- narrowing is a nop: we treat the high bits as undefined
1581       MO_S_Conv I32 to -> conversionNop to x
1582       MO_S_Conv I16 I8 -> conversionNop I8 x
1583       MO_S_Conv I8 to -> trivialUCode to (EXTS I8) x
1584       MO_S_Conv I16 to -> trivialUCode to (EXTS I16) x
1585
1586       MO_U_Conv from to
1587         | from == to -> conversionNop to x
1588         -- narrowing is a nop: we treat the high bits as undefined
1589       MO_U_Conv I32 to -> conversionNop to x
1590       MO_U_Conv I16 I8 -> conversionNop I8 x
1591       MO_U_Conv I8 to -> trivialCode to False AND x (CmmLit (CmmInt 255 I32))
1592       MO_U_Conv I16 to -> trivialCode to False AND x (CmmLit (CmmInt 65535 I32)) 
1593
1594       MO_S_Neg F32      -> trivialUCode F32 FNEG x
1595       MO_S_Neg F64      -> trivialUCode F64 FNEG x
1596       MO_S_Neg rep      -> trivialUCode rep NEG x
1597       
1598     where
1599         conversionNop new_rep expr
1600             = do e_code <- getRegister expr
1601                  return (swizzleRegisterRep e_code new_rep)
1602
1603 getRegister (CmmMachOp mop [x, y]) -- dyadic PrimOps
1604   = case mop of
1605       MO_Eq F32 -> condFltReg EQQ x y
1606       MO_Ne F32 -> condFltReg NE  x y
1607
1608       MO_S_Gt F32 -> condFltReg GTT x y
1609       MO_S_Ge F32 -> condFltReg GE  x y
1610       MO_S_Lt F32 -> condFltReg LTT x y
1611       MO_S_Le F32 -> condFltReg LE  x y
1612
1613       MO_Eq F64 -> condFltReg EQQ x y
1614       MO_Ne F64 -> condFltReg NE  x y
1615
1616       MO_S_Gt F64 -> condFltReg GTT x y
1617       MO_S_Ge F64 -> condFltReg GE  x y
1618       MO_S_Lt F64 -> condFltReg LTT x y
1619       MO_S_Le F64 -> condFltReg LE  x y
1620
1621       MO_Eq rep -> condIntReg EQQ  (extendUExpr rep x) (extendUExpr rep y)
1622       MO_Ne rep -> condIntReg NE   (extendUExpr rep x) (extendUExpr rep y)
1623
1624       MO_S_Gt rep -> condIntReg GTT  (extendSExpr rep x) (extendSExpr rep y)
1625       MO_S_Ge rep -> condIntReg GE   (extendSExpr rep x) (extendSExpr rep y)
1626       MO_S_Lt rep -> condIntReg LTT  (extendSExpr rep x) (extendSExpr rep y)
1627       MO_S_Le rep -> condIntReg LE   (extendSExpr rep x) (extendSExpr rep y)
1628
1629       MO_U_Gt rep -> condIntReg GU   (extendUExpr rep x) (extendUExpr rep y)
1630       MO_U_Ge rep -> condIntReg GEU  (extendUExpr rep x) (extendUExpr rep y)
1631       MO_U_Lt rep -> condIntReg LU   (extendUExpr rep x) (extendUExpr rep y)
1632       MO_U_Le rep -> condIntReg LEU  (extendUExpr rep x) (extendUExpr rep y)
1633
1634       MO_Add F32   -> trivialCodeNoImm F32 (FADD F32) x y
1635       MO_Sub F32   -> trivialCodeNoImm F32 (FSUB F32) x y
1636       MO_Mul F32   -> trivialCodeNoImm F32 (FMUL F32) x y
1637       MO_S_Quot F32   -> trivialCodeNoImm F32 (FDIV F32) x y
1638       
1639       MO_Add F64   -> trivialCodeNoImm F64 (FADD F64) x y
1640       MO_Sub F64   -> trivialCodeNoImm F64 (FSUB F64) x y
1641       MO_Mul F64   -> trivialCodeNoImm F64 (FMUL F64) x y
1642       MO_S_Quot F64   -> trivialCodeNoImm F64 (FDIV F64) x y
1643
1644          -- optimize addition with 32-bit immediate
1645          -- (needed for PIC)
1646       MO_Add I32 ->
1647         case y of
1648           CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate I32 True (-imm)
1649             -> trivialCode I32 True ADD x (CmmLit $ CmmInt imm immrep)
1650           CmmLit lit
1651             -> do
1652                 (src, srcCode) <- getSomeReg x
1653                 let imm = litToImm lit
1654                     code dst = srcCode `appOL` toOL [
1655                                     ADDIS dst src (HA imm),
1656                                     ADD dst dst (RIImm (LO imm))
1657                                 ]
1658                 return (Any I32 code)
1659           _ -> trivialCode I32 True ADD x y
1660
1661       MO_Add rep -> trivialCode rep True ADD x y
1662       MO_Sub rep ->
1663         case y of    -- subfi ('substract from' with immediate) doesn't exist
1664           CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate rep True (-imm)
1665             -> trivialCode rep True ADD x (CmmLit $ CmmInt (-imm) immrep)
1666           _ -> trivialCodeNoImm rep SUBF y x
1667
1668       MO_Mul rep -> trivialCode rep True MULLW x y
1669
1670       MO_S_MulMayOflo I32 -> trivialCodeNoImm I32 MULLW_MayOflo x y
1671       
1672       MO_S_MulMayOflo rep -> panic "S_MulMayOflo (rep /= I32): not implemented"
1673       MO_U_MulMayOflo rep -> panic "U_MulMayOflo: not implemented"
1674
1675       MO_S_Quot rep -> trivialCodeNoImm rep DIVW (extendSExpr rep x) (extendSExpr rep y)
1676       MO_U_Quot rep -> trivialCodeNoImm rep DIVWU (extendUExpr rep x) (extendUExpr rep y)
1677       
1678       MO_S_Rem rep -> remainderCode rep DIVW (extendSExpr rep x) (extendSExpr rep y)
1679       MO_U_Rem rep -> remainderCode rep DIVWU (extendUExpr rep x) (extendUExpr rep y)
1680       
1681       MO_And rep   -> trivialCode rep False AND x y
1682       MO_Or rep    -> trivialCode rep False OR x y
1683       MO_Xor rep   -> trivialCode rep False XOR x y
1684
1685       MO_Shl rep   -> trivialCode rep False SLW x y
1686       MO_S_Shr rep -> trivialCode rep False SRAW (extendSExpr rep x) y
1687       MO_U_Shr rep -> trivialCode rep False SRW (extendUExpr rep x) y
1688
1689 getRegister (CmmLit (CmmInt i rep))
1690   | Just imm <- makeImmediate rep True i
1691   = let
1692         code dst = unitOL (LI dst imm)
1693     in
1694         return (Any rep code)
1695
1696 getRegister (CmmLit (CmmFloat f frep)) = do
1697     lbl <- getNewLabelNat
1698     dynRef <- cmmMakeDynamicReference addImportNat DataReference lbl
1699     Amode addr addr_code <- getAmode dynRef
1700     let code dst = 
1701             LDATA ReadOnlyData  [CmmDataLabel lbl,
1702                                  CmmStaticLit (CmmFloat f frep)]
1703             `consOL` (addr_code `snocOL` LD frep dst addr)
1704     return (Any frep code)
1705
1706 getRegister (CmmLit lit)
1707   = let rep = cmmLitRep lit
1708         imm = litToImm lit
1709         code dst = toOL [
1710               LIS dst (HI imm),
1711               OR dst dst (RIImm (LO imm))
1712           ]
1713     in return (Any rep code)
1714
1715 getRegister other = pprPanic "getRegister(ppc)" (pprExpr other)
1716     
1717     -- extend?Rep: wrap integer expression of type rep
1718     -- in a conversion to I32
1719 extendSExpr I32 x = x
1720 extendSExpr rep x = CmmMachOp (MO_S_Conv rep I32) [x]
1721 extendUExpr I32 x = x
1722 extendUExpr rep x = CmmMachOp (MO_U_Conv rep I32) [x]
1723
1724 #endif /* powerpc_TARGET_ARCH */
1725
1726
1727 -- -----------------------------------------------------------------------------
1728 --  The 'Amode' type: Memory addressing modes passed up the tree.
1729
1730 data Amode = Amode AddrMode InstrBlock
1731
1732 {-
1733 Now, given a tree (the argument to an CmmLoad) that references memory,
1734 produce a suitable addressing mode.
1735
1736 A Rule of the Game (tm) for Amodes: use of the addr bit must
1737 immediately follow use of the code part, since the code part puts
1738 values in registers which the addr then refers to.  So you can't put
1739 anything in between, lest it overwrite some of those registers.  If
1740 you need to do some other computation between the code part and use of
1741 the addr bit, first store the effective address from the amode in a
1742 temporary, then do the other computation, and then use the temporary:
1743
1744     code
1745     LEA amode, tmp
1746     ... other computation ...
1747     ... (tmp) ...
1748 -}
1749
1750 getAmode :: CmmExpr -> NatM Amode
1751 getAmode tree@(CmmRegOff _ _) = getAmode (mangleIndexTree tree)
1752
1753 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1754
1755 #if alpha_TARGET_ARCH
1756
1757 getAmode (StPrim IntSubOp [x, StInt i])
1758   = getNewRegNat PtrRep         `thenNat` \ tmp ->
1759     getRegister x               `thenNat` \ register ->
1760     let
1761         code = registerCode register tmp
1762         reg  = registerName register tmp
1763         off  = ImmInt (-(fromInteger i))
1764     in
1765     return (Amode (AddrRegImm reg off) code)
1766
1767 getAmode (StPrim IntAddOp [x, StInt i])
1768   = getNewRegNat PtrRep         `thenNat` \ tmp ->
1769     getRegister x               `thenNat` \ register ->
1770     let
1771         code = registerCode register tmp
1772         reg  = registerName register tmp
1773         off  = ImmInt (fromInteger i)
1774     in
1775     return (Amode (AddrRegImm reg off) code)
1776
1777 getAmode leaf
1778   | isJust imm
1779   = return (Amode (AddrImm imm__2) id)
1780   where
1781     imm = maybeImm leaf
1782     imm__2 = case imm of Just x -> x
1783
1784 getAmode other
1785   = getNewRegNat PtrRep         `thenNat` \ tmp ->
1786     getRegister other           `thenNat` \ register ->
1787     let
1788         code = registerCode register tmp
1789         reg  = registerName register tmp
1790     in
1791     return (Amode (AddrReg reg) code)
1792
1793 #endif /* alpha_TARGET_ARCH */
1794
1795 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1796
1797 #if x86_64_TARGET_ARCH
1798
1799 getAmode (CmmMachOp (MO_Add I64) [CmmReg (CmmGlobal PicBaseReg),
1800                                      CmmLit displacement])
1801     = return $ Amode (ripRel (litToImm displacement)) nilOL
1802
1803 #endif
1804
1805 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
1806
1807 -- This is all just ridiculous, since it carefully undoes 
1808 -- what mangleIndexTree has just done.
1809 getAmode (CmmMachOp (MO_Sub rep) [x, CmmLit lit@(CmmInt i _)])
1810   | not (is64BitLit lit)
1811   -- ASSERT(rep == I32)???
1812   = do (x_reg, x_code) <- getSomeReg x
1813        let off = ImmInt (-(fromInteger i))
1814        return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
1815   
1816 getAmode (CmmMachOp (MO_Add rep) [x, CmmLit lit@(CmmInt i _)])
1817   | not (is64BitLit lit)
1818   -- ASSERT(rep == I32)???
1819   = do (x_reg, x_code) <- getSomeReg x
1820        let off = ImmInt (fromInteger i)
1821        return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
1822
1823 -- Turn (lit1 << n  + lit2) into  (lit2 + lit1 << n) so it will be 
1824 -- recognised by the next rule.
1825 getAmode (CmmMachOp (MO_Add rep) [a@(CmmMachOp (MO_Shl _) _),
1826                                   b@(CmmLit _)])
1827   = getAmode (CmmMachOp (MO_Add rep) [b,a])
1828
1829 getAmode (CmmMachOp (MO_Add rep) [x, CmmMachOp (MO_Shl _) 
1830                                         [y, CmmLit (CmmInt shift _)]])
1831   | shift == 0 || shift == 1 || shift == 2 || shift == 3
1832   = x86_complex_amode x y shift 0
1833
1834 getAmode (CmmMachOp (MO_Add rep) 
1835                 [x, CmmMachOp (MO_Add _)
1836                         [CmmMachOp (MO_Shl _) [y, CmmLit (CmmInt shift _)],
1837                          CmmLit (CmmInt offset _)]])
1838   | shift == 0 || shift == 1 || shift == 2 || shift == 3
1839   && not (is64BitInteger offset)
1840   = x86_complex_amode x y shift offset
1841
1842 getAmode (CmmLit lit) | not (is64BitLit lit)
1843   = return (Amode (ImmAddr (litToImm lit) 0) nilOL)
1844
1845 getAmode expr = do
1846   (reg,code) <- getSomeReg expr
1847   return (Amode (AddrBaseIndex (EABaseReg reg) EAIndexNone (ImmInt 0)) code)
1848
1849
1850 x86_complex_amode :: CmmExpr -> CmmExpr -> Integer -> Integer -> NatM Amode
1851 x86_complex_amode base index shift offset
1852   = do (x_reg, x_code) <- getNonClobberedReg base
1853         -- x must be in a temp, because it has to stay live over y_code
1854         -- we could compre x_reg and y_reg and do something better here...
1855        (y_reg, y_code) <- getSomeReg index
1856        let
1857            code = x_code `appOL` y_code
1858            base = case shift of 0 -> 1; 1 -> 2; 2 -> 4; 3 -> 8
1859        return (Amode (AddrBaseIndex (EABaseReg x_reg) (EAIndex y_reg base) (ImmInt (fromIntegral offset)))
1860                code)
1861
1862 #endif /* i386_TARGET_ARCH || x86_64_TARGET_ARCH */
1863
1864 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1865
1866 #if sparc_TARGET_ARCH
1867
1868 getAmode (CmmMachOp (MO_Sub rep) [x, CmmLit (CmmInt i _)])
1869   | fits13Bits (-i)
1870   = do
1871        (reg, code) <- getSomeReg x
1872        let
1873          off  = ImmInt (-(fromInteger i))
1874        return (Amode (AddrRegImm reg off) code)
1875
1876
1877 getAmode (CmmMachOp (MO_Add rep) [x, CmmLit (CmmInt i _)])
1878   | fits13Bits i
1879   = do
1880        (reg, code) <- getSomeReg x
1881        let
1882          off  = ImmInt (fromInteger i)
1883        return (Amode (AddrRegImm reg off) code)
1884
1885 getAmode (CmmMachOp (MO_Add rep) [x, y])
1886   = do
1887     (regX, codeX) <- getSomeReg x
1888     (regY, codeY) <- getSomeReg y
1889     let
1890         code = codeX `appOL` codeY
1891     return (Amode (AddrRegReg regX regY) code)
1892
1893 -- XXX Is this same as "leaf" in Stix?
1894 getAmode (CmmLit lit)
1895   = do
1896       tmp <- getNewRegNat I32
1897       let
1898         code = unitOL (SETHI (HI imm__2) tmp)
1899       return (Amode (AddrRegImm tmp (LO imm__2)) code)
1900       where
1901          imm__2 = litToImm lit
1902
1903 getAmode other
1904   = do
1905        (reg, code) <- getSomeReg other
1906        let
1907             off  = ImmInt 0
1908        return (Amode (AddrRegImm reg off) code)
1909
1910 #endif /* sparc_TARGET_ARCH */
1911
1912 #ifdef powerpc_TARGET_ARCH
1913 getAmode (CmmMachOp (MO_Sub I32) [x, CmmLit (CmmInt i _)])
1914   | Just off <- makeImmediate I32 True (-i)
1915   = do
1916         (reg, code) <- getSomeReg x
1917         return (Amode (AddrRegImm reg off) code)
1918
1919
1920 getAmode (CmmMachOp (MO_Add I32) [x, CmmLit (CmmInt i _)])
1921   | Just off <- makeImmediate I32 True i
1922   = do
1923         (reg, code) <- getSomeReg x
1924         return (Amode (AddrRegImm reg off) code)
1925
1926    -- optimize addition with 32-bit immediate
1927    -- (needed for PIC)
1928 getAmode (CmmMachOp (MO_Add I32) [x, CmmLit lit])
1929   = do
1930         tmp <- getNewRegNat I32
1931         (src, srcCode) <- getSomeReg x
1932         let imm = litToImm lit
1933             code = srcCode `snocOL` ADDIS tmp src (HA imm)
1934         return (Amode (AddrRegImm tmp (LO imm)) code)
1935
1936 getAmode (CmmLit lit)
1937   = do
1938         tmp <- getNewRegNat I32
1939         let imm = litToImm lit
1940             code = unitOL (LIS tmp (HA imm))
1941         return (Amode (AddrRegImm tmp (LO imm)) code)
1942     
1943 getAmode (CmmMachOp (MO_Add I32) [x, y])
1944   = do
1945         (regX, codeX) <- getSomeReg x
1946         (regY, codeY) <- getSomeReg y
1947         return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY))
1948     
1949 getAmode other
1950   = do
1951         (reg, code) <- getSomeReg other
1952         let
1953             off  = ImmInt 0
1954         return (Amode (AddrRegImm reg off) code)
1955 #endif /* powerpc_TARGET_ARCH */
1956
1957 -- -----------------------------------------------------------------------------
1958 -- getOperand: sometimes any operand will do.
1959
1960 -- getNonClobberedOperand: the value of the operand will remain valid across
1961 -- the computation of an arbitrary expression, unless the expression
1962 -- is computed directly into a register which the operand refers to
1963 -- (see trivialCode where this function is used for an example).
1964
1965 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
1966
1967 getNonClobberedOperand :: CmmExpr -> NatM (Operand, InstrBlock)
1968 #if x86_64_TARGET_ARCH
1969 getNonClobberedOperand (CmmLit lit)
1970   | isSuitableFloatingPointLit lit = do
1971     lbl <- getNewLabelNat
1972     let code = unitOL (LDATA ReadOnlyData  [CmmDataLabel lbl,
1973                                            CmmStaticLit lit])
1974     return (OpAddr (ripRel (ImmCLbl lbl)), code)
1975 #endif
1976 getNonClobberedOperand (CmmLit lit)
1977   | not (is64BitLit lit) && not (isFloatingRep (cmmLitRep lit)) =
1978     return (OpImm (litToImm lit), nilOL)
1979 getNonClobberedOperand (CmmLoad mem pk) 
1980   | IF_ARCH_i386(not (isFloatingRep pk) && pk /= I64, True) = do
1981     Amode src mem_code <- getAmode mem
1982     (src',save_code) <- 
1983         if (amodeCouldBeClobbered src) 
1984                 then do
1985                    tmp <- getNewRegNat wordRep
1986                    return (AddrBaseIndex (EABaseReg tmp) EAIndexNone (ImmInt 0),
1987                            unitOL (LEA I32 (OpAddr src) (OpReg tmp)))
1988                 else
1989                    return (src, nilOL)
1990     return (OpAddr src', save_code `appOL` mem_code)
1991 getNonClobberedOperand e = do
1992     (reg, code) <- getNonClobberedReg e
1993     return (OpReg reg, code)
1994
1995 amodeCouldBeClobbered :: AddrMode -> Bool
1996 amodeCouldBeClobbered amode = any regClobbered (addrModeRegs amode)
1997
1998 regClobbered (RealReg rr) = isFastTrue (freeReg rr)
1999 regClobbered _ = False
2000
2001 -- getOperand: the operand is not required to remain valid across the
2002 -- computation of an arbitrary expression.
2003 getOperand :: CmmExpr -> NatM (Operand, InstrBlock)
2004 #if x86_64_TARGET_ARCH
2005 getOperand (CmmLit lit)
2006   | isSuitableFloatingPointLit lit = do
2007     lbl <- getNewLabelNat
2008     let code = unitOL (LDATA ReadOnlyData  [CmmDataLabel lbl,
2009                                            CmmStaticLit lit])
2010     return (OpAddr (ripRel (ImmCLbl lbl)), code)
2011 #endif
2012 getOperand (CmmLit lit)
2013   | not (is64BitLit lit) && not (isFloatingRep (cmmLitRep lit)) = do
2014     return (OpImm (litToImm lit), nilOL)
2015 getOperand (CmmLoad mem pk)
2016   | IF_ARCH_i386(not (isFloatingRep pk) && pk /= I64, True) = do
2017     Amode src mem_code <- getAmode mem
2018     return (OpAddr src, mem_code)
2019 getOperand e = do
2020     (reg, code) <- getSomeReg e
2021     return (OpReg reg, code)
2022
2023 isOperand :: CmmExpr -> Bool
2024 isOperand (CmmLoad _ _) = True
2025 isOperand (CmmLit lit)  = not (is64BitLit lit)
2026                           || isSuitableFloatingPointLit lit
2027 isOperand _             = False
2028
2029 -- if we want a floating-point literal as an operand, we can
2030 -- use it directly from memory.  However, if the literal is
2031 -- zero, we're better off generating it into a register using
2032 -- xor.
2033 isSuitableFloatingPointLit (CmmFloat f _) = f /= 0.0
2034 isSuitableFloatingPointLit _ = False
2035
2036 getRegOrMem :: CmmExpr -> NatM (Operand, InstrBlock)
2037 getRegOrMem (CmmLoad mem pk)
2038   | IF_ARCH_i386(not (isFloatingRep pk) && pk /= I64, True) = do
2039     Amode src mem_code <- getAmode mem
2040     return (OpAddr src, mem_code)
2041 getRegOrMem e = do
2042     (reg, code) <- getNonClobberedReg e
2043     return (OpReg reg, code)
2044
2045 #if x86_64_TARGET_ARCH
2046 is64BitLit (CmmInt i I64) = is64BitInteger i
2047    -- assume that labels are in the range 0-2^31-1: this assumes the
2048    -- small memory model (see gcc docs, -mcmodel=small).
2049 #endif
2050 is64BitLit x = False
2051 #endif
2052
2053 is64BitInteger :: Integer -> Bool
2054 is64BitInteger i = i64 > 0x7fffffff || i64 < -0x80000000
2055   where i64 = fromIntegral i :: Int64
2056   -- a CmmInt is intended to be truncated to the appropriate 
2057   -- number of bits, so here we truncate it to Int64.  This is
2058   -- important because e.g. -1 as a CmmInt might be either
2059   -- -1 or 18446744073709551615.
2060
2061 -- -----------------------------------------------------------------------------
2062 --  The 'CondCode' type:  Condition codes passed up the tree.
2063
2064 data CondCode = CondCode Bool Cond InstrBlock
2065
2066 -- Set up a condition code for a conditional branch.
2067
2068 getCondCode :: CmmExpr -> NatM CondCode
2069
2070 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2071
2072 #if alpha_TARGET_ARCH
2073 getCondCode = panic "MachCode.getCondCode: not on Alphas"
2074 #endif /* alpha_TARGET_ARCH */
2075
2076 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2077
2078 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH || sparc_TARGET_ARCH
2079 -- yes, they really do seem to want exactly the same!
2080
2081 getCondCode (CmmMachOp mop [x, y])
2082   = 
2083     case mop of
2084       MO_Eq F32 -> condFltCode EQQ x y
2085       MO_Ne F32 -> condFltCode NE  x y
2086
2087       MO_S_Gt F32 -> condFltCode GTT x y
2088       MO_S_Ge F32 -> condFltCode GE  x y
2089       MO_S_Lt F32 -> condFltCode LTT x y
2090       MO_S_Le F32 -> condFltCode LE  x y
2091
2092       MO_Eq F64 -> condFltCode EQQ x y
2093       MO_Ne F64 -> condFltCode NE  x y
2094
2095       MO_S_Gt F64 -> condFltCode GTT x y
2096       MO_S_Ge F64 -> condFltCode GE  x y
2097       MO_S_Lt F64 -> condFltCode LTT x y
2098       MO_S_Le F64 -> condFltCode LE  x y
2099
2100       MO_Eq rep -> condIntCode EQQ  x y
2101       MO_Ne rep -> condIntCode NE   x y
2102
2103       MO_S_Gt rep -> condIntCode GTT  x y
2104       MO_S_Ge rep -> condIntCode GE   x y
2105       MO_S_Lt rep -> condIntCode LTT  x y
2106       MO_S_Le rep -> condIntCode LE   x y
2107
2108       MO_U_Gt rep -> condIntCode GU   x y
2109       MO_U_Ge rep -> condIntCode GEU  x y
2110       MO_U_Lt rep -> condIntCode LU   x y
2111       MO_U_Le rep -> condIntCode LEU  x y
2112
2113       other -> pprPanic "getCondCode(x86,x86_64,sparc)" (ppr (CmmMachOp mop [x,y]))
2114
2115 getCondCode other =  pprPanic "getCondCode(2)(x86,sparc)" (ppr other)
2116
2117 #elif powerpc_TARGET_ARCH
2118
2119 -- almost the same as everywhere else - but we need to
2120 -- extend small integers to 32 bit first
2121
2122 getCondCode (CmmMachOp mop [x, y])
2123   = case mop of
2124       MO_Eq F32 -> condFltCode EQQ x y
2125       MO_Ne F32 -> condFltCode NE  x y
2126
2127       MO_S_Gt F32 -> condFltCode GTT x y
2128       MO_S_Ge F32 -> condFltCode GE  x y
2129       MO_S_Lt F32 -> condFltCode LTT x y
2130       MO_S_Le F32 -> condFltCode LE  x y
2131
2132       MO_Eq F64 -> condFltCode EQQ x y
2133       MO_Ne F64 -> condFltCode NE  x y
2134
2135       MO_S_Gt F64 -> condFltCode GTT x y
2136       MO_S_Ge F64 -> condFltCode GE  x y
2137       MO_S_Lt F64 -> condFltCode LTT x y
2138       MO_S_Le F64 -> condFltCode LE  x y
2139
2140       MO_Eq rep -> condIntCode EQQ  (extendUExpr rep x) (extendUExpr rep y)
2141       MO_Ne rep -> condIntCode NE   (extendUExpr rep x) (extendUExpr rep y)
2142
2143       MO_S_Gt rep -> condIntCode GTT  (extendSExpr rep x) (extendSExpr rep y)
2144       MO_S_Ge rep -> condIntCode GE   (extendSExpr rep x) (extendSExpr rep y)
2145       MO_S_Lt rep -> condIntCode LTT  (extendSExpr rep x) (extendSExpr rep y)
2146       MO_S_Le rep -> condIntCode LE   (extendSExpr rep x) (extendSExpr rep y)
2147
2148       MO_U_Gt rep -> condIntCode GU   (extendUExpr rep x) (extendUExpr rep y)
2149       MO_U_Ge rep -> condIntCode GEU  (extendUExpr rep x) (extendUExpr rep y)
2150       MO_U_Lt rep -> condIntCode LU   (extendUExpr rep x) (extendUExpr rep y)
2151       MO_U_Le rep -> condIntCode LEU  (extendUExpr rep x) (extendUExpr rep y)
2152
2153       other -> pprPanic "getCondCode(powerpc)" (pprMachOp mop)
2154
2155 getCondCode other =  panic "getCondCode(2)(powerpc)"
2156
2157
2158 #endif
2159
2160
2161 -- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
2162 -- passed back up the tree.
2163
2164 condIntCode, condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
2165
2166 #if alpha_TARGET_ARCH
2167 condIntCode = panic "MachCode.condIntCode: not on Alphas"
2168 condFltCode = panic "MachCode.condFltCode: not on Alphas"
2169 #endif /* alpha_TARGET_ARCH */
2170
2171 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2172 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
2173
2174 -- memory vs immediate
2175 condIntCode cond (CmmLoad x pk) (CmmLit lit) | not (is64BitLit lit) = do
2176     Amode x_addr x_code <- getAmode x
2177     let
2178         imm  = litToImm lit
2179         code = x_code `snocOL`
2180                   CMP pk (OpImm imm) (OpAddr x_addr)
2181     --
2182     return (CondCode False cond code)
2183
2184 -- anything vs zero
2185 condIntCode cond x (CmmLit (CmmInt 0 pk)) = do
2186     (x_reg, x_code) <- getSomeReg x
2187     let
2188         code = x_code `snocOL`
2189                   TEST pk (OpReg x_reg) (OpReg x_reg)
2190     --
2191     return (CondCode False cond code)
2192
2193 -- anything vs operand
2194 condIntCode cond x y | isOperand y = do
2195     (x_reg, x_code) <- getNonClobberedReg x
2196     (y_op,  y_code) <- getOperand y    
2197     let
2198         code = x_code `appOL` y_code `snocOL`
2199                   CMP (cmmExprRep x) y_op (OpReg x_reg)
2200     -- in
2201     return (CondCode False cond code)
2202
2203 -- anything vs anything
2204 condIntCode cond x y = do
2205   (y_reg, y_code) <- getNonClobberedReg y
2206   (x_op, x_code) <- getRegOrMem x
2207   let
2208         code = y_code `appOL`
2209                x_code `snocOL`
2210                   CMP (cmmExprRep x) (OpReg y_reg) x_op
2211   -- in
2212   return (CondCode False cond code)
2213 #endif
2214
2215 #if i386_TARGET_ARCH
2216 condFltCode cond x y 
2217   = ASSERT(cond `elem` ([EQQ, NE, LE, LTT, GE, GTT])) do
2218   (x_reg, x_code) <- getNonClobberedReg x
2219   (y_reg, y_code) <- getSomeReg y
2220   let
2221         code = x_code `appOL` y_code `snocOL`
2222                 GCMP cond x_reg y_reg
2223   -- The GCMP insn does the test and sets the zero flag if comparable
2224   -- and true.  Hence we always supply EQQ as the condition to test.
2225   return (CondCode True EQQ code)
2226 #endif /* i386_TARGET_ARCH */
2227
2228 #if x86_64_TARGET_ARCH
2229 -- in the SSE2 comparison ops (ucomiss, ucomisd) the left arg may be
2230 -- an operand, but the right must be a reg.  We can probably do better
2231 -- than this general case...
2232 condFltCode cond x y = do
2233   (x_reg, x_code) <- getNonClobberedReg x
2234   (y_op, y_code) <- getOperand y
2235   let
2236         code = x_code `appOL`
2237                y_code `snocOL`
2238                   CMP (cmmExprRep x) y_op (OpReg x_reg)
2239         -- NB(1): we need to use the unsigned comparison operators on the
2240         -- result of this comparison.
2241   -- in
2242   return (CondCode True (condToUnsigned cond) code)
2243 #endif
2244
2245 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2246
2247 #if sparc_TARGET_ARCH
2248
2249 condIntCode cond x (CmmLit (CmmInt y rep))
2250   | fits13Bits y
2251   = do
2252        (src1, code) <- getSomeReg x
2253        let
2254            src2 = ImmInt (fromInteger y)
2255            code' = code `snocOL` SUB False True src1 (RIImm src2) g0
2256        return (CondCode False cond code')
2257
2258 condIntCode cond x y = do
2259     (src1, code1) <- getSomeReg x
2260     (src2, code2) <- getSomeReg y
2261     let
2262         code__2 = code1 `appOL` code2 `snocOL`
2263                   SUB False True src1 (RIReg src2) g0
2264     return (CondCode False cond code__2)
2265
2266 -----------
2267 condFltCode cond x y = do
2268     (src1, code1) <- getSomeReg x
2269     (src2, code2) <- getSomeReg y
2270     tmp <- getNewRegNat F64
2271     let
2272         promote x = FxTOy F32 F64 x tmp
2273
2274         pk1   = cmmExprRep x
2275         pk2   = cmmExprRep y
2276
2277         code__2 =
2278                 if pk1 == pk2 then
2279                     code1 `appOL` code2 `snocOL`
2280                     FCMP True pk1 src1 src2
2281                 else if pk1 == F32 then
2282                     code1 `snocOL` promote src1 `appOL` code2 `snocOL`
2283                     FCMP True F64 tmp src2
2284                 else
2285                     code1 `appOL` code2 `snocOL` promote src2 `snocOL`
2286                     FCMP True F64 src1 tmp
2287     return (CondCode True cond code__2)
2288
2289 #endif /* sparc_TARGET_ARCH */
2290
2291 #if powerpc_TARGET_ARCH
2292 --  ###FIXME: I16 and I8!
2293 condIntCode cond x (CmmLit (CmmInt y rep))
2294   | Just src2 <- makeImmediate rep (not $ condUnsigned cond) y
2295   = do
2296         (src1, code) <- getSomeReg x
2297         let
2298             code' = code `snocOL` 
2299                 (if condUnsigned cond then CMPL else CMP) I32 src1 (RIImm src2)
2300         return (CondCode False cond code')
2301
2302 condIntCode cond x y = do
2303     (src1, code1) <- getSomeReg x
2304     (src2, code2) <- getSomeReg y
2305     let
2306         code' = code1 `appOL` code2 `snocOL`
2307                   (if condUnsigned cond then CMPL else CMP) I32 src1 (RIReg src2)
2308     return (CondCode False cond code')
2309
2310 condFltCode cond x y = do
2311     (src1, code1) <- getSomeReg x
2312     (src2, code2) <- getSomeReg y
2313     let
2314         code'  = code1 `appOL` code2 `snocOL` FCMP src1 src2
2315         code'' = case cond of -- twiddle CR to handle unordered case
2316                     GE -> code' `snocOL` CRNOR ltbit eqbit gtbit
2317                     LE -> code' `snocOL` CRNOR gtbit eqbit ltbit
2318                     _ -> code'
2319                  where
2320                     ltbit = 0 ; eqbit = 2 ; gtbit = 1
2321     return (CondCode True cond code'')
2322
2323 #endif /* powerpc_TARGET_ARCH */
2324
2325 -- -----------------------------------------------------------------------------
2326 -- Generating assignments
2327
2328 -- Assignments are really at the heart of the whole code generation
2329 -- business.  Almost all top-level nodes of any real importance are
2330 -- assignments, which correspond to loads, stores, or register
2331 -- transfers.  If we're really lucky, some of the register transfers
2332 -- will go away, because we can use the destination register to
2333 -- complete the code generation for the right hand side.  This only
2334 -- fails when the right hand side is forced into a fixed register
2335 -- (e.g. the result of a call).
2336
2337 assignMem_IntCode :: MachRep -> CmmExpr -> CmmExpr -> NatM InstrBlock
2338 assignReg_IntCode :: MachRep -> CmmReg  -> CmmExpr -> NatM InstrBlock
2339
2340 assignMem_FltCode :: MachRep -> CmmExpr -> CmmExpr -> NatM InstrBlock
2341 assignReg_FltCode :: MachRep -> CmmReg  -> CmmExpr -> NatM InstrBlock
2342
2343 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2344
2345 #if alpha_TARGET_ARCH
2346
2347 assignIntCode pk (CmmLoad dst _) src
2348   = getNewRegNat IntRep             `thenNat` \ tmp ->
2349     getAmode dst                    `thenNat` \ amode ->
2350     getRegister src                 `thenNat` \ register ->
2351     let
2352         code1   = amodeCode amode []
2353         dst__2  = amodeAddr amode
2354         code2   = registerCode register tmp []
2355         src__2  = registerName register tmp
2356         sz      = primRepToSize pk
2357         code__2 = asmSeqThen [code1, code2] . mkSeqInstr (ST sz src__2 dst__2)
2358     in
2359     return code__2
2360
2361 assignIntCode pk dst src
2362   = getRegister dst                         `thenNat` \ register1 ->
2363     getRegister src                         `thenNat` \ register2 ->
2364     let
2365         dst__2  = registerName register1 zeroh
2366         code    = registerCode register2 dst__2
2367         src__2  = registerName register2 dst__2
2368         code__2 = if isFixed register2
2369                   then code . mkSeqInstr (OR src__2 (RIReg src__2) dst__2)
2370                   else code
2371     in
2372     return code__2
2373
2374 #endif /* alpha_TARGET_ARCH */
2375
2376 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2377
2378 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
2379
2380 -- integer assignment to memory
2381 assignMem_IntCode pk addr src = do
2382     Amode addr code_addr <- getAmode addr
2383     (code_src, op_src)   <- get_op_RI src
2384     let
2385         code = code_src `appOL`
2386                code_addr `snocOL`
2387                   MOV pk op_src (OpAddr addr)
2388         -- NOTE: op_src is stable, so it will still be valid
2389         -- after code_addr.  This may involve the introduction 
2390         -- of an extra MOV to a temporary register, but we hope
2391         -- the register allocator will get rid of it.
2392     --
2393     return code
2394   where
2395     get_op_RI :: CmmExpr -> NatM (InstrBlock,Operand)   -- code, operator
2396     get_op_RI (CmmLit lit) | not (is64BitLit lit)
2397       = return (nilOL, OpImm (litToImm lit))
2398     get_op_RI op
2399       = do (reg,code) <- getNonClobberedReg op
2400            return (code, OpReg reg)
2401
2402
2403 -- Assign; dst is a reg, rhs is mem
2404 assignReg_IntCode pk reg (CmmLoad src _) = do
2405   load_code <- intLoadCode (MOV pk) src
2406   return (load_code (getRegisterReg reg))
2407
2408 -- dst is a reg, but src could be anything
2409 assignReg_IntCode pk reg src = do
2410   code <- getAnyReg src
2411   return (code (getRegisterReg reg))
2412
2413 #endif /* i386_TARGET_ARCH */
2414
2415 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2416
2417 #if sparc_TARGET_ARCH
2418
2419 assignMem_IntCode pk addr src = do
2420     (srcReg, code) <- getSomeReg src
2421     Amode dstAddr addr_code <- getAmode addr
2422     return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr
2423
2424 assignReg_IntCode pk reg src = do
2425     r <- getRegister src
2426     return $ case r of
2427         Any _ code         -> code dst
2428         Fixed _ freg fcode -> fcode `snocOL` OR False g0 (RIReg dst) freg
2429     where
2430       dst = getRegisterReg reg
2431
2432
2433 #endif /* sparc_TARGET_ARCH */
2434
2435 #if powerpc_TARGET_ARCH
2436
2437 assignMem_IntCode pk addr src = do
2438     (srcReg, code) <- getSomeReg src
2439     Amode dstAddr addr_code <- getAmode addr
2440     return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr
2441
2442 -- dst is a reg, but src could be anything
2443 assignReg_IntCode pk reg src
2444     = do
2445         r <- getRegister src
2446         return $ case r of
2447             Any _ code         -> code dst
2448             Fixed _ freg fcode -> fcode `snocOL` MR dst freg
2449     where
2450         dst = getRegisterReg reg
2451
2452 #endif /* powerpc_TARGET_ARCH */
2453
2454
2455 -- -----------------------------------------------------------------------------
2456 -- Floating-point assignments
2457
2458 #if alpha_TARGET_ARCH
2459
2460 assignFltCode pk (CmmLoad dst _) src
2461   = getNewRegNat pk                 `thenNat` \ tmp ->
2462     getAmode dst                    `thenNat` \ amode ->
2463     getRegister src                         `thenNat` \ register ->
2464     let
2465         code1   = amodeCode amode []
2466         dst__2  = amodeAddr amode
2467         code2   = registerCode register tmp []
2468         src__2  = registerName register tmp
2469         sz      = primRepToSize pk
2470         code__2 = asmSeqThen [code1, code2] . mkSeqInstr (ST sz src__2 dst__2)
2471     in
2472     return code__2
2473
2474 assignFltCode pk dst src
2475   = getRegister dst                         `thenNat` \ register1 ->
2476     getRegister src                         `thenNat` \ register2 ->
2477     let
2478         dst__2  = registerName register1 zeroh
2479         code    = registerCode register2 dst__2
2480         src__2  = registerName register2 dst__2
2481         code__2 = if isFixed register2
2482                   then code . mkSeqInstr (FMOV src__2 dst__2)
2483                   else code
2484     in
2485     return code__2
2486
2487 #endif /* alpha_TARGET_ARCH */
2488
2489 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2490
2491 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
2492
2493 -- Floating point assignment to memory
2494 assignMem_FltCode pk addr src = do
2495   (src_reg, src_code) <- getNonClobberedReg src
2496   Amode addr addr_code <- getAmode addr
2497   let
2498         code = src_code `appOL`
2499                addr_code `snocOL`
2500                 IF_ARCH_i386(GST pk src_reg addr,
2501                              MOV pk (OpReg src_reg) (OpAddr addr))
2502   return code
2503
2504 -- Floating point assignment to a register/temporary
2505 assignReg_FltCode pk reg src = do
2506   src_code <- getAnyReg src
2507   return (src_code (getRegisterReg reg))
2508
2509 #endif /* i386_TARGET_ARCH */
2510
2511 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2512
2513 #if sparc_TARGET_ARCH
2514
2515 -- Floating point assignment to memory
2516 assignMem_FltCode pk addr src = do
2517     Amode dst__2 code1 <- getAmode addr
2518     (src__2, code2) <- getSomeReg src
2519     tmp1 <- getNewRegNat pk
2520     let
2521         pk__2   = cmmExprRep src
2522         code__2 = code1 `appOL` code2 `appOL`
2523             if   pk == pk__2 
2524             then unitOL (ST pk src__2 dst__2)
2525             else toOL [FxTOy pk__2 pk src__2 tmp1, ST pk tmp1 dst__2]
2526     return code__2
2527
2528 -- Floating point assignment to a register/temporary
2529 -- ToDo: Verify correctness
2530 assignReg_FltCode pk reg src = do
2531     r <- getRegister src
2532     v1 <- getNewRegNat pk
2533     return $ case r of
2534         Any _ code         -> code dst
2535         Fixed _ freg fcode -> fcode `snocOL` FMOV pk freg v1
2536     where
2537       dst = getRegisterReg reg
2538
2539 #endif /* sparc_TARGET_ARCH */
2540
2541 #if powerpc_TARGET_ARCH
2542
2543 -- Easy, isn't it?
2544 assignMem_FltCode = assignMem_IntCode
2545 assignReg_FltCode = assignReg_IntCode
2546
2547 #endif /* powerpc_TARGET_ARCH */
2548
2549
2550 -- -----------------------------------------------------------------------------
2551 -- Generating an non-local jump
2552
2553 -- (If applicable) Do not fill the delay slots here; you will confuse the
2554 -- register allocator.
2555
2556 genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock
2557
2558 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2559
2560 #if alpha_TARGET_ARCH
2561
2562 genJump (CmmLabel lbl)
2563   | isAsmTemp lbl = returnInstr (BR target)
2564   | otherwise     = returnInstrs [LDA pv (AddrImm target), JMP zeroh (AddrReg pv) 0]
2565   where
2566     target = ImmCLbl lbl
2567
2568 genJump tree
2569   = getRegister tree                `thenNat` \ register ->
2570     getNewRegNat PtrRep             `thenNat` \ tmp ->
2571     let
2572         dst    = registerName register pv
2573         code   = registerCode register pv
2574         target = registerName register pv
2575     in
2576     if isFixed register then
2577         returnSeq code [OR dst (RIReg dst) pv, JMP zeroh (AddrReg pv) 0]
2578     else
2579     return (code . mkSeqInstr (JMP zeroh (AddrReg pv) 0))
2580
2581 #endif /* alpha_TARGET_ARCH */
2582
2583 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2584
2585 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
2586
2587 genJump (CmmLoad mem pk) = do
2588   Amode target code <- getAmode mem
2589   return (code `snocOL` JMP (OpAddr target))
2590
2591 genJump (CmmLit lit) = do
2592   return (unitOL (JMP (OpImm (litToImm lit))))
2593
2594 genJump expr = do
2595   (reg,code) <- getSomeReg expr
2596   return (code `snocOL` JMP (OpReg reg))
2597
2598 #endif /* i386_TARGET_ARCH */
2599
2600 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2601
2602 #if sparc_TARGET_ARCH
2603
2604 genJump (CmmLit (CmmLabel lbl))
2605   = return (toOL [CALL (Left target) 0 True, NOP])
2606   where
2607     target = ImmCLbl lbl
2608
2609 genJump tree
2610   = do
2611         (target, code) <- getSomeReg tree
2612         return (code `snocOL` JMP (AddrRegReg target g0)  `snocOL` NOP)
2613
2614 #endif /* sparc_TARGET_ARCH */
2615
2616 #if powerpc_TARGET_ARCH
2617 genJump (CmmLit (CmmLabel lbl))
2618   = return (unitOL $ JMP lbl)
2619
2620 genJump tree
2621   = do
2622         (target,code) <- getSomeReg tree
2623         return (code `snocOL` MTCTR target `snocOL` BCTR [])
2624 #endif /* powerpc_TARGET_ARCH */
2625
2626
2627 -- -----------------------------------------------------------------------------
2628 --  Unconditional branches
2629
2630 genBranch :: BlockId -> NatM InstrBlock
2631
2632 genBranch = return . toOL . mkBranchInstr
2633
2634 -- -----------------------------------------------------------------------------
2635 --  Conditional jumps
2636
2637 {-
2638 Conditional jumps are always to local labels, so we can use branch
2639 instructions.  We peek at the arguments to decide what kind of
2640 comparison to do.
2641
2642 ALPHA: For comparisons with 0, we're laughing, because we can just do
2643 the desired conditional branch.
2644
2645 I386: First, we have to ensure that the condition
2646 codes are set according to the supplied comparison operation.
2647
2648 SPARC: First, we have to ensure that the condition codes are set
2649 according to the supplied comparison operation.  We generate slightly
2650 different code for floating point comparisons, because a floating
2651 point operation cannot directly precede a @BF@.  We assume the worst
2652 and fill that slot with a @NOP@.
2653
2654 SPARC: Do not fill the delay slots here; you will confuse the register
2655 allocator.
2656 -}
2657
2658
2659 genCondJump
2660     :: BlockId      -- the branch target
2661     -> CmmExpr      -- the condition on which to branch
2662     -> NatM InstrBlock
2663
2664 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2665
2666 #if alpha_TARGET_ARCH
2667
2668 genCondJump id (StPrim op [x, StInt 0])
2669   = getRegister x                           `thenNat` \ register ->
2670     getNewRegNat (registerRep register)
2671                                     `thenNat` \ tmp ->
2672     let
2673         code   = registerCode register tmp
2674         value  = registerName register tmp
2675         pk     = registerRep register
2676         target = ImmCLbl lbl
2677     in
2678     returnSeq code [BI (cmpOp op) value target]
2679   where
2680     cmpOp CharGtOp = GTT
2681     cmpOp CharGeOp = GE
2682     cmpOp CharEqOp = EQQ
2683     cmpOp CharNeOp = NE
2684     cmpOp CharLtOp = LTT
2685     cmpOp CharLeOp = LE
2686     cmpOp IntGtOp = GTT
2687     cmpOp IntGeOp = GE
2688     cmpOp IntEqOp = EQQ
2689     cmpOp IntNeOp = NE
2690     cmpOp IntLtOp = LTT
2691     cmpOp IntLeOp = LE
2692     cmpOp WordGtOp = NE
2693     cmpOp WordGeOp = ALWAYS
2694     cmpOp WordEqOp = EQQ
2695     cmpOp WordNeOp = NE
2696     cmpOp WordLtOp = NEVER
2697     cmpOp WordLeOp = EQQ
2698     cmpOp AddrGtOp = NE
2699     cmpOp AddrGeOp = ALWAYS
2700     cmpOp AddrEqOp = EQQ
2701     cmpOp AddrNeOp = NE
2702     cmpOp AddrLtOp = NEVER
2703     cmpOp AddrLeOp = EQQ
2704
2705 genCondJump lbl (StPrim op [x, StDouble 0.0])
2706   = getRegister x                           `thenNat` \ register ->
2707     getNewRegNat (registerRep register)
2708                                     `thenNat` \ tmp ->
2709     let
2710         code   = registerCode register tmp
2711         value  = registerName register tmp
2712         pk     = registerRep register
2713         target = ImmCLbl lbl
2714     in
2715     return (code . mkSeqInstr (BF (cmpOp op) value target))
2716   where
2717     cmpOp FloatGtOp = GTT
2718     cmpOp FloatGeOp = GE
2719     cmpOp FloatEqOp = EQQ
2720     cmpOp FloatNeOp = NE
2721     cmpOp FloatLtOp = LTT
2722     cmpOp FloatLeOp = LE
2723     cmpOp DoubleGtOp = GTT
2724     cmpOp DoubleGeOp = GE
2725     cmpOp DoubleEqOp = EQQ
2726     cmpOp DoubleNeOp = NE
2727     cmpOp DoubleLtOp = LTT
2728     cmpOp DoubleLeOp = LE
2729
2730 genCondJump lbl (StPrim op [x, y])
2731   | fltCmpOp op
2732   = trivialFCode pr instr x y       `thenNat` \ register ->
2733     getNewRegNat F64                `thenNat` \ tmp ->
2734     let
2735         code   = registerCode register tmp
2736         result = registerName register tmp
2737         target = ImmCLbl lbl
2738     in
2739     return (code . mkSeqInstr (BF cond result target))
2740   where
2741     pr = panic "trivialU?FCode: does not use PrimRep on Alpha"
2742
2743     fltCmpOp op = case op of
2744         FloatGtOp -> True
2745         FloatGeOp -> True
2746         FloatEqOp -> True
2747         FloatNeOp -> True
2748         FloatLtOp -> True
2749         FloatLeOp -> True
2750         DoubleGtOp -> True
2751         DoubleGeOp -> True
2752         DoubleEqOp -> True
2753         DoubleNeOp -> True
2754         DoubleLtOp -> True
2755         DoubleLeOp -> True
2756         _ -> False
2757     (instr, cond) = case op of
2758         FloatGtOp -> (FCMP TF LE, EQQ)
2759         FloatGeOp -> (FCMP TF LTT, EQQ)
2760         FloatEqOp -> (FCMP TF EQQ, NE)
2761         FloatNeOp -> (FCMP TF EQQ, EQQ)
2762         FloatLtOp -> (FCMP TF LTT, NE)
2763         FloatLeOp -> (FCMP TF LE, NE)
2764         DoubleGtOp -> (FCMP TF LE, EQQ)
2765         DoubleGeOp -> (FCMP TF LTT, EQQ)
2766         DoubleEqOp -> (FCMP TF EQQ, NE)
2767         DoubleNeOp -> (FCMP TF EQQ, EQQ)
2768         DoubleLtOp -> (FCMP TF LTT, NE)
2769         DoubleLeOp -> (FCMP TF LE, NE)
2770
2771 genCondJump lbl (StPrim op [x, y])
2772   = trivialCode instr x y           `thenNat` \ register ->
2773     getNewRegNat IntRep             `thenNat` \ tmp ->
2774     let
2775         code   = registerCode register tmp
2776         result = registerName register tmp
2777         target = ImmCLbl lbl
2778     in
2779     return (code . mkSeqInstr (BI cond result target))
2780   where
2781     (instr, cond) = case op of
2782         CharGtOp -> (CMP LE, EQQ)
2783         CharGeOp -> (CMP LTT, EQQ)
2784         CharEqOp -> (CMP EQQ, NE)
2785         CharNeOp -> (CMP EQQ, EQQ)
2786         CharLtOp -> (CMP LTT, NE)
2787         CharLeOp -> (CMP LE, NE)
2788         IntGtOp -> (CMP LE, EQQ)
2789         IntGeOp -> (CMP LTT, EQQ)
2790         IntEqOp -> (CMP EQQ, NE)
2791         IntNeOp -> (CMP EQQ, EQQ)
2792         IntLtOp -> (CMP LTT, NE)
2793         IntLeOp -> (CMP LE, NE)
2794         WordGtOp -> (CMP ULE, EQQ)
2795         WordGeOp -> (CMP ULT, EQQ)
2796         WordEqOp -> (CMP EQQ, NE)
2797         WordNeOp -> (CMP EQQ, EQQ)
2798         WordLtOp -> (CMP ULT, NE)
2799         WordLeOp -> (CMP ULE, NE)
2800         AddrGtOp -> (CMP ULE, EQQ)
2801         AddrGeOp -> (CMP ULT, EQQ)
2802         AddrEqOp -> (CMP EQQ, NE)
2803         AddrNeOp -> (CMP EQQ, EQQ)
2804         AddrLtOp -> (CMP ULT, NE)
2805         AddrLeOp -> (CMP ULE, NE)
2806
2807 #endif /* alpha_TARGET_ARCH */
2808
2809 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2810
2811 #if i386_TARGET_ARCH
2812
2813 genCondJump id bool = do
2814   CondCode _ cond code <- getCondCode bool
2815   return (code `snocOL` JXX cond id)
2816
2817 #endif
2818
2819 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2820
2821 #if x86_64_TARGET_ARCH
2822
2823 genCondJump id bool = do
2824   CondCode is_float cond cond_code <- getCondCode bool
2825   if not is_float
2826     then
2827         return (cond_code `snocOL` JXX cond id)
2828     else do
2829         lbl <- getBlockIdNat
2830
2831         -- see comment with condFltReg
2832         let code = case cond of
2833                         NE  -> or_unordered
2834                         GU  -> plain_test
2835                         GEU -> plain_test
2836                         _   -> and_ordered
2837
2838             plain_test = unitOL (
2839                   JXX cond id
2840                 )
2841             or_unordered = toOL [
2842                   JXX cond id,
2843                   JXX PARITY id
2844                 ]
2845             and_ordered = toOL [
2846                   JXX PARITY lbl,
2847                   JXX cond id,
2848                   JXX ALWAYS lbl,
2849                   NEWBLOCK lbl
2850                 ]
2851         return (cond_code `appOL` code)
2852
2853 #endif
2854
2855 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2856
2857 #if sparc_TARGET_ARCH
2858
2859 genCondJump (BlockId id) bool = do
2860   CondCode is_float cond code <- getCondCode bool
2861   return (
2862        code `appOL` 
2863        toOL (
2864          if   is_float
2865          then [NOP, BF cond False (ImmCLbl (mkAsmTempLabel id)), NOP]
2866          else [BI cond False (ImmCLbl (mkAsmTempLabel id)), NOP]
2867        )
2868     )
2869
2870 #endif /* sparc_TARGET_ARCH */
2871
2872
2873 #if powerpc_TARGET_ARCH
2874
2875 genCondJump id bool = do
2876   CondCode is_float cond code <- getCondCode bool
2877   return (code `snocOL` BCC cond id)
2878
2879 #endif /* powerpc_TARGET_ARCH */
2880
2881
2882 -- -----------------------------------------------------------------------------
2883 --  Generating C calls
2884
2885 -- Now the biggest nightmare---calls.  Most of the nastiness is buried in
2886 -- @get_arg@, which moves the arguments to the correct registers/stack
2887 -- locations.  Apart from that, the code is easy.
2888 -- 
2889 -- (If applicable) Do not fill the delay slots here; you will confuse the
2890 -- register allocator.
2891
2892 genCCall
2893     :: CmmCallTarget            -- function to call
2894     -> [(CmmReg,MachHint)]      -- where to put the result
2895     -> [(CmmExpr,MachHint)]     -- arguments (of mixed type)
2896     -> Maybe [GlobalReg]        -- volatile regs to save
2897     -> NatM InstrBlock
2898
2899 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2900
2901 #if alpha_TARGET_ARCH
2902
2903 ccallResultRegs = 
2904
2905 genCCall fn cconv result_regs args
2906   = mapAccumLNat get_arg (allArgRegs, eXTRA_STK_ARGS_HERE) args
2907                           `thenNat` \ ((unused,_), argCode) ->
2908     let
2909         nRegs = length allArgRegs - length unused
2910         code = asmSeqThen (map ($ []) argCode)
2911     in
2912         returnSeq code [
2913             LDA pv (AddrImm (ImmLab (ptext fn))),
2914             JSR ra (AddrReg pv) nRegs,
2915             LDGP gp (AddrReg ra)]
2916   where
2917     ------------------------
2918     {-  Try to get a value into a specific register (or registers) for
2919         a call.  The first 6 arguments go into the appropriate
2920         argument register (separate registers for integer and floating
2921         point arguments, but used in lock-step), and the remaining
2922         arguments are dumped to the stack, beginning at 0(sp).  Our
2923         first argument is a pair of the list of remaining argument
2924         registers to be assigned for this call and the next stack
2925         offset to use for overflowing arguments.  This way,
2926         @get_Arg@ can be applied to all of a call's arguments using
2927         @mapAccumLNat@.
2928     -}
2929     get_arg
2930         :: ([(Reg,Reg)], Int)   -- Argument registers and stack offset (accumulator)
2931         -> StixTree             -- Current argument
2932         -> NatM (([(Reg,Reg)],Int), InstrBlock) -- Updated accumulator and code
2933
2934     -- We have to use up all of our argument registers first...
2935
2936     get_arg ((iDst,fDst):dsts, offset) arg
2937       = getRegister arg                     `thenNat` \ register ->
2938         let
2939             reg  = if isFloatingRep pk then fDst else iDst
2940             code = registerCode register reg
2941             src  = registerName register reg
2942             pk   = registerRep register
2943         in
2944         return (
2945             if isFloatingRep pk then
2946                 ((dsts, offset), if isFixed register then
2947                     code . mkSeqInstr (FMOV src fDst)
2948                     else code)
2949             else
2950                 ((dsts, offset), if isFixed register then
2951                     code . mkSeqInstr (OR src (RIReg src) iDst)
2952                     else code))
2953
2954     -- Once we have run out of argument registers, we move to the
2955     -- stack...
2956
2957     get_arg ([], offset) arg
2958       = getRegister arg                 `thenNat` \ register ->
2959         getNewRegNat (registerRep register)
2960                                         `thenNat` \ tmp ->
2961         let
2962             code = registerCode register tmp
2963             src  = registerName register tmp
2964             pk   = registerRep register
2965             sz   = primRepToSize pk
2966         in
2967         return (([], offset + 1), code . mkSeqInstr (ST sz src (spRel offset)))
2968
2969 #endif /* alpha_TARGET_ARCH */
2970
2971 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2972
2973 #if i386_TARGET_ARCH
2974
2975 genCCall (CmmPrim MO_WriteBarrier) _ _ _ = return nilOL
2976         -- write barrier compiles to no code on x86/x86-64; 
2977         -- we keep it this long in order to prevent earlier optimisations.
2978
2979 -- we only cope with a single result for foreign calls
2980 genCCall (CmmPrim op) [(r,_)] args vols = do
2981   case op of
2982         MO_F32_Sqrt -> actuallyInlineFloatOp F32  (GSQRT F32) args
2983         MO_F64_Sqrt -> actuallyInlineFloatOp F64 (GSQRT F64) args
2984         
2985         MO_F32_Sin  -> actuallyInlineFloatOp F32  (GSIN F32) args
2986         MO_F64_Sin  -> actuallyInlineFloatOp F64 (GSIN F64) args
2987         
2988         MO_F32_Cos  -> actuallyInlineFloatOp F32  (GCOS F32) args
2989         MO_F64_Cos  -> actuallyInlineFloatOp F64 (GCOS F64) args
2990         
2991         MO_F32_Tan  -> actuallyInlineFloatOp F32  (GTAN F32) args
2992         MO_F64_Tan  -> actuallyInlineFloatOp F64 (GTAN F64) args
2993         
2994         other_op    -> outOfLineFloatOp op r args vols
2995  where
2996   actuallyInlineFloatOp rep instr [(x,_)]
2997         = do res <- trivialUFCode rep instr x
2998              any <- anyReg res
2999              return (any (getRegisterReg r))
3000
3001 genCCall target dest_regs args vols = do
3002     let
3003         sizes               = map (arg_size . cmmExprRep . fst) (reverse args)
3004 #if !darwin_TARGET_OS        
3005         tot_arg_size        = sum sizes
3006 #else
3007         raw_arg_size        = sum sizes
3008         tot_arg_size        = roundTo 16 raw_arg_size
3009         arg_pad_size        = tot_arg_size - raw_arg_size
3010     delta0 <- getDeltaNat
3011     setDeltaNat (delta0 - arg_pad_size)
3012 #endif
3013
3014     push_codes <- mapM push_arg (reverse args)
3015     delta <- getDeltaNat
3016
3017     -- in
3018     -- deal with static vs dynamic call targets
3019     (callinsns,cconv) <-
3020       case target of
3021         -- CmmPrim -> ...
3022         CmmForeignCall (CmmLit (CmmLabel lbl)) conv
3023            -> -- ToDo: stdcall arg sizes
3024               return (unitOL (CALL (Left fn_imm) []), conv)
3025            where fn_imm = ImmCLbl lbl
3026         CmmForeignCall expr conv
3027            -> do (dyn_c, dyn_r, dyn_rep) <- get_op expr
3028                  ASSERT(dyn_rep == I32)
3029                   return (dyn_c `snocOL` CALL (Right dyn_r) [], conv)
3030
3031     let push_code
3032 #if darwin_TARGET_OS
3033             | arg_pad_size /= 0
3034             = toOL [SUB I32 (OpImm (ImmInt arg_pad_size)) (OpReg esp),
3035                     DELTA (delta0 - arg_pad_size)]
3036               `appOL` concatOL push_codes
3037             | otherwise
3038 #endif
3039             = concatOL push_codes
3040         call = callinsns `appOL`
3041                toOL (
3042                         -- Deallocate parameters after call for ccall;
3043                         -- but not for stdcall (callee does it)
3044                   (if cconv == StdCallConv || tot_arg_size==0 then [] else 
3045                    [ADD I32 (OpImm (ImmInt tot_arg_size)) (OpReg esp)])
3046                   ++
3047                   [DELTA (delta + tot_arg_size)]
3048                )
3049     -- in
3050     setDeltaNat (delta + tot_arg_size)
3051
3052     let
3053         -- assign the results, if necessary
3054         assign_code []     = nilOL
3055         assign_code [(dest,_hint)] = 
3056           case rep of
3057                 I64 -> toOL [MOV I32 (OpReg eax) (OpReg r_dest),
3058                              MOV I32 (OpReg edx) (OpReg r_dest_hi)]
3059                 F32 -> unitOL (GMOV fake0 r_dest)
3060                 F64 -> unitOL (GMOV fake0 r_dest)
3061                 rep -> unitOL (MOV rep (OpReg eax) (OpReg r_dest))
3062           where 
3063                 r_dest_hi = getHiVRegFromLo r_dest
3064                 rep = cmmRegRep dest
3065                 r_dest = getRegisterReg dest
3066         assign_code many = panic "genCCall.assign_code many"
3067
3068     return (push_code `appOL` 
3069             call `appOL` 
3070             assign_code dest_regs)
3071
3072   where
3073     arg_size F64 = 8
3074     arg_size F32 = 4
3075     arg_size I64 = 8
3076     arg_size _   = 4
3077
3078     roundTo a x | x `mod` a == 0 = x
3079                 | otherwise = x + a - (x `mod` a)
3080
3081
3082     push_arg :: (CmmExpr,MachHint){-current argument-}
3083                     -> NatM InstrBlock  -- code
3084
3085     push_arg (arg,_hint) -- we don't need the hints on x86
3086       | arg_rep == I64 = do
3087         ChildCode64 code r_lo <- iselExpr64 arg
3088         delta <- getDeltaNat
3089         setDeltaNat (delta - 8)
3090         let 
3091             r_hi = getHiVRegFromLo r_lo
3092         -- in
3093         return (       code `appOL`
3094                        toOL [PUSH I32 (OpReg r_hi), DELTA (delta - 4),
3095                              PUSH I32 (OpReg r_lo), DELTA (delta - 8),
3096                              DELTA (delta-8)]
3097             )
3098
3099       | otherwise = do
3100         (code, reg, sz) <- get_op arg
3101         delta <- getDeltaNat
3102         let size = arg_size sz
3103         setDeltaNat (delta-size)
3104         if (case sz of F64 -> True; F32 -> True; _ -> False)
3105            then return (code `appOL`
3106                         toOL [SUB I32 (OpImm (ImmInt size)) (OpReg esp),
3107                               DELTA (delta-size),
3108                               GST sz reg (AddrBaseIndex (EABaseReg esp) 
3109                                                         EAIndexNone
3110                                                         (ImmInt 0))]
3111                        )
3112            else return (code `snocOL`
3113                         PUSH I32 (OpReg reg) `snocOL`
3114                         DELTA (delta-size)
3115                        )
3116       where
3117          arg_rep = cmmExprRep arg
3118
3119     ------------
3120     get_op :: CmmExpr -> NatM (InstrBlock, Reg, MachRep) -- code, reg, size
3121     get_op op = do
3122         (reg,code) <- getSomeReg op
3123         return (code, reg, cmmExprRep op)
3124
3125 #endif /* i386_TARGET_ARCH */
3126
3127 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
3128
3129 outOfLineFloatOp :: CallishMachOp -> CmmReg -> [(CmmExpr,MachHint)]
3130   -> Maybe [GlobalReg] -> NatM InstrBlock
3131 outOfLineFloatOp mop res args vols
3132   = do
3133       targetExpr <- cmmMakeDynamicReference addImportNat CallReference lbl
3134       let target = CmmForeignCall targetExpr CCallConv
3135         
3136       if cmmRegRep res == F64
3137         then
3138           stmtToInstrs (CmmCall target [(res,FloatHint)] args vols)  
3139         else do
3140           uq <- getUniqueNat
3141           let 
3142             tmp = CmmLocal (LocalReg uq F64)
3143           -- in
3144           code1 <- stmtToInstrs (CmmCall target [(tmp,FloatHint)] args vols)
3145           code2 <- stmtToInstrs (CmmAssign res (CmmReg tmp))
3146           return (code1 `appOL` code2)
3147   where
3148         lbl = mkForeignLabel fn Nothing False
3149
3150         fn = case mop of
3151               MO_F32_Sqrt  -> FSLIT("sqrtf")
3152               MO_F32_Sin   -> FSLIT("sinf")
3153               MO_F32_Cos   -> FSLIT("cosf")
3154               MO_F32_Tan   -> FSLIT("tanf")
3155               MO_F32_Exp   -> FSLIT("expf")
3156               MO_F32_Log   -> FSLIT("logf")
3157
3158               MO_F32_Asin  -> FSLIT("asinf")
3159               MO_F32_Acos  -> FSLIT("acosf")
3160               MO_F32_Atan  -> FSLIT("atanf")
3161
3162               MO_F32_Sinh  -> FSLIT("sinhf")
3163               MO_F32_Cosh  -> FSLIT("coshf")
3164               MO_F32_Tanh  -> FSLIT("tanhf")
3165               MO_F32_Pwr   -> FSLIT("powf")
3166
3167               MO_F64_Sqrt  -> FSLIT("sqrt")
3168               MO_F64_Sin   -> FSLIT("sin")
3169               MO_F64_Cos   -> FSLIT("cos")
3170               MO_F64_Tan   -> FSLIT("tan")
3171               MO_F64_Exp   -> FSLIT("exp")
3172               MO_F64_Log   -> FSLIT("log")
3173
3174               MO_F64_Asin  -> FSLIT("asin")
3175               MO_F64_Acos  -> FSLIT("acos")
3176               MO_F64_Atan  -> FSLIT("atan")
3177
3178               MO_F64_Sinh  -> FSLIT("sinh")
3179               MO_F64_Cosh  -> FSLIT("cosh")
3180               MO_F64_Tanh  -> FSLIT("tanh")
3181               MO_F64_Pwr   -> FSLIT("pow")
3182
3183 #endif /* i386_TARGET_ARCH || x86_64_TARGET_ARCH */
3184
3185 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3186
3187 #if x86_64_TARGET_ARCH
3188
3189 genCCall (CmmPrim MO_WriteBarrier) _ _ _ = return nilOL
3190         -- write barrier compiles to no code on x86/x86-64; 
3191         -- we keep it this long in order to prevent earlier optimisations.
3192
3193 genCCall (CmmPrim op) [(r,_)] args vols = 
3194   outOfLineFloatOp op r args vols
3195
3196 genCCall target dest_regs args vols = do
3197
3198         -- load up the register arguments
3199     (stack_args, aregs, fregs, load_args_code)
3200          <- load_args args allArgRegs allFPArgRegs nilOL
3201
3202     let
3203         fp_regs_used  = reverse (drop (length fregs) (reverse allFPArgRegs))
3204         int_regs_used = reverse (drop (length aregs) (reverse allArgRegs))
3205         arg_regs = [eax] ++ int_regs_used ++ fp_regs_used
3206                 -- for annotating the call instruction with
3207
3208         sse_regs = length fp_regs_used
3209
3210         tot_arg_size = arg_size * length stack_args
3211
3212         -- On entry to the called function, %rsp should be aligned
3213         -- on a 16-byte boundary +8 (i.e. the first stack arg after
3214         -- the return address is 16-byte aligned).  In STG land
3215         -- %rsp is kept 16-byte aligned (see StgCRun.c), so we just
3216         -- need to make sure we push a multiple of 16-bytes of args,
3217         -- plus the return address, to get the correct alignment.
3218         -- Urg, this is hard.  We need to feed the delta back into
3219         -- the arg pushing code.
3220     (real_size, adjust_rsp) <-
3221         if tot_arg_size `rem` 16 == 0
3222             then return (tot_arg_size, nilOL)
3223             else do -- we need to adjust...
3224                 delta <- getDeltaNat
3225                 setDeltaNat (delta-8)
3226                 return (tot_arg_size+8, toOL [
3227                                 SUB I64 (OpImm (ImmInt 8)) (OpReg rsp),
3228                                 DELTA (delta-8)
3229                         ])
3230
3231         -- push the stack args, right to left
3232     push_code <- push_args (reverse stack_args) nilOL
3233     delta <- getDeltaNat
3234
3235     -- deal with static vs dynamic call targets
3236     (callinsns,cconv) <-
3237       case target of
3238         -- CmmPrim -> ...
3239         CmmForeignCall (CmmLit (CmmLabel lbl)) conv
3240            -> -- ToDo: stdcall arg sizes
3241               return (unitOL (CALL (Left fn_imm) arg_regs), conv)
3242            where fn_imm = ImmCLbl lbl
3243         CmmForeignCall expr conv
3244            -> do (dyn_r, dyn_c) <- getSomeReg expr
3245                  return (dyn_c `snocOL` CALL (Right dyn_r) arg_regs, conv)
3246
3247     let
3248         -- The x86_64 ABI requires us to set %al to the number of SSE
3249         -- registers that contain arguments, if the called routine
3250         -- is a varargs function.  We don't know whether it's a
3251         -- varargs function or not, so we have to assume it is.
3252         --
3253         -- It's not safe to omit this assignment, even if the number
3254         -- of SSE regs in use is zero.  If %al is larger than 8
3255         -- on entry to a varargs function, seg faults ensue.
3256         assign_eax n = unitOL (MOV I32 (OpImm (ImmInt n)) (OpReg eax))
3257
3258     let call = callinsns `appOL`
3259                toOL (
3260                         -- Deallocate parameters after call for ccall;
3261                         -- but not for stdcall (callee does it)
3262                   (if cconv == StdCallConv || real_size==0 then [] else 
3263                    [ADD wordRep (OpImm (ImmInt real_size)) (OpReg esp)])
3264                   ++
3265                   [DELTA (delta + real_size)]
3266                )
3267     -- in
3268     setDeltaNat (delta + real_size)
3269
3270     let
3271         -- assign the results, if necessary
3272         assign_code []     = nilOL
3273         assign_code [(dest,_hint)] = 
3274           case rep of
3275                 F32 -> unitOL (MOV rep (OpReg xmm0) (OpReg r_dest))
3276                 F64 -> unitOL (MOV rep (OpReg xmm0) (OpReg r_dest))
3277                 rep -> unitOL (MOV rep (OpReg rax) (OpReg r_dest))
3278           where 
3279                 rep = cmmRegRep dest
3280                 r_dest = getRegisterReg dest
3281         assign_code many = panic "genCCall.assign_code many"
3282
3283     return (load_args_code      `appOL` 
3284             adjust_rsp          `appOL`
3285             push_code           `appOL`
3286             assign_eax sse_regs `appOL`
3287             call                `appOL` 
3288             assign_code dest_regs)
3289
3290   where
3291     arg_size = 8 -- always, at the mo
3292
3293     load_args :: [(CmmExpr,MachHint)]
3294               -> [Reg]                  -- int regs avail for args
3295               -> [Reg]                  -- FP regs avail for args
3296               -> InstrBlock
3297               -> NatM ([(CmmExpr,MachHint)],[Reg],[Reg],InstrBlock)
3298     load_args args [] [] code     =  return (args, [], [], code)
3299         -- no more regs to use
3300     load_args [] aregs fregs code =  return ([], aregs, fregs, code)
3301         -- no more args to push
3302     load_args ((arg,hint) : rest) aregs fregs code
3303         | isFloatingRep arg_rep = 
3304         case fregs of
3305           [] -> push_this_arg
3306           (r:rs) -> do
3307              arg_code <- getAnyReg arg
3308              load_args rest aregs rs (code `appOL` arg_code r)
3309         | otherwise =
3310         case aregs of
3311           [] -> push_this_arg
3312           (r:rs) -> do
3313              arg_code <- getAnyReg arg
3314              load_args rest rs fregs (code `appOL` arg_code r)
3315         where
3316           arg_rep = cmmExprRep arg
3317
3318           push_this_arg = do
3319             (args',ars,frs,code') <- load_args rest aregs fregs code
3320             return ((arg,hint):args', ars, frs, code')
3321
3322     push_args [] code = return code
3323     push_args ((arg,hint):rest) code
3324        | isFloatingRep arg_rep = do
3325          (arg_reg, arg_code) <- getSomeReg arg
3326          delta <- getDeltaNat
3327          setDeltaNat (delta-arg_size)
3328          let code' = code `appOL` toOL [
3329                         MOV arg_rep (OpReg arg_reg) (OpAddr  (spRel 0)),
3330                         SUB wordRep (OpImm (ImmInt arg_size)) (OpReg rsp) ,
3331                         DELTA (delta-arg_size)]
3332          push_args rest code'
3333
3334        | otherwise = do
3335        -- we only ever generate word-sized function arguments.  Promotion
3336        -- has already happened: our Int8# type is kept sign-extended
3337        -- in an Int#, for example.
3338          ASSERT(arg_rep == I64) return ()
3339          (arg_op, arg_code) <- getOperand arg
3340          delta <- getDeltaNat
3341          setDeltaNat (delta-arg_size)
3342          let code' = code `appOL` toOL [PUSH I64 arg_op, 
3343                                         DELTA (delta-arg_size)]
3344          push_args rest code'
3345         where
3346           arg_rep = cmmExprRep arg
3347 #endif
3348
3349 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3350
3351 #if sparc_TARGET_ARCH
3352 {- 
3353    The SPARC calling convention is an absolute
3354    nightmare.  The first 6x32 bits of arguments are mapped into
3355    %o0 through %o5, and the remaining arguments are dumped to the
3356    stack, beginning at [%sp+92].  (Note that %o6 == %sp.)
3357
3358    If we have to put args on the stack, move %o6==%sp down by
3359    the number of words to go on the stack, to ensure there's enough space.
3360
3361    According to Fraser and Hanson's lcc book, page 478, fig 17.2,
3362    16 words above the stack pointer is a word for the address of
3363    a structure return value.  I use this as a temporary location
3364    for moving values from float to int regs.  Certainly it isn't
3365    safe to put anything in the 16 words starting at %sp, since
3366    this area can get trashed at any time due to window overflows
3367    caused by signal handlers.
3368
3369    A final complication (if the above isn't enough) is that 
3370    we can't blithely calculate the arguments one by one into
3371    %o0 .. %o5.  Consider the following nested calls:
3372
3373        fff a (fff b c)
3374
3375    Naive code moves a into %o0, and (fff b c) into %o1.  Unfortunately
3376    the inner call will itself use %o0, which trashes the value put there
3377    in preparation for the outer call.  Upshot: we need to calculate the
3378    args into temporary regs, and move those to arg regs or onto the
3379    stack only immediately prior to the call proper.  Sigh.
3380 -}
3381
3382 genCCall target dest_regs argsAndHints vols = do
3383     let
3384         args = map fst argsAndHints
3385     argcode_and_vregs <- mapM arg_to_int_vregs args
3386     let 
3387         (argcodes, vregss) = unzip argcode_and_vregs
3388         n_argRegs          = length allArgRegs
3389         n_argRegs_used     = min (length vregs) n_argRegs
3390         vregs              = concat vregss
3391     -- deal with static vs dynamic call targets
3392     callinsns <- (case target of
3393         CmmForeignCall (CmmLit (CmmLabel lbl)) conv -> do
3394                 return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False))
3395         CmmForeignCall expr conv -> do
3396                 (dyn_c, [dyn_r]) <- arg_to_int_vregs expr
3397                 return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
3398         CmmPrim mop -> do
3399                   (res, reduce) <- outOfLineFloatOp mop
3400                   lblOrMopExpr <- case res of
3401                        Left lbl -> do
3402                             return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False))
3403                        Right mopExpr -> do
3404                             (dyn_c, [dyn_r]) <- arg_to_int_vregs mopExpr
3405                             return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
3406                   if reduce then panic "genCCall(sparc): can not reduce" else return lblOrMopExpr
3407
3408       )
3409     let
3410         argcode = concatOL argcodes
3411         (move_sp_down, move_sp_up)
3412            = let diff = length vregs - n_argRegs
3413                  nn   = if odd diff then diff + 1 else diff -- keep 8-byte alignment
3414              in  if   nn <= 0
3415                  then (nilOL, nilOL)
3416                  else (unitOL (moveSp (-1*nn)), unitOL (moveSp (1*nn)))
3417         transfer_code
3418            = toOL (move_final vregs allArgRegs eXTRA_STK_ARGS_HERE)
3419     return (argcode       `appOL`
3420             move_sp_down  `appOL`
3421             transfer_code `appOL`
3422             callinsns     `appOL`
3423             unitOL NOP    `appOL`
3424             move_sp_up)
3425   where
3426      -- move args from the integer vregs into which they have been 
3427      -- marshalled, into %o0 .. %o5, and the rest onto the stack.
3428      move_final :: [Reg] -> [Reg] -> Int -> [Instr]
3429
3430      move_final [] _ offset          -- all args done
3431         = []
3432
3433      move_final (v:vs) [] offset     -- out of aregs; move to stack
3434         = ST I32 v (spRel offset)
3435           : move_final vs [] (offset+1)
3436
3437      move_final (v:vs) (a:az) offset -- move into an arg (%o[0..5]) reg
3438         = OR False g0 (RIReg v) a
3439           : move_final vs az offset
3440
3441      -- generate code to calculate an argument, and move it into one
3442      -- or two integer vregs.
3443      arg_to_int_vregs :: CmmExpr -> NatM (OrdList Instr, [Reg])
3444      arg_to_int_vregs arg
3445         | (cmmExprRep arg) == I64
3446         = do
3447           (ChildCode64 code r_lo) <- iselExpr64 arg
3448           let 
3449               r_hi = getHiVRegFromLo r_lo
3450           return (code, [r_hi, r_lo])
3451         | otherwise
3452         = do
3453           (src, code) <- getSomeReg arg
3454           tmp <- getNewRegNat (cmmExprRep arg)
3455           let
3456               pk   = cmmExprRep arg
3457           case pk of
3458              F64 -> do
3459                       v1 <- getNewRegNat I32
3460                       v2 <- getNewRegNat I32
3461                       return (
3462                         code                          `snocOL`
3463                         FMOV F64 src f0                `snocOL`
3464                         ST   F32  f0 (spRel 16)         `snocOL`
3465                         LD   I32  (spRel 16) v1         `snocOL`
3466                         ST   F32  (fPair f0) (spRel 16) `snocOL`
3467                         LD   I32  (spRel 16) v2
3468                         ,
3469                         [v1,v2]
3470                        )
3471              F32 -> do
3472                       v1 <- getNewRegNat I32
3473                       return (
3474                         code                    `snocOL`
3475                         ST   F32  src (spRel 16)  `snocOL`
3476                         LD   I32  (spRel 16) v1
3477                         ,
3478                         [v1]
3479                        )
3480              other -> do
3481                         v1 <- getNewRegNat I32
3482                         return (
3483                           code `snocOL` OR False g0 (RIReg src) v1
3484                           , 
3485                           [v1]
3486                          )
3487 outOfLineFloatOp mop =
3488     do
3489       mopExpr <- cmmMakeDynamicReference addImportNat CallReference $
3490                   mkForeignLabel functionName Nothing True
3491       let mopLabelOrExpr = case mopExpr of
3492                         CmmLit (CmmLabel lbl) -> Left lbl
3493                         _ -> Right mopExpr
3494       return (mopLabelOrExpr, reduce)
3495             where
3496                 (reduce, functionName) = case mop of
3497                   MO_F32_Exp    -> (True,  FSLIT("exp"))
3498                   MO_F32_Log    -> (True,  FSLIT("log"))
3499                   MO_F32_Sqrt   -> (True,  FSLIT("sqrt"))
3500
3501                   MO_F32_Sin    -> (True,  FSLIT("sin"))
3502                   MO_F32_Cos    -> (True,  FSLIT("cos"))
3503                   MO_F32_Tan    -> (True,  FSLIT("tan"))
3504
3505                   MO_F32_Asin   -> (True,  FSLIT("asin"))
3506                   MO_F32_Acos   -> (True,  FSLIT("acos"))
3507                   MO_F32_Atan   -> (True,  FSLIT("atan"))
3508
3509                   MO_F32_Sinh   -> (True,  FSLIT("sinh"))
3510                   MO_F32_Cosh   -> (True,  FSLIT("cosh"))
3511                   MO_F32_Tanh   -> (True,  FSLIT("tanh"))
3512
3513                   MO_F64_Exp    -> (False, FSLIT("exp"))
3514                   MO_F64_Log    -> (False, FSLIT("log"))
3515                   MO_F64_Sqrt   -> (False, FSLIT("sqrt"))
3516
3517                   MO_F64_Sin    -> (False, FSLIT("sin"))
3518                   MO_F64_Cos    -> (False, FSLIT("cos"))
3519                   MO_F64_Tan    -> (False, FSLIT("tan"))
3520
3521                   MO_F64_Asin   -> (False, FSLIT("asin"))
3522                   MO_F64_Acos   -> (False, FSLIT("acos"))
3523                   MO_F64_Atan   -> (False, FSLIT("atan"))
3524
3525                   MO_F64_Sinh   -> (False, FSLIT("sinh"))
3526                   MO_F64_Cosh   -> (False, FSLIT("cosh"))
3527                   MO_F64_Tanh   -> (False, FSLIT("tanh"))
3528
3529                   other -> pprPanic "outOfLineFloatOp(sparc) "
3530                                 (pprCallishMachOp mop)
3531
3532 #endif /* sparc_TARGET_ARCH */
3533
3534 #if powerpc_TARGET_ARCH
3535
3536 #if darwin_TARGET_OS || linux_TARGET_OS
3537 {-
3538     The PowerPC calling convention for Darwin/Mac OS X
3539     is described in Apple's document
3540     "Inside Mac OS X - Mach-O Runtime Architecture".
3541     
3542     PowerPC Linux uses the System V Release 4 Calling Convention
3543     for PowerPC. It is described in the
3544     "System V Application Binary Interface PowerPC Processor Supplement".
3545
3546     Both conventions are similar:
3547     Parameters may be passed in general-purpose registers starting at r3, in
3548     floating point registers starting at f1, or on the stack. 
3549     
3550     But there are substantial differences:
3551     * The number of registers used for parameter passing and the exact set of
3552       nonvolatile registers differs (see MachRegs.lhs).
3553     * On Darwin, stack space is always reserved for parameters, even if they are
3554       passed in registers. The called routine may choose to save parameters from
3555       registers to the corresponding space on the stack.
3556     * On Darwin, a corresponding amount of GPRs is skipped when a floating point
3557       parameter is passed in an FPR.
3558     * SysV insists on either passing I64 arguments on the stack, or in two GPRs,
3559       starting with an odd-numbered GPR. It may skip a GPR to achieve this.
3560       Darwin just treats an I64 like two separate I32s (high word first).
3561     * I64 and F64 arguments are 8-byte aligned on the stack for SysV, but only
3562       4-byte aligned like everything else on Darwin.
3563     * The SysV spec claims that F32 is represented as F64 on the stack. GCC on
3564       PowerPC Linux does not agree, so neither do we.
3565       
3566     According to both conventions, The parameter area should be part of the
3567     caller's stack frame, allocated in the caller's prologue code (large enough
3568     to hold the parameter lists for all called routines). The NCG already
3569     uses the stack for register spilling, leaving 64 bytes free at the top.
3570     If we need a larger parameter area than that, we just allocate a new stack
3571     frame just before ccalling.
3572 -}
3573
3574
3575 genCCall (CmmPrim MO_WriteBarrier) _ _ _
3576  = return $ unitOL LWSYNC
3577
3578 genCCall target dest_regs argsAndHints vols
3579   = ASSERT (not $ any (`elem` [I8,I16]) argReps)
3580         -- we rely on argument promotion in the codeGen
3581     do
3582         (finalStack,passArgumentsCode,usedRegs) <- passArguments
3583                                                         (zip args argReps)
3584                                                         allArgRegs allFPArgRegs
3585                                                         initialStackOffset
3586                                                         (toOL []) []
3587                                                 
3588         (labelOrExpr, reduceToF32) <- case target of
3589             CmmForeignCall (CmmLit (CmmLabel lbl)) conv -> return (Left lbl, False)
3590             CmmForeignCall expr conv -> return  (Right expr, False)
3591             CmmPrim mop -> outOfLineFloatOp mop
3592                                                         
3593         let codeBefore = move_sp_down finalStack `appOL` passArgumentsCode
3594             codeAfter = move_sp_up finalStack `appOL` moveResult reduceToF32
3595
3596         case labelOrExpr of
3597             Left lbl -> do
3598                 return (         codeBefore
3599                         `snocOL` BL lbl usedRegs
3600                         `appOL`  codeAfter)
3601             Right dyn -> do
3602                 (dynReg, dynCode) <- getSomeReg dyn
3603                 return (         dynCode
3604                         `snocOL` MTCTR dynReg
3605                         `appOL`  codeBefore
3606                         `snocOL` BCTRL usedRegs
3607                         `appOL`  codeAfter)
3608     where
3609 #if darwin_TARGET_OS
3610         initialStackOffset = 24
3611             -- size of linkage area + size of arguments, in bytes       
3612         stackDelta _finalStack = roundTo 16 $ (24 +) $ max 32 $ sum $
3613                                        map machRepByteWidth argReps
3614 #elif linux_TARGET_OS
3615         initialStackOffset = 8
3616         stackDelta finalStack = roundTo 16 finalStack
3617 #endif
3618         args = map fst argsAndHints
3619         argReps = map cmmExprRep args
3620
3621         roundTo a x | x `mod` a == 0 = x
3622                     | otherwise = x + a - (x `mod` a)
3623
3624         move_sp_down finalStack
3625                | delta > 64 =
3626                         toOL [STU I32 sp (AddrRegImm sp (ImmInt (-delta))),
3627                               DELTA (-delta)]
3628                | otherwise = nilOL
3629                where delta = stackDelta finalStack
3630         move_sp_up finalStack
3631                | delta > 64 =
3632                         toOL [ADD sp sp (RIImm (ImmInt delta)),
3633                               DELTA 0]
3634                | otherwise = nilOL
3635                where delta = stackDelta finalStack
3636                
3637
3638         passArguments [] _ _ stackOffset accumCode accumUsed = return (stackOffset, accumCode, accumUsed)
3639         passArguments ((arg,I64):args) gprs fprs stackOffset
3640                accumCode accumUsed =
3641             do
3642                 ChildCode64 code vr_lo <- iselExpr64 arg
3643                 let vr_hi = getHiVRegFromLo vr_lo
3644
3645 #if darwin_TARGET_OS                
3646                 passArguments args
3647                               (drop 2 gprs)
3648                               fprs
3649                               (stackOffset+8)
3650                               (accumCode `appOL` code
3651                                     `snocOL` storeWord vr_hi gprs stackOffset
3652                                     `snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4))
3653                               ((take 2 gprs) ++ accumUsed)
3654             where
3655                 storeWord vr (gpr:_) offset = MR gpr vr
3656                 storeWord vr [] offset = ST I32 vr (AddrRegImm sp (ImmInt offset))
3657                 
3658 #elif linux_TARGET_OS
3659                 let stackOffset' = roundTo 8 stackOffset
3660                     stackCode = accumCode `appOL` code
3661                         `snocOL` ST I32 vr_hi (AddrRegImm sp (ImmInt stackOffset'))
3662                         `snocOL` ST I32 vr_lo (AddrRegImm sp (ImmInt (stackOffset'+4)))
3663                     regCode hireg loreg =
3664                         accumCode `appOL` code
3665                             `snocOL` MR hireg vr_hi
3666                             `snocOL` MR loreg vr_lo
3667                                         
3668                 case gprs of
3669                     hireg : loreg : regs | even (length gprs) ->
3670                         passArguments args regs fprs stackOffset
3671                                       (regCode hireg loreg) (hireg : loreg : accumUsed)
3672                     _skipped : hireg : loreg : regs ->
3673                         passArguments args regs fprs stackOffset
3674                                       (regCode hireg loreg) (hireg : loreg : accumUsed)
3675                     _ -> -- only one or no regs left
3676                         passArguments args [] fprs (stackOffset'+8)
3677                                       stackCode accumUsed
3678 #endif
3679         
3680         passArguments ((arg,rep):args) gprs fprs stackOffset accumCode accumUsed
3681             | reg : _ <- regs = do
3682                 register <- getRegister arg
3683                 let code = case register of
3684                             Fixed _ freg fcode -> fcode `snocOL` MR reg freg
3685                             Any _ acode -> acode reg
3686                 passArguments args
3687                               (drop nGprs gprs)
3688                               (drop nFprs fprs)
3689 #if darwin_TARGET_OS
3690         -- The Darwin ABI requires that we reserve stack slots for register parameters
3691                               (stackOffset + stackBytes)
3692 #elif linux_TARGET_OS
3693         -- ... the SysV ABI doesn't.
3694                               stackOffset
3695 #endif
3696                               (accumCode `appOL` code)
3697                               (reg : accumUsed)
3698             | otherwise = do
3699                 (vr, code) <- getSomeReg arg
3700                 passArguments args
3701                               (drop nGprs gprs)
3702                               (drop nFprs fprs)
3703                               (stackOffset' + stackBytes)
3704                               (accumCode `appOL` code `snocOL` ST rep vr stackSlot)
3705                               accumUsed
3706             where
3707 #if darwin_TARGET_OS
3708         -- stackOffset is at least 4-byte aligned
3709         -- The Darwin ABI is happy with that.
3710                 stackOffset' = stackOffset
3711 #else
3712         -- ... the SysV ABI requires 8-byte alignment for doubles.
3713                 stackOffset' | rep == F64 = roundTo 8 stackOffset
3714                              | otherwise  =           stackOffset
3715 #endif
3716                 stackSlot = AddrRegImm sp (ImmInt stackOffset')
3717                 (nGprs, nFprs, stackBytes, regs) = case rep of
3718                     I32 -> (1, 0, 4, gprs)
3719 #if darwin_TARGET_OS
3720         -- The Darwin ABI requires that we skip a corresponding number of GPRs when
3721         -- we use the FPRs.
3722                     F32 -> (1, 1, 4, fprs)
3723                     F64 -> (2, 1, 8, fprs)
3724 #elif linux_TARGET_OS
3725         -- ... the SysV ABI doesn't.
3726                     F32 -> (0, 1, 4, fprs)
3727                     F64 -> (0, 1, 8, fprs)
3728 #endif
3729         
3730         moveResult reduceToF32 =
3731             case dest_regs of
3732                 [] -> nilOL
3733                 [(dest, _hint)]
3734                     | reduceToF32 && rep == F32 -> unitOL (FRSP r_dest f1)
3735                     | rep == F32 || rep == F64 -> unitOL (MR r_dest f1)
3736                     | rep == I64 -> toOL [MR (getHiVRegFromLo r_dest) r3,
3737                                           MR r_dest r4]
3738                     | otherwise -> unitOL (MR r_dest r3)
3739                     where rep = cmmRegRep dest
3740                           r_dest = getRegisterReg dest
3741                           
3742         outOfLineFloatOp mop =
3743             do
3744                 mopExpr <- cmmMakeDynamicReference addImportNat CallReference $
3745                               mkForeignLabel functionName Nothing True
3746                 let mopLabelOrExpr = case mopExpr of
3747                         CmmLit (CmmLabel lbl) -> Left lbl
3748                         _ -> Right mopExpr
3749                 return (mopLabelOrExpr, reduce)
3750             where
3751                 (functionName, reduce) = case mop of
3752                     MO_F32_Exp   -> (FSLIT("exp"), True)
3753                     MO_F32_Log   -> (FSLIT("log"), True)
3754                     MO_F32_Sqrt  -> (FSLIT("sqrt"), True)
3755                         
3756                     MO_F32_Sin   -> (FSLIT("sin"), True)
3757                     MO_F32_Cos   -> (FSLIT("cos"), True)
3758                     MO_F32_Tan   -> (FSLIT("tan"), True)
3759                     
3760                     MO_F32_Asin  -> (FSLIT("asin"), True)
3761                     MO_F32_Acos  -> (FSLIT("acos"), True)
3762                     MO_F32_Atan  -> (FSLIT("atan"), True)
3763                     
3764                     MO_F32_Sinh  -> (FSLIT("sinh"), True)
3765                     MO_F32_Cosh  -> (FSLIT("cosh"), True)
3766                     MO_F32_Tanh  -> (FSLIT("tanh"), True)
3767                     MO_F32_Pwr   -> (FSLIT("pow"), True)
3768                         
3769                     MO_F64_Exp   -> (FSLIT("exp"), False)
3770                     MO_F64_Log   -> (FSLIT("log"), False)
3771                     MO_F64_Sqrt  -> (FSLIT("sqrt"), False)
3772                         
3773                     MO_F64_Sin   -> (FSLIT("sin"), False)
3774                     MO_F64_Cos   -> (FSLIT("cos"), False)
3775                     MO_F64_Tan   -> (FSLIT("tan"), False)
3776                      
3777                     MO_F64_Asin  -> (FSLIT("asin"), False)
3778                     MO_F64_Acos  -> (FSLIT("acos"), False)
3779                     MO_F64_Atan  -> (FSLIT("atan"), False)
3780                     
3781                     MO_F64_Sinh  -> (FSLIT("sinh"), False)
3782                     MO_F64_Cosh  -> (FSLIT("cosh"), False)
3783                     MO_F64_Tanh  -> (FSLIT("tanh"), False)
3784                     MO_F64_Pwr   -> (FSLIT("pow"), False)
3785                     other -> pprPanic "genCCall(ppc): unknown callish op"
3786                                     (pprCallishMachOp other)
3787
3788 #endif /* darwin_TARGET_OS || linux_TARGET_OS */
3789                 
3790 #endif /* powerpc_TARGET_ARCH */
3791
3792
3793 -- -----------------------------------------------------------------------------
3794 -- Generating a table-branch
3795
3796 genSwitch :: CmmExpr -> [Maybe BlockId] -> NatM InstrBlock
3797
3798 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
3799 genSwitch expr ids
3800   | opt_PIC
3801   = do
3802         (reg,e_code) <- getSomeReg expr
3803         lbl <- getNewLabelNat
3804         dynRef <- cmmMakeDynamicReference addImportNat DataReference lbl
3805         (tableReg,t_code) <- getSomeReg $ dynRef
3806         let
3807             jumpTable = map jumpTableEntryRel ids
3808             
3809             jumpTableEntryRel Nothing
3810                 = CmmStaticLit (CmmInt 0 wordRep)
3811             jumpTableEntryRel (Just (BlockId id))
3812                 = CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
3813                 where blockLabel = mkAsmTempLabel id
3814
3815             op = OpAddr (AddrBaseIndex (EABaseReg tableReg)
3816                                        (EAIndex reg wORD_SIZE) (ImmInt 0))
3817
3818 #if x86_64_TARGET_ARCH && darwin_TARGET_OS
3819     -- on Mac OS X/x86_64, put the jump table in the text section
3820     -- to work around a limitation of the linker.
3821     -- ld64 is unable to handle the relocations for
3822     --     .quad L1 - L0
3823     -- if L0 is not preceded by a non-anonymous label in its section.
3824     
3825             code = e_code `appOL` t_code `appOL` toOL [
3826                             ADD wordRep op (OpReg tableReg),
3827                             JMP_TBL (OpReg tableReg) [ id | Just id <- ids ],
3828                             LDATA Text (CmmDataLabel lbl : jumpTable)
3829                     ]
3830 #else
3831             code = e_code `appOL` t_code `appOL` toOL [
3832                             LDATA ReadOnlyData (CmmDataLabel lbl : jumpTable),
3833                             ADD wordRep op (OpReg tableReg),
3834                             JMP_TBL (OpReg tableReg) [ id | Just id <- ids ]
3835                     ]
3836 #endif
3837         return code
3838   | otherwise
3839   = do
3840         (reg,e_code) <- getSomeReg expr
3841         lbl <- getNewLabelNat
3842         let
3843             jumpTable = map jumpTableEntry ids
3844             op = OpAddr (AddrBaseIndex EABaseNone (EAIndex reg wORD_SIZE) (ImmCLbl lbl))
3845             code = e_code `appOL` toOL [
3846                     LDATA ReadOnlyData (CmmDataLabel lbl : jumpTable),
3847                     JMP_TBL op [ id | Just id <- ids ]
3848                  ]
3849         -- in
3850         return code
3851 #elif powerpc_TARGET_ARCH
3852 genSwitch expr ids 
3853   | opt_PIC
3854   = do
3855         (reg,e_code) <- getSomeReg expr
3856         tmp <- getNewRegNat I32
3857         lbl <- getNewLabelNat
3858         dynRef <- cmmMakeDynamicReference addImportNat DataReference lbl
3859         (tableReg,t_code) <- getSomeReg $ dynRef
3860         let
3861             jumpTable = map jumpTableEntryRel ids
3862             
3863             jumpTableEntryRel Nothing
3864                 = CmmStaticLit (CmmInt 0 wordRep)
3865             jumpTableEntryRel (Just (BlockId id))
3866                 = CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
3867                 where blockLabel = mkAsmTempLabel id
3868
3869             code = e_code `appOL` t_code `appOL` toOL [
3870                             LDATA ReadOnlyData (CmmDataLabel lbl : jumpTable),
3871                             SLW tmp reg (RIImm (ImmInt 2)),
3872                             LD I32 tmp (AddrRegReg tableReg tmp),
3873                             ADD tmp tmp (RIReg tableReg),
3874                             MTCTR tmp,
3875                             BCTR [ id | Just id <- ids ]
3876                     ]
3877         return code
3878   | otherwise
3879   = do
3880         (reg,e_code) <- getSomeReg expr
3881         tmp <- getNewRegNat I32
3882         lbl <- getNewLabelNat
3883         let
3884             jumpTable = map jumpTableEntry ids
3885         
3886             code = e_code `appOL` toOL [
3887                             LDATA ReadOnlyData (CmmDataLabel lbl : jumpTable),
3888                             SLW tmp reg (RIImm (ImmInt 2)),
3889                             ADDIS tmp tmp (HA (ImmCLbl lbl)),
3890                             LD I32 tmp (AddrRegImm tmp (LO (ImmCLbl lbl))),
3891                             MTCTR tmp,
3892                             BCTR [ id | Just id <- ids ]
3893                     ]
3894         return code
3895 #else
3896 genSwitch expr ids = panic "ToDo: genSwitch"
3897 #endif
3898
3899 jumpTableEntry Nothing = CmmStaticLit (CmmInt 0 wordRep)
3900 jumpTableEntry (Just (BlockId id)) = CmmStaticLit (CmmLabel blockLabel)
3901     where blockLabel = mkAsmTempLabel id
3902
3903 -- -----------------------------------------------------------------------------
3904 -- Support bits
3905 -- -----------------------------------------------------------------------------
3906
3907
3908 -- -----------------------------------------------------------------------------
3909 -- 'condIntReg' and 'condFltReg': condition codes into registers
3910
3911 -- Turn those condition codes into integers now (when they appear on
3912 -- the right hand side of an assignment).
3913 -- 
3914 -- (If applicable) Do not fill the delay slots here; you will confuse the
3915 -- register allocator.
3916
3917 condIntReg, condFltReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register
3918
3919 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3920
3921 #if alpha_TARGET_ARCH
3922 condIntReg = panic "MachCode.condIntReg (not on Alpha)"
3923 condFltReg = panic "MachCode.condFltReg (not on Alpha)"
3924 #endif /* alpha_TARGET_ARCH */
3925
3926 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3927
3928 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
3929
3930 condIntReg cond x y = do
3931   CondCode _ cond cond_code <- condIntCode cond x y
3932   tmp <- getNewRegNat I8
3933   let 
3934         code dst = cond_code `appOL` toOL [
3935                     SETCC cond (OpReg tmp),
3936                     MOVZxL I8 (OpReg tmp) (OpReg dst)
3937                   ]
3938   -- in
3939   return (Any I32 code)
3940
3941 #endif
3942
3943 #if i386_TARGET_ARCH
3944
3945 condFltReg cond x y = do
3946   CondCode _ cond cond_code <- condFltCode cond x y
3947   tmp <- getNewRegNat I8
3948   let 
3949         code dst = cond_code `appOL` toOL [
3950                     SETCC cond (OpReg tmp),
3951                     MOVZxL I8 (OpReg tmp) (OpReg dst)
3952                   ]
3953   -- in
3954   return (Any I32 code)
3955
3956 #endif
3957
3958 #if x86_64_TARGET_ARCH
3959
3960 condFltReg cond x y = do
3961   CondCode _ cond cond_code <- condFltCode cond x y
3962   tmp1 <- getNewRegNat wordRep
3963   tmp2 <- getNewRegNat wordRep
3964   let 
3965         -- We have to worry about unordered operands (eg. comparisons
3966         -- against NaN).  If the operands are unordered, the comparison
3967         -- sets the parity flag, carry flag and zero flag.
3968         -- All comparisons are supposed to return false for unordered
3969         -- operands except for !=, which returns true.
3970         --
3971         -- Optimisation: we don't have to test the parity flag if we
3972         -- know the test has already excluded the unordered case: eg >
3973         -- and >= test for a zero carry flag, which can only occur for
3974         -- ordered operands.
3975         --
3976         -- ToDo: by reversing comparisons we could avoid testing the
3977         -- parity flag in more cases.
3978
3979         code dst = 
3980            cond_code `appOL` 
3981              (case cond of
3982                 NE  -> or_unordered dst
3983                 GU  -> plain_test   dst
3984                 GEU -> plain_test   dst
3985                 _   -> and_ordered  dst)
3986
3987         plain_test dst = toOL [
3988                     SETCC cond (OpReg tmp1),
3989                     MOVZxL I8 (OpReg tmp1) (OpReg dst)
3990                  ]
3991         or_unordered dst = toOL [
3992                     SETCC cond (OpReg tmp1),
3993                     SETCC PARITY (OpReg tmp2),
3994                     OR I8 (OpReg tmp1) (OpReg tmp2),
3995                     MOVZxL I8 (OpReg tmp2) (OpReg dst)
3996                   ]
3997         and_ordered dst = toOL [
3998                     SETCC cond (OpReg tmp1),
3999                     SETCC NOTPARITY (OpReg tmp2),
4000                     AND I8 (OpReg tmp1) (OpReg tmp2),
4001                     MOVZxL I8 (OpReg tmp2) (OpReg dst)
4002                   ]
4003   -- in
4004   return (Any I32 code)
4005
4006 #endif
4007
4008 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4009
4010 #if sparc_TARGET_ARCH
4011
4012 condIntReg EQQ x (CmmLit (CmmInt 0 d)) = do
4013     (src, code) <- getSomeReg x
4014     tmp <- getNewRegNat I32
4015     let
4016         code__2 dst = code `appOL` toOL [
4017             SUB False True g0 (RIReg src) g0,
4018             SUB True False g0 (RIImm (ImmInt (-1))) dst]
4019     return (Any I32 code__2)
4020
4021 condIntReg EQQ x y = do
4022     (src1, code1) <- getSomeReg x
4023     (src2, code2) <- getSomeReg y
4024     tmp1 <- getNewRegNat I32
4025     tmp2 <- getNewRegNat I32
4026     let
4027         code__2 dst = code1 `appOL` code2 `appOL` toOL [
4028             XOR False src1 (RIReg src2) dst,
4029             SUB False True g0 (RIReg dst) g0,
4030             SUB True False g0 (RIImm (ImmInt (-1))) dst]
4031     return (Any I32 code__2)
4032
4033 condIntReg NE x (CmmLit (CmmInt 0 d)) = do
4034     (src, code) <- getSomeReg x
4035     tmp <- getNewRegNat I32
4036     let
4037         code__2 dst = code `appOL` toOL [
4038             SUB False True g0 (RIReg src) g0,
4039             ADD True False g0 (RIImm (ImmInt 0)) dst]
4040     return (Any I32 code__2)
4041
4042 condIntReg NE x y = do
4043     (src1, code1) <- getSomeReg x
4044     (src2, code2) <- getSomeReg y
4045     tmp1 <- getNewRegNat I32
4046     tmp2 <- getNewRegNat I32
4047     let
4048         code__2 dst = code1 `appOL` code2 `appOL` toOL [
4049             XOR False src1 (RIReg src2) dst,
4050             SUB False True g0 (RIReg dst) g0,
4051             ADD True False g0 (RIImm (ImmInt 0)) dst]
4052     return (Any I32 code__2)
4053
4054 condIntReg cond x y = do
4055     BlockId lbl1 <- getBlockIdNat
4056     BlockId lbl2 <- getBlockIdNat
4057     CondCode _ cond cond_code <- condIntCode cond x y
4058     let
4059         code__2 dst = cond_code `appOL` toOL [
4060             BI cond False (ImmCLbl (mkAsmTempLabel lbl1)), NOP,
4061             OR False g0 (RIImm (ImmInt 0)) dst,
4062             BI ALWAYS False (ImmCLbl (mkAsmTempLabel lbl2)), NOP,
4063             NEWBLOCK (BlockId lbl1),
4064             OR False g0 (RIImm (ImmInt 1)) dst,
4065             NEWBLOCK (BlockId lbl2)]
4066     return (Any I32 code__2)
4067
4068 condFltReg cond x y = do
4069     BlockId lbl1 <- getBlockIdNat
4070     BlockId lbl2 <- getBlockIdNat
4071     CondCode _ cond cond_code <- condFltCode cond x y
4072     let
4073         code__2 dst = cond_code `appOL` toOL [ 
4074             NOP,
4075             BF cond False (ImmCLbl (mkAsmTempLabel lbl1)), NOP,
4076             OR False g0 (RIImm (ImmInt 0)) dst,
4077             BI ALWAYS False (ImmCLbl (mkAsmTempLabel lbl2)), NOP,
4078             NEWBLOCK (BlockId lbl1),
4079             OR False g0 (RIImm (ImmInt 1)) dst,
4080             NEWBLOCK (BlockId lbl2)]
4081     return (Any I32 code__2)
4082
4083 #endif /* sparc_TARGET_ARCH */
4084
4085 #if powerpc_TARGET_ARCH
4086 condReg getCond = do
4087     lbl1 <- getBlockIdNat
4088     lbl2 <- getBlockIdNat
4089     CondCode _ cond cond_code <- getCond
4090     let
4091 {-        code dst = cond_code `appOL` toOL [
4092                 BCC cond lbl1,
4093                 LI dst (ImmInt 0),
4094                 BCC ALWAYS lbl2,
4095                 NEWBLOCK lbl1,
4096                 LI dst (ImmInt 1),
4097                 BCC ALWAYS lbl2,
4098                 NEWBLOCK lbl2
4099             ]-}
4100         code dst = cond_code
4101             `appOL` negate_code
4102             `appOL` toOL [
4103                 MFCR dst,
4104                 RLWINM dst dst (bit + 1) 31 31
4105             ]
4106         
4107         negate_code | do_negate = unitOL (CRNOR bit bit bit)
4108                     | otherwise = nilOL
4109                     
4110         (bit, do_negate) = case cond of
4111             LTT -> (0, False)
4112             LE  -> (1, True)
4113             EQQ -> (2, False)
4114             GE  -> (0, True)
4115             GTT -> (1, False)
4116             
4117             NE  -> (2, True)
4118             
4119             LU  -> (0, False)
4120             LEU -> (1, True)
4121             GEU -> (0, True)
4122             GU  -> (1, False)
4123                 
4124     return (Any I32 code)
4125     
4126 condIntReg cond x y = condReg (condIntCode cond x y)
4127 condFltReg cond x y = condReg (condFltCode cond x y)
4128 #endif /* powerpc_TARGET_ARCH */
4129
4130
4131 -- -----------------------------------------------------------------------------
4132 -- 'trivial*Code': deal with trivial instructions
4133
4134 -- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
4135 -- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
4136 -- Only look for constants on the right hand side, because that's
4137 -- where the generic optimizer will have put them.
4138
4139 -- Similarly, for unary instructions, we don't have to worry about
4140 -- matching an StInt as the argument, because genericOpt will already
4141 -- have handled the constant-folding.
4142
4143 trivialCode
4144     :: MachRep 
4145     -> IF_ARCH_alpha((Reg -> RI -> Reg -> Instr)
4146       ,IF_ARCH_i386 ((Operand -> Operand -> Instr) 
4147                      -> Maybe (Operand -> Operand -> Instr)
4148       ,IF_ARCH_x86_64 ((Operand -> Operand -> Instr) 
4149                      -> Maybe (Operand -> Operand -> Instr)
4150       ,IF_ARCH_sparc((Reg -> RI -> Reg -> Instr)
4151       ,IF_ARCH_powerpc(Bool -> (Reg -> Reg -> RI -> Instr)
4152       ,)))))
4153     -> CmmExpr -> CmmExpr -- the two arguments
4154     -> NatM Register
4155
4156 #ifndef powerpc_TARGET_ARCH
4157 trivialFCode
4158     :: MachRep
4159     -> IF_ARCH_alpha((Reg -> Reg -> Reg -> Instr)
4160       ,IF_ARCH_sparc((MachRep -> Reg -> Reg -> Reg -> Instr)
4161       ,IF_ARCH_i386 ((MachRep -> Reg -> Reg -> Reg -> Instr)
4162       ,IF_ARCH_x86_64 ((MachRep -> Operand -> Operand -> Instr)
4163       ,))))
4164     -> CmmExpr -> CmmExpr -- the two arguments
4165     -> NatM Register
4166 #endif
4167
4168 trivialUCode
4169     :: MachRep 
4170     -> IF_ARCH_alpha((RI -> Reg -> Instr)
4171       ,IF_ARCH_i386 ((Operand -> Instr)
4172       ,IF_ARCH_x86_64 ((Operand -> Instr)
4173       ,IF_ARCH_sparc((RI -> Reg -> Instr)
4174       ,IF_ARCH_powerpc((Reg -> Reg -> Instr)
4175       ,)))))
4176     -> CmmExpr  -- the one argument
4177     -> NatM Register
4178
4179 #ifndef powerpc_TARGET_ARCH
4180 trivialUFCode
4181     :: MachRep
4182     -> IF_ARCH_alpha((Reg -> Reg -> Instr)
4183       ,IF_ARCH_i386 ((Reg -> Reg -> Instr)
4184       ,IF_ARCH_x86_64 ((Reg -> Reg -> Instr)
4185       ,IF_ARCH_sparc((Reg -> Reg -> Instr)
4186       ,))))
4187     -> CmmExpr -- the one argument
4188     -> NatM Register
4189 #endif
4190
4191 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4192
4193 #if alpha_TARGET_ARCH
4194
4195 trivialCode instr x (StInt y)
4196   | fits8Bits y
4197   = getRegister x               `thenNat` \ register ->
4198     getNewRegNat IntRep         `thenNat` \ tmp ->
4199     let
4200         code = registerCode register tmp
4201         src1 = registerName register tmp
4202         src2 = ImmInt (fromInteger y)
4203         code__2 dst = code . mkSeqInstr (instr src1 (RIImm src2) dst)
4204     in
4205     return (Any IntRep code__2)
4206
4207 trivialCode instr x y
4208   = getRegister x               `thenNat` \ register1 ->
4209     getRegister y               `thenNat` \ register2 ->
4210     getNewRegNat IntRep         `thenNat` \ tmp1 ->
4211     getNewRegNat IntRep         `thenNat` \ tmp2 ->
4212     let
4213         code1 = registerCode register1 tmp1 []
4214         src1  = registerName register1 tmp1
4215         code2 = registerCode register2 tmp2 []
4216         src2  = registerName register2 tmp2
4217         code__2 dst = asmSeqThen [code1, code2] .
4218                      mkSeqInstr (instr src1 (RIReg src2) dst)
4219     in
4220     return (Any IntRep code__2)
4221
4222 ------------
4223 trivialUCode instr x
4224   = getRegister x               `thenNat` \ register ->
4225     getNewRegNat IntRep         `thenNat` \ tmp ->
4226     let
4227         code = registerCode register tmp
4228         src  = registerName register tmp
4229         code__2 dst = code . mkSeqInstr (instr (RIReg src) dst)
4230     in
4231     return (Any IntRep code__2)
4232
4233 ------------
4234 trivialFCode _ instr x y
4235   = getRegister x               `thenNat` \ register1 ->
4236     getRegister y               `thenNat` \ register2 ->
4237     getNewRegNat F64    `thenNat` \ tmp1 ->
4238     getNewRegNat F64    `thenNat` \ tmp2 ->
4239     let
4240         code1 = registerCode register1 tmp1
4241         src1  = registerName register1 tmp1
4242
4243         code2 = registerCode register2 tmp2
4244         src2  = registerName register2 tmp2
4245
4246         code__2 dst = asmSeqThen [code1 [], code2 []] .
4247                       mkSeqInstr (instr src1 src2 dst)
4248     in
4249     return (Any F64 code__2)
4250
4251 trivialUFCode _ instr x
4252   = getRegister x               `thenNat` \ register ->
4253     getNewRegNat F64    `thenNat` \ tmp ->
4254     let
4255         code = registerCode register tmp
4256         src  = registerName register tmp
4257         code__2 dst = code . mkSeqInstr (instr src dst)
4258     in
4259     return (Any F64 code__2)
4260
4261 #endif /* alpha_TARGET_ARCH */
4262
4263 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4264
4265 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
4266
4267 {-
4268 The Rules of the Game are:
4269
4270 * You cannot assume anything about the destination register dst;
4271   it may be anything, including a fixed reg.
4272
4273 * You may compute an operand into a fixed reg, but you may not 
4274   subsequently change the contents of that fixed reg.  If you
4275   want to do so, first copy the value either to a temporary
4276   or into dst.  You are free to modify dst even if it happens
4277   to be a fixed reg -- that's not your problem.
4278
4279 * You cannot assume that a fixed reg will stay live over an
4280   arbitrary computation.  The same applies to the dst reg.
4281
4282 * Temporary regs obtained from getNewRegNat are distinct from 
4283   each other and from all other regs, and stay live over 
4284   arbitrary computations.
4285
4286 --------------------
4287
4288 SDM's version of The Rules:
4289
4290 * If getRegister returns Any, that means it can generate correct
4291   code which places the result in any register, period.  Even if that
4292   register happens to be read during the computation.
4293
4294   Corollary #1: this means that if you are generating code for an
4295   operation with two arbitrary operands, you cannot assign the result
4296   of the first operand into the destination register before computing
4297   the second operand.  The second operand might require the old value
4298   of the destination register.
4299
4300   Corollary #2: A function might be able to generate more efficient
4301   code if it knows the destination register is a new temporary (and
4302   therefore not read by any of the sub-computations).
4303
4304 * If getRegister returns Any, then the code it generates may modify only:
4305         (a) fresh temporaries
4306         (b) the destination register
4307         (c) known registers (eg. %ecx is used by shifts)
4308   In particular, it may *not* modify global registers, unless the global
4309   register happens to be the destination register.
4310 -}
4311
4312 trivialCode rep instr (Just revinstr) (CmmLit lit_a) b
4313   | not (is64BitLit lit_a) = do
4314   b_code <- getAnyReg b
4315   let
4316        code dst 
4317          = b_code dst `snocOL`
4318            revinstr (OpImm (litToImm lit_a)) (OpReg dst)
4319   -- in
4320   return (Any rep code)
4321
4322 trivialCode rep instr maybe_revinstr a b = genTrivialCode rep instr a b
4323
4324 -- This is re-used for floating pt instructions too.
4325 genTrivialCode rep instr a b = do
4326   (b_op, b_code) <- getNonClobberedOperand b
4327   a_code <- getAnyReg a
4328   tmp <- getNewRegNat rep
4329   let
4330      -- We want the value of b to stay alive across the computation of a.
4331      -- But, we want to calculate a straight into the destination register,
4332      -- because the instruction only has two operands (dst := dst `op` src).
4333      -- The troublesome case is when the result of b is in the same register
4334      -- as the destination reg.  In this case, we have to save b in a
4335      -- new temporary across the computation of a.
4336      code dst
4337         | dst `regClashesWithOp` b_op =
4338                 b_code `appOL`
4339                 unitOL (MOV rep b_op (OpReg tmp)) `appOL`
4340                 a_code dst `snocOL`
4341                 instr (OpReg tmp) (OpReg dst)
4342         | otherwise =
4343                 b_code `appOL`
4344                 a_code dst `snocOL`
4345                 instr b_op (OpReg dst)
4346   -- in
4347   return (Any rep code)
4348
4349 reg `regClashesWithOp` OpReg reg2   = reg == reg2
4350 reg `regClashesWithOp` OpAddr amode = any (==reg) (addrModeRegs amode)
4351 reg `regClashesWithOp` _            = False
4352
4353 -----------
4354
4355 trivialUCode rep instr x = do
4356   x_code <- getAnyReg x
4357   let
4358      code dst =
4359         x_code dst `snocOL`
4360         instr (OpReg dst)
4361   -- in
4362   return (Any rep code)
4363
4364 -----------
4365
4366 #if i386_TARGET_ARCH
4367
4368 trivialFCode pk instr x y = do
4369   (x_reg, x_code) <- getNonClobberedReg x -- these work for float regs too
4370   (y_reg, y_code) <- getSomeReg y
4371   let
4372      code dst =
4373         x_code `appOL`
4374         y_code `snocOL`
4375         instr pk x_reg y_reg dst
4376   -- in
4377   return (Any pk code)
4378
4379 #endif
4380
4381 #if x86_64_TARGET_ARCH
4382
4383 trivialFCode pk instr x y = genTrivialCode  pk (instr pk) x y
4384
4385 #endif
4386
4387 -------------
4388
4389 trivialUFCode rep instr x = do
4390   (x_reg, x_code) <- getSomeReg x
4391   let
4392      code dst =
4393         x_code `snocOL`
4394         instr x_reg dst
4395   -- in
4396   return (Any rep code)
4397
4398 #endif /* i386_TARGET_ARCH */
4399
4400 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4401
4402 #if sparc_TARGET_ARCH
4403
4404 trivialCode pk instr x (CmmLit (CmmInt y d))
4405   | fits13Bits y
4406   = do
4407       (src1, code) <- getSomeReg x
4408       tmp <- getNewRegNat I32
4409       let
4410         src2 = ImmInt (fromInteger y)
4411         code__2 dst = code `snocOL` instr src1 (RIImm src2) dst
4412       return (Any I32 code__2)
4413
4414 trivialCode pk instr x y = do
4415     (src1, code1) <- getSomeReg x
4416     (src2, code2) <- getSomeReg y
4417     tmp1 <- getNewRegNat I32
4418     tmp2 <- getNewRegNat I32
4419     let
4420         code__2 dst = code1 `appOL` code2 `snocOL`
4421                       instr src1 (RIReg src2) dst
4422     return (Any I32 code__2)
4423
4424 ------------
4425 trivialFCode pk instr x y = do
4426     (src1, code1) <- getSomeReg x
4427     (src2, code2) <- getSomeReg y
4428     tmp1 <- getNewRegNat (cmmExprRep x)
4429     tmp2 <- getNewRegNat (cmmExprRep y)
4430     tmp <- getNewRegNat F64
4431     let
4432         promote x = FxTOy F32 F64 x tmp
4433
4434         pk1   = cmmExprRep x
4435         pk2   = cmmExprRep y
4436
4437         code__2 dst =
4438                 if pk1 == pk2 then
4439                     code1 `appOL` code2 `snocOL`
4440                     instr pk src1 src2 dst
4441                 else if pk1 == F32 then
4442                     code1 `snocOL` promote src1 `appOL` code2 `snocOL`
4443                     instr F64 tmp src2 dst
4444                 else
4445                     code1 `appOL` code2 `snocOL` promote src2 `snocOL`
4446                     instr F64 src1 tmp dst
4447     return (Any (if pk1 == pk2 then pk1 else F64) code__2)
4448
4449 ------------
4450 trivialUCode pk instr x = do
4451     (src, code) <- getSomeReg x
4452     tmp <- getNewRegNat pk
4453     let
4454         code__2 dst = code `snocOL` instr (RIReg src) dst
4455     return (Any pk code__2)
4456
4457 -------------
4458 trivialUFCode pk instr x = do
4459     (src, code) <- getSomeReg x
4460     tmp <- getNewRegNat pk
4461     let
4462         code__2 dst = code `snocOL` instr src dst
4463     return (Any pk code__2)
4464
4465 #endif /* sparc_TARGET_ARCH */
4466
4467 #if powerpc_TARGET_ARCH
4468
4469 {-
4470 Wolfgang's PowerPC version of The Rules:
4471
4472 A slightly modified version of The Rules to take advantage of the fact
4473 that PowerPC instructions work on all registers and don't implicitly
4474 clobber any fixed registers.
4475
4476 * The only expression for which getRegister returns Fixed is (CmmReg reg).
4477
4478 * If getRegister returns Any, then the code it generates may modify only:
4479         (a) fresh temporaries
4480         (b) the destination register
4481   It may *not* modify global registers, unless the global
4482   register happens to be the destination register.
4483   It may not clobber any other registers. In fact, only ccalls clobber any
4484   fixed registers.
4485   Also, it may not modify the counter register (used by genCCall).
4486   
4487   Corollary: If a getRegister for a subexpression returns Fixed, you need
4488   not move it to a fresh temporary before evaluating the next subexpression.
4489   The Fixed register won't be modified.
4490   Therefore, we don't need a counterpart for the x86's getStableReg on PPC.
4491   
4492 * SDM's First Rule is valid for PowerPC, too: subexpressions can depend on
4493   the value of the destination register.
4494 -}
4495
4496 trivialCode rep signed instr x (CmmLit (CmmInt y _))
4497     | Just imm <- makeImmediate rep signed y 
4498     = do
4499         (src1, code1) <- getSomeReg x
4500         let code dst = code1 `snocOL` instr dst src1 (RIImm imm)
4501         return (Any rep code)
4502   
4503 trivialCode rep signed instr x y = do
4504     (src1, code1) <- getSomeReg x
4505     (src2, code2) <- getSomeReg y
4506     let code dst = code1 `appOL` code2 `snocOL` instr dst src1 (RIReg src2)
4507     return (Any rep code)
4508
4509 trivialCodeNoImm :: MachRep -> (Reg -> Reg -> Reg -> Instr)
4510     -> CmmExpr -> CmmExpr -> NatM Register
4511 trivialCodeNoImm rep instr x y = do
4512     (src1, code1) <- getSomeReg x
4513     (src2, code2) <- getSomeReg y
4514     let code dst = code1 `appOL` code2 `snocOL` instr dst src1 src2
4515     return (Any rep code)
4516     
4517 trivialUCode rep instr x = do
4518     (src, code) <- getSomeReg x
4519     let code' dst = code `snocOL` instr dst src
4520     return (Any rep code')
4521     
4522 -- There is no "remainder" instruction on the PPC, so we have to do
4523 -- it the hard way.
4524 -- The "div" parameter is the division instruction to use (DIVW or DIVWU)
4525
4526 remainderCode :: MachRep -> (Reg -> Reg -> Reg -> Instr)
4527     -> CmmExpr -> CmmExpr -> NatM Register
4528 remainderCode rep div x y = do
4529     (src1, code1) <- getSomeReg x
4530     (src2, code2) <- getSomeReg y
4531     let code dst = code1 `appOL` code2 `appOL` toOL [
4532                 div dst src1 src2,
4533                 MULLW dst dst (RIReg src2),
4534                 SUBF dst dst src1
4535             ]
4536     return (Any rep code)
4537
4538 #endif /* powerpc_TARGET_ARCH */
4539
4540
4541 -- -----------------------------------------------------------------------------
4542 --  Coercing to/from integer/floating-point...
4543
4544 -- @coerce(Int2FP|FP2Int)@ are more complicated integer/float
4545 -- conversions.  We have to store temporaries in memory to move
4546 -- between the integer and the floating point register sets.
4547
4548 -- @coerceDbl2Flt@ and @coerceFlt2Dbl@ are done this way because we
4549 -- pretend, on sparc at least, that double and float regs are seperate
4550 -- kinds, so the value has to be computed into one kind before being
4551 -- explicitly "converted" to live in the other kind.
4552
4553 coerceInt2FP :: MachRep -> MachRep -> CmmExpr -> NatM Register
4554 coerceFP2Int :: MachRep -> MachRep -> CmmExpr -> NatM Register
4555
4556 #if sparc_TARGET_ARCH
4557 coerceDbl2Flt :: CmmExpr -> NatM Register
4558 coerceFlt2Dbl :: CmmExpr -> NatM Register
4559 #endif
4560
4561 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4562
4563 #if alpha_TARGET_ARCH
4564
4565 coerceInt2FP _ x
4566   = getRegister x               `thenNat` \ register ->
4567     getNewRegNat IntRep         `thenNat` \ reg ->
4568     let
4569         code = registerCode register reg
4570         src  = registerName register reg
4571
4572         code__2 dst = code . mkSeqInstrs [
4573             ST Q src (spRel 0),
4574             LD TF dst (spRel 0),
4575             CVTxy Q TF dst dst]
4576     in
4577     return (Any F64 code__2)
4578
4579 -------------
4580 coerceFP2Int x
4581   = getRegister x               `thenNat` \ register ->
4582     getNewRegNat F64    `thenNat` \ tmp ->
4583     let
4584         code = registerCode register tmp
4585         src  = registerName register tmp
4586
4587         code__2 dst = code . mkSeqInstrs [
4588             CVTxy TF Q src tmp,
4589             ST TF tmp (spRel 0),
4590             LD Q dst (spRel 0)]
4591     in
4592     return (Any IntRep code__2)
4593
4594 #endif /* alpha_TARGET_ARCH */
4595
4596 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4597
4598 #if i386_TARGET_ARCH
4599
4600 coerceInt2FP from to x = do
4601   (x_reg, x_code) <- getSomeReg x
4602   let
4603         opc  = case to of F32 -> GITOF; F64 -> GITOD
4604         code dst = x_code `snocOL` opc x_reg dst
4605         -- ToDo: works for non-I32 reps?
4606   -- in
4607   return (Any to code)
4608
4609 ------------
4610
4611 coerceFP2Int from to x = do
4612   (x_reg, x_code) <- getSomeReg x
4613   let
4614         opc  = case from of F32 -> GFTOI; F64 -> GDTOI
4615         code dst = x_code `snocOL` opc x_reg dst
4616         -- ToDo: works for non-I32 reps?
4617   -- in
4618   return (Any to code)
4619
4620 #endif /* i386_TARGET_ARCH */
4621
4622 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4623
4624 #if x86_64_TARGET_ARCH
4625
4626 coerceFP2Int from to x = do
4627   (x_op, x_code) <- getOperand x  -- ToDo: could be a safe operand
4628   let
4629         opc  = case from of F32 -> CVTSS2SI; F64 -> CVTSD2SI
4630         code dst = x_code `snocOL` opc x_op dst
4631   -- in
4632   return (Any to code) -- works even if the destination rep is <I32
4633
4634 coerceInt2FP from to x = do
4635   (x_op, x_code) <- getOperand x  -- ToDo: could be a safe operand
4636   let
4637         opc  = case to of F32 -> CVTSI2SS; F64 -> CVTSI2SD
4638         code dst = x_code `snocOL` opc x_op dst
4639   -- in
4640   return (Any to code) -- works even if the destination rep is <I32
4641
4642 coerceFP2FP :: MachRep -> CmmExpr -> NatM Register
4643 coerceFP2FP to x = do
4644   (x_reg, x_code) <- getSomeReg x
4645   let
4646         opc  = case to of F32 -> CVTSD2SS; F64 -> CVTSS2SD
4647         code dst = x_code `snocOL` opc x_reg dst
4648   -- in
4649   return (Any to code)
4650
4651 #endif
4652
4653 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4654
4655 #if sparc_TARGET_ARCH
4656
4657 coerceInt2FP pk1 pk2 x = do
4658     (src, code) <- getSomeReg x
4659     let
4660         code__2 dst = code `appOL` toOL [
4661             ST pk1 src (spRel (-2)),
4662             LD pk1 (spRel (-2)) dst,
4663             FxTOy pk1 pk2 dst dst]
4664     return (Any pk2 code__2)
4665
4666 ------------
4667 coerceFP2Int pk fprep x = do
4668     (src, code) <- getSomeReg x
4669     reg <- getNewRegNat fprep
4670     tmp <- getNewRegNat pk
4671     let
4672         code__2 dst = ASSERT(fprep == F64 || fprep == F32)
4673             code `appOL` toOL [
4674             FxTOy fprep pk src tmp,
4675             ST pk tmp (spRel (-2)),
4676             LD pk (spRel (-2)) dst]
4677     return (Any pk code__2)
4678
4679 ------------
4680 coerceDbl2Flt x = do
4681     (src, code) <- getSomeReg x
4682     return (Any F32 (\dst -> code `snocOL` FxTOy F64 F32 src dst)) 
4683
4684 ------------
4685 coerceFlt2Dbl x = do
4686     (src, code) <- getSomeReg x
4687     return (Any F64 (\dst -> code `snocOL` FxTOy F32 F64 src dst))
4688
4689 #endif /* sparc_TARGET_ARCH */
4690
4691 #if powerpc_TARGET_ARCH
4692 coerceInt2FP fromRep toRep x = do
4693     (src, code) <- getSomeReg x
4694     lbl <- getNewLabelNat
4695     itmp <- getNewRegNat I32
4696     ftmp <- getNewRegNat F64
4697     dynRef <- cmmMakeDynamicReference addImportNat DataReference lbl
4698     Amode addr addr_code <- getAmode dynRef
4699     let
4700         code' dst = code `appOL` maybe_exts `appOL` toOL [
4701                 LDATA ReadOnlyData
4702                                 [CmmDataLabel lbl,
4703                                  CmmStaticLit (CmmInt 0x43300000 I32),
4704                                  CmmStaticLit (CmmInt 0x80000000 I32)],
4705                 XORIS itmp src (ImmInt 0x8000),
4706                 ST I32 itmp (spRel 3),
4707                 LIS itmp (ImmInt 0x4330),
4708                 ST I32 itmp (spRel 2),
4709                 LD F64 ftmp (spRel 2)
4710             ] `appOL` addr_code `appOL` toOL [
4711                 LD F64 dst addr,
4712                 FSUB F64 dst ftmp dst
4713             ] `appOL` maybe_frsp dst
4714             
4715         maybe_exts = case fromRep of
4716                         I8 ->  unitOL $ EXTS I8 src src
4717                         I16 -> unitOL $ EXTS I16 src src
4718                         I32 -> nilOL
4719         maybe_frsp dst = case toRep of
4720                         F32 -> unitOL $ FRSP dst dst
4721                         F64 -> nilOL
4722     return (Any toRep code')
4723
4724 coerceFP2Int fromRep toRep x = do
4725     -- the reps don't really matter: F*->F64 and I32->I* are no-ops
4726     (src, code) <- getSomeReg x
4727     tmp <- getNewRegNat F64
4728     let
4729         code' dst = code `appOL` toOL [
4730                 -- convert to int in FP reg
4731             FCTIWZ tmp src,
4732                 -- store value (64bit) from FP to stack
4733             ST F64 tmp (spRel 2),
4734                 -- read low word of value (high word is undefined)
4735             LD I32 dst (spRel 3)]       
4736     return (Any toRep code')
4737 #endif /* powerpc_TARGET_ARCH */
4738
4739
4740 -- -----------------------------------------------------------------------------
4741 -- eXTRA_STK_ARGS_HERE
4742
4743 -- We (allegedly) put the first six C-call arguments in registers;
4744 -- where do we start putting the rest of them?
4745
4746 -- Moved from MachInstrs (SDM):
4747
4748 #if alpha_TARGET_ARCH || sparc_TARGET_ARCH
4749 eXTRA_STK_ARGS_HERE :: Int
4750 eXTRA_STK_ARGS_HERE
4751   = IF_ARCH_alpha(0, IF_ARCH_sparc(23, ???))
4752 #endif
4753