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 pprDataExterns info $$
89 pprWordArray (entryLblToInfoLbl clbl) info
93 -- the first block doesn't get a label:
94 (BasicBlock _ stmts : rest) -> vcat [
97 (if (externallyVisibleCLabel clbl)
98 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
101 nest 8 (vcat (map pprStmt stmts)) $$
102 vcat (map pprBBlock rest),
107 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
110 -- Chunks of static data.
112 -- We only handle (a) arrays of word-sized things and (b) strings.
114 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
116 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
117 ptext SLIT("[] = "), pprStringInCStyle str, semi
120 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
122 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
123 brackets (int size), semi
126 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
127 pprDataExterns lits $$
128 pprWordArray lbl lits
130 -- these shouldn't appear?
131 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
134 -- --------------------------------------------------------------------------
135 -- BasicBlocks are self-contained entities: they always end in a jump.
137 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
138 -- as many jumps as possible into fall throughs.
141 pprBBlock :: CmmBasicBlock -> SDoc
142 pprBBlock (BasicBlock lbl stmts) =
144 pprTrace "pprC.pprBBlock: curious empty code block for"
145 (pprBlockId lbl) empty
147 nest 4 (pprBlockId lbl <> colon) $$
148 nest 8 (vcat (map pprStmt stmts))
150 -- --------------------------------------------------------------------------
151 -- Info tables. Just arrays of words.
152 -- See codeGen/ClosureInfo, and nativeGen/PprMach
154 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
156 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
157 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
158 $$ nest 8 (commafy (pprStatics ds))
162 -- has to be static, if it isn't globally visible
164 pprLocalness :: CLabel -> SDoc
165 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
168 -- --------------------------------------------------------------------------
172 pprStmt :: CmmStmt -> SDoc
174 pprStmt stmt = case stmt of
176 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
178 CmmAssign dest src -> pprAssign dest src
182 -> ptext SLIT("ASSIGN_Word64") <>
183 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
186 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
190 CmmCall (CmmForeignCall fn cconv) results args volatile ->
191 -- Controversial: leave this out for now.
194 pprCall ppr_fn cconv results args volatile
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).
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
207 pprUndef (CmmLit (CmmLabel lbl)) =
208 ptext SLIT("#undef") <+> pprCLabel lbl
211 CmmCall (CmmPrim op) results args volatile ->
212 pprCall ppr_fn CCallConv results args volatile
214 ppr_fn = pprCallishMachOp_for_C op
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
221 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
222 pprCFunType cconv ress args
225 parens (text (ccallConvAttribute cconv) <> char '*'),
226 parens (commafy (map arg_type args))
229 res_type [] = ptext SLIT("void")
230 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
232 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
234 -- ---------------------------------------------------------------------
235 -- unconditional branches
236 pprBranch :: BlockId -> SDoc
237 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
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 ]
248 -- ---------------------------------------------------------------------
249 -- a local table branch
251 -- we find the fall-through cases
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.
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 ]
262 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
263 4 (vcat ( map caseify pairs2 )))
267 sndEq (_,x) (_,y) = x == y
270 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
273 hsep [ ptext SLIT("case") , pprHexVal ix <> colon ,
274 ptext SLIT("/* fall through */") ]
277 hsep [ ptext SLIT("case") , pprHexVal ix <> colon ,
278 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
280 -- ---------------------------------------------------------------------
284 -- C Types: the invariant is that the C expression generated by
288 -- has a type in C which is also given by
290 -- machRepCType (cmmExprRep e)
292 -- (similar invariants apply to the rest of the pretty printer).
294 pprExpr :: CmmExpr -> SDoc
295 pprExpr e = case e of
296 CmmLit lit -> pprLit lit
299 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
301 CmmLoad (CmmReg r) rep
302 | isPtrReg r && rep == wordRep
303 -> char '*' <> pprAsPtrReg r
305 CmmLoad (CmmRegOff r 0) rep
306 | isPtrReg r && rep == wordRep
307 -> char '*' <> pprAsPtrReg r
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))
316 char '*' <> parens (cCast (machRepPtrCType rep) expr)
318 CmmReg reg -> pprCastReg reg
319 CmmRegOff reg 0 -> pprCastReg reg
322 | i > 0 -> pprRegOff (char '+') i
323 | otherwise -> pprRegOff (char '-') (-i)
325 pprRegOff op i' = pprCastReg reg <> op <> int i'
327 CmmMachOp mop args -> pprMachOpApp mop args
329 pprExpr1 :: CmmExpr -> SDoc
330 pprExpr1 (CmmLit lit) = pprLit1 lit
331 pprExpr1 e@(CmmReg _reg) = pprExpr e
332 pprExpr1 other = parens (pprExpr other)
334 -- --------------------------------------------------------------------------
335 -- MachOp applications
337 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
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
346 pprMachOpApp mop args
349 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
352 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
354 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
357 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
358 | otherwise = pprExpr1 e
360 -- --------------------------------------------------------------------------
363 pprLit :: CmmLit -> SDoc
364 pprLit lit = case lit of
365 CmmInt i I64 | machRepByteWidth I32 == wORD_SIZE
366 -> pprHexVal i <> ptext SLIT("LL")
367 -- Append an 'LL' suffix to 64-bit integers on a 32-bit
368 -- platform. This might not be strictly necessary (the
369 -- type will always be apparent from the context), but
370 -- it avoids some warnings from gcc.
371 CmmInt i _rep -> pprHexVal i
372 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
373 CmmLabel clbl -> mkW_ <> pprCLabel clbl
374 CmmLabelOff clbl i -> mkW_ <> pprCLabel clbl <> char '+' <> int i
375 CmmLabelDiffOff clbl1 clbl2 i
377 -- * the lit must occur in the info table clbl2
378 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
379 -- The Mangler is expected to convert any reference to an SRT,
380 -- a slow entry point or a large bitmap
381 -- from an info table to an offset.
382 -> mkW_ <> pprCLabel clbl1 <> char '+' <> int i
384 pprLit1 :: CmmLit -> SDoc
385 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
386 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
387 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
388 pprLit1 other = pprLit other
390 -- ---------------------------------------------------------------------------
393 pprStatics :: [CmmStatic] -> [SDoc]
395 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
396 = pprLit1 (floatToWord f) : pprStatics rest
397 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
398 = map pprLit1 (doubleToWords f) ++ pprStatics rest
399 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
400 | machRepByteWidth I32 == wORD_SIZE
401 #ifdef WORDS_BIGENDIAN
402 = pprStatics (CmmStaticLit (CmmInt q I32) :
403 CmmStaticLit (CmmInt r I32) : rest)
405 = pprStatics (CmmStaticLit (CmmInt r I32) :
406 CmmStaticLit (CmmInt q I32) : rest)
408 where r = i .&. 0xffffffff
410 pprStatics (CmmStaticLit lit : rest)
411 = pprLit1 lit : pprStatics rest
412 pprStatics (other : rest)
413 = pprPanic "pprWord" (pprStatic other)
415 pprStatic :: CmmStatic -> SDoc
416 pprStatic s = case s of
418 CmmStaticLit lit -> nest 4 (pprLit lit)
419 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
420 CmmDataLabel clbl -> pprCLabel clbl <> colon
421 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
423 -- these should be inlined, like the old .hc
424 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
427 -- ---------------------------------------------------------------------------
430 pprBlockId :: BlockId -> SDoc
431 pprBlockId b = char '_' <> ppr (getUnique b)
433 -- --------------------------------------------------------------------------
434 -- Print a MachOp in a way suitable for emitting via C.
437 pprMachOp_for_C :: MachOp -> SDoc
439 pprMachOp_for_C mop = case mop of
441 -- Integer operations
444 MO_Eq _ -> ptext SLIT("==")
445 MO_Ne _ -> ptext SLIT("!=")
448 MO_S_Quot _ -> char '/'
449 MO_S_Rem _ -> char '%'
450 MO_S_Neg _ -> char '-'
452 MO_U_Quot _ -> char '/'
453 MO_U_Rem _ -> char '%'
455 -- Signed comparisons (floating-point comparisons also use these)
456 -- & Unsigned comparisons
457 MO_S_Ge _ -> ptext SLIT(">=")
458 MO_S_Le _ -> ptext SLIT("<=")
459 MO_S_Gt _ -> char '>'
460 MO_S_Lt _ -> char '<'
462 MO_U_Ge _ -> ptext SLIT(">=")
463 MO_U_Le _ -> ptext SLIT("<=")
464 MO_U_Gt _ -> char '>'
465 MO_U_Lt _ -> char '<'
467 -- Bitwise operations. Not all of these may be supported at all
468 -- sizes, and only integral MachReps are valid.
473 MO_Shl _ -> ptext SLIT("<<")
474 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
475 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
477 -- Conversions. Some of these will be NOPs.
478 -- Floating-point conversions use the signed variant.
479 -- We won't know to generate (void*) casts here, but maybe from
483 MO_U_Conv I8 I8 -> empty
484 MO_U_Conv I16 I16 -> empty
485 MO_U_Conv I32 I32 -> empty
486 MO_U_Conv I64 I64 -> empty
487 MO_U_Conv I128 I128 -> empty
488 MO_S_Conv I8 I8 -> empty
489 MO_S_Conv I16 I16 -> empty
490 MO_S_Conv I32 I32 -> empty
491 MO_S_Conv I64 I64 -> empty
492 MO_S_Conv I128 I128 -> empty
494 MO_U_Conv _from to -> parens (machRepCType to)
495 MO_S_Conv _from to -> parens (machRepSignedCType to)
497 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
499 signedOp :: MachOp -> Bool
500 signedOp (MO_S_Quot _) = True
501 signedOp (MO_S_Rem _) = True
502 signedOp (MO_S_Neg _) = True
503 signedOp (MO_S_Ge _) = True
504 signedOp (MO_S_Le _) = True
505 signedOp (MO_S_Gt _) = True
506 signedOp (MO_S_Lt _) = True
507 signedOp (MO_S_Shr _) = True
508 signedOp (MO_S_Conv _ _) = True
511 -- ---------------------------------------------------------------------
512 -- tend to be implemented by foreign calls
514 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
516 pprCallishMachOp_for_C mop
518 MO_F64_Pwr -> ptext SLIT("pow")
519 MO_F64_Sin -> ptext SLIT("sin")
520 MO_F64_Cos -> ptext SLIT("cos")
521 MO_F64_Tan -> ptext SLIT("tan")
522 MO_F64_Sinh -> ptext SLIT("sinh")
523 MO_F64_Cosh -> ptext SLIT("cosh")
524 MO_F64_Tanh -> ptext SLIT("tanh")
525 MO_F64_Asin -> ptext SLIT("asin")
526 MO_F64_Acos -> ptext SLIT("acos")
527 MO_F64_Atan -> ptext SLIT("atan")
528 MO_F64_Log -> ptext SLIT("log")
529 MO_F64_Exp -> ptext SLIT("exp")
530 MO_F64_Sqrt -> ptext SLIT("sqrt")
531 MO_F32_Pwr -> ptext SLIT("pow")
532 MO_F32_Sin -> ptext SLIT("sin")
533 MO_F32_Cos -> ptext SLIT("cos")
534 MO_F32_Tan -> ptext SLIT("tan")
535 MO_F32_Sinh -> ptext SLIT("sinh")
536 MO_F32_Cosh -> ptext SLIT("cosh")
537 MO_F32_Tanh -> ptext SLIT("tanh")
538 MO_F32_Asin -> ptext SLIT("asin")
539 MO_F32_Acos -> ptext SLIT("acos")
540 MO_F32_Atan -> ptext SLIT("atan")
541 MO_F32_Log -> ptext SLIT("log")
542 MO_F32_Exp -> ptext SLIT("exp")
543 MO_F32_Sqrt -> ptext SLIT("sqrt")
545 -- ---------------------------------------------------------------------
549 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
551 mkJMP_ i = ptext SLIT("JMP_") <> parens i
552 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
553 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
557 mkFB_ = ptext SLIT("FB_") -- function code begin
558 mkFE_ = ptext SLIT("FE_") -- function code end
560 -- from includes/Stg.h
562 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
564 mkC_ = ptext SLIT("(C_)") -- StgChar
565 mkW_ = ptext SLIT("(W_)") -- StgWord
566 mkP_ = ptext SLIT("(P_)") -- StgWord*
567 mkPP_ = ptext SLIT("(PP_)") -- P_*
568 mkI_ = ptext SLIT("(I_)") -- StgInt
569 mkA_ = ptext SLIT("(A_)") -- StgAddr
570 mkD_ = ptext SLIT("(D_)") -- const StgWord*
571 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
572 mkB_ = ptext SLIT("(B_)") -- StgByteArray
573 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
575 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
576 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
579 -- ---------------------------------------------------------------------
583 -- Generating assignments is what we're all about, here
585 pprAssign :: CmmReg -> CmmExpr -> SDoc
587 -- dest is a reg, rhs is a reg
588 pprAssign r1 (CmmReg r2)
589 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
590 || isPtrReg r1 && isPtrReg r2
591 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
593 -- dest is a reg, rhs is a CmmRegOff
594 pprAssign r1 (CmmRegOff r2 off)
595 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
596 || isPtrReg r1 && isPtrReg r2
597 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
599 off1 | isPtrReg r2 = off `shiftR` wordShift
602 (op,off') | off >= 0 = (char '+', off1)
603 | otherwise = (char '-', -off1)
605 -- dest is a reg, rhs is anything.
606 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
607 -- the lvalue elicits a warning from new GCC versions (3.4+).
610 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
611 | Just ty <- strangeRegType r1
612 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
614 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
616 -- ---------------------------------------------------------------------
620 | isStrangeTypeReg reg = mkW_ <> pprReg reg
621 | otherwise = pprReg reg
623 -- True if the register has type StgPtr in C, otherwise it has an
624 -- integer type. We need to take care with pointer arithmetic on registers
626 isPtrReg :: CmmReg -> Bool
627 isPtrReg (CmmLocal _) = False
628 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
630 isPtrGlobalReg :: GlobalReg -> Bool
631 isPtrGlobalReg (VanillaReg n) = True
632 isPtrGlobalReg Sp = True
633 isPtrGlobalReg Hp = True
634 isPtrGlobalReg HpLim = True
635 isPtrGlobalReg SpLim = True
636 isPtrGlobalReg _ = False
638 -- True if in C this register doesn't have the type given by
639 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
640 isStrangeTypeReg :: CmmReg -> Bool
641 isStrangeTypeReg (CmmLocal _) = False
642 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
644 isStrangeTypeGlobal :: GlobalReg -> Bool
645 isStrangeTypeGlobal CurrentTSO = True
646 isStrangeTypeGlobal CurrentNursery = True
647 isStrangeTypeGlobal r = isPtrGlobalReg r
649 strangeRegType :: CmmReg -> Maybe SDoc
650 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
651 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
652 strangeRegType _ = Nothing
654 -- pprReg just prints the register name.
656 pprReg :: CmmReg -> SDoc
658 CmmLocal local -> pprLocalReg local
659 CmmGlobal global -> pprGlobalReg global
661 pprAsPtrReg :: CmmReg -> SDoc
662 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
663 pprAsPtrReg other_reg = pprReg other_reg
665 pprGlobalReg :: GlobalReg -> SDoc
666 pprGlobalReg gr = case gr of
667 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
668 FloatReg n -> char 'F' <> int n
669 DoubleReg n -> char 'D' <> int n
670 LongReg n -> char 'L' <> int n
671 Sp -> ptext SLIT("Sp")
672 SpLim -> ptext SLIT("SpLim")
673 Hp -> ptext SLIT("Hp")
674 HpLim -> ptext SLIT("HpLim")
675 CurrentTSO -> ptext SLIT("CurrentTSO")
676 CurrentNursery -> ptext SLIT("CurrentNursery")
677 HpAlloc -> ptext SLIT("HpAlloc")
678 BaseReg -> ptext SLIT("BaseReg")
679 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
680 GCFun -> ptext SLIT("stg_gc_fun")
682 pprLocalReg :: LocalReg -> SDoc
683 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
685 -- -----------------------------------------------------------------------------
688 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
689 -> Maybe [GlobalReg] -> SDoc
691 pprCall ppr_fn cconv results args vols
692 | not (is_cish cconv)
693 = panic "pprForeignCall: unknown calling convention"
697 ptext SLIT("CALLER_SAVE_SYSTEM") $$
698 hcat [ ppr_results results, ppr_fn,
699 parens (commafy (map pprArg args)), semi ] $$
700 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
703 ppr_results [] = empty
704 ppr_results [(one,hint)]
705 = pprExpr (CmmReg one) <> ptext SLIT(" = ")
706 <> pprUnHint hint (cmmRegRep one)
707 ppr_results _other = panic "pprCall: multiple results"
709 pprArg (expr, PtrHint)
710 = cCast (ptext SLIT("void *")) expr
711 -- see comment by machRepHintCType below
712 pprArg (expr, SignedHint)
713 = cCast (machRepSignedCType (cmmExprRep expr)) expr
714 pprArg (expr, _other)
717 pprUnHint PtrHint rep = parens (machRepCType rep)
718 pprUnHint SignedHint rep = parens (machRepCType rep)
719 pprUnHint _ _ = empty
721 save = save_restore SLIT("CALLER_SAVE")
722 restore = save_restore SLIT("CALLER_RESTORE")
724 -- Nothing says "I don't know what's live; save everything"
725 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
726 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
727 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
728 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
730 pprGlobalRegName :: GlobalReg -> SDoc
731 pprGlobalRegName gr = case gr of
732 VanillaReg n -> char 'R' <> int n -- without the .w suffix
735 is_cish CCallConv = True
736 is_cish StdCallConv = True
739 -- ---------------------------------------------------------------------
740 -- Find and print local and external declarations for a list of
743 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
744 pprTempAndExternDecls stmts
745 = (vcat (map pprTempDecl (eltsUFM temps)),
746 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
747 where (temps, lbls) = runTE (mapM_ te_BB stmts)
749 pprDataExterns :: [CmmStatic] -> SDoc
750 pprDataExterns statics
751 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
752 where (_, lbls) = runTE (mapM_ te_Static statics)
754 pprTempDecl :: LocalReg -> SDoc
755 pprTempDecl l@(LocalReg _uniq rep)
756 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
758 pprExternDecl :: Bool -> CLabel -> SDoc
759 pprExternDecl in_srt lbl
760 -- do not print anything for "known external" things
761 | not (needsCDecl lbl) = empty
763 hcat [ visibility, label_type (labelType lbl),
764 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
767 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
770 label_type CodeLabel = ptext SLIT("F_")
771 label_type DataLabel = ptext SLIT("I_")
774 | externallyVisibleCLabel lbl = char 'E'
775 | otherwise = char 'I'
778 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
779 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
781 instance Monad TE where
782 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
783 return a = TE $ \s -> (a, s)
785 te_lbl :: CLabel -> TE ()
786 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
788 te_temp :: LocalReg -> TE ()
789 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
791 runTE :: TE () -> TEState
792 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
794 te_Static :: CmmStatic -> TE ()
795 te_Static (CmmStaticLit lit) = te_Lit lit
796 te_Static _ = return ()
798 te_BB :: CmmBasicBlock -> TE ()
799 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
801 te_Lit :: CmmLit -> TE ()
802 te_Lit (CmmLabel l) = te_lbl l
803 te_Lit (CmmLabelOff l _) = te_lbl l
804 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
807 te_Stmt :: CmmStmt -> TE ()
808 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
809 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
810 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
811 mapM_ (te_Expr.fst) es
812 te_Stmt (CmmCondBranch e _) = te_Expr e
813 te_Stmt (CmmSwitch e _) = te_Expr e
814 te_Stmt (CmmJump e _) = te_Expr e
815 te_Stmt _ = return ()
817 te_Expr :: CmmExpr -> TE ()
818 te_Expr (CmmLit lit) = te_Lit lit
819 te_Expr (CmmReg r) = te_Reg r
820 te_Expr (CmmLoad e _) = te_Expr e
821 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
822 te_Expr (CmmRegOff r _) = te_Reg r
823 te_Expr _ = return ()
825 te_Reg :: CmmReg -> TE ()
826 te_Reg (CmmLocal l) = te_temp l
830 -- ---------------------------------------------------------------------
831 -- C types for MachReps
833 cCast :: SDoc -> CmmExpr -> SDoc
834 cCast ty expr = parens ty <> pprExpr1 expr
836 -- This is for finding the types of foreign call arguments. For a pointer
837 -- argument, we always cast the argument to (void *), to avoid warnings from
839 machRepHintCType :: MachRep -> MachHint -> SDoc
840 machRepHintCType rep PtrHint = ptext SLIT("void *")
841 machRepHintCType rep SignedHint = machRepSignedCType rep
842 machRepHintCType rep _other = machRepCType rep
844 machRepPtrCType :: MachRep -> SDoc
845 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
846 | otherwise = machRepCType r <> char '*'
848 machRepCType :: MachRep -> SDoc
849 machRepCType r | r == wordRep = ptext SLIT("W_")
850 | otherwise = sized_type
851 where sized_type = case r of
852 I8 -> ptext SLIT("StgWord8")
853 I16 -> ptext SLIT("StgWord16")
854 I32 -> ptext SLIT("StgWord32")
855 I64 -> ptext SLIT("StgWord64")
856 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
857 F64 -> ptext SLIT("StgDouble")
858 _ -> panic "machRepCType"
860 machRepSignedCType :: MachRep -> SDoc
861 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
862 | otherwise = sized_type
863 where sized_type = case r of
864 I8 -> ptext SLIT("StgInt8")
865 I16 -> ptext SLIT("StgInt16")
866 I32 -> ptext SLIT("StgInt32")
867 I64 -> ptext SLIT("StgInt64")
868 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
869 F64 -> ptext SLIT("StgDouble")
870 _ -> panic "machRepCType"
872 -- ---------------------------------------------------------------------
873 -- print strings as valid C strings
875 -- Assumes it contains only characters '\0'..'\xFF'!
876 pprFSInCStyle :: FastString -> SDoc
877 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
879 pprStringInCStyle :: String -> SDoc
880 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
882 charToC :: Char -> String
883 charToC '\"' = "\\\""
884 charToC '\'' = "\\\'"
885 charToC '\\' = "\\\\"
886 charToC c | c >= ' ' && c <= '~' = [c]
887 | c > '\xFF' = panic ("charToC "++show c)
889 chr (ord '0' + ord c `div` 64),
890 chr (ord '0' + ord c `div` 8 `mod` 8),
891 chr (ord '0' + ord c `mod` 8)]
894 -- ---------------------------------------------------------------------------
895 -- Initialising static objects with floating-point numbers. We can't
896 -- just emit the floating point number, because C will cast it to an int
897 -- by rounding it. We want the actual bit-representation of the float.
899 -- This is a hack to turn the floating point numbers into ints that we
900 -- can safely initialise to static locations.
903 | machRepByteWidth F64 == 2 * wORD_SIZE = True
904 | machRepByteWidth F64 == wORD_SIZE = False
905 | otherwise = panic "big_doubles"
907 #if __GLASGOW_HASKELL__ >= 504
908 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
909 newFloatArray = newArray_
911 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
912 newDoubleArray = newArray_
914 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
915 castFloatToIntArray = castSTUArray
917 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
918 castDoubleToIntArray = castSTUArray
920 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
921 writeFloatArray = writeArray
923 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
924 writeDoubleArray = writeArray
926 readIntArray :: STUArray s Int Int -> Int -> ST s Int
927 readIntArray = readArray
931 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
932 castFloatToIntArray = return
934 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
935 castDoubleToIntArray = return
939 -- floats are always 1 word
940 floatToWord :: Rational -> CmmLit
943 arr <- newFloatArray ((0::Int),0)
944 writeFloatArray arr 0 (fromRational r)
945 arr' <- castFloatToIntArray arr
946 i <- readIntArray arr' 0
947 return (CmmInt (toInteger i) wordRep)
950 doubleToWords :: Rational -> [CmmLit]
952 | big_doubles -- doubles are 2 words
954 arr <- newDoubleArray ((0::Int),1)
955 writeDoubleArray arr 0 (fromRational r)
956 arr' <- castDoubleToIntArray arr
957 i1 <- readIntArray arr' 0
958 i2 <- readIntArray arr' 1
959 return [ CmmInt (toInteger i1) wordRep
960 , CmmInt (toInteger i2) wordRep
963 | otherwise -- doubles are 1 word
965 arr <- newDoubleArray ((0::Int),0)
966 writeDoubleArray arr 0 (fromRational r)
967 arr' <- castDoubleToIntArray arr
968 i <- readIntArray arr' 0
969 return [ CmmInt (toInteger i) wordRep ]
972 -- ---------------------------------------------------------------------------
976 wordShift = machRepLogWidth wordRep
978 commafy :: [SDoc] -> SDoc
979 commafy xs = hsep $ punctuate comma xs
981 -- Print in C hex format: 0x13fa
982 pprHexVal :: Integer -> SDoc
983 pprHexVal 0 = ptext SLIT("0x0")
985 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w))
986 | otherwise = ptext SLIT("0x") <> go w
991 (q,r) = w' `quotRem` 16
992 dig | r < 10 = char (chr (fromInteger r + ord '0'))
993 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))