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