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