[project @ 2004-08-25 10:37:06 by simonmar]
[ghc-hetmet.git] / ghc / compiler / cmm / PprC.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
4 --
5 -- (c) The University of Glasgow 2004
6 --
7 -----------------------------------------------------------------------------
8
9 --
10 -- Print Cmm as real C, for -fvia-C
11 --
12 -- This is simpler than the old PprAbsC, because Cmm is "macro-expanded"
13 -- relative to the old AbstractC, and many oddities/decorations have
14 -- disappeared from the data type.
15 --
16
17 -- ToDo: save/restore volatile registers around calls.
18
19 module PprC (
20         writeCs,
21         pprStringInCStyle 
22   ) where
23
24 #include "HsVersions.h"
25
26 -- Cmm stuff
27 import Cmm
28 import CLabel
29 import MachOp
30 import ForeignCall
31
32 -- Utils
33 import Unique           ( getUnique )
34 import UniqSet
35 import FiniteMap
36 import UniqFM           ( eltsUFM )
37 import FastString
38 import Outputable
39 import Constants
40 import CmdLineOpts      ( opt_EnsureSplittableC )
41
42 -- The rest
43 import Data.List        ( intersperse, groupBy )
44 import Data.Bits        ( shiftR )
45 import Char             ( ord, chr )
46 import IO               ( Handle )
47 import DATA_BITS
48
49 #ifdef DEBUG
50 import PprCmm           () -- instances only
51 -- import Debug.Trace
52 #endif
53
54 #if __GLASGOW_HASKELL__ >= 504
55 import Data.Array.ST
56 #endif
57 import MONAD_ST
58
59 -- --------------------------------------------------------------------------
60 -- Top level
61
62 pprCs :: [Cmm] -> SDoc
63 pprCs cmms = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
64
65 writeCs :: Handle -> [Cmm] -> IO ()
66 writeCs handle cmms = printForUser handle alwaysQualify (pprCs cmms)
67                         -- ToDo: should be printForC
68
69 split_marker
70   | opt_EnsureSplittableC = ptext SLIT("__STG_SPLIT_MARKER")
71   | otherwise             = empty
72
73 -- --------------------------------------------------------------------------
74 -- Now do some real work
75 --
76 -- for fun, we could call cmmToCmm over the tops...
77 --
78
79 pprC :: Cmm -> SDoc
80 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
81
82 --
83 -- top level procs
84 -- 
85 pprTop :: CmmTop -> SDoc
86 pprTop (CmmProc info clbl _params blocks) =
87     (if not (null info)
88         then pprWordArray (entryLblToInfoLbl clbl) info
89         else empty) $$
90     (case blocks of
91         [] -> empty
92          -- the first block doesn't get a label:
93         (BasicBlock _ stmts : rest) -> vcat [
94            text "",
95            extern_decls,
96            (if (externallyVisibleCLabel clbl)
97                     then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
98            nest 8 temp_decls,
99            nest 8 mkFB_,
100            nest 8 (vcat (map pprStmt stmts)) $$
101               vcat (map pprBBlock rest),
102            nest 8 mkFE_,
103            rbrace ]
104     )
105   where
106         (temp_decls, extern_decls) = pprTempAndExternDecls blocks 
107
108
109 -- Chunks of static data.
110
111 -- We only handle (a) arrays of word-sized things and (b) strings.
112
113 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) = 
114   hcat [
115     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
116     ptext SLIT("[] = "), pprStringInCStyle str, semi
117   ]
118
119 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) = 
120   hcat [
121     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
122     brackets (int size), semi
123   ]
124
125 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) = 
126   pprDataExterns lits $$
127   pprWordArray lbl lits  
128
129 -- these shouldn't appear?
130 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
131
132
133 -- --------------------------------------------------------------------------
134 -- BasicBlocks are self-contained entities: they always end in a jump.
135 --
136 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
137 -- as many jumps as possible into fall throughs.
138 --
139
140 pprBBlock :: CmmBasicBlock -> SDoc
141 pprBBlock (BasicBlock lbl stmts) = 
142     if null stmts then
143         pprTrace "pprC.pprBBlock: curious empty code block for" 
144                         (pprBlockId lbl) empty
145     else 
146         nest 4 (pprBlockId lbl <> colon) $$
147         nest 8 (vcat (map pprStmt stmts))
148
149 -- --------------------------------------------------------------------------
150 -- Info tables. Just arrays of words. 
151 -- See codeGen/ClosureInfo, and nativeGen/PprMach
152
153 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
154 pprWordArray lbl ds
155   = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
156          , space, pprCLabel lbl, ptext SLIT("[] = {") ] 
157     $$ nest 8 (commafy (pprStatics ds))
158     $$ ptext SLIT("};")
159
160 --
161 -- has to be static, if it isn't globally visible
162 --
163 pprLocalness :: CLabel -> SDoc
164 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
165                  | otherwise = empty
166
167 -- --------------------------------------------------------------------------
168 -- Statements.
169 --
170
171 pprStmt :: CmmStmt -> SDoc
172
173 pprStmt stmt = case stmt of
174     CmmNop       -> empty
175     CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
176
177     CmmAssign dest src -> pprAssign dest src
178
179     CmmStore  dest src
180         | rep == I64
181         -> ptext SLIT("ASSIGN_Word64") <> 
182                 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
183
184         | otherwise
185         -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
186         where
187           rep = cmmExprRep src
188
189     CmmCall (CmmForeignCall fn cconv) results args volatile -> 
190         -- Controversial: leave this out for now.
191         -- pprUndef fn $$
192
193         pprCall ppr_fn cconv results args volatile
194         where
195         ppr_fn = case fn of
196                    CmmLit (CmmLabel lbl) -> pprCLabel lbl
197                    _other -> parens (cCast (pprCFunType results args) fn)
198                         -- for a dynamic call, cast the expression to
199                         -- a function of the right type (we hope).
200
201         -- we #undef a function before calling it: the FFI is supposed to be
202         -- an interface specifically to C, not to C+CPP.  For one thing, this
203         -- makes the via-C route more compatible with the NCG.  If macros
204         -- are being used for optimisation, then inline functions are probably
205         -- better anyway.
206         pprUndef (CmmLit (CmmLabel lbl)) = 
207            ptext SLIT("#undef") <+> pprCLabel lbl
208         pprUndef _ = empty
209
210     CmmCall (CmmPrim op) results args volatile -> 
211         pprCall ppr_fn CCallConv results args volatile
212         where
213         ppr_fn = pprCallishMachOp_for_C op
214
215     CmmBranch ident          -> pprBranch ident
216     CmmCondBranch expr ident -> pprCondBranch expr ident
217     CmmJump lbl _params      -> mkJMP_(pprExpr lbl) <> semi
218     CmmSwitch arg ids        -> pprSwitch arg ids
219
220 pprCFunType :: [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
221 pprCFunType ress args = 
222   res_type ress <> parens (char '*') <> parens (commafy (map arg_type args))
223   where
224         res_type [] = ptext SLIT("void")
225         res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
226
227         arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
228
229 -- ---------------------------------------------------------------------
230 -- unconditional branches
231 pprBranch :: BlockId -> SDoc
232 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
233
234
235 -- ---------------------------------------------------------------------
236 -- conditional branches to local labels
237 pprCondBranch :: CmmExpr -> BlockId -> SDoc
238 pprCondBranch expr ident 
239         = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
240                         ptext SLIT("goto") , (pprBlockId ident) <> semi ]
241
242
243 -- ---------------------------------------------------------------------
244 -- a local table branch
245 --
246 -- we find the fall-through cases
247 --
248 -- N.B. we remove Nothing's from the list of branches, as they are
249 -- 'undefined'. However, they may be defined one day, so we better
250 -- document this behaviour.
251 --
252 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
253 pprSwitch e maybe_ids 
254   = let pairs  = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
255         pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
256     in 
257         (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
258                 4 (vcat ( map caseify pairs2 )))
259         $$ rbrace
260
261   where
262     sndEq (_,x) (_,y) = x == y
263
264     -- fall through case
265     caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
266         where 
267         do_fallthrough ix =
268                  hsep [ ptext SLIT("case") , pprHexVal ix <> colon ,
269                         ptext SLIT("/* fall through */") ]
270
271         final_branch ix = 
272                 hsep [ ptext SLIT("case") , pprHexVal ix <> colon ,
273                        ptext SLIT("goto") , (pprBlockId ident) <> semi ]
274
275 -- ---------------------------------------------------------------------
276 -- Expressions.
277 --
278
279 -- C Types: the invariant is that the C expression generated by
280 --
281 --      pprExpr e
282 --
283 -- has a type in C which is also given by
284 --
285 --      machRepCType (cmmExprRep e)
286 --
287 -- (similar invariants apply to the rest of the pretty printer).
288
289 pprExpr :: CmmExpr -> SDoc
290 pprExpr e = case e of
291     CmmLit lit -> pprLit lit
292
293     CmmLoad e I64
294         -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
295
296     CmmLoad (CmmReg r) rep 
297         | isPtrReg r && rep == wordRep
298         -> char '*' <> pprAsPtrReg r
299
300     CmmLoad (CmmRegOff r 0) rep 
301         | isPtrReg r && rep == wordRep
302         -> char '*' <> pprAsPtrReg r
303
304     CmmLoad (CmmRegOff r off) rep
305         | isPtrReg r && rep == wordRep 
306         -- ToDo: check that the offset is a word multiple?
307         -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
308
309     CmmLoad expr rep ->
310         -- the general case:
311         char '*' <> parens (cCast (machRepPtrCType rep) expr)
312
313     CmmReg reg      -> pprCastReg reg
314     CmmRegOff reg 0 -> pprCastReg reg
315
316     CmmRegOff reg i
317         | i >  0    -> pprRegOff (char '+') i
318         | otherwise -> pprRegOff (char '-') (-i)
319       where
320         pprRegOff op i' = pprCastReg reg <> op <> int i'
321
322     CmmMachOp mop args -> pprMachOpApp mop args
323
324 pprExpr1 :: CmmExpr -> SDoc
325 pprExpr1 (CmmLit lit)     = pprLit1 lit
326 pprExpr1 e@(CmmReg _reg)  = pprExpr e
327 pprExpr1 other            = parens (pprExpr other)
328
329 -- --------------------------------------------------------------------------
330 -- MachOp applications
331
332 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
333
334 pprMachOpApp op args
335   | isMulMayOfloOp op
336   = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
337   where isMulMayOfloOp (MO_U_MulMayOflo _) = True
338         isMulMayOfloOp (MO_S_MulMayOflo _) = True
339         isMulMayOfloOp _ = False
340
341 pprMachOpApp mop args
342  = case args of
343     -- dyadic
344     [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
345
346     -- unary
347     [x]   -> pprMachOp_for_C mop <> parens (pprArg x)
348
349     _     -> panic "PprC.pprMachOp : machop with wrong number of args"
350
351   where
352     pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
353              | otherwise    = pprExpr1 e
354
355 -- --------------------------------------------------------------------------
356 -- Literals
357
358 pprLit :: CmmLit -> SDoc
359 pprLit lit = case lit of
360     CmmInt i _rep      -> pprHexVal i
361     CmmFloat f rep     -> parens (machRepCType rep) <> (rational f)
362     CmmLabel clbl      -> mkW_ <> pprCLabel clbl
363     CmmLabelOff clbl i -> mkW_ <> pprCLabel clbl <> char '+' <> int i
364
365 pprLit1 :: CmmLit -> SDoc
366 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
367 pprLit1 lit@(CmmFloat _ _)    = parens (pprLit lit)
368 pprLit1 other = pprLit other
369
370 -- ---------------------------------------------------------------------------
371 -- Static data
372
373 pprStatics :: [CmmStatic] -> [SDoc]
374 pprStatics [] = []
375 pprStatics (CmmStaticLit (CmmFloat f F32) : rest) 
376   = pprLit1 (floatToWord f) : pprStatics rest
377 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
378   = map pprLit1 (doubleToWords f) ++ pprStatics rest
379 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
380   | machRepByteWidth I32 == wORD_SIZE
381 #ifdef WORDS_BIGENDIAN
382   = pprStatics (CmmStaticLit (CmmInt q I32) : 
383                 CmmStaticLit (CmmInt r I32) : rest)
384 #else
385   = pprStatics (CmmStaticLit (CmmInt r I32) : 
386                 CmmStaticLit (CmmInt q I32) : rest)
387 #endif
388   where r = i .&. 0xffffffff
389         q = i `shiftR` 32
390 pprStatics (CmmStaticLit lit : rest)
391   = pprLit1 lit : pprStatics rest
392 pprStatics (other : rest)
393   = pprPanic "pprWord" (pprStatic other)
394
395 pprStatic :: CmmStatic -> SDoc
396 pprStatic s = case s of
397
398     CmmStaticLit lit   -> nest 4 (pprLit lit)
399     CmmAlign i         -> nest 4 (ptext SLIT("/* align */") <+> int i)
400     CmmDataLabel clbl  -> pprCLabel clbl <> colon
401     CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
402
403     -- these should be inlined, like the old .hc
404     CmmString s'       -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
405
406
407 -- ---------------------------------------------------------------------------
408 -- Block Ids
409
410 pprBlockId :: BlockId -> SDoc
411 pprBlockId b = char '_' <> ppr (getUnique b)
412
413 -- --------------------------------------------------------------------------
414 -- Print a MachOp in a way suitable for emitting via C.
415 --
416
417 pprMachOp_for_C :: MachOp -> SDoc
418
419 pprMachOp_for_C mop = case mop of 
420
421         -- Integer operations
422         MO_Add          _ -> char '+'
423         MO_Sub          _ -> char '-'
424         MO_Eq           _ -> ptext SLIT("==")
425         MO_Ne           _ -> ptext SLIT("!=")
426         MO_Mul          _ -> char '*'
427
428         MO_S_Quot       _ -> char '/'
429         MO_S_Rem        _ -> char '%'
430         MO_S_Neg        _ -> char '-'
431
432         MO_U_Quot       _ -> char '/'
433         MO_U_Rem        _ -> char '%'
434
435         -- Signed comparisons (floating-point comparisons also use these)
436         -- & Unsigned comparisons
437         MO_S_Ge         _ -> ptext SLIT(">=")
438         MO_S_Le         _ -> ptext SLIT("<=")
439         MO_S_Gt         _ -> char '>'
440         MO_S_Lt         _ -> char '<'
441
442         MO_U_Ge         _ -> ptext SLIT(">=")
443         MO_U_Le         _ -> ptext SLIT("<=")
444         MO_U_Gt         _ -> char '>'
445         MO_U_Lt         _ -> char '<'
446
447         -- Bitwise operations.  Not all of these may be supported at all
448         -- sizes, and only integral MachReps are valid.
449         MO_And          _ -> char '&'
450         MO_Or           _ -> char '|'
451         MO_Xor          _ -> char '^'
452         MO_Not          _ -> char '~'
453         MO_Shl          _ -> ptext SLIT("<<")
454         MO_U_Shr        _ -> ptext SLIT(">>") -- unsigned shift right
455         MO_S_Shr        _ -> ptext SLIT(">>") -- signed shift right
456
457 -- Conversions.  Some of these will be NOPs.
458 -- Floating-point conversions use the signed variant.
459 -- We won't know to generate (void*) casts here, but maybe from
460 -- context elsewhere
461
462 -- noop casts
463         MO_U_Conv I8 I8     -> empty
464         MO_U_Conv I16 I16   -> empty
465         MO_U_Conv I32 I32   -> empty
466         MO_U_Conv I64 I64   -> empty
467         MO_U_Conv I128 I128 -> empty
468         MO_S_Conv I8 I8     -> empty
469         MO_S_Conv I16 I16   -> empty
470         MO_S_Conv I32 I32   -> empty
471         MO_S_Conv I64 I64   -> empty
472         MO_S_Conv I128 I128 -> empty
473
474         MO_U_Conv _from to  -> parens (machRepCType to)
475         MO_S_Conv _from to  -> parens (machRepSignedCType to)
476
477         _ -> panic "PprC.pprMachOp_for_C: unknown machop"
478
479 signedOp :: MachOp -> Bool
480 signedOp (MO_S_Quot _)   = True
481 signedOp (MO_S_Rem  _)   = True
482 signedOp (MO_S_Neg  _)   = True
483 signedOp (MO_S_Ge   _)   = True
484 signedOp (MO_S_Le   _)   = True
485 signedOp (MO_S_Gt   _)   = True
486 signedOp (MO_S_Lt   _)   = True
487 signedOp (MO_S_Shr  _)   = True
488 signedOp (MO_S_Conv _ _) = True
489 signedOp _ = False
490
491 -- ---------------------------------------------------------------------
492 -- tend to be implemented by foreign calls
493
494 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
495
496 pprCallishMachOp_for_C mop 
497     = case mop of
498         MO_F64_Pwr  -> ptext SLIT("pow")
499         MO_F64_Sin  -> ptext SLIT("sin")
500         MO_F64_Cos  -> ptext SLIT("cos")
501         MO_F64_Tan  -> ptext SLIT("tan")
502         MO_F64_Sinh -> ptext SLIT("sinh")
503         MO_F64_Cosh -> ptext SLIT("cosh")
504         MO_F64_Tanh -> ptext SLIT("tanh")
505         MO_F64_Asin -> ptext SLIT("asin")
506         MO_F64_Acos -> ptext SLIT("asin")
507         MO_F64_Atan -> ptext SLIT("atan")
508         MO_F64_Log  -> ptext SLIT("log")
509         MO_F64_Exp  -> ptext SLIT("exp")
510         MO_F64_Sqrt -> ptext SLIT("sqrt")
511         MO_F32_Pwr  -> ptext SLIT("pow")
512         MO_F32_Sin  -> ptext SLIT("sin")
513         MO_F32_Cos  -> ptext SLIT("cos")
514         MO_F32_Tan  -> ptext SLIT("tan")
515         MO_F32_Sinh -> ptext SLIT("sinh")
516         MO_F32_Cosh -> ptext SLIT("cosh")
517         MO_F32_Tanh -> ptext SLIT("tanh")
518         MO_F32_Asin -> ptext SLIT("asin")
519         MO_F32_Acos -> ptext SLIT("acos")
520         MO_F32_Atan -> ptext SLIT("atan")
521         MO_F32_Log  -> ptext SLIT("log")
522         MO_F32_Exp  -> ptext SLIT("exp")
523         MO_F32_Sqrt -> ptext SLIT("sqrt")
524
525 -- ---------------------------------------------------------------------
526 -- Useful #defines
527 --
528
529 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
530
531 mkJMP_ i = ptext SLIT("JMP_") <> parens i
532 mkFN_  i = ptext SLIT("FN_")  <> parens i -- externally visible function
533 mkIF_  i = ptext SLIT("IF_")  <> parens i -- locally visible
534
535
536 mkFB_, mkFE_ :: SDoc
537 mkFB_ = ptext SLIT("FB_") -- function code begin
538 mkFE_ = ptext SLIT("FE_") -- function code end
539
540 -- from includes/Stg.h
541 --
542 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
543
544 mkC_  = ptext SLIT("(C_)")        -- StgChar
545 mkW_  = ptext SLIT("(W_)")        -- StgWord
546 mkP_  = ptext SLIT("(P_)")        -- StgWord*
547 mkPP_ = ptext SLIT("(PP_)")       -- P_*
548 mkI_  = ptext SLIT("(I_)")        -- StgInt
549 mkA_  = ptext SLIT("(A_)")        -- StgAddr
550 mkD_  = ptext SLIT("(D_)")        -- const StgWord*
551 mkF_  = ptext SLIT("(F_)")        -- StgFunPtr
552 mkB_  = ptext SLIT("(B_)")        -- StgByteArray
553 mkL_  = ptext SLIT("(L_)")        -- StgClosurePtr
554
555 mkLI_ = ptext SLIT("(LI_)")       -- StgInt64
556 mkLW_ = ptext SLIT("(LW_)")       -- StgWord64
557
558
559 -- ---------------------------------------------------------------------
560 --
561 -- Assignments
562 --
563 -- Generating assignments is what we're all about, here
564 --
565 pprAssign :: CmmReg -> CmmExpr -> SDoc
566
567 -- dest is a reg, rhs is a reg
568 pprAssign r1 (CmmReg r2)
569    | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
570    || isPtrReg r1 && isPtrReg r2
571    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
572
573 -- dest is a reg, rhs is a CmmRegOff
574 pprAssign r1 (CmmRegOff r2 off)
575    | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
576    || isPtrReg r1 && isPtrReg r2
577    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
578   where
579         off1 | isPtrReg r2 = off `shiftR` wordShift
580              | otherwise   = off
581
582         (op,off') | off >= 0  = (char '+', off1)
583                   | otherwise = (char '-', -off1)
584
585 -- dest is a reg, rhs is anything.
586 -- We can't cast the lvalue, so we have to cast the rhs if necessary.  Casting
587 -- the lvalue elicits a warning from new GCC versions (3.4+).
588 pprAssign r1 r2
589   | isPtrReg r1
590   = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
591   | Just ty <- strangeRegType r1
592   = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
593   | otherwise
594   = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
595
596 -- ---------------------------------------------------------------------
597 -- Registers
598
599 pprCastReg reg
600    | isStrangeTypeReg reg = mkW_ <> pprReg reg
601    | otherwise            = pprReg reg
602
603 -- True if the register has type StgPtr in C, otherwise it has an
604 -- integer type.  We need to take care with pointer arithmetic on registers
605 -- with type StgPtr.
606 isPtrReg :: CmmReg -> Bool
607 isPtrReg (CmmLocal _) = False
608 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
609
610 isPtrGlobalReg :: GlobalReg -> Bool
611 isPtrGlobalReg (VanillaReg n)   = True
612 isPtrGlobalReg Sp               = True
613 isPtrGlobalReg Hp               = True
614 isPtrGlobalReg HpLim            = True
615 isPtrGlobalReg SpLim            = True
616 isPtrGlobalReg _                = False
617
618 -- True if in C this register doesn't have the type given by 
619 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
620 isStrangeTypeReg :: CmmReg -> Bool
621 isStrangeTypeReg (CmmLocal _)   = False
622 isStrangeTypeReg (CmmGlobal g)  = isStrangeTypeGlobal g
623
624 isStrangeTypeGlobal :: GlobalReg -> Bool
625 isStrangeTypeGlobal CurrentTSO          = True
626 isStrangeTypeGlobal CurrentNursery      = True
627 isStrangeTypeGlobal r                   = isPtrGlobalReg r
628
629 strangeRegType :: CmmReg -> Maybe SDoc
630 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
631 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
632 strangeRegType _ = Nothing
633
634 -- pprReg just prints the register name.
635 --
636 pprReg :: CmmReg -> SDoc
637 pprReg r = case r of
638         CmmLocal  local  -> pprLocalReg local
639         CmmGlobal global -> pprGlobalReg global
640                 
641 pprAsPtrReg :: CmmReg -> SDoc
642 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
643 pprAsPtrReg other_reg = pprReg other_reg
644
645 pprGlobalReg :: GlobalReg -> SDoc
646 pprGlobalReg gr = case gr of
647     VanillaReg n   -> char 'R' <> int n  <> ptext SLIT(".w")
648     FloatReg   n   -> char 'F' <> int n
649     DoubleReg  n   -> char 'D' <> int n
650     LongReg    n   -> char 'L' <> int n
651     Sp             -> ptext SLIT("Sp")
652     SpLim          -> ptext SLIT("SpLim")
653     Hp             -> ptext SLIT("Hp")
654     HpLim          -> ptext SLIT("HpLim")
655     CurrentTSO     -> ptext SLIT("CurrentTSO")
656     CurrentNursery -> ptext SLIT("CurrentNursery")
657     HpAlloc        -> ptext SLIT("HpAlloc")
658     BaseReg        -> ptext SLIT("BaseReg")
659     GCEnter1       -> ptext SLIT("stg_gc_enter_1")
660     GCFun          -> ptext SLIT("stg_gc_fun")
661
662 pprLocalReg :: LocalReg -> SDoc
663 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
664
665 -- -----------------------------------------------------------------------------
666 -- Foreign Calls
667
668 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
669         -> Maybe [GlobalReg] -> SDoc
670
671 pprCall ppr_fn cconv results args vols
672   | not (is_cish cconv)
673   = panic "pprForeignCall: unknown calling convention"
674
675   | otherwise
676   = save vols $$
677     ptext SLIT("CALLER_SAVE_SYSTEM") $$
678     hcat [ ppr_results results, ppr_fn, 
679            parens (commafy (map pprArg args)), semi ] $$
680     ptext SLIT("CALLER_RESTORE_SYSTEM") $$
681     restore vols
682   where 
683      ppr_results []     = empty
684      ppr_results [(one,hint)] 
685          = pprExpr (CmmReg one) <> ptext SLIT(" = ")
686                  <> pprUnHint hint (cmmRegRep one)
687      ppr_results _other = panic "pprCall: multiple results"
688
689      pprArg (expr, PtrHint)
690         = cCast (ptext SLIT("void *")) expr
691         -- see comment by machRepHintCType below
692      pprArg (expr, SignedHint)
693         = cCast (machRepSignedCType (cmmExprRep expr)) expr
694      pprArg (expr, _other)
695         = pprExpr expr
696
697      pprUnHint PtrHint    rep = parens (machRepCType rep)
698      pprUnHint SignedHint rep = parens (machRepCType rep)
699      pprUnHint _          _   = empty
700
701      save    = save_restore SLIT("CALLER_SAVE")
702      restore = save_restore SLIT("CALLER_RESTORE")
703
704         -- Nothing says "I don't know what's live; save everything"
705         -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
706      save_restore txt Nothing     = ptext txt <> ptext SLIT("_USER")
707      save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
708         where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
709
710 pprGlobalRegName :: GlobalReg -> SDoc
711 pprGlobalRegName gr = case gr of
712     VanillaReg n   -> char 'R' <> int n  -- without the .w suffix
713     _              -> pprGlobalReg gr
714
715 is_cish CCallConv   = True
716 is_cish StdCallConv = True
717 is_cish _           = False
718
719 -- ---------------------------------------------------------------------
720 -- Find and print local and external declarations for a list of
721 -- Cmm statements.
722 -- 
723 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
724 pprTempAndExternDecls stmts 
725   = (vcat (map pprTempDecl (eltsUFM temps)), 
726      vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
727   where (temps, lbls) = runTE (mapM_ te_BB stmts)
728
729 pprDataExterns :: [CmmStatic] -> SDoc
730 pprDataExterns statics
731   = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
732   where (_, lbls) = runTE (mapM_ te_Static statics)
733
734 pprTempDecl :: LocalReg -> SDoc
735 pprTempDecl l@(LocalReg _uniq rep)
736   = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
737
738 pprExternDecl :: Bool -> CLabel -> SDoc
739 pprExternDecl in_srt lbl
740   -- do not print anything for "known external" things
741   | not (needsCDecl lbl) = empty
742   | otherwise               = 
743         hcat [ visibility, label_type (labelType lbl), 
744                lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
745  where
746   dyn_wrapper d
747     | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
748     | otherwise                  = d
749
750   label_type CodeLabel = ptext SLIT("F_")
751   label_type DataLabel = ptext SLIT("I_")
752
753   visibility
754      | externallyVisibleCLabel lbl = char 'E'
755      | otherwise                   = char 'I'
756
757
758 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
759 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
760
761 instance Monad TE where
762    TE m >>= k  = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
763    return a    = TE $ \s -> (a, s)
764
765 te_lbl :: CLabel -> TE ()
766 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
767
768 te_temp :: LocalReg -> TE ()
769 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
770
771 runTE :: TE () -> TEState
772 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
773
774 te_Static :: CmmStatic -> TE ()
775 te_Static (CmmStaticLit lit) = te_Lit lit
776 te_Static _ = return ()
777
778 te_BB :: CmmBasicBlock -> TE ()
779 te_BB (BasicBlock _ ss)         = mapM_ te_Stmt ss
780
781 te_Lit :: CmmLit -> TE ()
782 te_Lit (CmmLabel l) = te_lbl l
783 te_Lit _ = return ()
784
785 te_Stmt :: CmmStmt -> TE ()
786 te_Stmt (CmmAssign r e)         = te_Reg r >> te_Expr e
787 te_Stmt (CmmStore l r)          = te_Expr l >> te_Expr r
788 te_Stmt (CmmCall _ rs es _)     = mapM_ (te_Reg.fst) rs >>
789                                   mapM_ (te_Expr.fst) es
790 te_Stmt (CmmCondBranch e _)     = te_Expr e
791 te_Stmt (CmmSwitch e _)         = te_Expr e
792 te_Stmt (CmmJump e _)           = te_Expr e
793 te_Stmt _                       = return ()
794
795 te_Expr :: CmmExpr -> TE ()
796 te_Expr (CmmLit lit)            = te_Lit lit
797 te_Expr (CmmReg r)              = te_Reg r
798 te_Expr (CmmLoad e _)           = te_Expr e
799 te_Expr (CmmMachOp _ es)        = mapM_ te_Expr es
800 te_Expr (CmmRegOff r _)         = te_Reg r
801 te_Expr _                       = return ()
802
803 te_Reg :: CmmReg -> TE ()
804 te_Reg (CmmLocal l) = te_temp l
805 te_Reg _            = return ()
806
807
808 -- ---------------------------------------------------------------------
809 -- C types for MachReps
810
811 cCast :: SDoc -> CmmExpr -> SDoc
812 cCast ty expr = parens ty <> pprExpr1 expr
813
814 -- This is for finding the types of foreign call arguments.  For a pointer
815 -- argument, we always cast the argument to (void *), to avoid warnings from
816 -- the C compiler.
817 machRepHintCType :: MachRep -> MachHint -> SDoc
818 machRepHintCType rep PtrHint    = ptext SLIT("void *")
819 machRepHintCType rep SignedHint = machRepSignedCType rep
820 machRepHintCType rep _other     = machRepCType rep
821
822 machRepPtrCType :: MachRep -> SDoc
823 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
824                   | otherwise    = machRepCType r <> char '*'
825
826 machRepCType :: MachRep -> SDoc
827 machRepCType r | r == wordRep = ptext SLIT("W_")
828                | otherwise    = sized_type
829   where sized_type = case r of
830                         I8      -> ptext SLIT("StgWord8")
831                         I16     -> ptext SLIT("StgWord16")
832                         I32     -> ptext SLIT("StgWord32")
833                         I64     -> ptext SLIT("StgWord64")
834                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
835                         F64     -> ptext SLIT("StgDouble")
836                         _  -> panic "machRepCType"
837
838 machRepSignedCType :: MachRep -> SDoc
839 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
840                      | otherwise    = sized_type
841   where sized_type = case r of
842                         I8      -> ptext SLIT("StgInt8")
843                         I16     -> ptext SLIT("StgInt16")
844                         I32     -> ptext SLIT("StgInt32")
845                         I64     -> ptext SLIT("StgInt64")
846                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
847                         F64     -> ptext SLIT("StgDouble")
848                         _ -> panic "machRepCType"
849
850 -- ---------------------------------------------------------------------
851 -- print strings as valid C strings
852
853 -- Assumes it contains only characters '\0'..'\xFF'!
854 pprFSInCStyle :: FastString -> SDoc
855 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
856
857 pprStringInCStyle :: String -> SDoc
858 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
859
860 charToC :: Char -> String
861 charToC '\"' = "\\\""
862 charToC '\'' = "\\\'"
863 charToC '\\' = "\\\\"
864 charToC c | c >= ' ' && c <= '~' = [c]
865           | c > '\xFF' = panic ("charToC "++show c)
866           | otherwise = ['\\',
867                          chr (ord '0' + ord c `div` 64),
868                          chr (ord '0' + ord c `div` 8 `mod` 8),
869                          chr (ord '0' + ord c         `mod` 8)]
870
871
872 -- ---------------------------------------------------------------------------
873 -- Initialising static objects with floating-point numbers.  We can't
874 -- just emit the floating point number, because C will cast it to an int
875 -- by rounding it.  We want the actual bit-representation of the float.
876
877 -- This is a hack to turn the floating point numbers into ints that we
878 -- can safely initialise to static locations.
879
880 big_doubles 
881   | machRepByteWidth F64 == 2 * wORD_SIZE  = True
882   | machRepByteWidth F64 == wORD_SIZE      = False
883   | otherwise = panic "big_doubles"
884
885 #if __GLASGOW_HASKELL__ >= 504
886 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
887 newFloatArray = newArray_
888
889 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
890 newDoubleArray = newArray_
891
892 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
893 castFloatToIntArray = castSTUArray
894
895 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
896 castDoubleToIntArray = castSTUArray
897
898 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
899 writeFloatArray = writeArray
900
901 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
902 writeDoubleArray = writeArray
903
904 readIntArray :: STUArray s Int Int -> Int -> ST s Int
905 readIntArray = readArray
906
907 #else
908
909 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
910 castFloatToIntArray = return
911
912 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
913 castDoubleToIntArray = return
914
915 #endif
916
917 -- floats are always 1 word
918 floatToWord :: Rational -> CmmLit
919 floatToWord r
920   = runST (do
921         arr <- newFloatArray ((0::Int),0)
922         writeFloatArray arr 0 (fromRational r)
923         arr' <- castFloatToIntArray arr
924         i <- readIntArray arr' 0
925         return (CmmInt (toInteger i) wordRep)
926     )
927
928 doubleToWords :: Rational -> [CmmLit]
929 doubleToWords r
930   | big_doubles                         -- doubles are 2 words
931   = runST (do
932         arr <- newDoubleArray ((0::Int),1)
933         writeDoubleArray arr 0 (fromRational r)
934         arr' <- castDoubleToIntArray arr
935         i1 <- readIntArray arr' 0
936         i2 <- readIntArray arr' 1
937         return [ CmmInt (toInteger i1) wordRep
938                , CmmInt (toInteger i2) wordRep
939                ]
940     )
941   | otherwise                           -- doubles are 1 word
942   = runST (do
943         arr <- newDoubleArray ((0::Int),0)
944         writeDoubleArray arr 0 (fromRational r)
945         arr' <- castDoubleToIntArray arr
946         i <- readIntArray arr' 0
947         return [ CmmInt (toInteger i) wordRep ]
948     )
949
950 -- ---------------------------------------------------------------------------
951 -- Utils
952
953 wordShift :: Int
954 wordShift = machRepLogWidth wordRep
955
956 commafy :: [SDoc] -> SDoc
957 commafy xs = hsep $ punctuate comma xs
958
959 -- Print in C hex format: 0x13fa
960 pprHexVal :: Integer -> SDoc
961 pprHexVal 0 = ptext SLIT("0x0")
962 pprHexVal w 
963   | w < 0     = parens (char '-' <> ptext SLIT("0x") <> go (-w))
964   | otherwise = ptext SLIT("0x") <> go w
965   where
966       go 0 = empty
967       go w' = go q <> dig
968            where
969              (q,r) = w' `quotRem` 16
970              dig | r < 10    = char (chr (fromInteger r + ord '0'))
971                  | otherwise = char (chr (fromInteger r - 10 + ord 'a'))
972