PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/nativeGen/AsmCodeGen.lhs

https://github.com/crdueck/ghc
Haskell | 1029 lines | 657 code | 149 blank | 223 comment | 37 complexity | 7bb73c72487ed1385a5769cd743f7b79 MD5 | raw file
  1. -- -----------------------------------------------------------------------------
  2. --
  3. -- (c) The University of Glasgow 1993-2004
  4. --
  5. -- This is the top-level module in the native code generator.
  6. --
  7. -- -----------------------------------------------------------------------------
  8. \begin{code}
  9. {-# LANGUAGE GADTs #-}
  10. module AsmCodeGen ( nativeCodeGen ) where
  11. #include "HsVersions.h"
  12. #include "nativeGen/NCG.h"
  13. import qualified X86.CodeGen
  14. import qualified X86.Regs
  15. import qualified X86.Instr
  16. import qualified X86.Ppr
  17. import qualified SPARC.CodeGen
  18. import qualified SPARC.Regs
  19. import qualified SPARC.Instr
  20. import qualified SPARC.Ppr
  21. import qualified SPARC.ShortcutJump
  22. import qualified SPARC.CodeGen.Expand
  23. import qualified PPC.CodeGen
  24. import qualified PPC.Regs
  25. import qualified PPC.RegInfo
  26. import qualified PPC.Instr
  27. import qualified PPC.Ppr
  28. import RegAlloc.Liveness
  29. import qualified RegAlloc.Linear.Main as Linear
  30. import qualified GraphColor as Color
  31. import qualified RegAlloc.Graph.Main as Color
  32. import qualified RegAlloc.Graph.Stats as Color
  33. import qualified RegAlloc.Graph.TrivColorable as Color
  34. import TargetReg
  35. import Platform
  36. import Config
  37. import Instruction
  38. import PIC
  39. import Reg
  40. import NCGMonad
  41. import BlockId
  42. import CgUtils ( fixStgRegisters )
  43. import Cmm
  44. import CmmUtils
  45. import Hoopl
  46. import CmmOpt ( cmmMachOpFold )
  47. import PprCmm
  48. import CLabel
  49. import UniqFM
  50. import UniqSupply
  51. import DynFlags
  52. import Util
  53. import BasicTypes ( Alignment )
  54. import Digraph
  55. import qualified Pretty
  56. import BufWrite
  57. import Outputable
  58. import FastString
  59. import UniqSet
  60. import ErrUtils
  61. import Module
  62. import Stream (Stream)
  63. import qualified Stream
  64. -- DEBUGGING ONLY
  65. --import OrdList
  66. import Data.List
  67. import Data.Maybe
  68. import Control.Exception
  69. import Control.Monad
  70. import System.IO
  71. {-
  72. The native-code generator has machine-independent and
  73. machine-dependent modules.
  74. This module ("AsmCodeGen") is the top-level machine-independent
  75. module. Before entering machine-dependent land, we do some
  76. machine-independent optimisations (defined below) on the
  77. 'CmmStmts's.
  78. We convert to the machine-specific 'Instr' datatype with
  79. 'cmmCodeGen', assuming an infinite supply of registers. We then use
  80. a machine-independent register allocator ('regAlloc') to rejoin
  81. reality. Obviously, 'regAlloc' has machine-specific helper
  82. functions (see about "RegAllocInfo" below).
  83. Finally, we order the basic blocks of the function so as to minimise
  84. the number of jumps between blocks, by utilising fallthrough wherever
  85. possible.
  86. The machine-dependent bits break down as follows:
  87. * ["MachRegs"] Everything about the target platform's machine
  88. registers (and immediate operands, and addresses, which tend to
  89. intermingle/interact with registers).
  90. * ["MachInstrs"] Includes the 'Instr' datatype (possibly should
  91. have a module of its own), plus a miscellany of other things
  92. (e.g., 'targetDoubleSize', 'smStablePtrTable', ...)
  93. * ["MachCodeGen"] is where 'Cmm' stuff turns into
  94. machine instructions.
  95. * ["PprMach"] 'pprInstr' turns an 'Instr' into text (well, really
  96. a 'SDoc').
  97. * ["RegAllocInfo"] In the register allocator, we manipulate
  98. 'MRegsState's, which are 'BitSet's, one bit per machine register.
  99. When we want to say something about a specific machine register
  100. (e.g., ``it gets clobbered by this instruction''), we set/unset
  101. its bit. Obviously, we do this 'BitSet' thing for efficiency
  102. reasons.
  103. The 'RegAllocInfo' module collects together the machine-specific
  104. info needed to do register allocation.
  105. * ["RegisterAlloc"] The (machine-independent) register allocator.
  106. -}
  107. -- -----------------------------------------------------------------------------
  108. -- Top-level of the native codegen
  109. data NcgImpl statics instr jumpDest = NcgImpl {
  110. cmmTopCodeGen :: RawCmmDecl -> NatM [NatCmmDecl statics instr],
  111. generateJumpTableForInstr :: instr -> Maybe (NatCmmDecl statics instr),
  112. getJumpDestBlockId :: jumpDest -> Maybe BlockId,
  113. canShortcut :: instr -> Maybe jumpDest,
  114. shortcutStatics :: (BlockId -> Maybe jumpDest) -> statics -> statics,
  115. shortcutJump :: (BlockId -> Maybe jumpDest) -> instr -> instr,
  116. pprNatCmmDecl :: NatCmmDecl statics instr -> SDoc,
  117. maxSpillSlots :: Int,
  118. allocatableRegs :: [RealReg],
  119. ncg_x86fp_kludge :: [NatCmmDecl statics instr] -> [NatCmmDecl statics instr],
  120. ncgExpandTop :: [NatCmmDecl statics instr] -> [NatCmmDecl statics instr],
  121. ncgAllocMoreStack :: Int -> NatCmmDecl statics instr -> UniqSM (NatCmmDecl statics instr),
  122. ncgMakeFarBranches :: BlockEnv CmmStatics -> [NatBasicBlock instr] -> [NatBasicBlock instr]
  123. }
  124. --------------------
  125. nativeCodeGen :: DynFlags -> Module -> Handle -> UniqSupply
  126. -> Stream IO RawCmmGroup ()
  127. -> IO UniqSupply
  128. nativeCodeGen dflags this_mod h us cmms
  129. = let platform = targetPlatform dflags
  130. nCG' :: (Outputable statics, Outputable instr, Instruction instr)
  131. => NcgImpl statics instr jumpDest -> IO UniqSupply
  132. nCG' ncgImpl = nativeCodeGen' dflags this_mod ncgImpl h us cmms
  133. in case platformArch platform of
  134. ArchX86 -> nCG' (x86NcgImpl dflags)
  135. ArchX86_64 -> nCG' (x86_64NcgImpl dflags)
  136. ArchPPC -> nCG' (ppcNcgImpl dflags)
  137. ArchSPARC -> nCG' (sparcNcgImpl dflags)
  138. ArchARM {} -> panic "nativeCodeGen: No NCG for ARM"
  139. ArchPPC_64 -> panic "nativeCodeGen: No NCG for PPC 64"
  140. ArchAlpha -> panic "nativeCodeGen: No NCG for Alpha"
  141. ArchMipseb -> panic "nativeCodeGen: No NCG for mipseb"
  142. ArchMipsel -> panic "nativeCodeGen: No NCG for mipsel"
  143. ArchUnknown -> panic "nativeCodeGen: No NCG for unknown arch"
  144. x86NcgImpl :: DynFlags -> NcgImpl (Alignment, CmmStatics) X86.Instr.Instr X86.Instr.JumpDest
  145. x86NcgImpl dflags
  146. = (x86_64NcgImpl dflags) { ncg_x86fp_kludge = map x86fp_kludge }
  147. x86_64NcgImpl :: DynFlags -> NcgImpl (Alignment, CmmStatics) X86.Instr.Instr X86.Instr.JumpDest
  148. x86_64NcgImpl dflags
  149. = NcgImpl {
  150. cmmTopCodeGen = X86.CodeGen.cmmTopCodeGen
  151. ,generateJumpTableForInstr = X86.CodeGen.generateJumpTableForInstr dflags
  152. ,getJumpDestBlockId = X86.Instr.getJumpDestBlockId
  153. ,canShortcut = X86.Instr.canShortcut
  154. ,shortcutStatics = X86.Instr.shortcutStatics
  155. ,shortcutJump = X86.Instr.shortcutJump
  156. ,pprNatCmmDecl = X86.Ppr.pprNatCmmDecl
  157. ,maxSpillSlots = X86.Instr.maxSpillSlots dflags
  158. ,allocatableRegs = X86.Regs.allocatableRegs platform
  159. ,ncg_x86fp_kludge = id
  160. ,ncgAllocMoreStack = X86.Instr.allocMoreStack platform
  161. ,ncgExpandTop = id
  162. ,ncgMakeFarBranches = const id
  163. }
  164. where platform = targetPlatform dflags
  165. ppcNcgImpl :: DynFlags -> NcgImpl CmmStatics PPC.Instr.Instr PPC.RegInfo.JumpDest
  166. ppcNcgImpl dflags
  167. = NcgImpl {
  168. cmmTopCodeGen = PPC.CodeGen.cmmTopCodeGen
  169. ,generateJumpTableForInstr = PPC.CodeGen.generateJumpTableForInstr dflags
  170. ,getJumpDestBlockId = PPC.RegInfo.getJumpDestBlockId
  171. ,canShortcut = PPC.RegInfo.canShortcut
  172. ,shortcutStatics = PPC.RegInfo.shortcutStatics
  173. ,shortcutJump = PPC.RegInfo.shortcutJump
  174. ,pprNatCmmDecl = PPC.Ppr.pprNatCmmDecl
  175. ,maxSpillSlots = PPC.Instr.maxSpillSlots dflags
  176. ,allocatableRegs = PPC.Regs.allocatableRegs platform
  177. ,ncg_x86fp_kludge = id
  178. ,ncgAllocMoreStack = PPC.Instr.allocMoreStack platform
  179. ,ncgExpandTop = id
  180. ,ncgMakeFarBranches = PPC.Instr.makeFarBranches
  181. }
  182. where platform = targetPlatform dflags
  183. sparcNcgImpl :: DynFlags -> NcgImpl CmmStatics SPARC.Instr.Instr SPARC.ShortcutJump.JumpDest
  184. sparcNcgImpl dflags
  185. = NcgImpl {
  186. cmmTopCodeGen = SPARC.CodeGen.cmmTopCodeGen
  187. ,generateJumpTableForInstr = SPARC.CodeGen.generateJumpTableForInstr dflags
  188. ,getJumpDestBlockId = SPARC.ShortcutJump.getJumpDestBlockId
  189. ,canShortcut = SPARC.ShortcutJump.canShortcut
  190. ,shortcutStatics = SPARC.ShortcutJump.shortcutStatics
  191. ,shortcutJump = SPARC.ShortcutJump.shortcutJump
  192. ,pprNatCmmDecl = SPARC.Ppr.pprNatCmmDecl
  193. ,maxSpillSlots = SPARC.Instr.maxSpillSlots dflags
  194. ,allocatableRegs = SPARC.Regs.allocatableRegs
  195. ,ncg_x86fp_kludge = id
  196. ,ncgAllocMoreStack = noAllocMoreStack
  197. ,ncgExpandTop = map SPARC.CodeGen.Expand.expandTop
  198. ,ncgMakeFarBranches = const id
  199. }
  200. --
  201. -- Allocating more stack space for spilling is currently only
  202. -- supported for the linear register allocator on x86/x86_64, the rest
  203. -- default to the panic below. To support allocating extra stack on
  204. -- more platforms provide a definition of ncgAllocMoreStack.
  205. --
  206. noAllocMoreStack :: Int -> NatCmmDecl statics instr -> UniqSM (NatCmmDecl statics instr)
  207. noAllocMoreStack amount _
  208. = panic $ "Register allocator: out of stack slots (need " ++ show amount ++ ")\n"
  209. ++ " If you are trying to compile SHA1.hs from the crypto library then this\n"
  210. ++ " is a known limitation in the linear allocator.\n"
  211. ++ "\n"
  212. ++ " Try enabling the graph colouring allocator with -fregs-graph instead."
  213. ++ " You can still file a bug report if you like.\n"
  214. type NativeGenAcc statics instr
  215. = ([[CLabel]],
  216. [([NatCmmDecl statics instr],
  217. Maybe [Color.RegAllocStats statics instr],
  218. Maybe [Linear.RegAllocStats])])
  219. nativeCodeGen' :: (Outputable statics, Outputable instr, Instruction instr)
  220. => DynFlags
  221. -> Module
  222. -> NcgImpl statics instr jumpDest
  223. -> Handle
  224. -> UniqSupply
  225. -> Stream IO RawCmmGroup ()
  226. -> IO UniqSupply
  227. nativeCodeGen' dflags this_mod ncgImpl h us cmms
  228. = do
  229. let split_cmms = Stream.map add_split cmms
  230. -- BufHandle is a performance hack. We could hide it inside
  231. -- Pretty if it weren't for the fact that we do lots of little
  232. -- printDocs here (in order to do codegen in constant space).
  233. bufh <- newBufHandle h
  234. (ngs, us') <- cmmNativeGenStream dflags this_mod ncgImpl bufh us split_cmms ([], [])
  235. finishNativeGen dflags ncgImpl bufh ngs
  236. return us'
  237. where add_split tops
  238. | gopt Opt_SplitObjs dflags = split_marker : tops
  239. | otherwise = tops
  240. split_marker = CmmProc mapEmpty mkSplitMarkerLabel []
  241. (ofBlockList (panic "split_marker_entry") [])
  242. finishNativeGen :: Instruction instr
  243. => DynFlags
  244. -> NcgImpl statics instr jumpDest
  245. -> BufHandle
  246. -> NativeGenAcc statics instr
  247. -> IO ()
  248. finishNativeGen dflags ncgImpl bufh@(BufHandle _ _ h) (imports, prof)
  249. = do
  250. bFlush bufh
  251. let platform = targetPlatform dflags
  252. let (native, colorStats, linearStats)
  253. = unzip3 prof
  254. -- dump native code
  255. dumpIfSet_dyn dflags
  256. Opt_D_dump_asm "Asm code"
  257. (vcat $ map (pprNatCmmDecl ncgImpl) $ concat native)
  258. -- dump global NCG stats for graph coloring allocator
  259. (case concat $ catMaybes colorStats of
  260. [] -> return ()
  261. stats -> do
  262. -- build the global register conflict graph
  263. let graphGlobal
  264. = foldl Color.union Color.initGraph
  265. $ [ Color.raGraph stat
  266. | stat@Color.RegAllocStatsStart{} <- stats]
  267. dumpSDoc dflags Opt_D_dump_asm_stats "NCG stats"
  268. $ Color.pprStats stats graphGlobal
  269. dumpIfSet_dyn dflags
  270. Opt_D_dump_asm_conflicts "Register conflict graph"
  271. $ Color.dotGraph
  272. (targetRegDotColor platform)
  273. (Color.trivColorable platform
  274. (targetVirtualRegSqueeze platform)
  275. (targetRealRegSqueeze platform))
  276. $ graphGlobal)
  277. -- dump global NCG stats for linear allocator
  278. (case concat $ catMaybes linearStats of
  279. [] -> return ()
  280. stats -> dumpSDoc dflags Opt_D_dump_asm_stats "NCG stats"
  281. $ Linear.pprStats (concat native) stats)
  282. -- write out the imports
  283. Pretty.printDoc Pretty.LeftMode (pprCols dflags) h
  284. $ withPprStyleDoc dflags (mkCodeStyle AsmStyle)
  285. $ makeImportsDoc dflags (concat imports)
  286. cmmNativeGenStream :: (Outputable statics, Outputable instr, Instruction instr)
  287. => DynFlags
  288. -> Module
  289. -> NcgImpl statics instr jumpDest
  290. -> BufHandle
  291. -> UniqSupply
  292. -> Stream IO RawCmmGroup ()
  293. -> NativeGenAcc statics instr
  294. -> IO (NativeGenAcc statics instr, UniqSupply)
  295. cmmNativeGenStream dflags this_mod ncgImpl h us cmm_stream ngs@(impAcc, profAcc)
  296. = do r <- Stream.runStream cmm_stream
  297. case r of
  298. Left () ->
  299. return ((reverse impAcc, reverse profAcc) , us)
  300. Right (cmms, cmm_stream') -> do
  301. (ngs',us') <- cmmNativeGens dflags this_mod ncgImpl h us cmms ngs 0
  302. cmmNativeGenStream dflags this_mod ncgImpl h us' cmm_stream' ngs'
  303. -- | Do native code generation on all these cmms.
  304. --
  305. cmmNativeGens :: (Outputable statics, Outputable instr, Instruction instr)
  306. => DynFlags
  307. -> Module
  308. -> NcgImpl statics instr jumpDest
  309. -> BufHandle
  310. -> UniqSupply
  311. -> [RawCmmDecl]
  312. -> NativeGenAcc statics instr
  313. -> Int
  314. -> IO (NativeGenAcc statics instr, UniqSupply)
  315. cmmNativeGens _ _ _ _ us [] ngs _
  316. = return (ngs, us)
  317. cmmNativeGens dflags this_mod ncgImpl h us (cmm : cmms) (impAcc, profAcc) count
  318. = do
  319. (us', native, imports, colorStats, linearStats)
  320. <- {-# SCC "cmmNativeGen" #-} cmmNativeGen dflags this_mod ncgImpl us cmm count
  321. {-# SCC "pprNativeCode" #-} Pretty.bufLeftRender h
  322. $ withPprStyleDoc dflags (mkCodeStyle AsmStyle)
  323. $ vcat $ map (pprNatCmmDecl ncgImpl) native
  324. let !lsPprNative =
  325. if dopt Opt_D_dump_asm dflags
  326. || dopt Opt_D_dump_asm_stats dflags
  327. then native
  328. else []
  329. let !count' = count + 1
  330. -- force evaluation all this stuff to avoid space leaks
  331. {-# SCC "seqString" #-} evaluate $ seqString (showSDoc dflags $ vcat $ map ppr imports)
  332. cmmNativeGens dflags this_mod ncgImpl h
  333. us' cmms ((imports : impAcc),
  334. ((lsPprNative, colorStats, linearStats) : profAcc))
  335. count'
  336. where seqString [] = ()
  337. seqString (x:xs) = x `seq` seqString xs
  338. -- | Complete native code generation phase for a single top-level chunk of Cmm.
  339. -- Dumping the output of each stage along the way.
  340. -- Global conflict graph and NGC stats
  341. cmmNativeGen
  342. :: (Outputable statics, Outputable instr, Instruction instr)
  343. => DynFlags
  344. -> Module
  345. -> NcgImpl statics instr jumpDest
  346. -> UniqSupply
  347. -> RawCmmDecl -- ^ the cmm to generate code for
  348. -> Int -- ^ sequence number of this top thing
  349. -> IO ( UniqSupply
  350. , [NatCmmDecl statics instr] -- native code
  351. , [CLabel] -- things imported by this cmm
  352. , Maybe [Color.RegAllocStats statics instr] -- stats for the coloring register allocator
  353. , Maybe [Linear.RegAllocStats]) -- stats for the linear register allocators
  354. cmmNativeGen dflags this_mod ncgImpl us cmm count
  355. = do
  356. let platform = targetPlatform dflags
  357. -- rewrite assignments to global regs
  358. let fixed_cmm =
  359. {-# SCC "fixStgRegisters" #-}
  360. fixStgRegisters dflags cmm
  361. -- cmm to cmm optimisations
  362. let (opt_cmm, imports) =
  363. {-# SCC "cmmToCmm" #-}
  364. cmmToCmm dflags this_mod fixed_cmm
  365. dumpIfSet_dyn dflags
  366. Opt_D_dump_opt_cmm "Optimised Cmm"
  367. (pprCmmGroup [opt_cmm])
  368. -- generate native code from cmm
  369. let ((native, lastMinuteImports), usGen) =
  370. {-# SCC "genMachCode" #-}
  371. initUs us $ genMachCode dflags this_mod (cmmTopCodeGen ncgImpl) opt_cmm
  372. dumpIfSet_dyn dflags
  373. Opt_D_dump_asm_native "Native code"
  374. (vcat $ map (pprNatCmmDecl ncgImpl) native)
  375. -- tag instructions with register liveness information
  376. let (withLiveness, usLive) =
  377. {-# SCC "regLiveness" #-}
  378. initUs usGen
  379. $ mapM (regLiveness platform)
  380. $ map natCmmTopToLive native
  381. dumpIfSet_dyn dflags
  382. Opt_D_dump_asm_liveness "Liveness annotations added"
  383. (vcat $ map ppr withLiveness)
  384. -- allocate registers
  385. (alloced, usAlloc, ppr_raStatsColor, ppr_raStatsLinear) <-
  386. if ( gopt Opt_RegsGraph dflags
  387. || gopt Opt_RegsIterative dflags)
  388. then do
  389. -- the regs usable for allocation
  390. let (alloc_regs :: UniqFM (UniqSet RealReg))
  391. = foldr (\r -> plusUFM_C unionUniqSets
  392. $ unitUFM (targetClassOfRealReg platform r) (unitUniqSet r))
  393. emptyUFM
  394. $ allocatableRegs ncgImpl
  395. -- do the graph coloring register allocation
  396. let ((alloced, regAllocStats), usAlloc)
  397. = {-# SCC "RegAlloc" #-}
  398. initUs usLive
  399. $ Color.regAlloc
  400. dflags
  401. alloc_regs
  402. (mkUniqSet [0 .. maxSpillSlots ncgImpl])
  403. withLiveness
  404. -- dump out what happened during register allocation
  405. dumpIfSet_dyn dflags
  406. Opt_D_dump_asm_regalloc "Registers allocated"
  407. (vcat $ map (pprNatCmmDecl ncgImpl) alloced)
  408. dumpIfSet_dyn dflags
  409. Opt_D_dump_asm_regalloc_stages "Build/spill stages"
  410. (vcat $ map (\(stage, stats)
  411. -> text "# --------------------------"
  412. $$ text "# cmm " <> int count <> text " Stage " <> int stage
  413. $$ ppr stats)
  414. $ zip [0..] regAllocStats)
  415. let mPprStats =
  416. if dopt Opt_D_dump_asm_stats dflags
  417. then Just regAllocStats else Nothing
  418. -- force evaluation of the Maybe to avoid space leak
  419. mPprStats `seq` return ()
  420. return ( alloced, usAlloc
  421. , mPprStats
  422. , Nothing)
  423. else do
  424. -- do linear register allocation
  425. let reg_alloc proc = do
  426. (alloced, maybe_more_stack, ra_stats) <-
  427. Linear.regAlloc dflags proc
  428. case maybe_more_stack of
  429. Nothing -> return ( alloced, ra_stats )
  430. Just amount -> do
  431. alloced' <- ncgAllocMoreStack ncgImpl amount alloced
  432. return (alloced', ra_stats )
  433. let ((alloced, regAllocStats), usAlloc)
  434. = {-# SCC "RegAlloc" #-}
  435. initUs usLive
  436. $ liftM unzip
  437. $ mapM reg_alloc withLiveness
  438. dumpIfSet_dyn dflags
  439. Opt_D_dump_asm_regalloc "Registers allocated"
  440. (vcat $ map (pprNatCmmDecl ncgImpl) alloced)
  441. let mPprStats =
  442. if dopt Opt_D_dump_asm_stats dflags
  443. then Just (catMaybes regAllocStats) else Nothing
  444. -- force evaluation of the Maybe to avoid space leak
  445. mPprStats `seq` return ()
  446. return ( alloced, usAlloc
  447. , Nothing
  448. , mPprStats)
  449. ---- x86fp_kludge. This pass inserts ffree instructions to clear
  450. ---- the FPU stack on x86. The x86 ABI requires that the FPU stack
  451. ---- is clear, and library functions can return odd results if it
  452. ---- isn't.
  453. ----
  454. ---- NB. must happen before shortcutBranches, because that
  455. ---- generates JXX_GBLs which we can't fix up in x86fp_kludge.
  456. let kludged = {-# SCC "x86fp_kludge" #-} ncg_x86fp_kludge ncgImpl alloced
  457. ---- generate jump tables
  458. let tabled =
  459. {-# SCC "generateJumpTables" #-}
  460. generateJumpTables ncgImpl kludged
  461. ---- shortcut branches
  462. let shorted =
  463. {-# SCC "shortcutBranches" #-}
  464. shortcutBranches dflags ncgImpl tabled
  465. ---- sequence blocks
  466. let sequenced =
  467. {-# SCC "sequenceBlocks" #-}
  468. map (sequenceTop ncgImpl) shorted
  469. ---- expansion of SPARC synthetic instrs
  470. let expanded =
  471. {-# SCC "sparc_expand" #-}
  472. ncgExpandTop ncgImpl sequenced
  473. dumpIfSet_dyn dflags
  474. Opt_D_dump_asm_expanded "Synthetic instructions expanded"
  475. (vcat $ map (pprNatCmmDecl ncgImpl) expanded)
  476. return ( usAlloc
  477. , expanded
  478. , lastMinuteImports ++ imports
  479. , ppr_raStatsColor
  480. , ppr_raStatsLinear)
  481. x86fp_kludge :: NatCmmDecl (Alignment, CmmStatics) X86.Instr.Instr -> NatCmmDecl (Alignment, CmmStatics) X86.Instr.Instr
  482. x86fp_kludge top@(CmmData _ _) = top
  483. x86fp_kludge (CmmProc info lbl live (ListGraph code)) =
  484. CmmProc info lbl live (ListGraph $ X86.Instr.i386_insert_ffrees code)
  485. -- | Build a doc for all the imports.
  486. --
  487. makeImportsDoc :: DynFlags -> [CLabel] -> SDoc
  488. makeImportsDoc dflags imports
  489. = dyld_stubs imports
  490. $$
  491. -- On recent versions of Darwin, the linker supports
  492. -- dead-stripping of code and data on a per-symbol basis.
  493. -- There's a hack to make this work in PprMach.pprNatCmmDecl.
  494. (if platformHasSubsectionsViaSymbols platform
  495. then text ".subsections_via_symbols"
  496. else empty)
  497. $$
  498. -- On recent GNU ELF systems one can mark an object file
  499. -- as not requiring an executable stack. If all objects
  500. -- linked into a program have this note then the program
  501. -- will not use an executable stack, which is good for
  502. -- security. GHC generated code does not need an executable
  503. -- stack so add the note in:
  504. (if platformHasGnuNonexecStack platform
  505. then text ".section .note.GNU-stack,\"\",@progbits"
  506. else empty)
  507. $$
  508. -- And just because every other compiler does, lets stick in
  509. -- an identifier directive: .ident "GHC x.y.z"
  510. (if platformHasIdentDirective platform
  511. then let compilerIdent = text "GHC" <+> text cProjectVersion
  512. in text ".ident" <+> doubleQuotes compilerIdent
  513. else empty)
  514. where
  515. platform = targetPlatform dflags
  516. arch = platformArch platform
  517. os = platformOS platform
  518. -- Generate "symbol stubs" for all external symbols that might
  519. -- come from a dynamic library.
  520. dyld_stubs :: [CLabel] -> SDoc
  521. {- dyld_stubs imps = vcat $ map pprDyldSymbolStub $
  522. map head $ group $ sort imps-}
  523. -- (Hack) sometimes two Labels pretty-print the same, but have
  524. -- different uniques; so we compare their text versions...
  525. dyld_stubs imps
  526. | needImportedSymbols dflags arch os
  527. = vcat $
  528. (pprGotDeclaration dflags arch os :) $
  529. map ( pprImportedSymbol dflags platform . fst . head) $
  530. groupBy (\(_,a) (_,b) -> a == b) $
  531. sortBy (\(_,a) (_,b) -> compare a b) $
  532. map doPpr $
  533. imps
  534. | otherwise
  535. = empty
  536. doPpr lbl = (lbl, renderWithStyle dflags (pprCLabel platform lbl) astyle)
  537. astyle = mkCodeStyle AsmStyle
  538. -- -----------------------------------------------------------------------------
  539. -- Sequencing the basic blocks
  540. -- Cmm BasicBlocks are self-contained entities: they always end in a
  541. -- jump, either non-local or to another basic block in the same proc.
  542. -- In this phase, we attempt to place the basic blocks in a sequence
  543. -- such that as many of the local jumps as possible turn into
  544. -- fallthroughs.
  545. sequenceTop
  546. :: Instruction instr
  547. => NcgImpl statics instr jumpDest -> NatCmmDecl statics instr -> NatCmmDecl statics instr
  548. sequenceTop _ top@(CmmData _ _) = top
  549. sequenceTop ncgImpl (CmmProc info lbl live (ListGraph blocks)) =
  550. CmmProc info lbl live (ListGraph $ ncgMakeFarBranches ncgImpl info $ sequenceBlocks info blocks)
  551. -- The algorithm is very simple (and stupid): we make a graph out of
  552. -- the blocks where there is an edge from one block to another iff the
  553. -- first block ends by jumping to the second. Then we topologically
  554. -- sort this graph. Then traverse the list: for each block, we first
  555. -- output the block, then if it has an out edge, we move the
  556. -- destination of the out edge to the front of the list, and continue.
  557. -- FYI, the classic layout for basic blocks uses postorder DFS; this
  558. -- algorithm is implemented in Hoopl.
  559. sequenceBlocks
  560. :: Instruction instr
  561. => BlockEnv i
  562. -> [NatBasicBlock instr]
  563. -> [NatBasicBlock instr]
  564. sequenceBlocks _ [] = []
  565. sequenceBlocks infos (entry:blocks) =
  566. seqBlocks infos (mkNode entry : reverse (flattenSCCs (sccBlocks blocks)))
  567. -- the first block is the entry point ==> it must remain at the start.
  568. sccBlocks
  569. :: Instruction instr
  570. => [NatBasicBlock instr]
  571. -> [SCC ( NatBasicBlock instr
  572. , BlockId
  573. , [BlockId])]
  574. sccBlocks blocks = stronglyConnCompFromEdgedVerticesR (map mkNode blocks)
  575. -- we're only interested in the last instruction of
  576. -- the block, and only if it has a single destination.
  577. getOutEdges
  578. :: Instruction instr
  579. => [instr] -> [BlockId]
  580. getOutEdges instrs
  581. = case jumpDestsOfInstr (last instrs) of
  582. [one] -> [one]
  583. _many -> []
  584. mkNode :: (Instruction t)
  585. => GenBasicBlock t
  586. -> (GenBasicBlock t, BlockId, [BlockId])
  587. mkNode block@(BasicBlock id instrs) = (block, id, getOutEdges instrs)
  588. seqBlocks :: BlockEnv i -> [(GenBasicBlock t1, BlockId, [BlockId])]
  589. -> [GenBasicBlock t1]
  590. seqBlocks _ [] = []
  591. seqBlocks infos ((block,_,[]) : rest)
  592. = block : seqBlocks infos rest
  593. seqBlocks infos ((block@(BasicBlock id instrs),_,[next]) : rest)
  594. | can_fallthrough = BasicBlock id (init instrs) : seqBlocks infos rest'
  595. | otherwise = block : seqBlocks infos rest'
  596. where
  597. can_fallthrough = not (mapMember next infos) && can_reorder
  598. (can_reorder, rest') = reorder next [] rest
  599. -- TODO: we should do a better job for cycles; try to maximise the
  600. -- fallthroughs within a loop.
  601. seqBlocks _ _ = panic "AsmCodegen:seqBlocks"
  602. reorder :: (Eq a) => a -> [(t, a, t1)] -> [(t, a, t1)] -> (Bool, [(t, a, t1)])
  603. reorder _ accum [] = (False, reverse accum)
  604. reorder id accum (b@(block,id',out) : rest)
  605. | id == id' = (True, (block,id,out) : reverse accum ++ rest)
  606. | otherwise = reorder id (b:accum) rest
  607. -- -----------------------------------------------------------------------------
  608. -- Generate jump tables
  609. -- Analyzes all native code and generates data sections for all jump
  610. -- table instructions.
  611. generateJumpTables
  612. :: NcgImpl statics instr jumpDest
  613. -> [NatCmmDecl statics instr] -> [NatCmmDecl statics instr]
  614. generateJumpTables ncgImpl xs = concatMap f xs
  615. where f p@(CmmProc _ _ _ (ListGraph xs)) = p : concatMap g xs
  616. f p = [p]
  617. g (BasicBlock _ xs) = catMaybes (map (generateJumpTableForInstr ncgImpl) xs)
  618. -- -----------------------------------------------------------------------------
  619. -- Shortcut branches
  620. shortcutBranches
  621. :: DynFlags
  622. -> NcgImpl statics instr jumpDest
  623. -> [NatCmmDecl statics instr]
  624. -> [NatCmmDecl statics instr]
  625. shortcutBranches dflags ncgImpl tops
  626. | optLevel dflags < 1 = tops -- only with -O or higher
  627. | otherwise = map (apply_mapping ncgImpl mapping) tops'
  628. where
  629. (tops', mappings) = mapAndUnzip (build_mapping ncgImpl) tops
  630. mapping = foldr plusUFM emptyUFM mappings
  631. build_mapping :: NcgImpl statics instr jumpDest
  632. -> GenCmmDecl d (BlockEnv t) (ListGraph instr)
  633. -> (GenCmmDecl d (BlockEnv t) (ListGraph instr), UniqFM jumpDest)
  634. build_mapping _ top@(CmmData _ _) = (top, emptyUFM)
  635. build_mapping _ (CmmProc info lbl live (ListGraph []))
  636. = (CmmProc info lbl live (ListGraph []), emptyUFM)
  637. build_mapping ncgImpl (CmmProc info lbl live (ListGraph (head:blocks)))
  638. = (CmmProc info lbl live (ListGraph (head:others)), mapping)
  639. -- drop the shorted blocks, but don't ever drop the first one,
  640. -- because it is pointed to by a global label.
  641. where
  642. -- find all the blocks that just consist of a jump that can be
  643. -- shorted.
  644. -- Don't completely eliminate loops here -- that can leave a dangling jump!
  645. (_, shortcut_blocks, others) = foldl split (emptyBlockSet, [], []) blocks
  646. split (s, shortcut_blocks, others) b@(BasicBlock id [insn])
  647. | Just jd <- canShortcut ncgImpl insn,
  648. Just dest <- getJumpDestBlockId ncgImpl jd,
  649. not (has_info id),
  650. (setMember dest s) || dest == id -- loop checks
  651. = (s, shortcut_blocks, b : others)
  652. split (s, shortcut_blocks, others) (BasicBlock id [insn])
  653. | Just dest <- canShortcut ncgImpl insn,
  654. not (has_info id)
  655. = (setInsert id s, (id,dest) : shortcut_blocks, others)
  656. split (s, shortcut_blocks, others) other = (s, shortcut_blocks, other : others)
  657. -- do not eliminate blocks that have an info table
  658. has_info l = mapMember l info
  659. -- build a mapping from BlockId to JumpDest for shorting branches
  660. mapping = foldl add emptyUFM shortcut_blocks
  661. add ufm (id,dest) = addToUFM ufm id dest
  662. apply_mapping :: NcgImpl statics instr jumpDest
  663. -> UniqFM jumpDest
  664. -> GenCmmDecl statics h (ListGraph instr)
  665. -> GenCmmDecl statics h (ListGraph instr)
  666. apply_mapping ncgImpl ufm (CmmData sec statics)
  667. = CmmData sec (shortcutStatics ncgImpl (lookupUFM ufm) statics)
  668. apply_mapping ncgImpl ufm (CmmProc info lbl live (ListGraph blocks))
  669. = CmmProc info lbl live (ListGraph $ map short_bb blocks)
  670. where
  671. short_bb (BasicBlock id insns) = BasicBlock id $! map short_insn insns
  672. short_insn i = shortcutJump ncgImpl (lookupUFM ufm) i
  673. -- shortcutJump should apply the mapping repeatedly,
  674. -- just in case we can short multiple branches.
  675. -- -----------------------------------------------------------------------------
  676. -- Instruction selection
  677. -- Native code instruction selection for a chunk of stix code. For
  678. -- this part of the computation, we switch from the UniqSM monad to
  679. -- the NatM monad. The latter carries not only a Unique, but also an
  680. -- Int denoting the current C stack pointer offset in the generated
  681. -- code; this is needed for creating correct spill offsets on
  682. -- architectures which don't offer, or for which it would be
  683. -- prohibitively expensive to employ, a frame pointer register. Viz,
  684. -- x86.
  685. -- The offset is measured in bytes, and indicates the difference
  686. -- between the current (simulated) C stack-ptr and the value it was at
  687. -- the beginning of the block. For stacks which grow down, this value
  688. -- should be either zero or negative.
  689. -- Switching between the two monads whilst carrying along the same
  690. -- Unique supply breaks abstraction. Is that bad?
  691. genMachCode
  692. :: DynFlags
  693. -> Module
  694. -> (RawCmmDecl -> NatM [NatCmmDecl statics instr])
  695. -> RawCmmDecl
  696. -> UniqSM
  697. ( [NatCmmDecl statics instr]
  698. , [CLabel])
  699. genMachCode dflags this_mod cmmTopCodeGen cmm_top
  700. = do { initial_us <- getUs
  701. ; let initial_st = mkNatM_State initial_us 0 dflags this_mod
  702. (new_tops, final_st) = initNat initial_st (cmmTopCodeGen cmm_top)
  703. final_delta = natm_delta final_st
  704. final_imports = natm_imports final_st
  705. ; if final_delta == 0
  706. then return (new_tops, final_imports)
  707. else pprPanic "genMachCode: nonzero final delta" (int final_delta)
  708. }
  709. -- -----------------------------------------------------------------------------
  710. -- Generic Cmm optimiser
  711. {-
  712. Here we do:
  713. (a) Constant folding
  714. (c) Position independent code and dynamic linking
  715. (i) introduce the appropriate indirections
  716. and position independent refs
  717. (ii) compile a list of imported symbols
  718. (d) Some arch-specific optimizations
  719. (a) will be moving to the new Hoopl pipeline, however, (c) and
  720. (d) are only needed by the native backend and will continue to live
  721. here.
  722. Ideas for other things we could do (put these in Hoopl please!):
  723. - shortcut jumps-to-jumps
  724. - simple CSE: if an expr is assigned to a temp, then replace later occs of
  725. that expr with the temp, until the expr is no longer valid (can push through
  726. temp assignments, and certain assigns to mem...)
  727. -}
  728. cmmToCmm :: DynFlags -> Module -> RawCmmDecl -> (RawCmmDecl, [CLabel])
  729. cmmToCmm _ _ top@(CmmData _ _) = (top, [])
  730. cmmToCmm dflags this_mod (CmmProc info lbl live graph)
  731. = runCmmOpt dflags this_mod $
  732. do blocks' <- mapM cmmBlockConFold (toBlockList graph)
  733. return $ CmmProc info lbl live (ofBlockList (g_entry graph) blocks')
  734. newtype CmmOptM a = CmmOptM (DynFlags -> Module -> [CLabel] -> (# a, [CLabel] #))
  735. instance Monad CmmOptM where
  736. return x = CmmOptM $ \_ _ imports -> (# x, imports #)
  737. (CmmOptM f) >>= g =
  738. CmmOptM $ \dflags this_mod imports ->
  739. case f dflags this_mod imports of
  740. (# x, imports' #) ->
  741. case g x of
  742. CmmOptM g' -> g' dflags this_mod imports'
  743. instance CmmMakeDynamicReferenceM CmmOptM where
  744. addImport = addImportCmmOpt
  745. getThisModule = CmmOptM $ \_ this_mod imports -> (# this_mod, imports #)
  746. addImportCmmOpt :: CLabel -> CmmOptM ()
  747. addImportCmmOpt lbl = CmmOptM $ \_ _ imports -> (# (), lbl:imports #)
  748. instance HasDynFlags CmmOptM where
  749. getDynFlags = CmmOptM $ \dflags _ imports -> (# dflags, imports #)
  750. runCmmOpt :: DynFlags -> Module -> CmmOptM a -> (a, [CLabel])
  751. runCmmOpt dflags this_mod (CmmOptM f) = case f dflags this_mod [] of
  752. (# result, imports #) -> (result, imports)
  753. cmmBlockConFold :: CmmBlock -> CmmOptM CmmBlock
  754. cmmBlockConFold block = do
  755. let (entry, middle, last) = blockSplit block
  756. stmts = blockToList middle
  757. stmts' <- mapM cmmStmtConFold stmts
  758. last' <- cmmStmtConFold last
  759. return $ blockJoin entry (blockFromList stmts') last'
  760. -- This does three optimizations, but they're very quick to check, so we don't
  761. -- bother turning them off even when the Hoopl code is active. Since
  762. -- this is on the old Cmm representation, we can't reuse the code either:
  763. -- * reg = reg --> nop
  764. -- * if 0 then jump --> nop
  765. -- * if 1 then jump --> jump
  766. -- We might be tempted to skip this step entirely of not Opt_PIC, but
  767. -- there is some PowerPC code for the non-PIC case, which would also
  768. -- have to be separated.
  769. cmmStmtConFold :: CmmNode e x -> CmmOptM (CmmNode e x)
  770. cmmStmtConFold stmt
  771. = case stmt of
  772. CmmAssign reg src
  773. -> do src' <- cmmExprConFold DataReference src
  774. return $ case src' of
  775. CmmReg reg' | reg == reg' -> CmmComment (fsLit "nop")
  776. new_src -> CmmAssign reg new_src
  777. CmmStore addr src
  778. -> do addr' <- cmmExprConFold DataReference addr
  779. src' <- cmmExprConFold DataReference src
  780. return $ CmmStore addr' src'
  781. CmmCall { cml_target = addr }
  782. -> do addr' <- cmmExprConFold JumpReference addr
  783. return $ stmt { cml_target = addr' }
  784. CmmUnsafeForeignCall target regs args
  785. -> do target' <- case target of
  786. ForeignTarget e conv -> do
  787. e' <- cmmExprConFold CallReference e
  788. return $ ForeignTarget e' conv
  789. PrimTarget _ ->
  790. return target
  791. args' <- mapM (cmmExprConFold DataReference) args
  792. return $ CmmUnsafeForeignCall target' regs args'
  793. CmmCondBranch test true false
  794. -> do test' <- cmmExprConFold DataReference test
  795. return $ case test' of
  796. CmmLit (CmmInt 0 _) -> CmmBranch false
  797. CmmLit (CmmInt _ _) -> CmmBranch true
  798. _other -> CmmCondBranch test' true false
  799. CmmSwitch expr ids
  800. -> do expr' <- cmmExprConFold DataReference expr
  801. return $ CmmSwitch expr' ids
  802. other
  803. -> return other
  804. cmmExprConFold :: ReferenceKind -> CmmExpr -> CmmOptM CmmExpr
  805. cmmExprConFold referenceKind expr = do
  806. dflags <- getDynFlags
  807. -- With -O1 and greater, the cmmSink pass does constant-folding, so
  808. -- we don't need to do it again here.
  809. let expr' = if optLevel dflags >= 1
  810. then expr
  811. else cmmExprCon dflags expr
  812. cmmExprNative referenceKind expr'
  813. cmmExprCon :: DynFlags -> CmmExpr -> CmmExpr
  814. cmmExprCon dflags (CmmLoad addr rep) = CmmLoad (cmmExprCon dflags addr) rep
  815. cmmExprCon dflags (CmmMachOp mop args)
  816. = cmmMachOpFold dflags mop (map (cmmExprCon dflags) args)
  817. cmmExprCon _ other = other
  818. -- handles both PIC and non-PIC cases... a very strange mixture
  819. -- of things to do.
  820. cmmExprNative :: ReferenceKind -> CmmExpr -> CmmOptM CmmExpr
  821. cmmExprNative referenceKind expr = do
  822. dflags <- getDynFlags
  823. let platform = targetPlatform dflags
  824. arch = platformArch platform
  825. case expr of
  826. CmmLoad addr rep
  827. -> do addr' <- cmmExprNative DataReference addr
  828. return $ CmmLoad addr' rep
  829. CmmMachOp mop args
  830. -> do args' <- mapM (cmmExprNative DataReference) args
  831. return $ CmmMachOp mop args'
  832. CmmLit (CmmBlock id)
  833. -> cmmExprNative referenceKind (CmmLit (CmmLabel (infoTblLbl id)))
  834. -- we must convert block Ids to CLabels here, because we
  835. -- might have to do the PIC transformation. Hence we must
  836. -- not modify BlockIds beyond this point.
  837. CmmLit (CmmLabel lbl)
  838. -> do
  839. cmmMakeDynamicReference dflags referenceKind lbl
  840. CmmLit (CmmLabelOff lbl off)
  841. -> do
  842. dynRef <- cmmMakeDynamicReference dflags referenceKind lbl
  843. -- need to optimize here, since it's late
  844. return $ cmmMachOpFold dflags (MO_Add (wordWidth dflags)) [
  845. dynRef,
  846. (CmmLit $ CmmInt (fromIntegral off) (wordWidth dflags))
  847. ]
  848. -- On powerpc (non-PIC), it's easier to jump directly to a label than
  849. -- to use the register table, so we replace these registers
  850. -- with the corresponding labels:
  851. CmmReg (CmmGlobal EagerBlackholeInfo)
  852. | arch == ArchPPC && not (gopt Opt_PIC dflags)
  853. -> cmmExprNative referenceKind $
  854. CmmLit (CmmLabel (mkCmmCodeLabel rtsPackageId (fsLit "__stg_EAGER_BLACKHOLE_info")))
  855. CmmReg (CmmGlobal GCEnter1)
  856. | arch == ArchPPC && not (gopt Opt_PIC dflags)
  857. -> cmmExprNative referenceKind $
  858. CmmLit (CmmLabel (mkCmmCodeLabel rtsPackageId (fsLit "__stg_gc_enter_1")))
  859. CmmReg (CmmGlobal GCFun)
  860. | arch == ArchPPC && not (gopt Opt_PIC dflags)
  861. -> cmmExprNative referenceKind $
  862. CmmLit (CmmLabel (mkCmmCodeLabel rtsPackageId (fsLit "__stg_gc_fun")))
  863. other
  864. -> return other
  865. \end{code}