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