[project @ 2005-04-11 08:52:29 by simonmar]
[ghc-hetmet.git] / ghc / compiler / codeGen / CgUtils.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Code generator utilities; mostly monadic
4 --
5 -- (c) The University of Glasgow 2004
6 --
7 -----------------------------------------------------------------------------
8
9 module CgUtils (
10         addIdReps,
11         cgLit,
12         emitDataLits, emitRODataLits, emitIf, emitIfThenElse,
13         emitRtsCall, emitRtsCallWithVols, emitRtsCallWithResult,
14         assignTemp, newTemp,
15         emitSimultaneously,
16         emitSwitch, emitLitSwitch,
17         tagToClosure,
18
19         cmmAndWord, cmmOrWord, cmmNegate, cmmEqWord, cmmNeWord,
20         cmmOffsetExprW, cmmOffsetExprB,
21         cmmRegOffW, cmmRegOffB,
22         cmmLabelOffW, cmmLabelOffB,
23         cmmOffsetW, cmmOffsetB,
24         cmmOffsetLitW, cmmOffsetLitB,
25         cmmLoadIndexW,
26
27         addToMem, addToMemE,
28         mkWordCLit,
29         mkStringCLit,
30         packHalfWordsCLit,
31         blankWord
32   ) where
33
34 #include "HsVersions.h"
35
36 import CgMonad
37 import TyCon            ( TyCon, tyConName )
38 import Id               ( Id )
39 import Constants        ( wORD_SIZE )
40 import SMRep            ( CgRep, StgWord, hALF_WORD_SIZE_IN_BITS, ByteOff,
41                           WordOff, idCgRep )
42 import PprCmm           ( {- instances -} )
43 import Cmm
44 import CLabel
45 import CmmUtils
46 import MachOp           ( MachRep(..), wordRep, MachOp(..),  MachHint(..),
47                           mo_wordOr, mo_wordAnd, mo_wordNe, mo_wordEq,
48                           mo_wordULt, mo_wordUGt, mo_wordUGe, machRepByteWidth )
49 import ForeignCall      ( CCallConv(..) )
50 import Literal          ( Literal(..) )
51 import CLabel           ( CLabel, mkStringLitLabel )
52 import Digraph          ( SCC(..), stronglyConnComp )
53 import ListSetOps       ( assocDefault )
54 import Util             ( filterOut, sortLe )
55 import DynFlags ( DynFlags(..), HscTarget(..) )
56 import FastString       ( LitString, FastString, unpackFS )
57 import Outputable
58
59 import Char             ( ord )
60 import DATA_BITS
61 import Maybe            ( isNothing )
62
63 -------------------------------------------------------------------------
64 --
65 --      Random small functions
66 --
67 -------------------------------------------------------------------------
68
69 addIdReps :: [Id] -> [(CgRep, Id)]
70 addIdReps ids = [(idCgRep id, id) | id <- ids]
71
72 -------------------------------------------------------------------------
73 --
74 --      Literals
75 --
76 -------------------------------------------------------------------------
77
78 cgLit :: Literal -> FCode CmmLit
79 cgLit (MachStr s) = mkStringCLit (unpackFS s)
80 cgLit other_lit   = return (mkSimpleLit other_lit)
81
82 mkSimpleLit :: Literal -> CmmLit
83 mkSimpleLit (MachChar   c)    = CmmInt (fromIntegral (ord c)) wordRep
84 mkSimpleLit MachNullAddr      = zeroCLit
85 mkSimpleLit (MachInt i)       = CmmInt i wordRep
86 mkSimpleLit (MachInt64 i)     = CmmInt i I64
87 mkSimpleLit (MachWord i)      = CmmInt i wordRep
88 mkSimpleLit (MachWord64 i)    = CmmInt i I64
89 mkSimpleLit (MachFloat r)     = CmmFloat r F32
90 mkSimpleLit (MachDouble r)    = CmmFloat r F64
91 mkSimpleLit (MachLabel fs ms) = CmmLabel (mkForeignLabel fs ms is_dyn)
92                               where
93                                 is_dyn = False  -- ToDo: fix me
94         
95 mkLtOp :: Literal -> MachOp
96 -- On signed literals we must do a signed comparison
97 mkLtOp (MachInt _)    = MO_S_Lt wordRep
98 mkLtOp (MachFloat _)  = MO_S_Lt F32
99 mkLtOp (MachDouble _) = MO_S_Lt F64
100 mkLtOp lit            = MO_U_Lt (cmmLitRep (mkSimpleLit lit))
101
102
103 ---------------------------------------------------
104 --
105 --      Cmm data type functions
106 --
107 ---------------------------------------------------
108
109 -----------------------
110 -- The "B" variants take byte offsets
111 cmmRegOffB :: CmmReg -> ByteOff -> CmmExpr
112 cmmRegOffB = cmmRegOff
113
114 cmmOffsetB :: CmmExpr -> ByteOff -> CmmExpr
115 cmmOffsetB = cmmOffset
116
117 cmmOffsetExprB :: CmmExpr -> CmmExpr -> CmmExpr
118 cmmOffsetExprB = cmmOffsetExpr
119
120 cmmLabelOffB :: CLabel -> ByteOff -> CmmLit
121 cmmLabelOffB = cmmLabelOff
122
123 cmmOffsetLitB :: CmmLit -> ByteOff -> CmmLit
124 cmmOffsetLitB = cmmOffsetLit
125
126 -----------------------
127 -- The "W" variants take word offsets
128 cmmOffsetExprW :: CmmExpr -> CmmExpr -> CmmExpr
129 -- The second arg is a *word* offset; need to change it to bytes
130 cmmOffsetExprW e (CmmLit (CmmInt n _)) = cmmOffsetW e (fromInteger n)
131 cmmOffsetExprW e wd_off = cmmIndexExpr wordRep e wd_off
132
133 cmmOffsetW :: CmmExpr -> WordOff -> CmmExpr
134 cmmOffsetW e n = cmmOffsetB e (wORD_SIZE * n)
135
136 cmmRegOffW :: CmmReg -> WordOff -> CmmExpr
137 cmmRegOffW reg wd_off = cmmRegOffB reg (wd_off * wORD_SIZE)
138
139 cmmOffsetLitW :: CmmLit -> WordOff -> CmmLit
140 cmmOffsetLitW lit wd_off = cmmOffsetLitB lit (wORD_SIZE * wd_off)
141
142 cmmLabelOffW :: CLabel -> WordOff -> CmmLit
143 cmmLabelOffW lbl wd_off = cmmLabelOffB lbl (wORD_SIZE * wd_off)
144
145 cmmLoadIndexW :: CmmExpr -> Int -> CmmExpr
146 cmmLoadIndexW base off
147   = CmmLoad (cmmOffsetW base off) wordRep
148
149 -----------------------
150 cmmNeWord, cmmEqWord, cmmOrWord, cmmAndWord :: CmmExpr -> CmmExpr -> CmmExpr
151 cmmOrWord  e1 e2 = CmmMachOp mo_wordOr  [e1, e2]
152 cmmAndWord e1 e2 = CmmMachOp mo_wordAnd [e1, e2]
153 cmmNeWord  e1 e2 = CmmMachOp mo_wordNe  [e1, e2]
154 cmmEqWord  e1 e2 = CmmMachOp mo_wordEq  [e1, e2]
155 cmmULtWord e1 e2 = CmmMachOp mo_wordULt [e1, e2]
156 cmmUGeWord e1 e2 = CmmMachOp mo_wordUGe [e1, e2]
157 cmmUGtWord e1 e2 = CmmMachOp mo_wordUGt [e1, e2]
158
159 cmmNegate :: CmmExpr -> CmmExpr
160 cmmNegate (CmmLit (CmmInt n rep)) = CmmLit (CmmInt (-n) rep)
161 cmmNegate e                       = CmmMachOp (MO_S_Neg (cmmExprRep e)) [e]
162
163 blankWord :: CmmStatic
164 blankWord = CmmUninitialised wORD_SIZE
165
166 -----------------------
167 --      Making literals
168
169 mkWordCLit :: StgWord -> CmmLit
170 mkWordCLit wd = CmmInt (fromIntegral wd) wordRep
171
172 packHalfWordsCLit :: (Integral a, Integral b) => a -> b -> CmmLit
173 -- Make a single word literal in which the lower_half_word is
174 -- at the lower address, and the upper_half_word is at the 
175 -- higher address
176 -- ToDo: consider using half-word lits instead
177 --       but be careful: that's vulnerable when reversed
178 packHalfWordsCLit lower_half_word upper_half_word
179 #ifdef WORDS_BIGENDIAN
180    = mkWordCLit ((fromIntegral lower_half_word `shiftL` hALF_WORD_SIZE_IN_BITS)
181                  .|. fromIntegral upper_half_word)
182 #else 
183    = mkWordCLit ((fromIntegral lower_half_word) 
184                  .|. (fromIntegral upper_half_word `shiftL` hALF_WORD_SIZE_IN_BITS))
185 #endif
186
187 --------------------------------------------------------------------------
188 --
189 -- Incrementing a memory location
190 --
191 --------------------------------------------------------------------------
192
193 addToMem :: MachRep     -- rep of the counter
194          -> CmmExpr     -- Address
195          -> Int         -- What to add (a word)
196          -> CmmStmt
197 addToMem rep ptr n = addToMemE rep ptr (CmmLit (CmmInt (toInteger n) rep))
198
199 addToMemE :: MachRep    -- rep of the counter
200           -> CmmExpr    -- Address
201           -> CmmExpr    -- What to add (a word-typed expression)
202           -> CmmStmt
203 addToMemE rep ptr n
204   = CmmStore ptr (CmmMachOp (MO_Add rep) [CmmLoad ptr rep, n])
205
206 -------------------------------------------------------------------------
207 --
208 --      Converting a closure tag to a closure for enumeration types
209 --      (this is the implementation of tagToEnum#).
210 --
211 -------------------------------------------------------------------------
212
213 tagToClosure :: DynFlags -> TyCon -> CmmExpr -> CmmExpr
214 tagToClosure dflags tycon tag
215   = CmmLoad (cmmOffsetExprW closure_tbl tag) wordRep
216   where closure_tbl = CmmLit (CmmLabel lbl)
217         lbl = mkClosureTableLabel dflags (tyConName tycon)
218
219 -------------------------------------------------------------------------
220 --
221 --      Conditionals and rts calls
222 --
223 -------------------------------------------------------------------------
224
225 emitIf :: CmmExpr       -- Boolean
226        -> Code          -- Then part
227        -> Code          
228 -- Emit (if e then x)
229 -- ToDo: reverse the condition to avoid the extra branch instruction if possible
230 -- (some conditionals aren't reversible. eg. floating point comparisons cannot
231 -- be inverted because there exist some values for which both comparisons
232 -- return False, such as NaN.)
233 emitIf cond then_part
234   = do { then_id <- newLabelC
235        ; join_id <- newLabelC
236        ; stmtC (CmmCondBranch cond then_id)
237        ; stmtC (CmmBranch join_id)
238        ; labelC then_id
239        ; then_part
240        ; labelC join_id
241        }
242
243 emitIfThenElse :: CmmExpr       -- Boolean
244                 -> Code         -- Then part
245                 -> Code         -- Else part
246                 -> Code         
247 -- Emit (if e then x else y)
248 emitIfThenElse cond then_part else_part
249   = do { then_id <- newLabelC
250        ; else_id <- newLabelC
251        ; join_id <- newLabelC
252        ; stmtC (CmmCondBranch cond then_id)
253        ; else_part
254        ; stmtC (CmmBranch join_id)
255        ; labelC then_id
256        ; then_part
257        ; labelC join_id
258        }
259
260 emitRtsCall :: LitString -> [(CmmExpr,MachHint)] -> Code
261 emitRtsCall fun args = emitRtsCall' [] fun args Nothing
262    -- The 'Nothing' says "save all global registers"
263
264 emitRtsCallWithVols :: LitString -> [(CmmExpr,MachHint)] -> [GlobalReg] -> Code
265 emitRtsCallWithVols fun args vols
266    = emitRtsCall' [] fun args (Just vols)
267
268 emitRtsCallWithResult :: CmmReg -> MachHint -> LitString
269         -> [(CmmExpr,MachHint)] -> Code
270 emitRtsCallWithResult res hint fun args
271    = emitRtsCall' [(res,hint)] fun args Nothing
272
273 -- Make a call to an RTS C procedure
274 emitRtsCall'
275    :: [(CmmReg,MachHint)]
276    -> LitString
277    -> [(CmmExpr,MachHint)]
278    -> Maybe [GlobalReg]
279    -> Code
280 emitRtsCall' res fun args vols = stmtC (CmmCall target res args vols)
281   where
282     target   = CmmForeignCall fun_expr CCallConv
283     fun_expr = mkLblExpr (mkRtsCodeLabel fun)
284
285
286 -------------------------------------------------------------------------
287 --
288 --      Strings gnerate a top-level data block
289 --
290 -------------------------------------------------------------------------
291
292 emitDataLits :: CLabel -> [CmmLit] -> Code
293 -- Emit a data-segment data block
294 emitDataLits lbl lits
295   = emitData Data (CmmDataLabel lbl : map CmmStaticLit lits)
296
297 emitRODataLits :: CLabel -> [CmmLit] -> Code
298 -- Emit a read-only data block
299 emitRODataLits lbl lits
300   = emitData section (CmmDataLabel lbl : map CmmStaticLit lits)
301   where section | any needsRelocation lits = RelocatableReadOnlyData
302                 | otherwise                = ReadOnlyData
303         needsRelocation (CmmLabel _)      = True
304         needsRelocation (CmmLabelOff _ _) = True
305         needsRelocation _                 = False
306
307 mkStringCLit :: String -> FCode CmmLit
308 -- Make a global definition for the string,
309 -- and return its label
310 mkStringCLit str 
311   = do  { uniq <- newUnique
312         ; let lbl = mkStringLitLabel uniq
313         ; emitData ReadOnlyData [CmmDataLabel lbl, CmmString str]
314         ; return (CmmLabel lbl) }
315
316 -------------------------------------------------------------------------
317 --
318 --      Assigning expressions to temporaries
319 --
320 -------------------------------------------------------------------------
321
322 assignTemp :: CmmExpr -> FCode CmmExpr
323 -- For a non-trivial expression, e, create a local
324 -- variable and assign the expression to it
325 assignTemp e 
326   | isTrivialCmmExpr e = return e
327   | otherwise          = do { reg <- newTemp (cmmExprRep e)
328                             ; stmtC (CmmAssign reg e)
329                             ; return (CmmReg reg) }
330
331
332 newTemp :: MachRep -> FCode CmmReg
333 newTemp rep = do { uniq <- newUnique; return (CmmLocal (LocalReg uniq rep)) }
334
335
336 -------------------------------------------------------------------------
337 --
338 --      Building case analysis
339 --
340 -------------------------------------------------------------------------
341
342 emitSwitch
343         :: CmmExpr                -- Tag to switch on
344         -> [(ConTagZ, CgStmts)]   -- Tagged branches
345         -> Maybe CgStmts          -- Default branch (if any)
346         -> ConTagZ -> ConTagZ     -- Min and Max possible values; behaviour
347                                   --    outside this range is undefined
348         -> Code
349
350 -- ONLY A DEFAULT BRANCH: no case analysis to do
351 emitSwitch tag_expr [] (Just stmts) _ _
352   = emitCgStmts stmts
353
354 -- Right, off we go
355 emitSwitch tag_expr branches mb_deflt lo_tag hi_tag
356   =     -- Just sort the branches before calling mk_sritch
357     do  { mb_deflt_id <-
358                 case mb_deflt of
359                   Nothing    -> return Nothing
360                   Just stmts -> do id <- forkCgStmts stmts; return (Just id)
361
362         ; dflags <- getDynFlags
363         ; let via_C | HscC <- hscTarget dflags = True
364                     | otherwise                = False
365
366         ; stmts <- mk_switch tag_expr (sortLe le branches) 
367                         mb_deflt_id lo_tag hi_tag via_C
368         ; emitCgStmts stmts
369         }
370   where
371     (t1,_) `le` (t2,_) = t1 <= t2
372
373
374 mk_switch :: CmmExpr -> [(ConTagZ, CgStmts)]
375           -> Maybe BlockId -> ConTagZ -> ConTagZ -> Bool
376           -> FCode CgStmts
377
378 -- SINGLETON TAG RANGE: no case analysis to do
379 mk_switch tag_expr [(tag,stmts)] _ lo_tag hi_tag via_C
380   | lo_tag == hi_tag
381   = ASSERT( tag == lo_tag )
382     return stmts
383
384 -- SINGLETON BRANCH, NO DEFUALT: no case analysis to do
385 mk_switch tag_expr [(tag,stmts)] Nothing lo_tag hi_tag via_C
386   = return stmts
387         -- The simplifier might have eliminated a case
388         --       so we may have e.g. case xs of 
389         --                               [] -> e
390         -- In that situation we can be sure the (:) case 
391         -- can't happen, so no need to test
392
393 -- SINGLETON BRANCH: one equality check to do
394 mk_switch tag_expr [(tag,stmts)] (Just deflt) lo_tag hi_tag via_C
395   = return (CmmCondBranch cond deflt `consCgStmt` stmts)
396   where
397     cond  =  cmmNeWord tag_expr (CmmLit (mkIntCLit tag))
398         -- We have lo_tag < hi_tag, but there's only one branch, 
399         -- so there must be a default
400
401 -- ToDo: we might want to check for the two branch case, where one of
402 -- the branches is the tag 0, because comparing '== 0' is likely to be
403 -- more efficient than other kinds of comparison.
404
405 -- DENSE TAG RANGE: use a switch statment.
406 --
407 -- We also use a switch uncoditionally when compiling via C, because
408 -- this will get emitted as a C switch statement and the C compiler
409 -- should do a good job of optimising it.  Also, older GCC versions
410 -- (2.95 in particular) have problems compiling the complicated
411 -- if-trees generated by this code, so compiling to a switch every
412 -- time works around that problem.
413 --
414 mk_switch tag_expr branches mb_deflt lo_tag hi_tag via_C
415   | use_switch || via_C         -- Use a switch
416   = do  { branch_ids <- mapM forkCgStmts (map snd branches)
417         ; let 
418                 tagged_blk_ids = zip (map fst branches) (map Just branch_ids)
419
420                 find_branch :: ConTagZ -> Maybe BlockId
421                 find_branch i = assocDefault mb_deflt tagged_blk_ids i
422
423                 -- NB. we have eliminated impossible branches at
424                 -- either end of the range (see below), so the first
425                 -- tag of a real branch is real_lo_tag (not lo_tag).
426                 arms = [ find_branch i | i <- [real_lo_tag..real_hi_tag]]
427
428                 switch_stmt = CmmSwitch (cmmOffset tag_expr (- real_lo_tag)) arms
429
430         ; ASSERT(not (all isNothing arms)) 
431           return (oneCgStmt switch_stmt)
432         }
433
434   -- if we can knock off a bunch of default cases with one if, then do so
435   | Just deflt <- mb_deflt, (lowest_branch - lo_tag) >= n_branches
436   = do { (assign_tag, tag_expr') <- assignTemp' tag_expr
437        ; let cond = cmmULtWord tag_expr' (CmmLit (mkIntCLit lowest_branch))
438              branch = CmmCondBranch cond deflt
439        ; stmts <- mk_switch tag_expr' branches mb_deflt 
440                         lowest_branch hi_tag via_C
441        ; return (assign_tag `consCgStmt` (branch `consCgStmt` stmts))
442        }
443
444   | Just deflt <- mb_deflt, (hi_tag - highest_branch) >= n_branches
445   = do { (assign_tag, tag_expr') <- assignTemp' tag_expr
446        ; let cond = cmmUGtWord tag_expr' (CmmLit (mkIntCLit highest_branch))
447              branch = CmmCondBranch cond deflt
448        ; stmts <- mk_switch tag_expr' branches mb_deflt 
449                         lo_tag highest_branch via_C
450        ; return (assign_tag `consCgStmt` (branch `consCgStmt` stmts))
451        }
452
453   | otherwise   -- Use an if-tree
454   = do  { (assign_tag, tag_expr') <- assignTemp' tag_expr
455                 -- To avoid duplication
456         ; lo_stmts <- mk_switch tag_expr' lo_branches mb_deflt 
457                                 lo_tag (mid_tag-1) via_C
458         ; hi_stmts <- mk_switch tag_expr' hi_branches mb_deflt 
459                                 mid_tag hi_tag via_C
460         ; hi_id <- forkCgStmts hi_stmts
461         ; let cond = cmmUGeWord tag_expr' (CmmLit (mkIntCLit mid_tag))
462               branch_stmt = CmmCondBranch cond hi_id
463         ; return (assign_tag `consCgStmt` (branch_stmt `consCgStmt` lo_stmts)) 
464         }
465         -- we test (e >= mid_tag) rather than (e < mid_tag), because
466         -- the former works better when e is a comparison, and there
467         -- are two tags 0 & 1 (mid_tag == 1).  In this case, the code
468         -- generator can reduce the condition to e itself without
469         -- having to reverse the sense of the comparison: comparisons
470         -- can't always be easily reversed (eg. floating
471         -- pt. comparisons).
472   where
473     use_switch   = {- pprTrace "mk_switch" (
474                         ppr tag_expr <+> text "n_tags:" <+> int n_tags <+>
475                         text "n_branches:" <+> int n_branches <+>
476                         text "lo_tag: " <+> int lo_tag <+>
477                         text "hi_tag: " <+> int hi_tag <+>
478                         text "real_lo_tag: " <+> int real_lo_tag <+>
479                         text "real_hi_tag: " <+> int real_hi_tag) $ -}
480                    ASSERT( n_branches > 1 && n_tags > 1 ) 
481                    n_tags > 2 && (small || dense)
482                  -- a 2-branch switch always turns into an if.
483     small        = n_tags <= 4
484     dense        = n_branches > (n_tags `div` 2)
485     exhaustive   = n_tags == n_branches
486     n_branches   = length branches
487     
488     -- ignore default slots at each end of the range if there's 
489     -- no default branch defined.
490     lowest_branch  = fst (head branches)
491     highest_branch = fst (last branches)
492
493     real_lo_tag
494         | isNothing mb_deflt = lowest_branch
495         | otherwise          = lo_tag
496
497     real_hi_tag
498         | isNothing mb_deflt = highest_branch
499         | otherwise          = hi_tag
500
501     n_tags = real_hi_tag - real_lo_tag + 1
502
503         -- INVARIANT: Provided hi_tag > lo_tag (which is true)
504         --      lo_tag <= mid_tag < hi_tag
505         --      lo_branches have tags <  mid_tag
506         --      hi_branches have tags >= mid_tag
507
508     (mid_tag,_) = branches !! (n_branches `div` 2)
509         -- 2 branches => n_branches `div` 2 = 1
510         --            => branches !! 1 give the *second* tag
511         -- There are always at least 2 branches here
512
513     (lo_branches, hi_branches) = span is_lo branches
514     is_lo (t,_) = t < mid_tag
515
516
517 assignTemp' e
518   | isTrivialCmmExpr e = return (CmmNop, e)
519   | otherwise          = do { reg <- newTemp (cmmExprRep e)
520                             ; return (CmmAssign reg e, CmmReg reg) }
521
522
523 emitLitSwitch :: CmmExpr                        -- Tag to switch on
524               -> [(Literal, CgStmts)]           -- Tagged branches
525               -> CgStmts                        -- Default branch (always)
526               -> Code                           -- Emit the code
527 -- Used for general literals, whose size might not be a word, 
528 -- where there is always a default case, and where we don't know
529 -- the range of values for certain.  For simplicity we always generate a tree.
530 --
531 -- ToDo: for integers we could do better here, perhaps by generalising
532 -- mk_switch and using that.  --SDM 15/09/2004
533 emitLitSwitch scrut [] deflt 
534   = emitCgStmts deflt
535 emitLitSwitch scrut branches deflt_blk
536   = do  { scrut' <- assignTemp scrut
537         ; deflt_blk_id <- forkCgStmts deflt_blk
538         ; blk <- mk_lit_switch scrut' deflt_blk_id (sortLe le branches)
539         ; emitCgStmts blk }
540   where
541     le (t1,_) (t2,_) = t1 <= t2
542
543 mk_lit_switch :: CmmExpr -> BlockId 
544               -> [(Literal,CgStmts)]
545               -> FCode CgStmts
546 mk_lit_switch scrut deflt_blk_id [(lit,blk)] 
547   = return (consCgStmt if_stmt blk)
548   where
549     cmm_lit = mkSimpleLit lit
550     rep     = cmmLitRep cmm_lit
551     cond    = CmmMachOp (MO_Ne rep) [scrut, CmmLit cmm_lit]
552     if_stmt = CmmCondBranch cond deflt_blk_id
553
554 mk_lit_switch scrut deflt_blk_id branches
555   = do  { hi_blk <- mk_lit_switch scrut deflt_blk_id hi_branches
556         ; lo_blk <- mk_lit_switch scrut deflt_blk_id lo_branches
557         ; lo_blk_id <- forkCgStmts lo_blk
558         ; let if_stmt = CmmCondBranch cond lo_blk_id
559         ; return (if_stmt `consCgStmt` hi_blk) }
560   where
561     n_branches = length branches
562     (mid_lit,_) = branches !! (n_branches `div` 2)
563         -- See notes above re mid_tag
564
565     (lo_branches, hi_branches) = span is_lo branches
566     is_lo (t,_) = t < mid_lit
567
568     cond    = CmmMachOp (mkLtOp mid_lit) 
569                         [scrut, CmmLit (mkSimpleLit mid_lit)]
570
571 -------------------------------------------------------------------------
572 --
573 --      Simultaneous assignment
574 --
575 -------------------------------------------------------------------------
576
577
578 emitSimultaneously :: CmmStmts -> Code
579 -- Emit code to perform the assignments in the
580 -- input simultaneously, using temporary variables when necessary.
581 --
582 -- The Stmts must be:
583 --      CmmNop, CmmComment, CmmAssign, CmmStore
584 -- and nothing else
585
586
587 -- We use the strongly-connected component algorithm, in which
588 --      * the vertices are the statements
589 --      * an edge goes from s1 to s2 iff
590 --              s1 assigns to something s2 uses
591 --        that is, if s1 should *follow* s2 in the final order
592
593 type CVertex = (Int, CmmStmt)   -- Give each vertex a unique number,
594                                 -- for fast comparison
595
596 emitSimultaneously stmts
597   = codeOnly $
598     case filterOut isNopStmt (stmtList stmts) of 
599         -- Remove no-ops
600       []        -> nopC
601       [stmt]    -> stmtC stmt   -- It's often just one stmt
602       stmt_list -> doSimultaneously1 (zip [(1::Int)..] stmt_list)
603
604 doSimultaneously1 :: [CVertex] -> Code
605 doSimultaneously1 vertices
606   = let
607         edges = [ (vertex, key1, edges_from stmt1)
608                 | vertex@(key1, stmt1) <- vertices
609                 ]
610         edges_from stmt1 = [ key2 | (key2, stmt2) <- vertices, 
611                                     stmt1 `mustFollow` stmt2
612                            ]
613         components = stronglyConnComp edges
614
615         -- do_components deal with one strongly-connected component
616         -- Not cyclic, or singleton?  Just do it
617         do_component (AcyclicSCC (n,stmt))  = stmtC stmt
618         do_component (CyclicSCC [(n,stmt)]) = stmtC stmt
619
620                 -- Cyclic?  Then go via temporaries.  Pick one to
621                 -- break the loop and try again with the rest.
622         do_component (CyclicSCC ((n,first_stmt) : rest))
623           = do  { from_temp <- go_via_temp first_stmt
624                 ; doSimultaneously1 rest
625                 ; stmtC from_temp }
626
627         go_via_temp (CmmAssign dest src)
628           = do  { tmp <- newTemp (cmmRegRep dest)
629                 ; stmtC (CmmAssign tmp src)
630                 ; return (CmmAssign dest (CmmReg tmp)) }
631         go_via_temp (CmmStore dest src)
632           = do  { tmp <- newTemp (cmmExprRep src)
633                 ; stmtC (CmmAssign tmp src)
634                 ; return (CmmStore dest (CmmReg tmp)) }
635     in
636     mapCs do_component components
637
638 mustFollow :: CmmStmt -> CmmStmt -> Bool
639 CmmAssign reg _  `mustFollow` stmt = anySrc (reg `regUsedIn`) stmt
640 CmmStore loc e   `mustFollow` stmt = anySrc (locUsedIn loc (cmmExprRep e)) stmt
641 CmmNop           `mustFollow` stmt = False
642 CmmComment _     `mustFollow` stmt = False
643
644
645 anySrc :: (CmmExpr -> Bool) -> CmmStmt -> Bool
646 -- True if the fn is true of any input of the stmt
647 anySrc p (CmmAssign _ e)    = p e
648 anySrc p (CmmStore e1 e2)   = p e1 || p e2      -- Might be used in either side
649 anySrc p (CmmComment _)     = False
650 anySrc p CmmNop             = False
651 anySrc p other              = True              -- Conservative
652
653 regUsedIn :: CmmReg -> CmmExpr -> Bool
654 reg `regUsedIn` CmmLit _         = False
655 reg `regUsedIn` CmmLoad e  _     = reg `regUsedIn` e
656 reg `regUsedIn` CmmReg reg'      = reg == reg'
657 reg `regUsedIn` CmmRegOff reg' _ = reg == reg'
658 reg `regUsedIn` CmmMachOp _ es   = any (reg `regUsedIn`) es
659
660 locUsedIn :: CmmExpr -> MachRep -> CmmExpr -> Bool
661 -- (locUsedIn a r e) checks whether writing to r[a] could affect the value of
662 -- 'e'.  Returns True if it's not sure.
663 locUsedIn loc rep (CmmLit _)         = False
664 locUsedIn loc rep (CmmLoad e ld_rep) = possiblySameLoc loc rep e ld_rep
665 locUsedIn loc rep (CmmReg reg')      = False
666 locUsedIn loc rep (CmmRegOff reg' _) = False
667 locUsedIn loc rep (CmmMachOp _ es)   = any (locUsedIn loc rep) es
668
669 possiblySameLoc :: CmmExpr -> MachRep -> CmmExpr -> MachRep -> Bool
670 -- Assumes that distinct registers (eg Hp, Sp) do not 
671 -- point to the same location, nor any offset thereof.
672 possiblySameLoc (CmmReg r1)       rep1 (CmmReg r2)      rep2  = r1==r2
673 possiblySameLoc (CmmReg r1)       rep1 (CmmRegOff r2 0) rep2  = r1==r2
674 possiblySameLoc (CmmRegOff r1 0)  rep1 (CmmReg r2)      rep2  = r1==r2
675 possiblySameLoc (CmmRegOff r1 start1) rep1 (CmmRegOff r2 start2) rep2 
676   = r1==r2 && end1 > start2 && end2 > start1
677   where
678     end1 = start1 + machRepByteWidth rep1
679     end2 = start2 + machRepByteWidth rep2
680
681 possiblySameLoc l1 rep1 (CmmLit _) rep2 = False
682 possiblySameLoc l1 rep1 l2         rep2 = True  -- Conservative