CodeGen.hs 70.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
{-# OPTIONS -w #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and fix
-- any warnings in the module. See
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
-- for details

-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2004
--
-----------------------------------------------------------------------------

-- This is a big module, but, if you pay attention to
-- (a) the sectioning, (b) the type signatures, and
-- (c) the #if blah_TARGET_ARCH} things, the
-- structure should not be too overwhelming.

module X86.CodeGen ( 
	cmmTopCodeGen, 
	InstrBlock 
) 

where

#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "MachDeps.h"

-- NCG stuff:
import X86.Instr
import X86.Cond
import X86.Regs
import X86.RegInfo
import X86.Ppr
import Instruction
import PIC
import NCGMonad
import Size
import Reg
import RegClass
import Platform

-- Our intermediate code:
import BasicTypes
import BlockId
import PprCmm		( pprExpr )
import Cmm
import CLabel
import ClosureInfo	( C_SRT(..) )

-- The rest:
import StaticFlags	( opt_PIC )
import ForeignCall	( CCallConv(..) )
import OrdList
import Pretty
import qualified Outputable as O
import Outputable
import FastString
import FastBool		( isFastTrue )
import Constants	( wORD_SIZE )
import DynFlags

import Debug.Trace	( trace )

import Control.Monad	( mapAndUnzipM )
import Data.Maybe	( fromJust )
import Data.Bits
import Data.Word
import Data.Int


cmmTopCodeGen 
	:: DynFlags
	-> RawCmmTop
	-> NatM [NatCmmTop Instr]

cmmTopCodeGen dynflags 
	(CmmProc info lab params (ListGraph blocks)) = do
  (nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
  picBaseMb <- getPicBaseMaybeNat
  let proc = CmmProc info lab params (ListGraph $ concat nat_blocks)
      tops = proc : concat statics
      os   = platformOS $ targetPlatform dynflags

  case picBaseMb of
      Just picBase -> initializePicBase_x86 ArchX86 os picBase tops
      Nothing -> return tops
  
cmmTopCodeGen _ (CmmData sec dat) = do
  return [CmmData sec dat]  -- no translation, we just use CmmStatic


basicBlockCodeGen 
	:: CmmBasicBlock 
	-> NatM ( [NatBasicBlock Instr]
		, [NatCmmTop Instr])

basicBlockCodeGen (BasicBlock id stmts) = do
  instrs <- stmtsToInstrs stmts
  -- code generation may introduce new basic block boundaries, which
  -- are indicated by the NEWBLOCK instruction.  We must split up the
  -- instruction stream into basic blocks again.  Also, we extract
  -- LDATAs here too.
  let
	(top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs
	
	mkBlocks (NEWBLOCK id) (instrs,blocks,statics) 
	  = ([], BasicBlock id instrs : blocks, statics)
	mkBlocks (LDATA sec dat) (instrs,blocks,statics) 
	  = (instrs, blocks, CmmData sec dat:statics)
	mkBlocks instr (instrs,blocks,statics)
	  = (instr:instrs, blocks, statics)
  -- in
  return (BasicBlock id top : other_blocks, statics)


stmtsToInstrs :: [CmmStmt] -> NatM InstrBlock
stmtsToInstrs stmts
   = do instrss <- mapM stmtToInstrs stmts
        return (concatOL instrss)


stmtToInstrs :: CmmStmt -> NatM InstrBlock
stmtToInstrs stmt = case stmt of
    CmmNop	   -> return nilOL
    CmmComment s   -> return (unitOL (COMMENT s))

    CmmAssign reg src
      | isFloatType ty -> assignReg_FltCode size reg src
#if WORD_SIZE_IN_BITS==32
      | isWord64 ty    -> assignReg_I64Code      reg src
#endif
      | otherwise	 -> assignReg_IntCode size reg src
	where ty = cmmRegType reg
	      size = cmmTypeSize ty

    CmmStore addr src
      | isFloatType ty -> assignMem_FltCode size addr src
#if WORD_SIZE_IN_BITS==32
      | isWord64 ty 	 -> assignMem_I64Code      addr src
#endif
      | otherwise	 -> assignMem_IntCode size addr src
	where ty = cmmExprType src
	      size = cmmTypeSize ty

    CmmCall target result_regs args _ _
       -> genCCall target result_regs args

    CmmBranch id	  -> genBranch id
    CmmCondBranch arg id  -> genCondJump id arg
    CmmSwitch arg ids     -> genSwitch arg ids
    CmmJump arg params	  -> genJump arg
    CmmReturn params	  ->
      panic "stmtToInstrs: return statement should have been cps'd away"


--------------------------------------------------------------------------------
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- 	They are really trees of insns to facilitate fast appending, where a
-- 	left-to-right traversal yields the insns in the correct	order.
--
type InstrBlock 
	= OrdList Instr


-- | Condition codes passed up the tree.
--
data CondCode 	
	= CondCode Bool Cond InstrBlock


-- | a.k.a "Register64"
--	Reg is the lower 32-bit temporary which contains the result. 
--	Use getHiVRegFromLo to find the other VRegUnique.  
--
--	Rules of this simplified insn selection game are therefore that
--	the returned Reg may be modified
--
data ChildCode64 	
   = ChildCode64 
        InstrBlock
        Reg	 	


-- | Register's passed up the tree.  If the stix code forces the register
-- 	to live in a pre-decided machine register, it comes out as @Fixed@;
-- 	otherwise, it comes out as @Any@, and the parent can decide which
-- 	register to put it in.
--
data Register
	= Fixed	Size Reg InstrBlock
	| Any	Size (Reg -> InstrBlock)


swizzleRegisterRep :: Register -> Size -> Register
swizzleRegisterRep (Fixed _ reg code) size = Fixed size reg code
swizzleRegisterRep (Any _ codefn)     size = Any   size codefn


-- | Grab the Reg for a CmmReg
getRegisterReg :: CmmReg -> Reg

getRegisterReg (CmmLocal (LocalReg u pk))
  = mkVReg u (cmmTypeSize pk)

getRegisterReg (CmmGlobal mid)
  = case get_GlobalReg_reg_or_addr mid of
       Left (RealReg rrno) -> RealReg rrno
       _other -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
          -- By this stage, the only MagicIds remaining should be the
          -- ones which map to a real machine register on this
          -- platform.  Hence ...


-- | Memory addressing modes passed up the tree.
data Amode 
	= Amode AddrMode InstrBlock

{-
Now, given a tree (the argument to an CmmLoad) that references memory,
produce a suitable addressing mode.

A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to.  So you can't put
anything in between, lest it overwrite some of those registers.  If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:

    code
    LEA amode, tmp
    ... other computation ...
    ... (tmp) ...
-}


-- | Check whether an integer will fit in 32 bits.
--	A CmmInt is intended to be truncated to the appropriate 
-- 	number of bits, so here we truncate it to Int64.  This is
-- 	important because e.g. -1 as a CmmInt might be either
-- 	-1 or 18446744073709551615.
--
is32BitInteger :: Integer -> Bool
is32BitInteger i = i64 <= 0x7fffffff && i64 >= -0x80000000
  where i64 = fromIntegral i :: Int64


-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: Maybe BlockId -> CmmStatic
jumpTableEntry Nothing = CmmStaticLit (CmmInt 0 wordWidth)
jumpTableEntry (Just (BlockId id)) = CmmStaticLit (CmmLabel blockLabel)
    where blockLabel = mkAsmTempLabel id


-- -----------------------------------------------------------------------------
-- General things for putting together code sequences

-- Expand CmmRegOff.  ToDo: should we do it this way around, or convert
-- CmmExprs into CmmRegOff?
mangleIndexTree :: CmmExpr -> CmmExpr
mangleIndexTree (CmmRegOff reg off)
  = CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)]
  where width = typeWidth (cmmRegType reg)

-- | The dual to getAnyReg: compute an expression into a register, but
-- 	we don't mind which one it is.
getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
getSomeReg expr = do
  r <- getRegister expr
  case r of
    Any rep code -> do
	tmp <- getNewRegNat rep
	return (tmp, code tmp)
    Fixed _ reg code -> 
	return (reg, code)





assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_I64Code addrTree valueTree = do
  Amode addr addr_code <- getAmode addrTree
  ChildCode64 vcode rlo <- iselExpr64 valueTree
  let 
        rhi = getHiVRegFromLo rlo

        -- Little-endian store
        mov_lo = MOV II32 (OpReg rlo) (OpAddr addr)
        mov_hi = MOV II32 (OpReg rhi) (OpAddr (fromJust (addrOffset addr 4)))
  -- in
  return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)


assignReg_I64Code :: CmmReg  -> CmmExpr -> NatM InstrBlock
assignReg_I64Code (CmmLocal (LocalReg u_dst pk)) valueTree = do
   ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
   let 
         r_dst_lo = mkVReg u_dst II32
         r_dst_hi = getHiVRegFromLo r_dst_lo
         r_src_hi = getHiVRegFromLo r_src_lo
         mov_lo = MOV II32 (OpReg r_src_lo) (OpReg r_dst_lo)
         mov_hi = MOV II32 (OpReg r_src_hi) (OpReg r_dst_hi)
   -- in
   return (
        vcode `snocOL` mov_lo `snocOL` mov_hi
     )

assignReg_I64Code lvalue valueTree
   = panic "assignReg_I64Code(i386): invalid lvalue"




iselExpr64        :: CmmExpr -> NatM ChildCode64
iselExpr64 (CmmLit (CmmInt i _)) = do
  (rlo,rhi) <- getNewRegPairNat II32
  let
	r = fromIntegral (fromIntegral i :: Word32)
	q = fromIntegral ((fromIntegral i `shiftR` 32) :: Word32)
	code = toOL [
		MOV II32 (OpImm (ImmInteger r)) (OpReg rlo),
		MOV II32 (OpImm (ImmInteger q)) (OpReg rhi)
		]
  -- in
  return (ChildCode64 code rlo)

iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do
   Amode addr addr_code <- getAmode addrTree
   (rlo,rhi) <- getNewRegPairNat II32
   let 
        mov_lo = MOV II32 (OpAddr addr) (OpReg rlo)
        mov_hi = MOV II32 (OpAddr (fromJust (addrOffset addr 4))) (OpReg rhi)
   -- in
   return (
            ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi) 
                        rlo
     )

iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty
   = return (ChildCode64 nilOL (mkVReg vu II32))
         
-- we handle addition, but rather badly
iselExpr64 (CmmMachOp (MO_Add _) [e1, CmmLit (CmmInt i _)]) = do
   ChildCode64 code1 r1lo <- iselExpr64 e1
   (rlo,rhi) <- getNewRegPairNat II32
   let
	r = fromIntegral (fromIntegral i :: Word32)
	q = fromIntegral ((fromIntegral i `shiftR` 32) :: Word32)
	r1hi = getHiVRegFromLo r1lo
	code =  code1 `appOL`
		toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
		       ADD II32 (OpImm (ImmInteger r)) (OpReg rlo),
		       MOV II32 (OpReg r1hi) (OpReg rhi),
		       ADC II32 (OpImm (ImmInteger q)) (OpReg rhi) ]
   -- in
   return (ChildCode64 code rlo)

iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
   ChildCode64 code1 r1lo <- iselExpr64 e1
   ChildCode64 code2 r2lo <- iselExpr64 e2
   (rlo,rhi) <- getNewRegPairNat II32
   let
	r1hi = getHiVRegFromLo r1lo
	r2hi = getHiVRegFromLo r2lo
	code =  code1 `appOL`
		code2 `appOL`
		toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
		       ADD II32 (OpReg r2lo) (OpReg rlo),
		       MOV II32 (OpReg r1hi) (OpReg rhi),
		       ADC II32 (OpReg r2hi) (OpReg rhi) ]
   -- in
   return (ChildCode64 code rlo)

iselExpr64 (CmmMachOp (MO_UU_Conv _ W64) [expr]) = do
     fn <- getAnyReg expr
     r_dst_lo <-  getNewRegNat II32
     let r_dst_hi = getHiVRegFromLo r_dst_lo
         code = fn r_dst_lo
     return (
             ChildCode64 (code `snocOL` 
                          MOV II32 (OpImm (ImmInt 0)) (OpReg r_dst_hi))
                          r_dst_lo
            )

iselExpr64 expr
   = pprPanic "iselExpr64(i386)" (ppr expr)



--------------------------------------------------------------------------------
getRegister :: CmmExpr -> NatM Register

#if !x86_64_TARGET_ARCH
    -- on x86_64, we have %rip for PicBaseReg, but it's not a full-featured
    -- register, it can only be used for rip-relative addressing.
getRegister (CmmReg (CmmGlobal PicBaseReg))
  = do
      reg <- getPicBaseNat archWordSize
      return (Fixed archWordSize reg nilOL)
#endif

getRegister (CmmReg reg) 
  = return (Fixed (cmmTypeSize (cmmRegType reg)) 
		  (getRegisterReg reg) nilOL)

getRegister tree@(CmmRegOff _ _) 
  = getRegister (mangleIndexTree tree)


#if WORD_SIZE_IN_BITS==32
    -- for 32-bit architectuers, support some 64 -> 32 bit conversions:
    -- TO_W_(x), TO_W_(x >> 32)

getRegister (CmmMachOp (MO_UU_Conv W64 W32)
             [CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]]) = do
  ChildCode64 code rlo <- iselExpr64 x
  return $ Fixed II32 (getHiVRegFromLo rlo) code

getRegister (CmmMachOp (MO_SS_Conv W64 W32)
             [CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]]) = do
  ChildCode64 code rlo <- iselExpr64 x
  return $ Fixed II32 (getHiVRegFromLo rlo) code

getRegister (CmmMachOp (MO_UU_Conv W64 W32) [x]) = do
  ChildCode64 code rlo <- iselExpr64 x
  return $ Fixed II32 rlo code

getRegister (CmmMachOp (MO_SS_Conv W64 W32) [x]) = do
  ChildCode64 code rlo <- iselExpr64 x
  return $ Fixed II32 rlo code       

#endif




#if i386_TARGET_ARCH

getRegister (CmmLit (CmmFloat f W32)) = do
    lbl <- getNewLabelNat
    dflags <- getDynFlagsNat
    dynRef <- cmmMakeDynamicReference dflags addImportNat DataReference lbl
    Amode addr addr_code <- getAmode dynRef
    let code dst =
	    LDATA ReadOnlyData
			[CmmDataLabel lbl,
			 CmmStaticLit (CmmFloat f W32)]
	    `consOL` (addr_code `snocOL`
	    GLD FF32 addr dst)
    -- in
    return (Any FF32 code)


getRegister (CmmLit (CmmFloat d W64))
  | d == 0.0
  = let code dst = unitOL (GLDZ dst)
    in  return (Any FF64 code)

  | d == 1.0
  = let code dst = unitOL (GLD1 dst)
    in  return (Any FF64 code)

  | otherwise = do
    lbl <- getNewLabelNat
    dflags <- getDynFlagsNat
    dynRef <- cmmMakeDynamicReference dflags addImportNat DataReference lbl
    Amode addr addr_code <- getAmode dynRef
    let code dst =
	    LDATA ReadOnlyData
			[CmmDataLabel lbl,
			 CmmStaticLit (CmmFloat d W64)]
	    `consOL` (addr_code `snocOL`
	    GLD FF64 addr dst)
    -- in
    return (Any FF64 code)

#endif /* i386_TARGET_ARCH */




#if x86_64_TARGET_ARCH
getRegister (CmmLit (CmmFloat 0.0 w)) = do
   let size = floatSize w
       code dst = unitOL  (XOR size (OpReg dst) (OpReg dst))
	-- I don't know why there are xorpd, xorps, and pxor instructions.
	-- They all appear to do the same thing --SDM
   return (Any size code)

getRegister (CmmLit (CmmFloat f w)) = do
    lbl <- getNewLabelNat
    let code dst = toOL [
	    LDATA ReadOnlyData
			[CmmDataLabel lbl,
			 CmmStaticLit (CmmFloat f w)],
	    MOV size (OpAddr (ripRel (ImmCLbl lbl))) (OpReg dst)
	    ]
    -- in
    return (Any size code)
  where size = floatSize w

#endif /* x86_64_TARGET_ARCH */





-- catch simple cases of zero- or sign-extended load
getRegister (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad addr _]) = do
  code <- intLoadCode (MOVZxL II8) addr
  return (Any II32 code)

getRegister (CmmMachOp (MO_SS_Conv W8 W32) [CmmLoad addr _]) = do
  code <- intLoadCode (MOVSxL II8) addr
  return (Any II32 code)

getRegister (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad addr _]) = do
  code <- intLoadCode (MOVZxL II16) addr
  return (Any II32 code)

getRegister (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad addr _]) = do
  code <- intLoadCode (MOVSxL II16) addr
  return (Any II32 code)


#if x86_64_TARGET_ARCH

-- catch simple cases of zero- or sign-extended load
getRegister (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad addr _]) = do
  code <- intLoadCode (MOVZxL II8) addr
  return (Any II64 code)

getRegister (CmmMachOp (MO_SS_Conv W8 W64) [CmmLoad addr _]) = do
  code <- intLoadCode (MOVSxL II8) addr
  return (Any II64 code)

getRegister (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad addr _]) = do
  code <- intLoadCode (MOVZxL II16) addr
  return (Any II64 code)

getRegister (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad addr _]) = do
  code <- intLoadCode (MOVSxL II16) addr
  return (Any II64 code)

getRegister (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad addr _]) = do
  code <- intLoadCode (MOV II32) addr -- 32-bit loads zero-extend
  return (Any II64 code)

getRegister (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad addr _]) = do
  code <- intLoadCode (MOVSxL II32) addr
  return (Any II64 code)

getRegister (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg),
                                     CmmLit displacement])
    = return $ Any II64 (\dst -> unitOL $
        LEA II64 (OpAddr (ripRel (litToImm displacement))) (OpReg dst))

getRegister (CmmMachOp (MO_F_Neg W32) [x]) = do
  x_code <- getAnyReg x
  lbl <- getNewLabelNat
  let
    code dst = x_code dst `appOL` toOL [
	-- This is how gcc does it, so it can't be that bad:
	LDATA ReadOnlyData16 [
		CmmAlign 16,
		CmmDataLabel lbl,
		CmmStaticLit (CmmInt 0x80000000 W32),
		CmmStaticLit (CmmInt 0 W32),
		CmmStaticLit (CmmInt 0 W32),
		CmmStaticLit (CmmInt 0 W32)
	],
	XOR FF32 (OpAddr (ripRel (ImmCLbl lbl))) (OpReg dst)
		-- xorps, so we need the 128-bit constant
		-- ToDo: rip-relative
	]
  --
  return (Any FF32 code)

getRegister (CmmMachOp (MO_F_Neg W64) [x]) = do
  x_code <- getAnyReg x
  lbl <- getNewLabelNat
  let
	-- This is how gcc does it, so it can't be that bad:
    code dst = x_code dst `appOL` toOL [
	LDATA ReadOnlyData16 [
		CmmAlign 16,
		CmmDataLabel lbl,
		CmmStaticLit (CmmInt 0x8000000000000000 W64),
		CmmStaticLit (CmmInt 0 W64)
	],
		-- gcc puts an unpck here.  Wonder if we need it.
	XOR FF64 (OpAddr (ripRel (ImmCLbl lbl))) (OpReg dst)
		-- xorpd, so we need the 128-bit constant
	]
  --
  return (Any FF64 code)

#endif /* x86_64_TARGET_ARCH */





getRegister (CmmMachOp mop [x]) -- unary MachOps
  = case mop of
#if i386_TARGET_ARCH
      MO_F_Neg W32 -> trivialUFCode FF32 (GNEG FF32) x
      MO_F_Neg W64 -> trivialUFCode FF64 (GNEG FF64) x
#endif

      MO_S_Neg w -> triv_ucode NEGI (intSize w)
      MO_F_Neg w -> triv_ucode NEGI (floatSize w)
      MO_Not w   -> triv_ucode NOT  (intSize w)

      -- Nop conversions
      MO_UU_Conv W32 W8  -> toI8Reg  W32 x
      MO_SS_Conv W32 W8  -> toI8Reg  W32 x
      MO_UU_Conv W16 W8  -> toI8Reg  W16 x
      MO_SS_Conv W16 W8  -> toI8Reg  W16 x
      MO_UU_Conv W32 W16 -> toI16Reg W32 x
      MO_SS_Conv W32 W16 -> toI16Reg W32 x

#if x86_64_TARGET_ARCH
      MO_UU_Conv W64 W32 -> conversionNop II64 x
      MO_SS_Conv W64 W32 -> conversionNop II64 x
      MO_UU_Conv W64 W16 -> toI16Reg W64 x
      MO_SS_Conv W64 W16 -> toI16Reg W64 x
      MO_UU_Conv W64 W8  -> toI8Reg  W64 x
      MO_SS_Conv W64 W8  -> toI8Reg  W64 x
#endif

      MO_UU_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intSize rep1) x
      MO_SS_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intSize rep1) x

      -- widenings
      MO_UU_Conv W8  W32 -> integerExtend W8  W32 MOVZxL x
      MO_UU_Conv W16 W32 -> integerExtend W16 W32 MOVZxL x
      MO_UU_Conv W8  W16 -> integerExtend W8  W16 MOVZxL x

      MO_SS_Conv W8  W32 -> integerExtend W8  W32 MOVSxL x
      MO_SS_Conv W16 W32 -> integerExtend W16 W32 MOVSxL x
      MO_SS_Conv W8  W16 -> integerExtend W8  W16 MOVSxL x

#if x86_64_TARGET_ARCH
      MO_UU_Conv W8  W64 -> integerExtend W8  W64 MOVZxL x
      MO_UU_Conv W16 W64 -> integerExtend W16 W64 MOVZxL x
      MO_UU_Conv W32 W64 -> integerExtend W32 W64 MOVZxL x
      MO_SS_Conv W8  W64 -> integerExtend W8  W64 MOVSxL x
      MO_SS_Conv W16 W64 -> integerExtend W16 W64 MOVSxL x
      MO_SS_Conv W32 W64 -> integerExtend W32 W64 MOVSxL x
	-- for 32-to-64 bit zero extension, amd64 uses an ordinary movl.
	-- However, we don't want the register allocator to throw it
	-- away as an unnecessary reg-to-reg move, so we keep it in
	-- the form of a movzl and print it as a movl later.
#endif

#if i386_TARGET_ARCH
      MO_FF_Conv W32 W64 -> conversionNop FF64 x
      MO_FF_Conv W64 W32 -> conversionNop FF32 x
#else
      MO_FF_Conv W32 W64 -> coerceFP2FP W64 x
      MO_FF_Conv W64 W32 -> coerceFP2FP W32 x
#endif

      MO_FS_Conv from to -> coerceFP2Int from to x
      MO_SF_Conv from to -> coerceInt2FP from to x

      other -> pprPanic "getRegister" (pprMachOp mop)
   where
	triv_ucode :: (Size -> Operand -> Instr) -> Size -> NatM Register
	triv_ucode instr size = trivialUCode size (instr size) x

	-- signed or unsigned extension.
	integerExtend :: Width -> Width
		      -> (Size -> Operand -> Operand -> Instr)
		      -> CmmExpr -> NatM Register
	integerExtend from to instr expr = do
	    (reg,e_code) <- if from == W8 then getByteReg expr
					  else getSomeReg expr
	    let 
		code dst = 
		  e_code `snocOL`
		  instr (intSize from) (OpReg reg) (OpReg dst)
	    return (Any (intSize to) code)

	toI8Reg :: Width -> CmmExpr -> NatM Register
	toI8Reg new_rep expr
            = do codefn <- getAnyReg expr
		 return (Any (intSize new_rep) codefn)
		-- HACK: use getAnyReg to get a byte-addressable register.
		-- If the source was a Fixed register, this will add the
		-- mov instruction to put it into the desired destination.
		-- We're assuming that the destination won't be a fixed
		-- non-byte-addressable register; it won't be, because all
		-- fixed registers are word-sized.

	toI16Reg = toI8Reg -- for now

	conversionNop :: Size -> CmmExpr -> NatM Register
        conversionNop new_size expr
            = do e_code <- getRegister expr
                 return (swizzleRegisterRep e_code new_size)


getRegister e@(CmmMachOp mop [x, y]) -- dyadic MachOps
  = case mop of
      MO_F_Eq w -> condFltReg EQQ x y
      MO_F_Ne w -> condFltReg NE x y
      MO_F_Gt w -> condFltReg GTT x y
      MO_F_Ge w -> condFltReg GE x y
      MO_F_Lt w -> condFltReg LTT x y
      MO_F_Le w -> condFltReg LE x y

      MO_Eq rep   -> condIntReg EQQ x y
      MO_Ne rep   -> condIntReg NE x y

      MO_S_Gt rep -> condIntReg GTT x y
      MO_S_Ge rep -> condIntReg GE x y
      MO_S_Lt rep -> condIntReg LTT x y
      MO_S_Le rep -> condIntReg LE x y

      MO_U_Gt rep -> condIntReg GU  x y
      MO_U_Ge rep -> condIntReg GEU x y
      MO_U_Lt rep -> condIntReg LU  x y
      MO_U_Le rep -> condIntReg LEU x y

#if i386_TARGET_ARCH
      MO_F_Add w -> trivialFCode w GADD x y
      MO_F_Sub w -> trivialFCode w GSUB x y
      MO_F_Quot w -> trivialFCode w GDIV x y
      MO_F_Mul w -> trivialFCode w GMUL x y
#endif

#if x86_64_TARGET_ARCH
      MO_F_Add w -> trivialFCode w ADD x y
      MO_F_Sub w -> trivialFCode w SUB x y
      MO_F_Quot w -> trivialFCode w FDIV x y
      MO_F_Mul w -> trivialFCode w MUL x y
#endif

      MO_Add rep -> add_code rep x y
      MO_Sub rep -> sub_code rep x y

      MO_S_Quot rep -> div_code rep True  True  x y
      MO_S_Rem  rep -> div_code rep True  False x y
      MO_U_Quot rep -> div_code rep False True  x y
      MO_U_Rem  rep -> div_code rep False False x y

      MO_S_MulMayOflo rep -> imulMayOflo rep x y

      MO_Mul rep -> triv_op rep IMUL
      MO_And rep -> triv_op rep AND
      MO_Or  rep -> triv_op rep OR
      MO_Xor rep -> triv_op rep XOR

	{- Shift ops on x86s have constraints on their source, it
	   either has to be Imm, CL or 1
	    => trivialCode is not restrictive enough (sigh.)
	-}	   
      MO_Shl rep   -> shift_code rep SHL x y {-False-}
      MO_U_Shr rep -> shift_code rep SHR x y {-False-}
      MO_S_Shr rep -> shift_code rep SAR x y {-False-}

      other -> pprPanic "getRegister(x86) - binary CmmMachOp (1)" (pprMachOp mop)
  where
    --------------------
    triv_op width instr = trivialCode width op (Just op) x y
			where op   = instr (intSize width)

    imulMayOflo :: Width -> CmmExpr -> CmmExpr -> NatM Register
    imulMayOflo rep a b = do
         (a_reg, a_code) <- getNonClobberedReg a
         b_code <- getAnyReg b
         let 
	     shift_amt  = case rep of
			   W32 -> 31
			   W64 -> 63
			   _ -> panic "shift_amt"

	     size = intSize rep
             code = a_code `appOL` b_code eax `appOL`
                        toOL [
			   IMUL2 size (OpReg a_reg),   -- result in %edx:%eax
                           SAR size (OpImm (ImmInt shift_amt)) (OpReg eax),
				-- sign extend lower part
                           SUB size (OpReg edx) (OpReg eax)
				-- compare against upper
                           -- eax==0 if high part == sign extended low part
                        ]
         -- in
	 return (Fixed size eax code)

    --------------------
    shift_code :: Width
	       -> (Size -> Operand -> Operand -> Instr)
	       -> CmmExpr
	       -> CmmExpr
	       -> NatM Register

    {- Case1: shift length as immediate -}
    shift_code width instr x y@(CmmLit lit) = do
	  x_code <- getAnyReg x
	  let
	       size = intSize width
	       code dst
		  = x_code dst `snocOL` 
		    instr size (OpImm (litToImm lit)) (OpReg dst)
	  -- in
	  return (Any size code)
        
    {- Case2: shift length is complex (non-immediate)
      * y must go in %ecx.
      * we cannot do y first *and* put its result in %ecx, because
        %ecx might be clobbered by x.
      * if we do y second, then x cannot be 
        in a clobbered reg.  Also, we cannot clobber x's reg
        with the instruction itself.
      * so we can either:
        - do y first, put its result in a fresh tmp, then copy it to %ecx later
        - do y second and put its result into %ecx.  x gets placed in a fresh
          tmp.  This is likely to be better, becuase the reg alloc can
          eliminate this reg->reg move here (it won't eliminate the other one,
          because the move is into the fixed %ecx).
    -}
    shift_code width instr x y{-amount-} = do
        x_code <- getAnyReg x
	let size = intSize width
	tmp <- getNewRegNat size
        y_code <- getAnyReg y
	let 
	   code = x_code tmp `appOL`
		  y_code ecx `snocOL`
		  instr size (OpReg ecx) (OpReg tmp)
        -- in
        return (Fixed size tmp code)

    --------------------
    add_code :: Width -> CmmExpr -> CmmExpr -> NatM Register
    add_code rep x (CmmLit (CmmInt y _))
	| is32BitInteger y = add_int rep x y
    add_code rep x y = trivialCode rep (ADD size) (Just (ADD size)) x y
      where size = intSize rep

    --------------------
    sub_code :: Width -> CmmExpr -> CmmExpr -> NatM Register
    sub_code rep x (CmmLit (CmmInt y _))
	| is32BitInteger (-y) = add_int rep x (-y)
    sub_code rep x y = trivialCode rep (SUB (intSize rep)) Nothing x y

    -- our three-operand add instruction:
    add_int width x y = do
	(x_reg, x_code) <- getSomeReg x
	let
	    size = intSize width
	    imm = ImmInt (fromInteger y)
	    code dst
               = x_code `snocOL`
		 LEA size
			(OpAddr (AddrBaseIndex (EABaseReg x_reg) EAIndexNone imm))
                        (OpReg dst)
	-- 
	return (Any size code)

    ----------------------
    div_code width signed quotient x y = do
	   (y_op, y_code) <- getRegOrMem y -- cannot be clobbered
	   x_code <- getAnyReg x
	   let
	     size = intSize width
	     widen | signed    = CLTD size
		   | otherwise = XOR size (OpReg edx) (OpReg edx)

	     instr | signed    = IDIV
		   | otherwise = DIV

	     code = y_code `appOL`
		    x_code eax `appOL`
		    toOL [widen, instr size y_op]

	     result | quotient  = eax
		    | otherwise = edx

	   -- in
           return (Fixed size result code)


getRegister (CmmLoad mem pk)
  | isFloatType pk
  = do
    Amode src mem_code <- getAmode mem
    let
	size = cmmTypeSize pk
    	code dst = mem_code `snocOL` 
		   IF_ARCH_i386(GLD size src dst,
			        MOV size (OpAddr src) (OpReg dst))
    return (Any size code)

#if i386_TARGET_ARCH
getRegister (CmmLoad mem pk)
  | not (isWord64 pk)
  = do 
    code <- intLoadCode instr mem
    return (Any size code)
  where
    width = typeWidth pk
    size = intSize width
    instr = case width of
		W8     -> MOVZxL II8
		_other -> MOV size
	-- We always zero-extend 8-bit loads, if we
	-- can't think of anything better.  This is because
	-- we can't guarantee access to an 8-bit variant of every register
	-- (esi and edi don't have 8-bit variants), so to make things
	-- simpler we do our 8-bit arithmetic with full 32-bit registers.
#endif

#if x86_64_TARGET_ARCH
-- Simpler memory load code on x86_64
getRegister (CmmLoad mem pk)
  = do 
    code <- intLoadCode (MOV size) mem
    return (Any size code)
  where size = intSize $ typeWidth pk
#endif

getRegister (CmmLit (CmmInt 0 width))
  = let
	size = intSize width

	-- x86_64: 32-bit xor is one byte shorter, and zero-extends to 64 bits
	adj_size = case size of II64 -> II32; _ -> size
	size1 = IF_ARCH_i386( size, adj_size ) 
    	code dst 
           = unitOL (XOR size1 (OpReg dst) (OpReg dst))
    in
    	return (Any size code)

#if x86_64_TARGET_ARCH
  -- optimisation for loading small literals on x86_64: take advantage
  -- of the automatic zero-extension from 32 to 64 bits, because the 32-bit
  -- instruction forms are shorter.
getRegister (CmmLit lit) 
  | isWord64 (cmmLitType lit), not (isBigLit lit)
  = let 
	imm = litToImm lit
	code dst = unitOL (MOV II32 (OpImm imm) (OpReg dst))
    in
    	return (Any II64 code)
  where
   isBigLit (CmmInt i _) = i < 0 || i > 0xffffffff
   isBigLit _ = False
	-- note1: not the same as (not.is32BitLit), because that checks for
	-- signed literals that fit in 32 bits, but we want unsigned
	-- literals here.
	-- note2: all labels are small, because we're assuming the
	-- small memory model (see gcc docs, -mcmodel=small).
#endif

getRegister (CmmLit lit)
  = let 
	size = cmmTypeSize (cmmLitType lit)
	imm = litToImm lit
	code dst = unitOL (MOV size (OpImm imm) (OpReg dst))
    in
    	return (Any size code)

getRegister other = pprPanic "getRegister(x86)" (ppr other)


intLoadCode :: (Operand -> Operand -> Instr) -> CmmExpr
   -> NatM (Reg -> InstrBlock)
intLoadCode instr mem = do
  Amode src mem_code <- getAmode mem
  return (\dst -> mem_code `snocOL` instr (OpAddr src) (OpReg dst))

-- Compute an expression into *any* register, adding the appropriate
-- move instruction if necessary.
getAnyReg :: CmmExpr -> NatM (Reg -> InstrBlock)
getAnyReg expr = do
  r <- getRegister expr
  anyReg r

anyReg :: Register -> NatM (Reg -> InstrBlock)
anyReg (Any _ code)          = return code
anyReg (Fixed rep reg fcode) = return (\dst -> fcode `snocOL` reg2reg rep reg dst)

-- A bit like getSomeReg, but we want a reg that can be byte-addressed.
-- Fixed registers might not be byte-addressable, so we make sure we've
-- got a temporary, inserting an extra reg copy if necessary.
getByteReg :: CmmExpr -> NatM (Reg, InstrBlock)
#if x86_64_TARGET_ARCH
getByteReg = getSomeReg -- all regs are byte-addressable on x86_64
#else
getByteReg expr = do
  r <- getRegister expr
  case r of
    Any rep code -> do
	tmp <- getNewRegNat rep
	return (tmp, code tmp)
    Fixed rep reg code 
	| isVirtualReg reg -> return (reg,code)
	| otherwise -> do
	    tmp <- getNewRegNat rep
	    return (tmp, code `snocOL` reg2reg rep reg tmp)
	-- ToDo: could optimise slightly by checking for byte-addressable
	-- real registers, but that will happen very rarely if at all.
#endif

-- Another variant: this time we want the result in a register that cannot
-- be modified by code to evaluate an arbitrary expression.
getNonClobberedReg :: CmmExpr -> NatM (Reg, InstrBlock)
getNonClobberedReg expr = do
  r <- getRegister expr
  case r of
    Any rep code -> do
	tmp <- getNewRegNat rep
	return (tmp, code tmp)
    Fixed rep reg code
	-- only free regs can be clobbered
	| RealReg rr <- reg, isFastTrue (freeReg rr) -> do
		tmp <- getNewRegNat rep
		return (tmp, code `snocOL` reg2reg rep reg tmp)
	| otherwise -> 
		return (reg, code)

reg2reg :: Size -> Reg -> Reg -> Instr
reg2reg size src dst 
#if i386_TARGET_ARCH
  | isFloatSize size = GMOV src dst
#endif
  | otherwise	     = MOV size (OpReg src) (OpReg dst)



--------------------------------------------------------------------------------
getAmode :: CmmExpr -> NatM Amode
getAmode tree@(CmmRegOff _ _) = getAmode (mangleIndexTree tree)

#if x86_64_TARGET_ARCH

getAmode (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg),
                                     CmmLit displacement])
    = return $ Amode (ripRel (litToImm displacement)) nilOL

#endif


-- This is all just ridiculous, since it carefully undoes 
-- what mangleIndexTree has just done.
getAmode (CmmMachOp (MO_Sub rep) [x, CmmLit lit@(CmmInt i _)])
  | is32BitLit lit
  -- ASSERT(rep == II32)???
  = do (x_reg, x_code) <- getSomeReg x
       let off = ImmInt (-(fromInteger i))
       return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
  
getAmode (CmmMachOp (MO_Add rep) [x, CmmLit lit@(CmmInt i _)])
  | is32BitLit lit
  -- ASSERT(rep == II32)???
  = do (x_reg, x_code) <- getSomeReg x
       let off = ImmInt (fromInteger i)
       return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)

-- Turn (lit1 << n  + lit2) into  (lit2 + lit1 << n) so it will be 
-- recognised by the next rule.
getAmode (CmmMachOp (MO_Add rep) [a@(CmmMachOp (MO_Shl _) _),
				  b@(CmmLit _)])
  = getAmode (CmmMachOp (MO_Add rep) [b,a])

getAmode (CmmMachOp (MO_Add rep) [x, CmmMachOp (MO_Shl _) 
					[y, CmmLit (CmmInt shift _)]])
  | shift == 0 || shift == 1 || shift == 2 || shift == 3
  = x86_complex_amode x y shift 0

getAmode (CmmMachOp (MO_Add rep) 
                [x, CmmMachOp (MO_Add _)
                        [CmmMachOp (MO_Shl _) [y, CmmLit (CmmInt shift _)],
                         CmmLit (CmmInt offset _)]])
  | shift == 0 || shift == 1 || shift == 2 || shift == 3
  && is32BitInteger offset
  = x86_complex_amode x y shift offset

getAmode (CmmMachOp (MO_Add rep) [x,y])
  = x86_complex_amode x y 0 0

getAmode (CmmLit lit) | is32BitLit lit
  = return (Amode (ImmAddr (litToImm lit) 0) nilOL)

getAmode expr = do
  (reg,code) <- getSomeReg expr
  return (Amode (AddrBaseIndex (EABaseReg reg) EAIndexNone (ImmInt 0)) code)


x86_complex_amode :: CmmExpr -> CmmExpr -> Integer -> Integer -> NatM Amode
x86_complex_amode base index shift offset
  = do (x_reg, x_code) <- getNonClobberedReg base
	-- x must be in a temp, because it has to stay live over y_code
	-- we could compre x_reg and y_reg and do something better here...
       (y_reg, y_code) <- getSomeReg index
       let
    	   code = x_code `appOL` y_code
           base = case shift of 0 -> 1; 1 -> 2; 2 -> 4; 3 -> 8
       return (Amode (AddrBaseIndex (EABaseReg x_reg) (EAIndex y_reg base) (ImmInt (fromIntegral offset)))
               code)




-- -----------------------------------------------------------------------------
-- getOperand: sometimes any operand will do.

-- getNonClobberedOperand: the value of the operand will remain valid across
-- the computation of an arbitrary expression, unless the expression
-- is computed directly into a register which the operand refers to
-- (see trivialCode where this function is used for an example).

getNonClobberedOperand :: CmmExpr -> NatM (Operand, InstrBlock)
#if x86_64_TARGET_ARCH
getNonClobberedOperand (CmmLit lit)
  | isSuitableFloatingPointLit lit = do
    lbl <- getNewLabelNat
    let code = unitOL (LDATA ReadOnlyData  [CmmDataLabel lbl,
					   CmmStaticLit lit])
    return (OpAddr (ripRel (ImmCLbl lbl)), code)
#endif
getNonClobberedOperand (CmmLit lit)
  | is32BitLit lit && not (isFloatType (cmmLitType lit)) =
    return (OpImm (litToImm lit), nilOL)
getNonClobberedOperand (CmmLoad mem pk) 
  | IF_ARCH_i386(not (isFloatType pk) && not (isWord64 pk), True) = do
    Amode src mem_code <- getAmode mem
    (src',save_code) <- 
	if (amodeCouldBeClobbered src) 
		then do
		   tmp <- getNewRegNat archWordSize
		   return (AddrBaseIndex (EABaseReg tmp) EAIndexNone (ImmInt 0),
			   unitOL (LEA II32 (OpAddr src) (OpReg tmp)))
		else
		   return (src, nilOL)
    return (OpAddr src', save_code `appOL` mem_code)
getNonClobberedOperand e = do
    (reg, code) <- getNonClobberedReg e
    return (OpReg reg, code)

amodeCouldBeClobbered :: AddrMode -> Bool
amodeCouldBeClobbered amode = any regClobbered (addrModeRegs amode)

regClobbered (RealReg rr) = isFastTrue (freeReg rr)
regClobbered _ = False

-- getOperand: the operand is not required to remain valid across the
-- computation of an arbitrary expression.
getOperand :: CmmExpr -> NatM (Operand, InstrBlock)
#if x86_64_TARGET_ARCH
getOperand (CmmLit lit)
  | isSuitableFloatingPointLit lit = do
    lbl <- getNewLabelNat
    let code = unitOL (LDATA ReadOnlyData  [CmmDataLabel lbl,
					   CmmStaticLit lit])
    return (OpAddr (ripRel (ImmCLbl lbl)), code)
#endif
getOperand (CmmLit lit)
  | is32BitLit lit && not (isFloatType (cmmLitType lit)) = do
    return (OpImm (litToImm lit), nilOL)
getOperand (CmmLoad mem pk)
  | IF_ARCH_i386(not (isFloatType pk) && not (isWord64 pk), True) = do
    Amode src mem_code <- getAmode mem
    return (OpAddr src, mem_code)
getOperand e = do
    (reg, code) <- getSomeReg e
    return (OpReg reg, code)

isOperand :: CmmExpr -> Bool
isOperand (CmmLoad _ _) = True
isOperand (CmmLit lit)  = is32BitLit lit
			  || isSuitableFloatingPointLit lit
isOperand _             = False

-- if we want a floating-point literal as an operand, we can
-- use it directly from memory.  However, if the literal is
-- zero, we're better off generating it into a register using
-- xor.
isSuitableFloatingPointLit (CmmFloat f _) = f /= 0.0
isSuitableFloatingPointLit _ = False

getRegOrMem :: CmmExpr -> NatM (Operand, InstrBlock)
getRegOrMem (CmmLoad mem pk)
  | IF_ARCH_i386(not (isFloatType pk) && not (isWord64 pk), True) = do
    Amode src mem_code <- getAmode mem
    return (OpAddr src, mem_code)
getRegOrMem e = do
    (reg, code) <- getNonClobberedReg e
    return (OpReg reg, code)

#if x86_64_TARGET_ARCH
is32BitLit (CmmInt i W64) = is32BitInteger i
   -- assume that labels are in the range 0-2^31-1: this assumes the
   -- small memory model (see gcc docs, -mcmodel=small).
#endif
is32BitLit x = True




-- Set up a condition code for a conditional branch.

getCondCode :: CmmExpr -> NatM CondCode

-- yes, they really do seem to want exactly the same!

getCondCode (CmmMachOp mop [x, y])
  = 
    case mop of
      MO_F_Eq W32 -> condFltCode EQQ x y
      MO_F_Ne W32 -> condFltCode NE  x y
      MO_F_Gt W32 -> condFltCode GTT x y
      MO_F_Ge W32 -> condFltCode GE  x y
      MO_F_Lt W32 -> condFltCode LTT x y
      MO_F_Le W32 -> condFltCode LE  x y

      MO_F_Eq W64 -> condFltCode EQQ x y
      MO_F_Ne W64 -> condFltCode NE  x y
      MO_F_Gt W64 -> condFltCode GTT x y
      MO_F_Ge W64 -> condFltCode GE  x y
      MO_F_Lt W64 -> condFltCode LTT x y
      MO_F_Le W64 -> condFltCode LE  x y

      MO_Eq rep -> condIntCode EQQ  x y
      MO_Ne rep -> condIntCode NE   x y

      MO_S_Gt rep -> condIntCode GTT  x y
      MO_S_Ge rep -> condIntCode GE   x y
      MO_S_Lt rep -> condIntCode LTT  x y
      MO_S_Le rep -> condIntCode LE   x y

      MO_U_Gt rep -> condIntCode GU   x y
      MO_U_Ge rep -> condIntCode GEU  x y
      MO_U_Lt rep -> condIntCode LU   x y
      MO_U_Le rep -> condIntCode LEU  x y

      other -> pprPanic "getCondCode(x86,x86_64,sparc)" (ppr (CmmMachOp mop [x,y]))

getCondCode other =  pprPanic "getCondCode(2)(x86,sparc)" (ppr other)




-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.

condIntCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode

-- memory vs immediate
condIntCode cond (CmmLoad x pk) (CmmLit lit) | is32BitLit lit = do
    Amode x_addr x_code <- getAmode x
    let
	imm  = litToImm lit
    	code = x_code `snocOL`
    	    	  CMP (cmmTypeSize pk) (OpImm imm) (OpAddr x_addr)
    --
    return (CondCode False cond code)

-- anything vs zero, using a mask
-- TODO: Add some sanity checking!!!!
condIntCode cond (CmmMachOp (MO_And rep) [x,o2]) (CmmLit (CmmInt 0 pk))
    | (CmmLit lit@(CmmInt mask pk2)) <- o2, is32BitLit lit
    = do
      (x_reg, x_code) <- getSomeReg x
      let
         code = x_code `snocOL`
                TEST (intSize pk) (OpImm (ImmInteger mask)) (OpReg x_reg)
      --
      return (CondCode False cond code)

-- anything vs zero
condIntCode cond x (CmmLit (CmmInt 0 pk)) = do
    (x_reg, x_code) <- getSomeReg x
    let
	code = x_code `snocOL`
    	    	  TEST (intSize pk) (OpReg x_reg) (OpReg x_reg)
    --
    return (CondCode False cond code)

-- anything vs operand
condIntCode cond x y | isOperand y = do
    (x_reg, x_code) <- getNonClobberedReg x
    (y_op,  y_code) <- getOperand y    
    let
	code = x_code `appOL` y_code `snocOL`
                  CMP (cmmTypeSize (cmmExprType x)) y_op (OpReg x_reg)
    -- in
    return (CondCode False cond code)

-- anything vs anything
condIntCode cond x y = do
  (y_reg, y_code) <- getNonClobberedReg y
  (x_op, x_code) <- getRegOrMem x
  let
	code = y_code `appOL`
	       x_code `snocOL`
    	    	  CMP (cmmTypeSize (cmmExprType x)) (OpReg y_reg) x_op
  -- in
  return (CondCode False cond code)



--------------------------------------------------------------------------------
condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode

#if i386_TARGET_ARCH
condFltCode cond x y 
  = ASSERT(cond `elem` ([EQQ, NE, LE, LTT, GE, GTT])) do
  (x_reg, x_code) <- getNonClobberedReg x
  (y_reg, y_code) <- getSomeReg y
  let
	code = x_code `appOL` y_code `snocOL`
		GCMP cond x_reg y_reg
  -- The GCMP insn does the test and sets the zero flag if comparable
  -- and true.  Hence we always supply EQQ as the condition to test.
  return (CondCode True EQQ code)

#elif x86_64_TARGET_ARCH
-- in the SSE2 comparison ops (ucomiss, ucomisd) the left arg may be
-- an operand, but the right must be a reg.  We can probably do better
-- than this general case...
condFltCode cond x y = do
  (x_reg, x_code) <- getNonClobberedReg x
  (y_op, y_code) <- getOperand y
  let
	code = x_code `appOL`
	       y_code `snocOL`
    	    	  CMP (floatSize $ cmmExprWidth x) y_op (OpReg x_reg)
	-- NB(1): we need to use the unsigned comparison operators on the
	-- result of this comparison.
  -- in
  return (CondCode True (condToUnsigned cond) code)

#else
condFltCode 	= panic "X86.condFltCode: not defined"

#endif



-- -----------------------------------------------------------------------------
-- Generating assignments

-- Assignments are really at the heart of the whole code generation
-- business.  Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers.  If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side.  This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).

assignMem_IntCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_IntCode :: Size -> CmmReg  -> CmmExpr -> NatM InstrBlock

assignMem_FltCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_FltCode :: Size -> CmmReg  -> CmmExpr -> NatM InstrBlock


-- integer assignment to memory

-- specific case of adding/subtracting an integer to a particular address.
-- ToDo: catch other cases where we can use an operation directly on a memory 
-- address.
assignMem_IntCode pk addr (CmmMachOp op [CmmLoad addr2 _,
                                                 CmmLit (CmmInt i _)])
   | addr == addr2, pk /= II64 || is32BitInteger i,
     Just instr <- check op
   = do Amode amode code_addr <- getAmode addr
        let code = code_addr `snocOL`
                   instr pk (OpImm (ImmInt (fromIntegral i))) (OpAddr amode)
        return code
   where
        check (MO_Add _) = Just ADD
        check (MO_Sub _) = Just SUB
        check _ = Nothing
        -- ToDo: more?

-- general case
assignMem_IntCode pk addr src = do
    Amode addr code_addr <- getAmode addr
    (code_src, op_src)   <- get_op_RI src
    let
	code = code_src `appOL`
	       code_addr `snocOL`
                  MOV pk op_src (OpAddr addr)
	-- NOTE: op_src is stable, so it will still be valid
	-- after code_addr.  This may involve the introduction 
	-- of an extra MOV to a temporary register, but we hope
	-- the register allocator will get rid of it.
    --
    return code
  where
    get_op_RI :: CmmExpr -> NatM (InstrBlock,Operand)	-- code, operator
    get_op_RI (CmmLit lit) | is32BitLit lit
      = return (nilOL, OpImm (litToImm lit))
    get_op_RI op
      = do (reg,code) <- getNonClobberedReg op
	   return (code, OpReg reg)


-- Assign; dst is a reg, rhs is mem
assignReg_IntCode pk reg (CmmLoad src _) = do
  load_code <- intLoadCode (MOV pk) src
  return (load_code (getRegisterReg reg))

-- dst is a reg, but src could be anything
assignReg_IntCode pk reg src = do
  code <- getAnyReg src
  return (code (getRegisterReg reg))


-- Floating point assignment to memory
assignMem_FltCode pk addr src = do
  (src_reg, src_code) <- getNonClobberedReg src
  Amode addr addr_code <- getAmode addr
  let
	code = src_code `appOL`
	       addr_code `snocOL`
                IF_ARCH_i386(GST pk src_reg addr,
		             MOV pk (OpReg src_reg) (OpAddr addr))
  return code

-- Floating point assignment to a register/temporary
assignReg_FltCode pk reg src = do
  src_code <- getAnyReg src
  return (src_code (getRegisterReg reg))


genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock

genJump (CmmLoad mem pk) = do
  Amode target code <- getAmode mem
  return (code `snocOL` JMP (OpAddr target))

genJump (CmmLit lit) = do
  return (unitOL (JMP (OpImm (litToImm lit))))

genJump expr = do
  (reg,code) <- getSomeReg expr
  return (code `snocOL` JMP (OpReg reg))


-- -----------------------------------------------------------------------------
--  Unconditional branches

genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr



-- -----------------------------------------------------------------------------
--  Conditional jumps

{-
Conditional jumps are always to local labels, so we can use branch
instructions.  We peek at the arguments to decide what kind of
comparison to do.

I386: First, we have to ensure that the condition
codes are set according to the supplied comparison operation.
-}

genCondJump
    :: BlockId	    -- the branch target
    -> CmmExpr      -- the condition on which to branch
    -> NatM InstrBlock

#if i386_TARGET_ARCH
genCondJump id bool = do
  CondCode _ cond code <- getCondCode bool
  return (code `snocOL` JXX cond id)

#elif x86_64_TARGET_ARCH
genCondJump id bool = do
  CondCode is_float cond cond_code <- getCondCode bool
  if not is_float
    then
	return (cond_code `snocOL` JXX cond id)
    else do
	lbl <- getBlockIdNat

	-- see comment with condFltReg
	let code = case cond of
	  		NE  -> or_unordered
			GU  -> plain_test
			GEU -> plain_test
			_   -> and_ordered

	    plain_test = unitOL (
		  JXX cond id
		)
	    or_unordered = toOL [
		  JXX cond id,
		  JXX PARITY id
		]
	    and_ordered = toOL [
		  JXX PARITY lbl,
		  JXX cond id,
		  JXX ALWAYS lbl,
		  NEWBLOCK lbl
		]
	return (cond_code `appOL` code)

#else
genCondJump	= panic "X86.genCondJump: not defined"

#endif




-- -----------------------------------------------------------------------------
--  Generating C calls

-- Now the biggest nightmare---calls.  Most of the nastiness is buried in
-- @get_arg@, which moves the arguments to the correct registers/stack
-- locations.  Apart from that, the code is easy.
-- 
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.

genCCall
    :: CmmCallTarget		-- function to call
    -> HintedCmmFormals		-- where to put the result
    -> HintedCmmActuals		-- arguments (of mixed type)
    -> NatM InstrBlock

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

#if i386_TARGET_ARCH

genCCall (CmmPrim MO_WriteBarrier) _ _ = return nilOL
	-- write barrier compiles to no code on x86/x86-64; 
	-- we keep it this long in order to prevent earlier optimisations.

-- we only cope with a single result for foreign calls
genCCall (CmmPrim op) [CmmHinted r _] args = do
  l1 <- getNewLabelNat
  l2 <- getNewLabelNat
  case op of
	MO_F32_Sqrt -> actuallyInlineFloatOp GSQRT FF32 args
	MO_F64_Sqrt -> actuallyInlineFloatOp GSQRT FF64 args
	
	MO_F32_Sin  -> actuallyInlineFloatOp (\s -> GSIN s l1 l2) FF32 args
	MO_F64_Sin  -> actuallyInlineFloatOp (\s -> GSIN s l1 l2) FF64 args

	MO_F32_Cos  -> actuallyInlineFloatOp (\s -> GCOS s l1 l2) FF32 args
	MO_F64_Cos  -> actuallyInlineFloatOp (\s -> GCOS s l1 l2) FF64 args

	MO_F32_Tan  -> actuallyInlineFloatOp (\s -> GTAN s l1 l2) FF32 args
	MO_F64_Tan  -> actuallyInlineFloatOp (\s -> GTAN s l1 l2) FF64 args
	
	other_op    -> outOfLineFloatOp op r args
 where
  actuallyInlineFloatOp instr size [CmmHinted x _]
	= do res <- trivialUFCode size (instr size) x
	     any <- anyReg res
 	     return (any (getRegisterReg (CmmLocal r)))

genCCall target dest_regs args = do
    let
        sizes               = map (arg_size . cmmExprType . hintlessCmm) (reverse args)
#if !darwin_TARGET_OS        
        tot_arg_size        = sum sizes
#else
        raw_arg_size        = sum sizes
        tot_arg_size        = roundTo 16 raw_arg_size
        arg_pad_size        = tot_arg_size - raw_arg_size
    delta0 <- getDeltaNat
    setDeltaNat (delta0 - arg_pad_size)
#endif

    push_codes <- mapM push_arg (reverse args)
    delta <- getDeltaNat

    -- in
    -- deal with static vs dynamic call targets
    (callinsns,cconv) <-
      case target of
	-- CmmPrim -> ...
        CmmCallee (CmmLit (CmmLabel lbl)) conv
           -> -- ToDo: stdcall arg sizes
	      return (unitOL (CALL (Left fn_imm) []), conv)
	   where fn_imm = ImmCLbl lbl
        CmmCallee expr conv
           -> do { (dyn_c, dyn_r) <- get_op expr
                 ; ASSERT( isWord32 (cmmExprType expr) )
                   return (dyn_c `snocOL` CALL (Right dyn_r) [], conv) }

    let	push_code
#if darwin_TARGET_OS
            | arg_pad_size /= 0
            = toOL [SUB II32 (OpImm (ImmInt arg_pad_size)) (OpReg esp),
                    DELTA (delta0 - arg_pad_size)]
              `appOL` concatOL push_codes
            | otherwise
#endif
            = concatOL push_codes
	call = callinsns `appOL`
               toOL (
			-- Deallocate parameters after call for ccall;
			-- but not for stdcall (callee does it)
                  (if cconv == StdCallConv || tot_arg_size==0 then [] else 
		   [ADD II32 (OpImm (ImmInt tot_arg_size)) (OpReg esp)])
                  ++
                  [DELTA (delta + tot_arg_size)]
               )
    -- in
    setDeltaNat (delta + tot_arg_size)

    let
	-- assign the results, if necessary
	assign_code []     = nilOL
	assign_code [CmmHinted dest _hint]
	  | isFloatType ty = unitOL (GMOV fake0 r_dest)
	  | isWord64 ty    = toOL [MOV II32 (OpReg eax) (OpReg r_dest),
				    MOV II32 (OpReg edx) (OpReg r_dest_hi)]
	  | otherwise      = unitOL (MOV (intSize w) (OpReg eax) (OpReg r_dest))
	  where 
		ty = localRegType dest
		w  = typeWidth ty
		r_dest_hi = getHiVRegFromLo r_dest
		r_dest    = getRegisterReg (CmmLocal dest)
	assign_code many = panic "genCCall.assign_code many"

    return (push_code `appOL` 
	    call `appOL` 
	    assign_code dest_regs)

  where
    arg_size :: CmmType -> Int	-- Width in bytes
    arg_size ty = widthInBytes (typeWidth ty)

    roundTo a x | x `mod` a == 0 = x
                | otherwise = x + a - (x `mod` a)


    push_arg :: HintedCmmActual {-current argument-}
                    -> NatM InstrBlock  -- code

    push_arg (CmmHinted arg _hint) -- we don't need the hints on x86
      | isWord64 arg_ty = do
        ChildCode64 code r_lo <- iselExpr64 arg
        delta <- getDeltaNat
        setDeltaNat (delta - 8)
        let 
            r_hi = getHiVRegFromLo r_lo
        -- in
	return (       code `appOL`
                       toOL [PUSH II32 (OpReg r_hi), DELTA (delta - 4),
                             PUSH II32 (OpReg r_lo), DELTA (delta - 8),
			     DELTA (delta-8)]
            )

      | otherwise = do
        (code, reg) <- get_op arg
        delta <- getDeltaNat
        let size = arg_size arg_ty	-- Byte size
        setDeltaNat (delta-size)
        if (isFloatType arg_ty)
           then return (code `appOL`
                        toOL [SUB II32 (OpImm (ImmInt size)) (OpReg esp),
                              DELTA (delta-size),
                              GST (floatSize (typeWidth arg_ty))
				  reg (AddrBaseIndex (EABaseReg esp) 
                                                        EAIndexNone
                                                        (ImmInt 0))]
                       )
           else return (code `snocOL`
                        PUSH II32 (OpReg reg) `snocOL`
                        DELTA (delta-size)
                       )
      where
         arg_ty = cmmExprType arg

    ------------
    get_op :: CmmExpr -> NatM (InstrBlock, Reg) -- code, reg
    get_op op = do
        (reg,code) <- getSomeReg op
	return (code, reg)

#elif x86_64_TARGET_ARCH

genCCall (CmmPrim MO_WriteBarrier) _ _ = return nilOL
	-- write barrier compiles to no code on x86/x86-64; 
	-- we keep it this long in order to prevent earlier optimisations.


genCCall (CmmPrim op) [CmmHinted r _] args = 
  outOfLineFloatOp op r args

genCCall target dest_regs args = do

	-- load up the register arguments
    (stack_args, aregs, fregs, load_args_code)
	 <- load_args args allArgRegs allFPArgRegs nilOL

    let
	fp_regs_used  = reverse (drop (length fregs) (reverse allFPArgRegs))
	int_regs_used = reverse (drop (length aregs) (reverse allArgRegs))
	arg_regs = [eax] ++ int_regs_used ++ fp_regs_used
		-- for annotating the call instruction with

	sse_regs = length fp_regs_used

	tot_arg_size = arg_size * length stack_args

	-- On entry to the called function, %rsp should be aligned
	-- on a 16-byte boundary +8 (i.e. the first stack arg after
	-- the return address is 16-byte aligned).  In STG land
	-- %rsp is kept 16-byte aligned (see StgCRun.c), so we just
	-- need to make sure we push a multiple of 16-bytes of args,
	-- plus the return address, to get the correct alignment.
	-- Urg, this is hard.  We need to feed the delta back into
	-- the arg pushing code.
    (real_size, adjust_rsp) <-
	if tot_arg_size `rem` 16 == 0
	    then return (tot_arg_size, nilOL)
	    else do -- we need to adjust...
		delta <- getDeltaNat
		setDeltaNat (delta-8)
		return (tot_arg_size+8, toOL [
				SUB II64 (OpImm (ImmInt 8)) (OpReg rsp),
				DELTA (delta-8)
			])

	-- push the stack args, right to left
    push_code <- push_args (reverse stack_args) nilOL
    delta <- getDeltaNat

    -- deal with static vs dynamic call targets
    (callinsns,cconv) <-
      case target of
	-- CmmPrim -> ...
        CmmCallee (CmmLit (CmmLabel lbl)) conv
           -> -- ToDo: stdcall arg sizes
	      return (unitOL (CALL (Left fn_imm) arg_regs), conv)
	   where fn_imm = ImmCLbl lbl
        CmmCallee expr conv
           -> do (dyn_r, dyn_c) <- getSomeReg expr
		 return (dyn_c `snocOL` CALL (Right dyn_r) arg_regs, conv)

    let
	-- The x86_64 ABI requires us to set %al to the number of SSE
	-- registers that contain arguments, if the called routine
	-- is a varargs function.  We don't know whether it's a
	-- varargs function or not, so we have to assume it is.
	--
	-- It's not safe to omit this assignment, even if the number
	-- of SSE regs in use is zero.  If %al is larger than 8
	-- on entry to a varargs function, seg faults ensue.
	assign_eax n = unitOL (MOV II32 (OpImm (ImmInt n)) (OpReg eax))

    let call = callinsns `appOL`
               toOL (
			-- Deallocate parameters after call for ccall;
			-- but not for stdcall (callee does it)
                  (if cconv == StdCallConv || real_size==0 then [] else 
		   [ADD (intSize wordWidth) (OpImm (ImmInt real_size)) (OpReg esp)])
                  ++
                  [DELTA (delta + real_size)]
               )
    -- in
    setDeltaNat (delta + real_size)

    let
	-- assign the results, if necessary
	assign_code []     = nilOL
	assign_code [CmmHinted dest _hint] = 
	  case typeWidth rep of
		W32 | isFloatType rep -> unitOL (MOV (floatSize W32) (OpReg xmm0) (OpReg r_dest))
1782
		W64 | isFloatType rep -> unitOL (MOV (floatSize W64) (OpReg xmm0) (OpReg r_dest))
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
		_ -> unitOL (MOV (cmmTypeSize rep) (OpReg rax) (OpReg r_dest))
	  where 
		rep = localRegType dest
		r_dest = getRegisterReg (CmmLocal dest)
	assign_code many = panic "genCCall.assign_code many"

    return (load_args_code 	`appOL` 
	    adjust_rsp 		`appOL`
	    push_code 		`appOL`
	    assign_eax sse_regs `appOL`
	    call 		`appOL` 
	    assign_code dest_regs)

  where
    arg_size = 8 -- always, at the mo

    load_args :: [CmmHinted CmmExpr]
	      -> [Reg] 			-- int regs avail for args
	      -> [Reg] 			-- FP regs avail for args
	      -> InstrBlock
	      -> NatM ([CmmHinted CmmExpr],[Reg],[Reg],InstrBlock)
    load_args args [] [] code     =  return (args, [], [], code)
	-- no more regs to use
    load_args [] aregs fregs code =  return ([], aregs, fregs, code)
	-- no more args to push
    load_args ((CmmHinted arg hint) : rest) aregs fregs code
	| isFloatType arg_rep = 
	case fregs of
	  [] -> push_this_arg
	  (r:rs) -> do
	     arg_code <- getAnyReg arg
	     load_args rest aregs rs (code `appOL` arg_code r)
	| otherwise =
	case aregs of
	  [] -> push_this_arg
	  (r:rs) -> do
	     arg_code <- getAnyReg arg
	     load_args rest rs fregs (code `appOL` arg_code r)
	where
	  arg_rep = cmmExprType arg

	  push_this_arg = do
	    (args',ars,frs,code') <- load_args rest aregs fregs code
	    return ((CmmHinted arg hint):args', ars, frs, code')

    push_args [] code = return code
    push_args ((CmmHinted arg hint):rest) code
       | isFloatType arg_rep = do
	 (arg_reg, arg_code) <- getSomeReg arg
         delta <- getDeltaNat
         setDeltaNat (delta-arg_size)
	 let code' = code `appOL` arg_code `appOL` toOL [
			SUB (intSize wordWidth) (OpImm (ImmInt arg_size)) (OpReg rsp) ,
	 		DELTA (delta-arg_size),
			MOV (floatSize width) (OpReg arg_reg) (OpAddr  (spRel 0))]
	 push_args rest code'

       | otherwise = do
       -- we only ever generate word-sized function arguments.  Promotion
       -- has already happened: our Int8# type is kept sign-extended
       -- in an Int#, for example.
	 ASSERT(width == W64) return ()
	 (arg_op, arg_code) <- getOperand arg
         delta <- getDeltaNat
         setDeltaNat (delta-arg_size)
	 let code' = code `appOL` arg_code `appOL` toOL [
	 			PUSH II64 arg_op, 
	 		        DELTA (delta-arg_size)]
	 push_args rest code'
	where
	  arg_rep = cmmExprType arg
	  width = typeWidth arg_rep

#else
genCCall	= panic "X86.genCCAll: not defined"

#endif /* x86_64_TARGET_ARCH */




outOfLineFloatOp :: CallishMachOp -> CmmFormal -> HintedCmmActuals -> NatM InstrBlock
outOfLineFloatOp mop res args
  = do
      dflags <- getDynFlagsNat
      targetExpr <- cmmMakeDynamicReference dflags addImportNat CallReference lbl
      let target = CmmCallee targetExpr CCallConv
        
      if isFloat64 (localRegType res)
        then
          stmtToInstrs (CmmCall target [CmmHinted res NoHint] args CmmUnsafe CmmMayReturn)
        else do
          uq <- getUniqueNat
          let 
            tmp = LocalReg uq f64
          -- in
          code1 <- stmtToInstrs (CmmCall target [CmmHinted tmp NoHint] args CmmUnsafe CmmMayReturn)
          code2 <- stmtToInstrs (CmmAssign (CmmLocal res) (CmmReg (CmmLocal tmp)))
          return (code1 `appOL` code2)
  where
	lbl = mkForeignLabel fn Nothing False IsFunction

	fn = case mop of
	      MO_F32_Sqrt  -> fsLit "sqrtf"
	      MO_F32_Sin   -> fsLit "sinf"
	      MO_F32_Cos   -> fsLit "cosf"
	      MO_F32_Tan   -> fsLit "tanf"
	      MO_F32_Exp   -> fsLit "expf"
	      MO_F32_Log   -> fsLit "logf"

	      MO_F32_Asin  -> fsLit "asinf"
	      MO_F32_Acos  -> fsLit "acosf"
	      MO_F32_Atan  -> fsLit "atanf"

	      MO_F32_Sinh  -> fsLit "sinhf"
	      MO_F32_Cosh  -> fsLit "coshf"
	      MO_F32_Tanh  -> fsLit "tanhf"
	      MO_F32_Pwr   -> fsLit "powf"

	      MO_F64_Sqrt  -> fsLit "sqrt"
	      MO_F64_Sin   -> fsLit "sin"
	      MO_F64_Cos   -> fsLit "cos"
	      MO_F64_Tan   -> fsLit "tan"
	      MO_F64_Exp   -> fsLit "exp"
	      MO_F64_Log   -> fsLit "log"

	      MO_F64_Asin  -> fsLit "asin"
	      MO_F64_Acos  -> fsLit "acos"
	      MO_F64_Atan  -> fsLit "atan"

	      MO_F64_Sinh  -> fsLit "sinh"
	      MO_F64_Cosh  -> fsLit "cosh"
	      MO_F64_Tanh  -> fsLit "tanh"
	      MO_F64_Pwr   -> fsLit "pow"





-- -----------------------------------------------------------------------------
-- Generating a table-branch

genSwitch :: CmmExpr -> [Maybe BlockId] -> NatM InstrBlock

genSwitch expr ids
  | opt_PIC
  = do
        (reg,e_code) <- getSomeReg expr
        lbl <- getNewLabelNat
        dflags <- getDynFlagsNat
        dynRef <- cmmMakeDynamicReference dflags addImportNat DataReference lbl
        (tableReg,t_code) <- getSomeReg $ dynRef
        let
            jumpTable = map jumpTableEntryRel ids
            
            jumpTableEntryRel Nothing
                = CmmStaticLit (CmmInt 0 wordWidth)
            jumpTableEntryRel (Just (BlockId id))
                = CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
                where blockLabel = mkAsmTempLabel id

            op = OpAddr (AddrBaseIndex (EABaseReg tableReg)
                                       (EAIndex reg wORD_SIZE) (ImmInt 0))

#if x86_64_TARGET_ARCH
#if darwin_TARGET_OS
    -- on Mac OS X/x86_64, put the jump table in the text section
    -- to work around a limitation of the linker.
    -- ld64 is unable to handle the relocations for
    --     .quad L1 - L0
    -- if L0 is not preceded by a non-anonymous label in its section.
    
            code = e_code `appOL` t_code `appOL` toOL [
                            ADD (intSize wordWidth) op (OpReg tableReg),
                            JMP_TBL (OpReg tableReg) [ id | Just id <- ids ],
                            LDATA Text (CmmDataLabel lbl : jumpTable)
                    ]
#else
    -- HACK: On x86_64 binutils<2.17 is only able to generate PC32
    -- relocations, hence we only get 32-bit offsets in the jump
    -- table. As these offsets are always negative we need to properly
    -- sign extend them to 64-bit. This hack should be removed in
    -- conjunction with the hack in PprMach.hs/pprDataItem once
    -- binutils 2.17 is standard.
            code = e_code `appOL` t_code `appOL` toOL [
			    LDATA ReadOnlyData (CmmDataLabel lbl : jumpTable),
			    MOVSxL II32
				   (OpAddr (AddrBaseIndex (EABaseReg tableReg)
							  (EAIndex reg wORD_SIZE) (ImmInt 0)))
				   (OpReg reg),
			    ADD (intSize wordWidth) (OpReg reg) (OpReg tableReg),
			    JMP_TBL (OpReg tableReg) [ id | Just id <- ids ]
		   ]
#endif
#else
            code = e_code `appOL` t_code `appOL` toOL [
                            LDATA ReadOnlyData (CmmDataLabel lbl : jumpTable),
                            ADD (intSize wordWidth) op (OpReg tableReg),
                            JMP_TBL (OpReg tableReg) [ id | Just id <- ids ]
                    ]
#endif
        return code
  | otherwise
  = do
        (reg,e_code) <- getSomeReg expr
        lbl <- getNewLabelNat
        let
            jumpTable = map jumpTableEntry ids
            op = OpAddr (AddrBaseIndex EABaseNone (EAIndex reg wORD_SIZE) (ImmCLbl lbl))
            code = e_code `appOL` toOL [
                    LDATA ReadOnlyData (CmmDataLabel lbl : jumpTable),
                    JMP_TBL op [ id | Just id <- ids ]
                 ]
        -- in
        return code


-- -----------------------------------------------------------------------------
-- 'condIntReg' and 'condFltReg': condition codes into registers

-- Turn those condition codes into integers now (when they appear on
-- the right hand side of an assignment).
-- 
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.

condIntReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register

condIntReg cond x y = do
  CondCode _ cond cond_code <- condIntCode cond x y
  tmp <- getNewRegNat II8
  let 
	code dst = cond_code `appOL` toOL [
		    SETCC cond (OpReg tmp),
		    MOVZxL II8 (OpReg tmp) (OpReg dst)
		  ]
  -- in
  return (Any II32 code)



condFltReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register

#if i386_TARGET_ARCH
condFltReg cond x y = do
  CondCode _ cond cond_code <- condFltCode cond x y
  tmp <- getNewRegNat II8
  let 
	code dst = cond_code `appOL` toOL [
		    SETCC cond (OpReg tmp),
		    MOVZxL II8 (OpReg tmp) (OpReg dst)
		  ]
  -- in
  return (Any II32 code)

#elif x86_64_TARGET_ARCH
condFltReg cond x y = do
  CondCode _ cond cond_code <- condFltCode cond x y
2041 2042
  tmp1 <- getNewRegNat archWordSize
  tmp2 <- getNewRegNat archWordSize
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
  let 
	-- We have to worry about unordered operands (eg. comparisons
	-- against NaN).  If the operands are unordered, the comparison
	-- sets the parity flag, carry flag and zero flag.
	-- All comparisons are supposed to return false for unordered
	-- operands except for !=, which returns true.
	--
	-- Optimisation: we don't have to test the parity flag if we
	-- know the test has already excluded the unordered case: eg >
	-- and >= test for a zero carry flag, which can only occur for
	-- ordered operands.
	--
	-- ToDo: by reversing comparisons we could avoid testing the
	-- parity flag in more cases.

	code dst = 
	   cond_code `appOL` 
	     (case cond of
	  	NE  -> or_unordered dst
		GU  -> plain_test   dst
		GEU -> plain_test   dst
		_   -> and_ordered  dst)

	plain_test dst = toOL [
		    SETCC cond (OpReg tmp1),
		    MOVZxL II8 (OpReg tmp1) (OpReg dst)
		 ]
	or_unordered dst = toOL [
		    SETCC cond (OpReg tmp1),
		    SETCC PARITY (OpReg tmp2),
		    OR II8 (OpReg tmp1) (OpReg tmp2),
		    MOVZxL II8 (OpReg tmp2) (OpReg dst)
		  ]
	and_ordered dst = toOL [
		    SETCC cond (OpReg tmp1),
		    SETCC NOTPARITY (OpReg tmp2),
		    AND II8 (OpReg tmp1) (OpReg tmp2),
		    MOVZxL II8 (OpReg tmp2) (OpReg dst)
		  ]
  -- in
  return (Any II32 code)

#else
condFltReg	= panic "X86.condFltReg: not defined"

#endif




-- -----------------------------------------------------------------------------
-- 'trivial*Code': deal with trivial instructions

-- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
-- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
-- Only look for constants on the right hand side, because that's
-- where the generic optimizer will have put them.

-- Similarly, for unary instructions, we don't have to worry about
-- matching an StInt as the argument, because genericOpt will already
-- have handled the constant-folding.


{-
The Rules of the Game are:

* You cannot assume anything about the destination register dst;
  it may be anything, including a fixed reg.

* You may compute an operand into a fixed reg, but you may not 
  subsequently change the contents of that fixed reg.  If you
  want to do so, first copy the value either to a temporary
  or into dst.  You are free to modify dst even if it happens
  to be a fixed reg -- that's not your problem.

* You cannot assume that a fixed reg will stay live over an
  arbitrary computation.  The same applies to the dst reg.

* Temporary regs obtained from getNewRegNat are distinct from 
  each other and from all other regs, and stay live over 
  arbitrary computations.

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

SDM's version of The Rules:

* If getRegister returns Any, that means it can generate correct
  code which places the result in any register, period.  Even if that
  register happens to be read during the computation.

  Corollary #1: this means that if you are generating code for an
  operation with two arbitrary operands, you cannot assign the result
  of the first operand into the destination register before computing
  the second operand.  The second operand might require the old value
  of the destination register.

  Corollary #2: A function might be able to generate more efficient
  code if it knows the destination register is a new temporary (and
  therefore not read by any of the sub-computations).

* If getRegister returns Any, then the code it generates may modify only:
	(a) fresh temporaries
	(b) the destination register
	(c) known registers (eg. %ecx is used by shifts)
  In particular, it may *not* modify global registers, unless the global
  register happens to be the destination register.
-}

trivialCode width instr (Just revinstr) (CmmLit lit_a) b
  | is32BitLit lit_a = do
  b_code <- getAnyReg b
  let
       code dst 
	 = b_code dst `snocOL`
           revinstr (OpImm (litToImm lit_a)) (OpReg dst)
  -- in
  return (Any (intSize width) code)

trivialCode width instr maybe_revinstr a b
  = genTrivialCode (intSize width) instr a b

-- This is re-used for floating pt instructions too.
genTrivialCode rep instr a b = do
  (b_op, b_code) <- getNonClobberedOperand b
  a_code <- getAnyReg a
  tmp <- getNewRegNat rep
  let
     -- We want the value of b to stay alive across the computation of a.
     -- But, we want to calculate a straight into the destination register,
     -- because the instruction only has two operands (dst := dst `op` src).
     -- The troublesome case is when the result of b is in the same register
     -- as the destination reg.  In this case, we have to save b in a
     -- new temporary across the computation of a.
     code dst
	| dst `regClashesWithOp` b_op =
		b_code `appOL`
		unitOL (MOV rep b_op (OpReg tmp)) `appOL`
		a_code dst `snocOL`
		instr (OpReg tmp) (OpReg dst)
	| otherwise =
		b_code `appOL`
		a_code dst `snocOL`
		instr b_op (OpReg dst)
  -- in
  return (Any rep code)

reg `regClashesWithOp` OpReg reg2   = reg == reg2
reg `regClashesWithOp` OpAddr amode = any (==reg) (addrModeRegs amode)
reg `regClashesWithOp` _            = False

-----------

trivialUCode rep instr x = do
  x_code <- getAnyReg x
  let
     code dst =
	x_code dst `snocOL`
	instr (OpReg dst)
  return (Any rep code)

-----------

#if i386_TARGET_ARCH

trivialFCode width instr x y = do
  (x_reg, x_code) <- getNonClobberedReg x -- these work for float regs too
  (y_reg, y_code) <- getSomeReg y
  let
     size = floatSize width
     code dst =
	x_code `appOL`
	y_code `snocOL`
	instr size x_reg y_reg dst
  return (Any size code)

#endif

#if x86_64_TARGET_ARCH
trivialFCode pk instr x y 
  = genTrivialCode size (instr size) x y
  where size = floatSize pk
#endif

trivialUFCode size instr x = do
  (x_reg, x_code) <- getSomeReg x
  let
     code dst =
	x_code `snocOL`
	instr x_reg dst
  -- in
  return (Any size code)


--------------------------------------------------------------------------------
coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register

#if i386_TARGET_ARCH
coerceInt2FP from to x = do
  (x_reg, x_code) <- getSomeReg x
  let
        opc  = case to of W32 -> GITOF; W64 -> GITOD
        code dst = x_code `snocOL` opc x_reg dst
	-- ToDo: works for non-II32 reps?
  return (Any (floatSize to) code)

#elif x86_64_TARGET_ARCH
coerceInt2FP from to x = do
  (x_op, x_code) <- getOperand x  -- ToDo: could be a safe operand
  let
        opc  = case to of W32 -> CVTSI2SS; W64 -> CVTSI2SD
        code dst = x_code `snocOL` opc x_op dst
  -- in
  return (Any (floatSize to) code) -- works even if the destination rep is <II32

#else
coerceInt2FP	= panic "X86.coerceInt2FP: not defined"

#endif




--------------------------------------------------------------------------------
coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register

#if i386_TARGET_ARCH
coerceFP2Int from to x = do
  (x_reg, x_code) <- getSomeReg x
  let
        opc  = case from of W32 -> GFTOI; W64 -> GDTOI
        code dst = x_code `snocOL` opc x_reg dst
	-- ToDo: works for non-II32 reps?
  -- in
  return (Any (intSize to) code)

#elif x86_64_TARGET_ARCH
coerceFP2Int from to x = do
  (x_op, x_code) <- getOperand x  -- ToDo: could be a safe operand
  let
        opc  = case from of W32 -> CVTTSS2SIQ; W64 -> CVTTSD2SIQ
        code dst = x_code `snocOL` opc x_op dst
  -- in
  return (Any (intSize to) code) -- works even if the destination rep is <II32

#else
coerceFP2Int	= panic "X86.coerceFP2Int: not defined"

#endif




--------------------------------------------------------------------------------
coerceFP2FP :: Width -> CmmExpr -> NatM Register

#if x86_64_TARGET_ARCH
coerceFP2FP to x = do
  (x_reg, x_code) <- getSomeReg x
  let
        opc  = case to of W32 -> CVTSD2SS; W64 -> CVTSS2SD
        code dst = x_code `snocOL` opc x_reg dst
  -- in
  return (Any (floatSize to) code)

#else
coerceFP2FP	= panic "X86.coerceFP2FP: not defined"

#endif