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