a9aba407deb2ff4ca590d9d617ebd2a299cc2c11
[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 pprDataExterns info $$
89              pprWordArray (entryLblToInfoLbl clbl) info
90         else empty) $$
91     (case blocks of
92         [] -> empty
93          -- the first block doesn't get a label:
94         (BasicBlock _ stmts : rest) -> vcat [
95            text "",
96            extern_decls,
97            (if (externallyVisibleCLabel clbl)
98                     then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
99            nest 8 temp_decls,
100            nest 8 mkFB_,
101            nest 8 (vcat (map pprStmt stmts)) $$
102               vcat (map pprBBlock rest),
103            nest 8 mkFE_,
104            rbrace ]
105     )
106   where
107         (temp_decls, extern_decls) = pprTempAndExternDecls blocks 
108
109
110 -- Chunks of static data.
111
112 -- We only handle (a) arrays of word-sized things and (b) strings.
113
114 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) = 
115   hcat [
116     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
117     ptext SLIT("[] = "), pprStringInCStyle str, semi
118   ]
119
120 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) = 
121   hcat [
122     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
123     brackets (int size), semi
124   ]
125
126 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) = 
127   pprDataExterns lits $$
128   pprWordArray lbl lits  
129
130 -- these shouldn't appear?
131 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
132
133
134 -- --------------------------------------------------------------------------
135 -- BasicBlocks are self-contained entities: they always end in a jump.
136 --
137 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
138 -- as many jumps as possible into fall throughs.
139 --
140
141 pprBBlock :: CmmBasicBlock -> SDoc
142 pprBBlock (BasicBlock lbl stmts) = 
143     if null stmts then
144         pprTrace "pprC.pprBBlock: curious empty code block for" 
145                         (pprBlockId lbl) empty
146     else 
147         nest 4 (pprBlockId lbl <> colon) $$
148         nest 8 (vcat (map pprStmt stmts))
149
150 -- --------------------------------------------------------------------------
151 -- Info tables. Just arrays of words. 
152 -- See codeGen/ClosureInfo, and nativeGen/PprMach
153
154 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
155 pprWordArray lbl ds
156   = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
157          , space, pprCLabel lbl, ptext SLIT("[] = {") ] 
158     $$ nest 8 (commafy (pprStatics ds))
159     $$ ptext SLIT("};")
160
161 --
162 -- has to be static, if it isn't globally visible
163 --
164 pprLocalness :: CLabel -> SDoc
165 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
166                  | otherwise = empty
167
168 -- --------------------------------------------------------------------------
169 -- Statements.
170 --
171
172 pprStmt :: CmmStmt -> SDoc
173
174 pprStmt stmt = case stmt of
175     CmmNop       -> empty
176     CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
177
178     CmmAssign dest src -> pprAssign dest src
179
180     CmmStore  dest src
181         | rep == I64
182         -> ptext SLIT("ASSIGN_Word64") <> 
183                 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
184
185         | otherwise
186         -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
187         where
188           rep = cmmExprRep src
189
190     CmmCall (CmmForeignCall fn cconv) results args volatile -> 
191         -- Controversial: leave this out for now.
192         -- pprUndef fn $$
193
194         pprCall ppr_fn cconv results args volatile
195         where
196         ppr_fn = case fn of
197                    CmmLit (CmmLabel lbl) -> pprCLabel lbl
198                    _other -> parens (cCast (pprCFunType results args) fn)
199                         -- for a dynamic call, cast the expression to
200                         -- a function of the right type (we hope).
201
202         -- we #undef a function before calling it: the FFI is supposed to be
203         -- an interface specifically to C, not to C+CPP.  For one thing, this
204         -- makes the via-C route more compatible with the NCG.  If macros
205         -- are being used for optimisation, then inline functions are probably
206         -- better anyway.
207         pprUndef (CmmLit (CmmLabel lbl)) = 
208            ptext SLIT("#undef") <+> pprCLabel lbl
209         pprUndef _ = empty
210
211     CmmCall (CmmPrim op) results args volatile -> 
212         pprCall ppr_fn CCallConv results args volatile
213         where
214         ppr_fn = pprCallishMachOp_for_C op
215
216     CmmBranch ident          -> pprBranch ident
217     CmmCondBranch expr ident -> pprCondBranch expr ident
218     CmmJump lbl _params      -> mkJMP_(pprExpr lbl) <> semi
219     CmmSwitch arg ids        -> pprSwitch arg ids
220
221 pprCFunType :: [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
222 pprCFunType ress args = 
223   res_type ress <> parens (char '*') <> parens (commafy (map arg_type args))
224   where
225         res_type [] = ptext SLIT("void")
226         res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
227
228         arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
229
230 -- ---------------------------------------------------------------------
231 -- unconditional branches
232 pprBranch :: BlockId -> SDoc
233 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
234
235
236 -- ---------------------------------------------------------------------
237 -- conditional branches to local labels
238 pprCondBranch :: CmmExpr -> BlockId -> SDoc
239 pprCondBranch expr ident 
240         = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
241                         ptext SLIT("goto") , (pprBlockId ident) <> semi ]
242
243
244 -- ---------------------------------------------------------------------
245 -- a local table branch
246 --
247 -- we find the fall-through cases
248 --
249 -- N.B. we remove Nothing's from the list of branches, as they are
250 -- 'undefined'. However, they may be defined one day, so we better
251 -- document this behaviour.
252 --
253 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
254 pprSwitch e maybe_ids 
255   = let pairs  = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
256         pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
257     in 
258         (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
259                 4 (vcat ( map caseify pairs2 )))
260         $$ rbrace
261
262   where
263     sndEq (_,x) (_,y) = x == y
264
265     -- fall through case
266     caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
267         where 
268         do_fallthrough ix =
269                  hsep [ ptext SLIT("case") , pprHexVal ix <> colon ,
270                         ptext SLIT("/* fall through */") ]
271
272         final_branch ix = 
273                 hsep [ ptext SLIT("case") , pprHexVal ix <> colon ,
274                        ptext SLIT("goto") , (pprBlockId ident) <> semi ]
275
276 -- ---------------------------------------------------------------------
277 -- Expressions.
278 --
279
280 -- C Types: the invariant is that the C expression generated by
281 --
282 --      pprExpr e
283 --
284 -- has a type in C which is also given by
285 --
286 --      machRepCType (cmmExprRep e)
287 --
288 -- (similar invariants apply to the rest of the pretty printer).
289
290 pprExpr :: CmmExpr -> SDoc
291 pprExpr e = case e of
292     CmmLit lit -> pprLit lit
293
294     CmmLoad e I64
295         -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
296
297     CmmLoad (CmmReg r) rep 
298         | isPtrReg r && rep == wordRep
299         -> char '*' <> pprAsPtrReg r
300
301     CmmLoad (CmmRegOff r 0) rep 
302         | isPtrReg r && rep == wordRep
303         -> char '*' <> pprAsPtrReg r
304
305     CmmLoad (CmmRegOff r off) rep
306         | isPtrReg r && rep == wordRep 
307         -- ToDo: check that the offset is a word multiple?
308         -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
309
310     CmmLoad expr rep ->
311         -- the general case:
312         char '*' <> parens (cCast (machRepPtrCType rep) expr)
313
314     CmmReg reg      -> pprCastReg reg
315     CmmRegOff reg 0 -> pprCastReg reg
316
317     CmmRegOff reg i
318         | i >  0    -> pprRegOff (char '+') i
319         | otherwise -> pprRegOff (char '-') (-i)
320       where
321         pprRegOff op i' = pprCastReg reg <> op <> int i'
322
323     CmmMachOp mop args -> pprMachOpApp mop args
324
325 pprExpr1 :: CmmExpr -> SDoc
326 pprExpr1 (CmmLit lit)     = pprLit1 lit
327 pprExpr1 e@(CmmReg _reg)  = pprExpr e
328 pprExpr1 other            = parens (pprExpr other)
329
330 -- --------------------------------------------------------------------------
331 -- MachOp applications
332
333 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
334
335 pprMachOpApp op args
336   | isMulMayOfloOp op
337   = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
338   where isMulMayOfloOp (MO_U_MulMayOflo _) = True
339         isMulMayOfloOp (MO_S_MulMayOflo _) = True
340         isMulMayOfloOp _ = False
341
342 pprMachOpApp mop args
343  = case args of
344     -- dyadic
345     [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
346
347     -- unary
348     [x]   -> pprMachOp_for_C mop <> parens (pprArg x)
349
350     _     -> panic "PprC.pprMachOp : machop with wrong number of args"
351
352   where
353     pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
354              | otherwise    = pprExpr1 e
355
356 -- --------------------------------------------------------------------------
357 -- Literals
358
359 pprLit :: CmmLit -> SDoc
360 pprLit lit = case lit of
361     CmmInt i I64 | machRepByteWidth I32 == wORD_SIZE 
362                        -> pprHexVal i <> ptext SLIT("LL")
363         -- Append an 'LL' suffix to 64-bit integers on a 32-bit
364         -- platform.  This might not be strictly necessary (the
365         -- type will always be apparent from the context), but
366         -- it avoids some warnings from gcc.
367     CmmInt i _rep      -> pprHexVal i
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("asin")
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 r                   = isPtrGlobalReg r
644
645 strangeRegType :: CmmReg -> Maybe SDoc
646 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
647 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
648 strangeRegType _ = Nothing
649
650 -- pprReg just prints the register name.
651 --
652 pprReg :: CmmReg -> SDoc
653 pprReg r = case r of
654         CmmLocal  local  -> pprLocalReg local
655         CmmGlobal global -> pprGlobalReg global
656                 
657 pprAsPtrReg :: CmmReg -> SDoc
658 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
659 pprAsPtrReg other_reg = pprReg other_reg
660
661 pprGlobalReg :: GlobalReg -> SDoc
662 pprGlobalReg gr = case gr of
663     VanillaReg n   -> char 'R' <> int n  <> ptext SLIT(".w")
664     FloatReg   n   -> char 'F' <> int n
665     DoubleReg  n   -> char 'D' <> int n
666     LongReg    n   -> char 'L' <> int n
667     Sp             -> ptext SLIT("Sp")
668     SpLim          -> ptext SLIT("SpLim")
669     Hp             -> ptext SLIT("Hp")
670     HpLim          -> ptext SLIT("HpLim")
671     CurrentTSO     -> ptext SLIT("CurrentTSO")
672     CurrentNursery -> ptext SLIT("CurrentNursery")
673     HpAlloc        -> ptext SLIT("HpAlloc")
674     BaseReg        -> ptext SLIT("BaseReg")
675     GCEnter1       -> ptext SLIT("stg_gc_enter_1")
676     GCFun          -> ptext SLIT("stg_gc_fun")
677
678 pprLocalReg :: LocalReg -> SDoc
679 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
680
681 -- -----------------------------------------------------------------------------
682 -- Foreign Calls
683
684 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
685         -> Maybe [GlobalReg] -> SDoc
686
687 pprCall ppr_fn cconv results args vols
688   | not (is_cish cconv)
689   = panic "pprForeignCall: unknown calling convention"
690
691   | otherwise
692   = save vols $$
693     ptext SLIT("CALLER_SAVE_SYSTEM") $$
694     hcat [ ppr_results results, ppr_fn, 
695            parens (commafy (map pprArg args)), semi ] $$
696     ptext SLIT("CALLER_RESTORE_SYSTEM") $$
697     restore vols
698   where 
699      ppr_results []     = empty
700      ppr_results [(one,hint)] 
701          = pprExpr (CmmReg one) <> ptext SLIT(" = ")
702                  <> pprUnHint hint (cmmRegRep one)
703      ppr_results _other = panic "pprCall: multiple results"
704
705      pprArg (expr, PtrHint)
706         = cCast (ptext SLIT("void *")) expr
707         -- see comment by machRepHintCType below
708      pprArg (expr, SignedHint)
709         = cCast (machRepSignedCType (cmmExprRep expr)) expr
710      pprArg (expr, _other)
711         = pprExpr expr
712
713      pprUnHint PtrHint    rep = parens (machRepCType rep)
714      pprUnHint SignedHint rep = parens (machRepCType rep)
715      pprUnHint _          _   = empty
716
717      save    = save_restore SLIT("CALLER_SAVE")
718      restore = save_restore SLIT("CALLER_RESTORE")
719
720         -- Nothing says "I don't know what's live; save everything"
721         -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
722      save_restore txt Nothing     = ptext txt <> ptext SLIT("_USER")
723      save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
724         where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
725
726 pprGlobalRegName :: GlobalReg -> SDoc
727 pprGlobalRegName gr = case gr of
728     VanillaReg n   -> char 'R' <> int n  -- without the .w suffix
729     _              -> pprGlobalReg gr
730
731 is_cish CCallConv   = True
732 is_cish StdCallConv = True
733 is_cish _           = False
734
735 -- ---------------------------------------------------------------------
736 -- Find and print local and external declarations for a list of
737 -- Cmm statements.
738 -- 
739 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
740 pprTempAndExternDecls stmts 
741   = (vcat (map pprTempDecl (eltsUFM temps)), 
742      vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
743   where (temps, lbls) = runTE (mapM_ te_BB stmts)
744
745 pprDataExterns :: [CmmStatic] -> SDoc
746 pprDataExterns statics
747   = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
748   where (_, lbls) = runTE (mapM_ te_Static statics)
749
750 pprTempDecl :: LocalReg -> SDoc
751 pprTempDecl l@(LocalReg _uniq rep)
752   = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
753
754 pprExternDecl :: Bool -> CLabel -> SDoc
755 pprExternDecl in_srt lbl
756   -- do not print anything for "known external" things
757   | not (needsCDecl lbl) = empty
758   | otherwise               = 
759         hcat [ visibility, label_type (labelType lbl), 
760                lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
761  where
762   dyn_wrapper d
763     | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
764     | otherwise                  = d
765
766   label_type CodeLabel = ptext SLIT("F_")
767   label_type DataLabel = ptext SLIT("I_")
768
769   visibility
770      | externallyVisibleCLabel lbl = char 'E'
771      | otherwise                   = char 'I'
772
773
774 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
775 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
776
777 instance Monad TE where
778    TE m >>= k  = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
779    return a    = TE $ \s -> (a, s)
780
781 te_lbl :: CLabel -> TE ()
782 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
783
784 te_temp :: LocalReg -> TE ()
785 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
786
787 runTE :: TE () -> TEState
788 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
789
790 te_Static :: CmmStatic -> TE ()
791 te_Static (CmmStaticLit lit) = te_Lit lit
792 te_Static _ = return ()
793
794 te_BB :: CmmBasicBlock -> TE ()
795 te_BB (BasicBlock _ ss)         = mapM_ te_Stmt ss
796
797 te_Lit :: CmmLit -> TE ()
798 te_Lit (CmmLabel l) = te_lbl l
799 te_Lit (CmmLabelOff l _) = te_lbl l
800 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
801 te_Lit _ = return ()
802
803 te_Stmt :: CmmStmt -> TE ()
804 te_Stmt (CmmAssign r e)         = te_Reg r >> te_Expr e
805 te_Stmt (CmmStore l r)          = te_Expr l >> te_Expr r
806 te_Stmt (CmmCall _ rs es _)     = mapM_ (te_Reg.fst) rs >>
807                                   mapM_ (te_Expr.fst) es
808 te_Stmt (CmmCondBranch e _)     = te_Expr e
809 te_Stmt (CmmSwitch e _)         = te_Expr e
810 te_Stmt (CmmJump e _)           = te_Expr e
811 te_Stmt _                       = return ()
812
813 te_Expr :: CmmExpr -> TE ()
814 te_Expr (CmmLit lit)            = te_Lit lit
815 te_Expr (CmmReg r)              = te_Reg r
816 te_Expr (CmmLoad e _)           = te_Expr e
817 te_Expr (CmmMachOp _ es)        = mapM_ te_Expr es
818 te_Expr (CmmRegOff r _)         = te_Reg r
819 te_Expr _                       = return ()
820
821 te_Reg :: CmmReg -> TE ()
822 te_Reg (CmmLocal l) = te_temp l
823 te_Reg _            = return ()
824
825
826 -- ---------------------------------------------------------------------
827 -- C types for MachReps
828
829 cCast :: SDoc -> CmmExpr -> SDoc
830 cCast ty expr = parens ty <> pprExpr1 expr
831
832 -- This is for finding the types of foreign call arguments.  For a pointer
833 -- argument, we always cast the argument to (void *), to avoid warnings from
834 -- the C compiler.
835 machRepHintCType :: MachRep -> MachHint -> SDoc
836 machRepHintCType rep PtrHint    = ptext SLIT("void *")
837 machRepHintCType rep SignedHint = machRepSignedCType rep
838 machRepHintCType rep _other     = machRepCType rep
839
840 machRepPtrCType :: MachRep -> SDoc
841 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
842                   | otherwise    = machRepCType r <> char '*'
843
844 machRepCType :: MachRep -> SDoc
845 machRepCType r | r == wordRep = ptext SLIT("W_")
846                | otherwise    = sized_type
847   where sized_type = case r of
848                         I8      -> ptext SLIT("StgWord8")
849                         I16     -> ptext SLIT("StgWord16")
850                         I32     -> ptext SLIT("StgWord32")
851                         I64     -> ptext SLIT("StgWord64")
852                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
853                         F64     -> ptext SLIT("StgDouble")
854                         _  -> panic "machRepCType"
855
856 machRepSignedCType :: MachRep -> SDoc
857 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
858                      | otherwise    = sized_type
859   where sized_type = case r of
860                         I8      -> ptext SLIT("StgInt8")
861                         I16     -> ptext SLIT("StgInt16")
862                         I32     -> ptext SLIT("StgInt32")
863                         I64     -> ptext SLIT("StgInt64")
864                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
865                         F64     -> ptext SLIT("StgDouble")
866                         _ -> panic "machRepCType"
867
868 -- ---------------------------------------------------------------------
869 -- print strings as valid C strings
870
871 -- Assumes it contains only characters '\0'..'\xFF'!
872 pprFSInCStyle :: FastString -> SDoc
873 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
874
875 pprStringInCStyle :: String -> SDoc
876 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
877
878 charToC :: Char -> String
879 charToC '\"' = "\\\""
880 charToC '\'' = "\\\'"
881 charToC '\\' = "\\\\"
882 charToC c | c >= ' ' && c <= '~' = [c]
883           | c > '\xFF' = panic ("charToC "++show c)
884           | otherwise = ['\\',
885                          chr (ord '0' + ord c `div` 64),
886                          chr (ord '0' + ord c `div` 8 `mod` 8),
887                          chr (ord '0' + ord c         `mod` 8)]
888
889
890 -- ---------------------------------------------------------------------------
891 -- Initialising static objects with floating-point numbers.  We can't
892 -- just emit the floating point number, because C will cast it to an int
893 -- by rounding it.  We want the actual bit-representation of the float.
894
895 -- This is a hack to turn the floating point numbers into ints that we
896 -- can safely initialise to static locations.
897
898 big_doubles 
899   | machRepByteWidth F64 == 2 * wORD_SIZE  = True
900   | machRepByteWidth F64 == wORD_SIZE      = False
901   | otherwise = panic "big_doubles"
902
903 #if __GLASGOW_HASKELL__ >= 504
904 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
905 newFloatArray = newArray_
906
907 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
908 newDoubleArray = newArray_
909
910 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
911 castFloatToIntArray = castSTUArray
912
913 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
914 castDoubleToIntArray = castSTUArray
915
916 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
917 writeFloatArray = writeArray
918
919 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
920 writeDoubleArray = writeArray
921
922 readIntArray :: STUArray s Int Int -> Int -> ST s Int
923 readIntArray = readArray
924
925 #else
926
927 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
928 castFloatToIntArray = return
929
930 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
931 castDoubleToIntArray = return
932
933 #endif
934
935 -- floats are always 1 word
936 floatToWord :: Rational -> CmmLit
937 floatToWord r
938   = runST (do
939         arr <- newFloatArray ((0::Int),0)
940         writeFloatArray arr 0 (fromRational r)
941         arr' <- castFloatToIntArray arr
942         i <- readIntArray arr' 0
943         return (CmmInt (toInteger i) wordRep)
944     )
945
946 doubleToWords :: Rational -> [CmmLit]
947 doubleToWords r
948   | big_doubles                         -- doubles are 2 words
949   = runST (do
950         arr <- newDoubleArray ((0::Int),1)
951         writeDoubleArray arr 0 (fromRational r)
952         arr' <- castDoubleToIntArray arr
953         i1 <- readIntArray arr' 0
954         i2 <- readIntArray arr' 1
955         return [ CmmInt (toInteger i1) wordRep
956                , CmmInt (toInteger i2) wordRep
957                ]
958     )
959   | otherwise                           -- doubles are 1 word
960   = runST (do
961         arr <- newDoubleArray ((0::Int),0)
962         writeDoubleArray arr 0 (fromRational r)
963         arr' <- castDoubleToIntArray arr
964         i <- readIntArray arr' 0
965         return [ CmmInt (toInteger i) wordRep ]
966     )
967
968 -- ---------------------------------------------------------------------------
969 -- Utils
970
971 wordShift :: Int
972 wordShift = machRepLogWidth wordRep
973
974 commafy :: [SDoc] -> SDoc
975 commafy xs = hsep $ punctuate comma xs
976
977 -- Print in C hex format: 0x13fa
978 pprHexVal :: Integer -> SDoc
979 pprHexVal 0 = ptext SLIT("0x0")
980 pprHexVal w 
981   | w < 0     = parens (char '-' <> ptext SLIT("0x") <> go (-w))
982   | otherwise = ptext SLIT("0x") <> go w
983   where
984       go 0 = empty
985       go w' = go q <> dig
986            where
987              (q,r) = w' `quotRem` 16
988              dig | r < 10    = char (chr (fromInteger r + ord '0'))
989                  | otherwise = char (chr (fromInteger r - 10 + ord 'a'))
990