1 -----------------------------------------------------------------------------
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
5 -- (c) The University of Glasgow 2004
7 -----------------------------------------------------------------------------
10 -- Print Cmm as real C, for -fvia-C
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.
17 -- ToDo: save/restore volatile registers around calls.
24 #include "HsVersions.h"
33 import Unique ( getUnique )
36 import UniqFM ( eltsUFM )
40 import CmdLineOpts ( opt_EnsureSplittableC )
43 import Data.List ( intersperse, groupBy )
44 import Data.Bits ( shiftR )
45 import Char ( ord, chr )
50 import PprCmm () -- instances only
54 #if __GLASGOW_HASKELL__ >= 504
59 -- --------------------------------------------------------------------------
62 pprCs :: [Cmm] -> SDoc
63 pprCs cmms = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
65 writeCs :: Handle -> [Cmm] -> IO ()
66 writeCs handle cmms = printForUser handle alwaysQualify (pprCs cmms)
67 -- ToDo: should be printForC
70 | opt_EnsureSplittableC = ptext SLIT("__STG_SPLIT_MARKER")
73 -- --------------------------------------------------------------------------
74 -- Now do some real work
76 -- for fun, we could call cmmToCmm over the tops...
80 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
85 pprTop :: CmmTop -> SDoc
86 pprTop (CmmProc info clbl _params blocks) =
88 then pprWordArray (entryLblToInfoLbl clbl) info
92 -- the first block doesn't get a label:
93 (BasicBlock _ stmts : rest) -> vcat [
96 (if (externallyVisibleCLabel clbl)
97 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
100 nest 8 (vcat (map pprStmt stmts)) $$
101 vcat (map pprBBlock rest),
106 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
109 -- Chunks of static data.
111 -- We only handle (a) arrays of word-sized things and (b) strings.
113 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
115 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
116 ptext SLIT("[] = "), pprStringInCStyle str, semi
119 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
121 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
122 brackets (int size), semi
125 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
126 pprDataExterns lits $$
127 pprWordArray lbl lits
129 -- these shouldn't appear?
130 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
133 -- --------------------------------------------------------------------------
134 -- BasicBlocks are self-contained entities: they always end in a jump.
136 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
137 -- as many jumps as possible into fall throughs.
140 pprBBlock :: CmmBasicBlock -> SDoc
141 pprBBlock (BasicBlock lbl stmts) =
143 pprTrace "pprC.pprBBlock: curious empty code block for"
144 (pprBlockId lbl) empty
146 nest 4 (pprBlockId lbl <> colon) $$
147 nest 8 (vcat (map pprStmt stmts))
149 -- --------------------------------------------------------------------------
150 -- Info tables. Just arrays of words.
151 -- See codeGen/ClosureInfo, and nativeGen/PprMach
153 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
155 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
156 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
157 $$ nest 8 (commafy (pprStatics ds))
161 -- has to be static, if it isn't globally visible
163 pprLocalness :: CLabel -> SDoc
164 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
167 -- --------------------------------------------------------------------------
171 pprStmt :: CmmStmt -> SDoc
173 pprStmt stmt = case stmt of
175 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
177 CmmAssign dest src -> pprAssign dest src
181 -> ptext SLIT("ASSIGN_Word64") <>
182 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
185 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
189 CmmCall (CmmForeignCall fn cconv) results args volatile ->
190 -- Controversial: leave this out for now.
193 pprCall ppr_fn cconv results args volatile
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).
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
206 pprUndef (CmmLit (CmmLabel lbl)) =
207 ptext SLIT("#undef") <+> pprCLabel lbl
210 CmmCall (CmmPrim op) results args volatile ->
211 pprCall ppr_fn CCallConv results args volatile
213 ppr_fn = pprCallishMachOp_for_C op
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
220 pprCFunType :: [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
221 pprCFunType ress args =
222 res_type ress <> parens (char '*') <> parens (commafy (map arg_type args))
224 res_type [] = ptext SLIT("void")
225 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
227 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
229 -- ---------------------------------------------------------------------
230 -- unconditional branches
231 pprBranch :: BlockId -> SDoc
232 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
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 ]
243 -- ---------------------------------------------------------------------
244 -- a local table branch
246 -- we find the fall-through cases
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.
252 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
253 pprSwitch e maybe_ids
254 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
255 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
257 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
258 4 (vcat ( map caseify pairs2 )))
262 sndEq (_,x) (_,y) = x == y
265 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
268 hsep [ ptext SLIT("case") , pprHexVal ix <> colon ,
269 ptext SLIT("/* fall through */") ]
272 hsep [ ptext SLIT("case") , pprHexVal ix <> colon ,
273 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
275 -- ---------------------------------------------------------------------
279 -- C Types: the invariant is that the C expression generated by
283 -- has a type in C which is also given by
285 -- machRepCType (cmmExprRep e)
287 -- (similar invariants apply to the rest of the pretty printer).
289 pprExpr :: CmmExpr -> SDoc
290 pprExpr e = case e of
291 CmmLit lit -> pprLit lit
294 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
296 CmmLoad (CmmReg r) rep
297 | isPtrReg r && rep == wordRep
298 -> char '*' <> pprAsPtrReg r
300 CmmLoad (CmmRegOff r 0) rep
301 | isPtrReg r && rep == wordRep
302 -> char '*' <> pprAsPtrReg r
304 CmmLoad (CmmRegOff r off) rep
305 | isPtrReg r && rep == wordRep
306 -- ToDo: check that the offset is a word multiple?
307 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
311 char '*' <> parens (cCast (machRepPtrCType rep) expr)
313 CmmReg reg -> pprCastReg reg
314 CmmRegOff reg 0 -> pprCastReg reg
317 | i > 0 -> pprRegOff (char '+') i
318 | otherwise -> pprRegOff (char '-') (-i)
320 pprRegOff op i' = pprCastReg reg <> op <> int i'
322 CmmMachOp mop args -> pprMachOpApp mop args
324 pprExpr1 :: CmmExpr -> SDoc
325 pprExpr1 (CmmLit lit) = pprLit1 lit
326 pprExpr1 e@(CmmReg _reg) = pprExpr e
327 pprExpr1 other = parens (pprExpr other)
329 -- --------------------------------------------------------------------------
330 -- MachOp applications
332 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
336 = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
337 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
338 isMulMayOfloOp (MO_S_MulMayOflo _) = True
339 isMulMayOfloOp _ = False
341 pprMachOpApp mop args
344 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
347 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
349 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
352 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
353 | otherwise = pprExpr1 e
355 -- --------------------------------------------------------------------------
358 pprLit :: CmmLit -> SDoc
359 pprLit lit = case lit of
360 CmmInt i I64 | machRepByteWidth I32 == wORD_SIZE
361 -> pprHexVal i <> ptext SLIT("LL")
362 -- Append an 'LL' suffix to 64-bit integers on a 32-bit
363 -- platform. This might not be strictly necessary (the
364 -- type will always be apparent from the context), but
365 -- it avoids some warnings from gcc.
366 CmmInt i _rep -> pprHexVal i
367 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
368 CmmLabel clbl -> mkW_ <> pprCLabel clbl
369 CmmLabelOff clbl i -> mkW_ <> pprCLabel clbl <> char '+' <> int i
371 pprLit1 :: CmmLit -> SDoc
372 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
373 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
374 pprLit1 other = pprLit other
376 -- ---------------------------------------------------------------------------
379 pprStatics :: [CmmStatic] -> [SDoc]
381 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
382 = pprLit1 (floatToWord f) : pprStatics rest
383 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
384 = map pprLit1 (doubleToWords f) ++ pprStatics rest
385 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
386 | machRepByteWidth I32 == wORD_SIZE
387 #ifdef WORDS_BIGENDIAN
388 = pprStatics (CmmStaticLit (CmmInt q I32) :
389 CmmStaticLit (CmmInt r I32) : rest)
391 = pprStatics (CmmStaticLit (CmmInt r I32) :
392 CmmStaticLit (CmmInt q I32) : rest)
394 where r = i .&. 0xffffffff
396 pprStatics (CmmStaticLit lit : rest)
397 = pprLit1 lit : pprStatics rest
398 pprStatics (other : rest)
399 = pprPanic "pprWord" (pprStatic other)
401 pprStatic :: CmmStatic -> SDoc
402 pprStatic s = case s of
404 CmmStaticLit lit -> nest 4 (pprLit lit)
405 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
406 CmmDataLabel clbl -> pprCLabel clbl <> colon
407 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
409 -- these should be inlined, like the old .hc
410 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
413 -- ---------------------------------------------------------------------------
416 pprBlockId :: BlockId -> SDoc
417 pprBlockId b = char '_' <> ppr (getUnique b)
419 -- --------------------------------------------------------------------------
420 -- Print a MachOp in a way suitable for emitting via C.
423 pprMachOp_for_C :: MachOp -> SDoc
425 pprMachOp_for_C mop = case mop of
427 -- Integer operations
430 MO_Eq _ -> ptext SLIT("==")
431 MO_Ne _ -> ptext SLIT("!=")
434 MO_S_Quot _ -> char '/'
435 MO_S_Rem _ -> char '%'
436 MO_S_Neg _ -> char '-'
438 MO_U_Quot _ -> char '/'
439 MO_U_Rem _ -> char '%'
441 -- Signed comparisons (floating-point comparisons also use these)
442 -- & Unsigned comparisons
443 MO_S_Ge _ -> ptext SLIT(">=")
444 MO_S_Le _ -> ptext SLIT("<=")
445 MO_S_Gt _ -> char '>'
446 MO_S_Lt _ -> char '<'
448 MO_U_Ge _ -> ptext SLIT(">=")
449 MO_U_Le _ -> ptext SLIT("<=")
450 MO_U_Gt _ -> char '>'
451 MO_U_Lt _ -> char '<'
453 -- Bitwise operations. Not all of these may be supported at all
454 -- sizes, and only integral MachReps are valid.
459 MO_Shl _ -> ptext SLIT("<<")
460 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
461 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
463 -- Conversions. Some of these will be NOPs.
464 -- Floating-point conversions use the signed variant.
465 -- We won't know to generate (void*) casts here, but maybe from
469 MO_U_Conv I8 I8 -> empty
470 MO_U_Conv I16 I16 -> empty
471 MO_U_Conv I32 I32 -> empty
472 MO_U_Conv I64 I64 -> empty
473 MO_U_Conv I128 I128 -> empty
474 MO_S_Conv I8 I8 -> empty
475 MO_S_Conv I16 I16 -> empty
476 MO_S_Conv I32 I32 -> empty
477 MO_S_Conv I64 I64 -> empty
478 MO_S_Conv I128 I128 -> empty
480 MO_U_Conv _from to -> parens (machRepCType to)
481 MO_S_Conv _from to -> parens (machRepSignedCType to)
483 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
485 signedOp :: MachOp -> Bool
486 signedOp (MO_S_Quot _) = True
487 signedOp (MO_S_Rem _) = True
488 signedOp (MO_S_Neg _) = True
489 signedOp (MO_S_Ge _) = True
490 signedOp (MO_S_Le _) = True
491 signedOp (MO_S_Gt _) = True
492 signedOp (MO_S_Lt _) = True
493 signedOp (MO_S_Shr _) = True
494 signedOp (MO_S_Conv _ _) = True
497 -- ---------------------------------------------------------------------
498 -- tend to be implemented by foreign calls
500 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
502 pprCallishMachOp_for_C mop
504 MO_F64_Pwr -> ptext SLIT("pow")
505 MO_F64_Sin -> ptext SLIT("sin")
506 MO_F64_Cos -> ptext SLIT("cos")
507 MO_F64_Tan -> ptext SLIT("tan")
508 MO_F64_Sinh -> ptext SLIT("sinh")
509 MO_F64_Cosh -> ptext SLIT("cosh")
510 MO_F64_Tanh -> ptext SLIT("tanh")
511 MO_F64_Asin -> ptext SLIT("asin")
512 MO_F64_Acos -> ptext SLIT("asin")
513 MO_F64_Atan -> ptext SLIT("atan")
514 MO_F64_Log -> ptext SLIT("log")
515 MO_F64_Exp -> ptext SLIT("exp")
516 MO_F64_Sqrt -> ptext SLIT("sqrt")
517 MO_F32_Pwr -> ptext SLIT("pow")
518 MO_F32_Sin -> ptext SLIT("sin")
519 MO_F32_Cos -> ptext SLIT("cos")
520 MO_F32_Tan -> ptext SLIT("tan")
521 MO_F32_Sinh -> ptext SLIT("sinh")
522 MO_F32_Cosh -> ptext SLIT("cosh")
523 MO_F32_Tanh -> ptext SLIT("tanh")
524 MO_F32_Asin -> ptext SLIT("asin")
525 MO_F32_Acos -> ptext SLIT("acos")
526 MO_F32_Atan -> ptext SLIT("atan")
527 MO_F32_Log -> ptext SLIT("log")
528 MO_F32_Exp -> ptext SLIT("exp")
529 MO_F32_Sqrt -> ptext SLIT("sqrt")
531 -- ---------------------------------------------------------------------
535 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
537 mkJMP_ i = ptext SLIT("JMP_") <> parens i
538 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
539 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
543 mkFB_ = ptext SLIT("FB_") -- function code begin
544 mkFE_ = ptext SLIT("FE_") -- function code end
546 -- from includes/Stg.h
548 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
550 mkC_ = ptext SLIT("(C_)") -- StgChar
551 mkW_ = ptext SLIT("(W_)") -- StgWord
552 mkP_ = ptext SLIT("(P_)") -- StgWord*
553 mkPP_ = ptext SLIT("(PP_)") -- P_*
554 mkI_ = ptext SLIT("(I_)") -- StgInt
555 mkA_ = ptext SLIT("(A_)") -- StgAddr
556 mkD_ = ptext SLIT("(D_)") -- const StgWord*
557 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
558 mkB_ = ptext SLIT("(B_)") -- StgByteArray
559 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
561 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
562 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
565 -- ---------------------------------------------------------------------
569 -- Generating assignments is what we're all about, here
571 pprAssign :: CmmReg -> CmmExpr -> SDoc
573 -- dest is a reg, rhs is a reg
574 pprAssign r1 (CmmReg r2)
575 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
576 || isPtrReg r1 && isPtrReg r2
577 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
579 -- dest is a reg, rhs is a CmmRegOff
580 pprAssign r1 (CmmRegOff r2 off)
581 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
582 || isPtrReg r1 && isPtrReg r2
583 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
585 off1 | isPtrReg r2 = off `shiftR` wordShift
588 (op,off') | off >= 0 = (char '+', off1)
589 | otherwise = (char '-', -off1)
591 -- dest is a reg, rhs is anything.
592 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
593 -- the lvalue elicits a warning from new GCC versions (3.4+).
596 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
597 | Just ty <- strangeRegType r1
598 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
600 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
602 -- ---------------------------------------------------------------------
606 | isStrangeTypeReg reg = mkW_ <> pprReg reg
607 | otherwise = pprReg reg
609 -- True if the register has type StgPtr in C, otherwise it has an
610 -- integer type. We need to take care with pointer arithmetic on registers
612 isPtrReg :: CmmReg -> Bool
613 isPtrReg (CmmLocal _) = False
614 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
616 isPtrGlobalReg :: GlobalReg -> Bool
617 isPtrGlobalReg (VanillaReg n) = True
618 isPtrGlobalReg Sp = True
619 isPtrGlobalReg Hp = True
620 isPtrGlobalReg HpLim = True
621 isPtrGlobalReg SpLim = True
622 isPtrGlobalReg _ = False
624 -- True if in C this register doesn't have the type given by
625 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
626 isStrangeTypeReg :: CmmReg -> Bool
627 isStrangeTypeReg (CmmLocal _) = False
628 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
630 isStrangeTypeGlobal :: GlobalReg -> Bool
631 isStrangeTypeGlobal CurrentTSO = True
632 isStrangeTypeGlobal CurrentNursery = True
633 isStrangeTypeGlobal r = isPtrGlobalReg r
635 strangeRegType :: CmmReg -> Maybe SDoc
636 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
637 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
638 strangeRegType _ = Nothing
640 -- pprReg just prints the register name.
642 pprReg :: CmmReg -> SDoc
644 CmmLocal local -> pprLocalReg local
645 CmmGlobal global -> pprGlobalReg global
647 pprAsPtrReg :: CmmReg -> SDoc
648 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
649 pprAsPtrReg other_reg = pprReg other_reg
651 pprGlobalReg :: GlobalReg -> SDoc
652 pprGlobalReg gr = case gr of
653 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
654 FloatReg n -> char 'F' <> int n
655 DoubleReg n -> char 'D' <> int n
656 LongReg n -> char 'L' <> int n
657 Sp -> ptext SLIT("Sp")
658 SpLim -> ptext SLIT("SpLim")
659 Hp -> ptext SLIT("Hp")
660 HpLim -> ptext SLIT("HpLim")
661 CurrentTSO -> ptext SLIT("CurrentTSO")
662 CurrentNursery -> ptext SLIT("CurrentNursery")
663 HpAlloc -> ptext SLIT("HpAlloc")
664 BaseReg -> ptext SLIT("BaseReg")
665 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
666 GCFun -> ptext SLIT("stg_gc_fun")
668 pprLocalReg :: LocalReg -> SDoc
669 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
671 -- -----------------------------------------------------------------------------
674 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
675 -> Maybe [GlobalReg] -> SDoc
677 pprCall ppr_fn cconv results args vols
678 | not (is_cish cconv)
679 = panic "pprForeignCall: unknown calling convention"
683 ptext SLIT("CALLER_SAVE_SYSTEM") $$
684 hcat [ ppr_results results, ppr_fn,
685 parens (commafy (map pprArg args)), semi ] $$
686 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
689 ppr_results [] = empty
690 ppr_results [(one,hint)]
691 = pprExpr (CmmReg one) <> ptext SLIT(" = ")
692 <> pprUnHint hint (cmmRegRep one)
693 ppr_results _other = panic "pprCall: multiple results"
695 pprArg (expr, PtrHint)
696 = cCast (ptext SLIT("void *")) expr
697 -- see comment by machRepHintCType below
698 pprArg (expr, SignedHint)
699 = cCast (machRepSignedCType (cmmExprRep expr)) expr
700 pprArg (expr, _other)
703 pprUnHint PtrHint rep = parens (machRepCType rep)
704 pprUnHint SignedHint rep = parens (machRepCType rep)
705 pprUnHint _ _ = empty
707 save = save_restore SLIT("CALLER_SAVE")
708 restore = save_restore SLIT("CALLER_RESTORE")
710 -- Nothing says "I don't know what's live; save everything"
711 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
712 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
713 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
714 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
716 pprGlobalRegName :: GlobalReg -> SDoc
717 pprGlobalRegName gr = case gr of
718 VanillaReg n -> char 'R' <> int n -- without the .w suffix
721 is_cish CCallConv = True
722 is_cish StdCallConv = True
725 -- ---------------------------------------------------------------------
726 -- Find and print local and external declarations for a list of
729 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
730 pprTempAndExternDecls stmts
731 = (vcat (map pprTempDecl (eltsUFM temps)),
732 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
733 where (temps, lbls) = runTE (mapM_ te_BB stmts)
735 pprDataExterns :: [CmmStatic] -> SDoc
736 pprDataExterns statics
737 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
738 where (_, lbls) = runTE (mapM_ te_Static statics)
740 pprTempDecl :: LocalReg -> SDoc
741 pprTempDecl l@(LocalReg _uniq rep)
742 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
744 pprExternDecl :: Bool -> CLabel -> SDoc
745 pprExternDecl in_srt lbl
746 -- do not print anything for "known external" things
747 | not (needsCDecl lbl) = empty
749 hcat [ visibility, label_type (labelType lbl),
750 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
753 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
756 label_type CodeLabel = ptext SLIT("F_")
757 label_type DataLabel = ptext SLIT("I_")
760 | externallyVisibleCLabel lbl = char 'E'
761 | otherwise = char 'I'
764 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
765 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
767 instance Monad TE where
768 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
769 return a = TE $ \s -> (a, s)
771 te_lbl :: CLabel -> TE ()
772 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
774 te_temp :: LocalReg -> TE ()
775 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
777 runTE :: TE () -> TEState
778 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
780 te_Static :: CmmStatic -> TE ()
781 te_Static (CmmStaticLit lit) = te_Lit lit
782 te_Static _ = return ()
784 te_BB :: CmmBasicBlock -> TE ()
785 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
787 te_Lit :: CmmLit -> TE ()
788 te_Lit (CmmLabel l) = te_lbl l
791 te_Stmt :: CmmStmt -> TE ()
792 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
793 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
794 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
795 mapM_ (te_Expr.fst) es
796 te_Stmt (CmmCondBranch e _) = te_Expr e
797 te_Stmt (CmmSwitch e _) = te_Expr e
798 te_Stmt (CmmJump e _) = te_Expr e
799 te_Stmt _ = return ()
801 te_Expr :: CmmExpr -> TE ()
802 te_Expr (CmmLit lit) = te_Lit lit
803 te_Expr (CmmReg r) = te_Reg r
804 te_Expr (CmmLoad e _) = te_Expr e
805 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
806 te_Expr (CmmRegOff r _) = te_Reg r
807 te_Expr _ = return ()
809 te_Reg :: CmmReg -> TE ()
810 te_Reg (CmmLocal l) = te_temp l
814 -- ---------------------------------------------------------------------
815 -- C types for MachReps
817 cCast :: SDoc -> CmmExpr -> SDoc
818 cCast ty expr = parens ty <> pprExpr1 expr
820 -- This is for finding the types of foreign call arguments. For a pointer
821 -- argument, we always cast the argument to (void *), to avoid warnings from
823 machRepHintCType :: MachRep -> MachHint -> SDoc
824 machRepHintCType rep PtrHint = ptext SLIT("void *")
825 machRepHintCType rep SignedHint = machRepSignedCType rep
826 machRepHintCType rep _other = machRepCType rep
828 machRepPtrCType :: MachRep -> SDoc
829 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
830 | otherwise = machRepCType r <> char '*'
832 machRepCType :: MachRep -> SDoc
833 machRepCType r | r == wordRep = ptext SLIT("W_")
834 | otherwise = sized_type
835 where sized_type = case r of
836 I8 -> ptext SLIT("StgWord8")
837 I16 -> ptext SLIT("StgWord16")
838 I32 -> ptext SLIT("StgWord32")
839 I64 -> ptext SLIT("StgWord64")
840 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
841 F64 -> ptext SLIT("StgDouble")
842 _ -> panic "machRepCType"
844 machRepSignedCType :: MachRep -> SDoc
845 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
846 | otherwise = sized_type
847 where sized_type = case r of
848 I8 -> ptext SLIT("StgInt8")
849 I16 -> ptext SLIT("StgInt16")
850 I32 -> ptext SLIT("StgInt32")
851 I64 -> ptext SLIT("StgInt64")
852 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
853 F64 -> ptext SLIT("StgDouble")
854 _ -> panic "machRepCType"
856 -- ---------------------------------------------------------------------
857 -- print strings as valid C strings
859 -- Assumes it contains only characters '\0'..'\xFF'!
860 pprFSInCStyle :: FastString -> SDoc
861 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
863 pprStringInCStyle :: String -> SDoc
864 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
866 charToC :: Char -> String
867 charToC '\"' = "\\\""
868 charToC '\'' = "\\\'"
869 charToC '\\' = "\\\\"
870 charToC c | c >= ' ' && c <= '~' = [c]
871 | c > '\xFF' = panic ("charToC "++show c)
873 chr (ord '0' + ord c `div` 64),
874 chr (ord '0' + ord c `div` 8 `mod` 8),
875 chr (ord '0' + ord c `mod` 8)]
878 -- ---------------------------------------------------------------------------
879 -- Initialising static objects with floating-point numbers. We can't
880 -- just emit the floating point number, because C will cast it to an int
881 -- by rounding it. We want the actual bit-representation of the float.
883 -- This is a hack to turn the floating point numbers into ints that we
884 -- can safely initialise to static locations.
887 | machRepByteWidth F64 == 2 * wORD_SIZE = True
888 | machRepByteWidth F64 == wORD_SIZE = False
889 | otherwise = panic "big_doubles"
891 #if __GLASGOW_HASKELL__ >= 504
892 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
893 newFloatArray = newArray_
895 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
896 newDoubleArray = newArray_
898 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
899 castFloatToIntArray = castSTUArray
901 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
902 castDoubleToIntArray = castSTUArray
904 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
905 writeFloatArray = writeArray
907 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
908 writeDoubleArray = writeArray
910 readIntArray :: STUArray s Int Int -> Int -> ST s Int
911 readIntArray = readArray
915 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
916 castFloatToIntArray = return
918 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
919 castDoubleToIntArray = return
923 -- floats are always 1 word
924 floatToWord :: Rational -> CmmLit
927 arr <- newFloatArray ((0::Int),0)
928 writeFloatArray arr 0 (fromRational r)
929 arr' <- castFloatToIntArray arr
930 i <- readIntArray arr' 0
931 return (CmmInt (toInteger i) wordRep)
934 doubleToWords :: Rational -> [CmmLit]
936 | big_doubles -- doubles are 2 words
938 arr <- newDoubleArray ((0::Int),1)
939 writeDoubleArray arr 0 (fromRational r)
940 arr' <- castDoubleToIntArray arr
941 i1 <- readIntArray arr' 0
942 i2 <- readIntArray arr' 1
943 return [ CmmInt (toInteger i1) wordRep
944 , CmmInt (toInteger i2) wordRep
947 | otherwise -- doubles are 1 word
949 arr <- newDoubleArray ((0::Int),0)
950 writeDoubleArray arr 0 (fromRational r)
951 arr' <- castDoubleToIntArray arr
952 i <- readIntArray arr' 0
953 return [ CmmInt (toInteger i) wordRep ]
956 -- ---------------------------------------------------------------------------
960 wordShift = machRepLogWidth wordRep
962 commafy :: [SDoc] -> SDoc
963 commafy xs = hsep $ punctuate comma xs
965 -- Print in C hex format: 0x13fa
966 pprHexVal :: Integer -> SDoc
967 pprHexVal 0 = ptext SLIT("0x0")
969 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w))
970 | otherwise = ptext SLIT("0x") <> go w
975 (q,r) = w' `quotRem` 16
976 dig | r < 10 = char (chr (fromInteger r + ord '0'))
977 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))