AsmCodeGen.hs 45.2 KB
Newer Older
1 2 3
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 1993-2004
4
--
5 6 7
-- This is the top-level module in the native code generator.
--
-- -----------------------------------------------------------------------------
8

9 10
{-# LANGUAGE BangPatterns, CPP, GADTs, ScopedTypeVariables, UnboxedTuples #-}

11
module AsmCodeGen ( nativeCodeGen ) where
12

13
#include "HsVersions.h"
14
#include "nativeGen/NCG.h"
15

16

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import qualified X86.CodeGen
import qualified X86.Regs
import qualified X86.Instr
import qualified X86.Ppr

import qualified SPARC.CodeGen
import qualified SPARC.Regs
import qualified SPARC.Instr
import qualified SPARC.Ppr
import qualified SPARC.ShortcutJump
import qualified SPARC.CodeGen.Expand

import qualified PPC.CodeGen
import qualified PPC.Regs
import qualified PPC.RegInfo
import qualified PPC.Instr
import qualified PPC.Ppr
34 35

import RegAlloc.Liveness
36
import qualified RegAlloc.Linear.Main           as Linear
37

38 39 40 41
import qualified GraphColor                     as Color
import qualified RegAlloc.Graph.Main            as Color
import qualified RegAlloc.Graph.Stats           as Color
import qualified RegAlloc.Graph.TrivColorable   as Color
42

43
import TargetReg
44
import Platform
45
import Config
46 47 48 49
import Instruction
import PIC
import Reg
import NCGMonad
Peter Wortmann's avatar
Peter Wortmann committed
50
import Dwarf
51
import Debug
52

53
import BlockId
54
import CgUtils          ( fixStgRegisters )
55 56 57
import Cmm
import CmmUtils
import Hoopl
Simon Marlow's avatar
Simon Marlow committed
58
import CmmOpt           ( cmmMachOpFold )
59
import PprCmm
60
import CLabel
61

62
import UniqFM
63
import UniqSupply
64 65
import DynFlags
import Util
66
import Unique
67

68
import BasicTypes       ( Alignment )
69
import Digraph
70
import qualified Pretty
71
import BufWrite
72
import Outputable
73
import FastString
74
import UniqSet
75
import ErrUtils
76
import Module
77 78
import Stream (Stream)
import qualified Stream
79

80 81
-- DEBUGGING ONLY
--import OrdList
82

83
import Data.List
84
import Data.Maybe
85
import Control.Exception
86
#if __GLASGOW_HASKELL__ < 709
Austin Seipp's avatar
Austin Seipp committed
87
import Control.Applicative (Applicative(..))
88
#endif
89
import Control.Monad
90
import System.IO
91

92 93 94
{-
The native-code generator has machine-independent and
machine-dependent modules.
95

96 97 98 99
This module ("AsmCodeGen") is the top-level machine-independent
module.  Before entering machine-dependent land, we do some
machine-independent optimisations (defined below) on the
'CmmStmts's.
100

101 102 103 104 105 106 107 108 109
We convert to the machine-specific 'Instr' datatype with
'cmmCodeGen', assuming an infinite supply of registers.  We then use
a machine-independent register allocator ('regAlloc') to rejoin
reality.  Obviously, 'regAlloc' has machine-specific helper
functions (see about "RegAllocInfo" below).

Finally, we order the basic blocks of the function so as to minimise
the number of jumps between blocks, by utilising fallthrough wherever
possible.
110 111

The machine-dependent bits break down as follows:
112 113

  * ["MachRegs"]  Everything about the target platform's machine
114 115 116
    registers (and immediate operands, and addresses, which tend to
    intermingle/interact with registers).

117
  * ["MachInstrs"]  Includes the 'Instr' datatype (possibly should
118
    have a module of its own), plus a miscellany of other things
119
    (e.g., 'targetDoubleSize', 'smStablePtrTable', ...)
120

121
  * ["MachCodeGen"]  is where 'Cmm' stuff turns into
122
    machine instructions.
123

124
  * ["PprMach"] 'pprInstr' turns an 'Instr' into text (well, really
125
    a 'SDoc').
126

127 128
  * ["RegAllocInfo"] In the register allocator, we manipulate
    'MRegsState's, which are 'BitSet's, one bit per machine register.
129 130
    When we want to say something about a specific machine register
    (e.g., ``it gets clobbered by this instruction''), we set/unset
131
    its bit.  Obviously, we do this 'BitSet' thing for efficiency
132 133
    reasons.

134
    The 'RegAllocInfo' module collects together the machine-specific
135 136
    info needed to do register allocation.

137 138
   * ["RegisterAlloc"] The (machine-independent) register allocator.
-}
139

140 141
-- -----------------------------------------------------------------------------
-- Top-level of the native codegen
142

143
data NcgImpl statics instr jumpDest = NcgImpl {
Simon Peyton Jones's avatar
Simon Peyton Jones committed
144
    cmmTopCodeGen             :: RawCmmDecl -> NatM [NatCmmDecl statics instr],
145
    generateJumpTableForInstr :: instr -> Maybe (NatCmmDecl statics instr),
146 147
    getJumpDestBlockId        :: jumpDest -> Maybe BlockId,
    canShortcut               :: instr -> Maybe jumpDest,
148
    shortcutStatics           :: (BlockId -> Maybe jumpDest) -> statics -> statics,
149
    shortcutJump              :: (BlockId -> Maybe jumpDest) -> instr -> instr,
150
    pprNatCmmDecl             :: NatCmmDecl statics instr -> SDoc,
151 152
    maxSpillSlots             :: Int,
    allocatableRegs           :: [RealReg],
Simon Peyton Jones's avatar
Simon Peyton Jones committed
153 154
    ncg_x86fp_kludge          :: [NatCmmDecl statics instr] -> [NatCmmDecl statics instr],
    ncgExpandTop              :: [NatCmmDecl statics instr] -> [NatCmmDecl statics instr],
155
    ncgAllocMoreStack         :: Int -> NatCmmDecl statics instr -> UniqSM (NatCmmDecl statics instr),
156
    ncgMakeFarBranches        :: BlockEnv CmmStatics -> [NatBasicBlock instr] -> [NatBasicBlock instr]
157 158
    }

159
--------------------
160
nativeCodeGen :: DynFlags -> Module -> ModLocation -> Handle -> UniqSupply
161
              -> Stream IO RawCmmGroup ()
162
              -> IO UniqSupply
163
nativeCodeGen dflags this_mod modLoc h us cmms
164
 = let platform = targetPlatform dflags
165 166
       nCG' :: (Outputable statics, Outputable instr, Instruction instr)
            => NcgImpl statics instr jumpDest -> IO UniqSupply
167
       nCG' ncgImpl = nativeCodeGen' dflags this_mod modLoc ncgImpl h us cmms
168
   in case platformArch platform of
169 170 171 172 173 174 175 176 177 178 179 180
      ArchX86       -> nCG' (x86NcgImpl    dflags)
      ArchX86_64    -> nCG' (x86_64NcgImpl dflags)
      ArchPPC       -> nCG' (ppcNcgImpl    dflags)
      ArchSPARC     -> nCG' (sparcNcgImpl  dflags)
      ArchARM {}    -> panic "nativeCodeGen: No NCG for ARM"
      ArchARM64     -> panic "nativeCodeGen: No NCG for ARM64"
      ArchPPC_64 _  -> nCG' (ppcNcgImpl    dflags)
      ArchAlpha     -> panic "nativeCodeGen: No NCG for Alpha"
      ArchMipseb    -> panic "nativeCodeGen: No NCG for mipseb"
      ArchMipsel    -> panic "nativeCodeGen: No NCG for mipsel"
      ArchUnknown   -> panic "nativeCodeGen: No NCG for unknown arch"
      ArchJavaScript-> panic "nativeCodeGen: No NCG for JavaScript"
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

x86NcgImpl :: DynFlags -> NcgImpl (Alignment, CmmStatics) X86.Instr.Instr X86.Instr.JumpDest
x86NcgImpl dflags
 = (x86_64NcgImpl dflags) { ncg_x86fp_kludge = map x86fp_kludge }

x86_64NcgImpl :: DynFlags -> NcgImpl (Alignment, CmmStatics) X86.Instr.Instr X86.Instr.JumpDest
x86_64NcgImpl dflags
 = NcgImpl {
        cmmTopCodeGen             = X86.CodeGen.cmmTopCodeGen
       ,generateJumpTableForInstr = X86.CodeGen.generateJumpTableForInstr dflags
       ,getJumpDestBlockId        = X86.Instr.getJumpDestBlockId
       ,canShortcut               = X86.Instr.canShortcut
       ,shortcutStatics           = X86.Instr.shortcutStatics
       ,shortcutJump              = X86.Instr.shortcutJump
       ,pprNatCmmDecl             = X86.Ppr.pprNatCmmDecl
       ,maxSpillSlots             = X86.Instr.maxSpillSlots dflags
       ,allocatableRegs           = X86.Regs.allocatableRegs platform
       ,ncg_x86fp_kludge          = id
       ,ncgAllocMoreStack         = X86.Instr.allocMoreStack platform
       ,ncgExpandTop              = id
201
       ,ncgMakeFarBranches        = const id
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
   }
    where platform = targetPlatform dflags

ppcNcgImpl :: DynFlags -> NcgImpl CmmStatics PPC.Instr.Instr PPC.RegInfo.JumpDest
ppcNcgImpl dflags
 = NcgImpl {
        cmmTopCodeGen             = PPC.CodeGen.cmmTopCodeGen
       ,generateJumpTableForInstr = PPC.CodeGen.generateJumpTableForInstr dflags
       ,getJumpDestBlockId        = PPC.RegInfo.getJumpDestBlockId
       ,canShortcut               = PPC.RegInfo.canShortcut
       ,shortcutStatics           = PPC.RegInfo.shortcutStatics
       ,shortcutJump              = PPC.RegInfo.shortcutJump
       ,pprNatCmmDecl             = PPC.Ppr.pprNatCmmDecl
       ,maxSpillSlots             = PPC.Instr.maxSpillSlots dflags
       ,allocatableRegs           = PPC.Regs.allocatableRegs platform
       ,ncg_x86fp_kludge          = id
       ,ncgAllocMoreStack         = PPC.Instr.allocMoreStack platform
       ,ncgExpandTop              = id
220
       ,ncgMakeFarBranches        = PPC.Instr.makeFarBranches
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
   }
    where platform = targetPlatform dflags

sparcNcgImpl :: DynFlags -> NcgImpl CmmStatics SPARC.Instr.Instr SPARC.ShortcutJump.JumpDest
sparcNcgImpl dflags
 = NcgImpl {
        cmmTopCodeGen             = SPARC.CodeGen.cmmTopCodeGen
       ,generateJumpTableForInstr = SPARC.CodeGen.generateJumpTableForInstr dflags
       ,getJumpDestBlockId        = SPARC.ShortcutJump.getJumpDestBlockId
       ,canShortcut               = SPARC.ShortcutJump.canShortcut
       ,shortcutStatics           = SPARC.ShortcutJump.shortcutStatics
       ,shortcutJump              = SPARC.ShortcutJump.shortcutJump
       ,pprNatCmmDecl             = SPARC.Ppr.pprNatCmmDecl
       ,maxSpillSlots             = SPARC.Instr.maxSpillSlots dflags
       ,allocatableRegs           = SPARC.Regs.allocatableRegs
       ,ncg_x86fp_kludge          = id
       ,ncgAllocMoreStack         = noAllocMoreStack
       ,ncgExpandTop              = map SPARC.CodeGen.Expand.expandTop
239
       ,ncgMakeFarBranches        = const id
240
   }
241 242 243 244 245 246 247

--
-- Allocating more stack space for spilling is currently only
-- supported for the linear register allocator on x86/x86_64, the rest
-- default to the panic below.  To support allocating extra stack on
-- more platforms provide a definition of ncgAllocMoreStack.
--
248
noAllocMoreStack :: Int -> NatCmmDecl statics instr -> UniqSM (NatCmmDecl statics instr)
249 250 251 252 253 254 255 256 257
noAllocMoreStack amount _
  = panic $   "Register allocator: out of stack slots (need " ++ show amount ++ ")\n"
        ++  "   If you are trying to compile SHA1.hs from the crypto library then this\n"
        ++  "   is a known limitation in the linear allocator.\n"
        ++  "\n"
        ++  "   Try enabling the graph colouring allocator with -fregs-graph instead."
        ++  "   You can still file a bug report if you like.\n"


258 259 260 261 262 263 264 265 266 267 268 269 270
-- | Data accumulated during code generation. Mostly about statistics,
-- but also collects debug data for DWARF generation.
data NativeGenAcc statics instr
  = NGS { ngs_imports     :: ![[CLabel]]
        , ngs_natives     :: ![[NatCmmDecl statics instr]]
             -- ^ Native code generated, for statistics. This might
             -- hold a lot of data, so it is important to clear this
             -- field as early as possible if it isn't actually
             -- required.
        , ngs_colorStats  :: ![[Color.RegAllocStats statics instr]]
        , ngs_linearStats :: ![[Linear.RegAllocStats]]
        , ngs_labels      :: ![Label]
        , ngs_debug       :: ![DebugBlock]
271
        , ngs_dwarfFiles  :: !DwarfFiles
272
        }
273

Ian Lynagh's avatar
Ian Lynagh committed
274
nativeCodeGen' :: (Outputable statics, Outputable instr, Instruction instr)
275
               => DynFlags
276
               -> Module -> ModLocation
277
               -> NcgImpl statics instr jumpDest
278
               -> Handle
279 280 281
               -> UniqSupply
               -> Stream IO RawCmmGroup ()
               -> IO UniqSupply
282
nativeCodeGen' dflags this_mod modLoc ncgImpl h us cmms
283
 = do
284 285 286
        -- BufHandle is a performance hack.  We could hide it inside
        -- Pretty if it weren't for the fact that we do lots of little
        -- printDocs here (in order to do codegen in constant space).
287
        bufh <- newBufHandle h
288
        let ngs0 = NGS [] [] [] [] [] [] emptyUFM
289
        (ngs, us') <- cmmNativeGenStream dflags this_mod modLoc ncgImpl bufh us
290
                                         cmms ngs0
Peter Wortmann's avatar
Peter Wortmann committed
291
        finishNativeGen dflags modLoc bufh us' ngs
292 293

finishNativeGen :: Instruction instr
294
                => DynFlags
Peter Wortmann's avatar
Peter Wortmann committed
295
                -> ModLocation
296
                -> BufHandle
Peter Wortmann's avatar
Peter Wortmann committed
297
                -> UniqSupply
298
                -> NativeGenAcc statics instr
Peter Wortmann's avatar
Peter Wortmann committed
299 300
                -> IO UniqSupply
finishNativeGen dflags modLoc bufh@(BufHandle _ _ h) us ngs
301
 = do
Peter Wortmann's avatar
Peter Wortmann committed
302 303 304 305 306 307
        -- Write debug data and finish
        let emitDw = gopt Opt_Debug dflags && not (gopt Opt_SplitObjs dflags)
        us' <- if not emitDw then return us else do
          (dwarf, us') <- dwarfGen dflags modLoc us (ngs_debug ngs)
          emitNativeCode dflags bufh dwarf
          return us'
308
        bFlush bufh
309

310
        -- dump global NCG stats for graph coloring allocator
311 312 313
        let stats = concat (ngs_colorStats ngs)
        when (not (null stats)) $ do

Peter Wortmann's avatar
Peter Wortmann committed
314 315 316 317 318
          -- build the global register conflict graph
          let graphGlobal
                  = foldl Color.union Color.initGraph
                  $ [ Color.raGraph stat
                          | stat@Color.RegAllocStatsStart{} <- stats]
319

Peter Wortmann's avatar
Peter Wortmann committed
320
          dump_stats (Color.pprStats stats graphGlobal)
321

Peter Wortmann's avatar
Peter Wortmann committed
322 323 324 325 326 327 328 329 330
          let platform = targetPlatform dflags
          dumpIfSet_dyn dflags
                  Opt_D_dump_asm_conflicts "Register conflict graph"
                  $ Color.dotGraph
                          (targetRegDotColor platform)
                          (Color.trivColorable platform
                                  (targetVirtualRegSqueeze platform)
                                  (targetRealRegSqueeze platform))
                  $ graphGlobal
331 332 333


        -- dump global NCG stats for linear allocator
334 335 336
        let linearStats = concat (ngs_linearStats ngs)
        when (not (null linearStats)) $
          dump_stats (Linear.pprStats (concat (ngs_natives ngs)) linearStats)
337 338

        -- write out the imports
Ian Lynagh's avatar
Ian Lynagh committed
339
        Pretty.printDoc Pretty.LeftMode (pprCols dflags) h
Ian Lynagh's avatar
Ian Lynagh committed
340
                $ withPprStyleDoc dflags (mkCodeStyle AsmStyle)
341
                $ makeImportsDoc dflags (concat (ngs_imports ngs))
Peter Wortmann's avatar
Peter Wortmann committed
342
        return us'
343 344
  where
    dump_stats = dumpSDoc dflags alwaysQualify Opt_D_dump_asm_stats "NCG stats"
345

Simon Marlow's avatar
Simon Marlow committed
346
cmmNativeGenStream :: (Outputable statics, Outputable instr, Instruction instr)
347
              => DynFlags
348
              -> Module -> ModLocation
349 350
              -> NcgImpl statics instr jumpDest
              -> BufHandle
351 352
              -> UniqSupply
              -> Stream IO RawCmmGroup ()
353 354
              -> NativeGenAcc statics instr
              -> IO (NativeGenAcc statics instr, UniqSupply)
355

356
cmmNativeGenStream dflags this_mod modLoc ncgImpl h us cmm_stream ngs
357 358
 = do r <- Stream.runStream cmm_stream
      case r of
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
        Left () ->
          return (ngs { ngs_imports = reverse $ ngs_imports ngs
                      , ngs_natives = reverse $ ngs_natives ngs
                      , ngs_colorStats = reverse $ ngs_colorStats ngs
                      , ngs_linearStats = reverse $ ngs_linearStats ngs
                      },
                  us)
        Right (cmms, cmm_stream') -> do

          -- Generate debug information
          let debugFlag = gopt Opt_Debug dflags
              !ndbgs | debugFlag = cmmDebugGen modLoc cmms
                     | otherwise = []
              dbgMap = debugToMap ndbgs

          -- Insert split marker, generate native code
          let splitFlag = gopt Opt_SplitObjs dflags
              split_marker = CmmProc mapEmpty mkSplitMarkerLabel [] $
                             ofBlockList (panic "split_marker_entry") []
              cmms' | splitFlag  = split_marker : cmms
                    | otherwise  = cmms
          (ngs',us') <- cmmNativeGens dflags this_mod modLoc ncgImpl h dbgMap us
                                      cmms' ngs 0

          -- Link native code information into debug blocks
          let !ldbgs = cmmDebugLink (ngs_labels ngs') ndbgs
          dumpIfSet_dyn dflags Opt_D_dump_debug "Debug Infos"
            (vcat $ map ppr ldbgs)

Peter Wortmann's avatar
Peter Wortmann committed
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
          -- Emit & clear DWARF information when generating split
          -- object files, as we need it to land in the same object file
          (ngs'', us'') <-
            if debugFlag && splitFlag
            then do (dwarf, us'') <- dwarfGen dflags modLoc us ldbgs
                    emitNativeCode dflags h dwarf
                    return (ngs' { ngs_debug = []
                                 , ngs_dwarfFiles = emptyUFM
                                 , ngs_labels = [] },
                            us'')
            else return (ngs' { ngs_debug  = ngs_debug ngs' ++ ldbgs
                              , ngs_labels = [] },
                         us')

          cmmNativeGenStream dflags this_mod modLoc ncgImpl h us''
403
              cmm_stream' ngs''
404

405 406
-- | Do native code generation on all these cmms.
--
Ian Lynagh's avatar
Ian Lynagh committed
407
cmmNativeGens :: (Outputable statics, Outputable instr, Instruction instr)
408
              => DynFlags
409
              -> Module -> ModLocation
410 411
              -> NcgImpl statics instr jumpDest
              -> BufHandle
412
              -> LabelMap DebugBlock
dterei's avatar
dterei committed
413
              -> UniqSupply
Simon Peyton Jones's avatar
Simon Peyton Jones committed
414
              -> [RawCmmDecl]
415 416 417
              -> NativeGenAcc statics instr
              -> Int
              -> IO (NativeGenAcc statics instr, UniqSupply)
418

419
cmmNativeGens _ _ _ _ _ _ us [] ngs !_
420
        = return (ngs, us)
421

422 423
cmmNativeGens dflags this_mod modLoc ncgImpl h dbgMap us
              (cmm : cmms) ngs count
424
 = do
425 426 427 428 429 430 431 432 433
        let fileIds = ngs_dwarfFiles ngs
        (us', fileIds', native, imports, colorStats, linearStats)
          <- {-# SCC "cmmNativeGen" #-}
             cmmNativeGen dflags this_mod modLoc ncgImpl us fileIds dbgMap
                          cmm count

        let newFileIds = fileIds' `minusUFM` fileIds
            pprDecl (f,n) = ptext (sLit "\t.file ") <> ppr n <+>
                            doubleQuotes (ftext f)
434

435
        emitNativeCode dflags h $ vcat $
436
          map pprDecl (eltsUFM newFileIds) ++
437
          map (pprNatCmmDecl ncgImpl) native
438

Gabor Greif's avatar
typo  
Gabor Greif committed
439
        -- force evaluation all this stuff to avoid space leaks
440
        {-# SCC "seqString" #-} evaluate $ seqString (showSDoc dflags $ vcat $ map ppr imports)
441

442 443 444 445 446 447 448 449 450 451
        let !labels' = if gopt Opt_Debug dflags
                       then cmmDebugLabels isMetaInstr native else []
            !natives' = if dopt Opt_D_dump_asm_stats dflags
                        then native : ngs_natives ngs else []
            mCon = maybe id (:)
            ngs' = ngs{ ngs_imports     = imports : ngs_imports ngs
                      , ngs_natives     = natives'
                      , ngs_colorStats  = colorStats `mCon` ngs_colorStats ngs
                      , ngs_linearStats = linearStats `mCon` ngs_linearStats ngs
                      , ngs_labels      = ngs_labels ngs ++ labels'
452
                      , ngs_dwarfFiles  = fileIds'
453
                      }
454 455
        cmmNativeGens dflags this_mod modLoc ncgImpl h dbgMap us'
                      cmms ngs' (count + 1)
456

457
 where  seqString []            = ()
458
        seqString (x:xs)        = x `seq` seqString xs
459 460


461 462 463 464 465 466 467 468 469 470 471
emitNativeCode :: DynFlags -> BufHandle -> SDoc -> IO ()
emitNativeCode dflags h sdoc = do

        {-# SCC "pprNativeCode" #-} Pretty.bufLeftRender h
                $ withPprStyleDoc dflags (mkCodeStyle AsmStyle) sdoc

        -- dump native code
        dumpIfSet_dyn dflags
                Opt_D_dump_asm "Asm code"
                sdoc

472
-- | Complete native code generation phase for a single top-level chunk of Cmm.
473 474
--      Dumping the output of each stage along the way.
--      Global conflict graph and NGC stats
475
cmmNativeGen
Ian Lynagh's avatar
Ian Lynagh committed
476
        :: (Outputable statics, Outputable instr, Instruction instr)
477
    => DynFlags
478
    -> Module -> ModLocation
479
    -> NcgImpl statics instr jumpDest
480
        -> UniqSupply
481 482
        -> DwarfFiles
        -> LabelMap DebugBlock
483 484 485
        -> RawCmmDecl                                   -- ^ the cmm to generate code for
        -> Int                                          -- ^ sequence number of this top thing
        -> IO   ( UniqSupply
486
                , DwarfFiles
487 488 489 490
                , [NatCmmDecl statics instr]                -- native code
                , [CLabel]                                  -- things imported by this cmm
                , Maybe [Color.RegAllocStats statics instr] -- stats for the coloring register allocator
                , Maybe [Linear.RegAllocStats])             -- stats for the linear register allocators
491

492
cmmNativeGen dflags this_mod modLoc ncgImpl us fileIds dbgMap cmm count
493
 = do
494
        let platform = targetPlatform dflags
495

496 497 498
        -- rewrite assignments to global regs
        let fixed_cmm =
                {-# SCC "fixStgRegisters" #-}
499
                fixStgRegisters dflags cmm
500

501 502 503
        -- cmm to cmm optimisations
        let (opt_cmm, imports) =
                {-# SCC "cmmToCmm" #-}
504
                cmmToCmm dflags this_mod fixed_cmm
505

506 507
        dumpIfSet_dyn dflags
                Opt_D_dump_opt_cmm "Optimised Cmm"
508
                (pprCmmGroup [opt_cmm])
509

510
        -- generate native code from cmm
511
        let ((native, lastMinuteImports, fileIds'), usGen) =
512
                {-# SCC "genMachCode" #-}
513 514 515
                initUs us $ genMachCode dflags this_mod modLoc
                                        (cmmTopCodeGen ncgImpl)
                                        fileIds dbgMap opt_cmm
516 517 518

        dumpIfSet_dyn dflags
                Opt_D_dump_asm_native "Native code"
519
                (vcat $ map (pprNatCmmDecl ncgImpl) native)
520 521 522 523 524

        -- tag instructions with register liveness information
        let (withLiveness, usLive) =
                {-# SCC "regLiveness" #-}
                initUs usGen
525
                        $ mapM (regLiveness platform)
526 527 528 529
                        $ map natCmmTopToLive native

        dumpIfSet_dyn dflags
                Opt_D_dump_asm_liveness "Liveness annotations added"
Ian Lynagh's avatar
Ian Lynagh committed
530
                (vcat $ map ppr withLiveness)
531 532 533

        -- allocate registers
        (alloced, usAlloc, ppr_raStatsColor, ppr_raStatsLinear) <-
534 535 536 537
         if False
           -- Disabled, see #7679, #8657
           --  ( gopt Opt_RegsGraph dflags
           --  || gopt Opt_RegsIterative dflags)
538 539 540 541 542 543
          then do
                -- the regs usable for allocation
                let (alloc_regs :: UniqFM (UniqSet RealReg))
                        = foldr (\r -> plusUFM_C unionUniqSets
                                        $ unitUFM (targetClassOfRealReg platform r) (unitUniqSet r))
                                emptyUFM
544
                        $ allocatableRegs ncgImpl
545 546 547 548 549 550 551 552

                -- do the graph coloring register allocation
                let ((alloced, regAllocStats), usAlloc)
                        = {-# SCC "RegAlloc" #-}
                          initUs usLive
                          $ Color.regAlloc
                                dflags
                                alloc_regs
553
                                (mkUniqSet [0 .. maxSpillSlots ncgImpl])
554 555 556 557 558
                                withLiveness

                -- dump out what happened during register allocation
                dumpIfSet_dyn dflags
                        Opt_D_dump_asm_regalloc "Registers allocated"
559
                        (vcat $ map (pprNatCmmDecl ncgImpl) alloced)
560 561 562 563 564 565

                dumpIfSet_dyn dflags
                        Opt_D_dump_asm_regalloc_stages "Build/spill stages"
                        (vcat   $ map (\(stage, stats)
                                        -> text "# --------------------------"
                                        $$ text "#  cmm " <> int count <> text " Stage " <> int stage
Ian Lynagh's avatar
Ian Lynagh committed
566
                                        $$ ppr stats)
567 568 569
                                $ zip [0..] regAllocStats)

                let mPprStats =
570
                        if dopt Opt_D_dump_asm_stats dflags
571 572 573 574 575 576 577 578 579 580 581
                         then Just regAllocStats else Nothing

                -- force evaluation of the Maybe to avoid space leak
                mPprStats `seq` return ()

                return  ( alloced, usAlloc
                        , mPprStats
                        , Nothing)

          else do
                -- do linear register allocation
582 583 584 585 586
                let reg_alloc proc = do
                       (alloced, maybe_more_stack, ra_stats) <-
                               Linear.regAlloc dflags proc
                       case maybe_more_stack of
                         Nothing -> return ( alloced, ra_stats )
587 588 589
                         Just amount -> do
                           alloced' <- ncgAllocMoreStack ncgImpl amount alloced
                           return (alloced', ra_stats )
590

591 592 593 594
                let ((alloced, regAllocStats), usAlloc)
                        = {-# SCC "RegAlloc" #-}
                          initUs usLive
                          $ liftM unzip
595
                          $ mapM reg_alloc withLiveness
596 597 598

                dumpIfSet_dyn dflags
                        Opt_D_dump_asm_regalloc "Registers allocated"
599
                        (vcat $ map (pprNatCmmDecl ncgImpl) alloced)
600 601

                let mPprStats =
602
                        if dopt Opt_D_dump_asm_stats dflags
603 604 605 606 607 608 609 610
                         then Just (catMaybes regAllocStats) else Nothing

                -- force evaluation of the Maybe to avoid space leak
                mPprStats `seq` return ()

                return  ( alloced, usAlloc
                        , Nothing
                        , mPprStats)
611

612 613 614 615 616 617 618
        ---- x86fp_kludge.  This pass inserts ffree instructions to clear
        ---- the FPU stack on x86.  The x86 ABI requires that the FPU stack
        ---- is clear, and library functions can return odd results if it
        ---- isn't.
        ----
        ---- NB. must happen before shortcutBranches, because that
        ---- generates JXX_GBLs which we can't fix up in x86fp_kludge.
619
        let kludged = {-# SCC "x86fp_kludge" #-} ncg_x86fp_kludge ncgImpl alloced
620 621

        ---- generate jump tables
622 623
        let tabled      =
                {-# SCC "generateJumpTables" #-}
624
                generateJumpTables ncgImpl kludged
625

626 627 628 629
        ---- shortcut branches
        let shorted     =
                {-# SCC "shortcutBranches" #-}
                shortcutBranches dflags ncgImpl tabled
630

631 632 633 634
        ---- sequence blocks
        let sequenced   =
                {-# SCC "sequenceBlocks" #-}
                map (sequenceTop ncgImpl) shorted
635

636
        ---- expansion of SPARC synthetic instrs
637 638
        let expanded =
                {-# SCC "sparc_expand" #-}
639
                ncgExpandTop ncgImpl sequenced
640

641 642
        dumpIfSet_dyn dflags
                Opt_D_dump_asm_expanded "Synthetic instructions expanded"
643
                (vcat $ map (pprNatCmmDecl ncgImpl) expanded)
644

645
        return  ( usAlloc
646
                , fileIds'
647 648 649 650
                , expanded
                , lastMinuteImports ++ imports
                , ppr_raStatsColor
                , ppr_raStatsLinear)
651

652

Simon Peyton Jones's avatar
Simon Peyton Jones committed
653
x86fp_kludge :: NatCmmDecl (Alignment, CmmStatics) X86.Instr.Instr -> NatCmmDecl (Alignment, CmmStatics) X86.Instr.Instr
654
x86fp_kludge top@(CmmData _ _) = top
655 656
x86fp_kludge (CmmProc info lbl live (ListGraph code)) =
        CmmProc info lbl live (ListGraph $ X86.Instr.i386_insert_ffrees code)
657

658

659
-- | Build a doc for all the imports.
660
--
661
makeImportsDoc :: DynFlags -> [CLabel] -> SDoc
662
makeImportsDoc dflags imports
663
 = dyld_stubs imports
664
            $$
665 666 667
            -- On recent versions of Darwin, the linker supports
            -- dead-stripping of code and data on a per-symbol basis.
            -- There's a hack to make this work in PprMach.pprNatCmmDecl.
ian@well-typed.com's avatar
ian@well-typed.com committed
668
            (if platformHasSubsectionsViaSymbols platform
669
             then text ".subsections_via_symbols"
670
             else Outputable.empty)
671
            $$
672 673 674 675 676 677
                -- On recent GNU ELF systems one can mark an object file
                -- as not requiring an executable stack. If all objects
                -- linked into a program have this note then the program
                -- will not use an executable stack, which is good for
                -- security. GHC generated code does not need an executable
                -- stack so add the note in:
ian@well-typed.com's avatar
ian@well-typed.com committed
678
            (if platformHasGnuNonexecStack platform
679
             then text ".section .note.GNU-stack,\"\",@progbits"
680
             else Outputable.empty)
681
            $$
Gabor Greif's avatar
Gabor Greif committed
682
                -- And just because every other compiler does, let's stick in
683
                -- an identifier directive: .ident "GHC x.y.z"
ian@well-typed.com's avatar
ian@well-typed.com committed
684
            (if platformHasIdentDirective platform
685 686
             then let compilerIdent = text "GHC" <+> text cProjectVersion
                   in text ".ident" <+> doubleQuotes compilerIdent
687
             else Outputable.empty)
688

689
 where
ian@well-typed.com's avatar
ian@well-typed.com committed
690 691 692 693
        platform = targetPlatform dflags
        arch = platformArch platform
        os   = platformOS   platform

694 695
        -- Generate "symbol stubs" for all external symbols that might
        -- come from a dynamic library.
696 697
        dyld_stubs :: [CLabel] -> SDoc
{-      dyld_stubs imps = vcat $ map pprDyldSymbolStub $
698 699 700 701
                                    map head $ group $ sort imps-}
        -- (Hack) sometimes two Labels pretty-print the same, but have
        -- different uniques; so we compare their text versions...
        dyld_stubs imps
Ian Lynagh's avatar
Ian Lynagh committed
702
                | needImportedSymbols dflags arch os
703
                = vcat $
Ian Lynagh's avatar
Ian Lynagh committed
704 705
                        (pprGotDeclaration dflags arch os :) $
                        map ( pprImportedSymbol dflags platform . fst . head) $
706 707 708 709 710
                        groupBy (\(_,a) (_,b) -> a == b) $
                        sortBy (\(_,a) (_,b) -> compare a b) $
                        map doPpr $
                        imps
                | otherwise
711
                = Outputable.empty
712

Ian Lynagh's avatar
Ian Lynagh committed
713
        doPpr lbl = (lbl, renderWithStyle dflags (pprCLabel platform lbl) astyle)
714
        astyle = mkCodeStyle AsmStyle
715 716


717 718 719 720 721 722 723 724 725
-- -----------------------------------------------------------------------------
-- Sequencing the basic blocks

-- Cmm BasicBlocks are self-contained entities: they always end in a
-- jump, either non-local or to another basic block in the same proc.
-- In this phase, we attempt to place the basic blocks in a sequence
-- such that as many of the local jumps as possible turn into
-- fallthroughs.

726 727
sequenceTop
        :: Instruction instr
Simon Peyton Jones's avatar
Simon Peyton Jones committed
728
    => NcgImpl statics instr jumpDest -> NatCmmDecl statics instr -> NatCmmDecl statics instr
729

730
sequenceTop _       top@(CmmData _ _) = top
731
sequenceTop ncgImpl (CmmProc info lbl live (ListGraph blocks)) =
732
  CmmProc info lbl live (ListGraph $ ncgMakeFarBranches ncgImpl info $ sequenceBlocks info blocks)
733 734 735 736 737 738 739 740

-- The algorithm is very simple (and stupid): we make a graph out of
-- the blocks where there is an edge from one block to another iff the
-- first block ends by jumping to the second.  Then we topologically
-- sort this graph.  Then traverse the list: for each block, we first
-- output the block, then if it has an out edge, we move the
-- destination of the out edge to the front of the list, and continue.

741
-- FYI, the classic layout for basic blocks uses postorder DFS; this
742
-- algorithm is implemented in Hoopl.
743

744 745
sequenceBlocks
        :: Instruction instr
746 747
        => BlockEnv i
        -> [NatBasicBlock instr]
748
        -> [NatBasicBlock instr]
749

750 751 752
sequenceBlocks _ [] = []
sequenceBlocks infos (entry:blocks) =
  seqBlocks infos (mkNode entry : reverse (flattenSCCs (sccBlocks blocks)))
753 754
  -- the first block is the entry point ==> it must remain at the start.

755

756 757 758 759
sccBlocks
        :: Instruction instr
        => [NatBasicBlock instr]
        -> [SCC ( NatBasicBlock instr
760 761
                , BlockId
                , [BlockId])]
762

763
sccBlocks blocks = stronglyConnCompFromEdgedVerticesR (map mkNode blocks)
764

765 766
-- we're only interested in the last instruction of
-- the block, and only if it has a single destination.
767 768
getOutEdges
        :: Instruction instr
769
        => [instr] -> [BlockId]
770

771 772
getOutEdges instrs
        = case jumpDestsOfInstr (last instrs) of
773
                [one] -> [one]
774
                _many -> []
775

dterei's avatar
dterei committed
776 777
mkNode :: (Instruction t)
       => GenBasicBlock t
778 779 780 781 782
       -> (GenBasicBlock t, BlockId, [BlockId])
mkNode block@(BasicBlock id instrs) = (block, id, getOutEdges instrs)

seqBlocks :: BlockEnv i -> [(GenBasicBlock t1, BlockId, [BlockId])]
                        -> [GenBasicBlock t1]
783
seqBlocks infos blocks = placeNext pullable0 todo0
784
  where
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
    -- pullable: Blocks that are not yet placed
    -- todo:     Original order of blocks, to be followed if we have no good
    --           reason not to;
    --           may include blocks that have already been placed, but then
    --           these are not in pullable
    pullable0 = listToUFM [ (i,(b,n)) | (b,i,n) <- blocks ]
    todo0     = [i | (_,i,_) <- blocks ]

    placeNext _ [] = []
    placeNext pullable (i:rest)
        | Just (block, pullable') <- lookupDeleteUFM pullable i
        = place pullable' rest block
        | otherwise
        -- We already placed this block, so ignore
        = placeNext pullable rest

    place pullable todo (block,[])
                          = block : placeNext pullable todo
    place pullable todo (block@(BasicBlock id instrs),[next])
        | mapMember next infos
        = block : placeNext pullable todo
        | Just (nextBlock, pullable') <- lookupDeleteUFM pullable next
        = BasicBlock id (init instrs) : place pullable' todo nextBlock
        | otherwise
        = block : placeNext pullable todo
    place _ _ (_,tooManyNextNodes)
        = pprPanic "seqBlocks" (ppr tooManyNextNodes)


lookupDeleteUFM :: Uniquable key => UniqFM elt -> key -> Maybe (elt, UniqFM elt)
lookupDeleteUFM m k = do -- Maybe monad
    v <- lookupUFM m k
    return (v, delFromUFM m k)
818

819 820 821 822 823 824
-- -----------------------------------------------------------------------------
-- Generate jump tables

-- Analyzes all native code and generates data sections for all jump
-- table instructions.
generateJumpTables
825 826 827
        :: NcgImpl statics instr jumpDest
        -> [NatCmmDecl statics instr] -> [NatCmmDecl statics instr]
generateJumpTables ncgImpl xs = concatMap f xs
828
    where f p@(CmmProc _ _ _ (ListGraph xs)) = p : concatMap g xs
829
          f p = [p]
830
          g (BasicBlock _ xs) = catMaybes (map (generateJumpTableForInstr ncgImpl) xs)
831

832 833 834
-- -----------------------------------------------------------------------------
-- Shortcut branches

835
shortcutBranches
836
        :: DynFlags
837
    -> NcgImpl statics instr jumpDest
838 839
        -> [NatCmmDecl statics instr]
        -> [NatCmmDecl statics instr]
840

841
shortcutBranches dflags ncgImpl tops
842
  | optLevel dflags < 1 = tops    -- only with -O or higher
843
  | otherwise           = map (apply_mapping ncgImpl mapping) tops'
844
  where
845
    (tops', mappings) = mapAndUnzip (build_mapping ncgImpl) tops
846 847
    mapping = foldr plusUFM emptyUFM mappings

848
build_mapping :: NcgImpl statics instr jumpDest
849 850
              -> GenCmmDecl d (BlockEnv t) (ListGraph instr)
              -> (GenCmmDecl d (BlockEnv t) (ListGraph instr), UniqFM jumpDest)