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 DynFlags ( DynFlags, DynFlag(..), dopt )
34 import Unique ( getUnique )
37 import UniqFM ( eltsUFM )
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 :: DynFlags -> [Cmm] -> SDoc
64 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
67 | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
70 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
71 writeCs dflags handle cmms
72 = printForC handle (pprCs dflags cmms)
74 -- --------------------------------------------------------------------------
75 -- Now do some real work
77 -- for fun, we could call cmmToCmm over the tops...
81 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
86 pprTop :: CmmTop -> SDoc
87 pprTop (CmmProc info clbl _params blocks) =
89 then pprDataExterns info $$
90 pprWordArray (entryLblToInfoLbl clbl) info
94 -- the first block doesn't get a label:
95 (BasicBlock _ stmts : rest) -> vcat [
98 (if (externallyVisibleCLabel clbl)
99 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
102 nest 8 (vcat (map pprStmt stmts)) $$
103 vcat (map pprBBlock rest),
108 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
111 -- Chunks of static data.
113 -- We only handle (a) arrays of word-sized things and (b) strings.
115 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
117 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
118 ptext SLIT("[] = "), pprStringInCStyle str, semi
121 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
123 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
124 brackets (int size), semi
127 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
128 pprDataExterns lits $$
129 pprWordArray lbl lits
131 -- these shouldn't appear?
132 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
135 -- --------------------------------------------------------------------------
136 -- BasicBlocks are self-contained entities: they always end in a jump.
138 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
139 -- as many jumps as possible into fall throughs.
142 pprBBlock :: CmmBasicBlock -> SDoc
143 pprBBlock (BasicBlock lbl stmts) =
145 pprTrace "pprC.pprBBlock: curious empty code block for"
146 (pprBlockId lbl) empty
148 nest 4 (pprBlockId lbl <> colon) $$
149 nest 8 (vcat (map pprStmt stmts))
151 -- --------------------------------------------------------------------------
152 -- Info tables. Just arrays of words.
153 -- See codeGen/ClosureInfo, and nativeGen/PprMach
155 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
157 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
158 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
159 $$ nest 8 (commafy (pprStatics ds))
163 -- has to be static, if it isn't globally visible
165 pprLocalness :: CLabel -> SDoc
166 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
169 -- --------------------------------------------------------------------------
173 pprStmt :: CmmStmt -> SDoc
175 pprStmt stmt = case stmt of
177 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
179 CmmAssign dest src -> pprAssign dest src
182 | rep == I64 && wordRep /= I64
183 -> ptext SLIT("ASSIGN_Word64") <>
184 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
186 | rep == F64 && wordRep /= I64
187 -> ptext SLIT("ASSIGN_DBL") <>
188 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
191 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
195 CmmCall (CmmForeignCall fn cconv) results args volatile ->
196 -- Controversial: leave this out for now.
199 pprCall ppr_fn cconv results args volatile
202 CmmLit (CmmLabel lbl) -> pprCLabel lbl
203 _other -> parens (cCast (pprCFunType cconv results args) fn)
204 -- for a dynamic call, cast the expression to
205 -- a function of the right type (we hope).
207 -- we #undef a function before calling it: the FFI is supposed to be
208 -- an interface specifically to C, not to C+CPP. For one thing, this
209 -- makes the via-C route more compatible with the NCG. If macros
210 -- are being used for optimisation, then inline functions are probably
212 pprUndef (CmmLit (CmmLabel lbl)) =
213 ptext SLIT("#undef") <+> pprCLabel lbl
216 CmmCall (CmmPrim op) results args volatile ->
217 pprCall ppr_fn CCallConv results args volatile
219 ppr_fn = pprCallishMachOp_for_C op
221 CmmBranch ident -> pprBranch ident
222 CmmCondBranch expr ident -> pprCondBranch expr ident
223 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
224 CmmSwitch arg ids -> pprSwitch arg ids
226 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
227 pprCFunType cconv ress args
230 parens (text (ccallConvAttribute cconv) <> char '*'),
231 parens (commafy (map arg_type args))
234 res_type [] = ptext SLIT("void")
235 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
237 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
239 -- ---------------------------------------------------------------------
240 -- unconditional branches
241 pprBranch :: BlockId -> SDoc
242 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
245 -- ---------------------------------------------------------------------
246 -- conditional branches to local labels
247 pprCondBranch :: CmmExpr -> BlockId -> SDoc
248 pprCondBranch expr ident
249 = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
250 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
253 -- ---------------------------------------------------------------------
254 -- a local table branch
256 -- we find the fall-through cases
258 -- N.B. we remove Nothing's from the list of branches, as they are
259 -- 'undefined'. However, they may be defined one day, so we better
260 -- document this behaviour.
262 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
263 pprSwitch e maybe_ids
264 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
265 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
267 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
268 4 (vcat ( map caseify pairs2 )))
272 sndEq (_,x) (_,y) = x == y
275 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
278 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
279 ptext SLIT("/* fall through */") ]
282 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
283 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
285 -- ---------------------------------------------------------------------
289 -- C Types: the invariant is that the C expression generated by
293 -- has a type in C which is also given by
295 -- machRepCType (cmmExprRep e)
297 -- (similar invariants apply to the rest of the pretty printer).
299 pprExpr :: CmmExpr -> SDoc
300 pprExpr e = case e of
301 CmmLit lit -> pprLit lit
303 CmmLoad e I64 | wordRep /= I64
304 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
306 CmmLoad e F64 | wordRep /= I64
307 -> ptext SLIT("PK_DBL") <> parens (mkP_ <> pprExpr1 e)
309 CmmLoad (CmmReg r) rep
310 | isPtrReg r && rep == wordRep
311 -> char '*' <> pprAsPtrReg r
313 CmmLoad (CmmRegOff r 0) rep
314 | isPtrReg r && rep == wordRep
315 -> char '*' <> pprAsPtrReg r
317 CmmLoad (CmmRegOff r off) rep
318 | isPtrReg r && rep == wordRep
319 -- ToDo: check that the offset is a word multiple?
320 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
324 char '*' <> parens (cCast (machRepPtrCType rep) expr)
326 CmmReg reg -> pprCastReg reg
327 CmmRegOff reg 0 -> pprCastReg reg
330 | i > 0 -> pprRegOff (char '+') i
331 | otherwise -> pprRegOff (char '-') (-i)
333 pprRegOff op i' = pprCastReg reg <> op <> int i'
335 CmmMachOp mop args -> pprMachOpApp mop args
337 pprExpr1 :: CmmExpr -> SDoc
338 pprExpr1 (CmmLit lit) = pprLit1 lit
339 pprExpr1 e@(CmmReg _reg) = pprExpr e
340 pprExpr1 other = parens (pprExpr other)
342 -- --------------------------------------------------------------------------
343 -- MachOp applications
345 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
349 = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
350 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
351 isMulMayOfloOp (MO_S_MulMayOflo _) = True
352 isMulMayOfloOp _ = False
354 pprMachOpApp mop args
357 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
360 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
362 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
365 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
366 | otherwise = pprExpr1 e
368 -- --------------------------------------------------------------------------
371 pprLit :: CmmLit -> SDoc
372 pprLit lit = case lit of
373 CmmInt i rep -> pprHexVal i rep
374 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
375 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
376 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
377 CmmLabelDiffOff clbl1 clbl2 i
379 -- * the lit must occur in the info table clbl2
380 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
381 -- The Mangler is expected to convert any reference to an SRT,
382 -- a slow entry point or a large bitmap
383 -- from an info table to an offset.
384 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
386 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
388 pprLit1 :: CmmLit -> SDoc
389 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
390 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
391 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
392 pprLit1 other = pprLit other
394 -- ---------------------------------------------------------------------------
397 pprStatics :: [CmmStatic] -> [SDoc]
399 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
400 = pprLit1 (floatToWord f) : pprStatics rest
401 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
402 = map pprLit1 (doubleToWords f) ++ pprStatics rest
403 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
404 | machRepByteWidth I32 == wORD_SIZE
405 #ifdef WORDS_BIGENDIAN
406 = pprStatics (CmmStaticLit (CmmInt q I32) :
407 CmmStaticLit (CmmInt r I32) : rest)
409 = pprStatics (CmmStaticLit (CmmInt r I32) :
410 CmmStaticLit (CmmInt q I32) : rest)
412 where r = i .&. 0xffffffff
414 pprStatics (CmmStaticLit lit : rest)
415 = pprLit1 lit : pprStatics rest
416 pprStatics (other : rest)
417 = pprPanic "pprWord" (pprStatic other)
419 pprStatic :: CmmStatic -> SDoc
420 pprStatic s = case s of
422 CmmStaticLit lit -> nest 4 (pprLit lit)
423 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
424 CmmDataLabel clbl -> pprCLabel clbl <> colon
425 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
427 -- these should be inlined, like the old .hc
428 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
431 -- ---------------------------------------------------------------------------
434 pprBlockId :: BlockId -> SDoc
435 pprBlockId b = char '_' <> ppr (getUnique b)
437 -- --------------------------------------------------------------------------
438 -- Print a MachOp in a way suitable for emitting via C.
441 pprMachOp_for_C :: MachOp -> SDoc
443 pprMachOp_for_C mop = case mop of
445 -- Integer operations
448 MO_Eq _ -> ptext SLIT("==")
449 MO_Ne _ -> ptext SLIT("!=")
452 MO_S_Quot _ -> char '/'
453 MO_S_Rem _ -> char '%'
454 MO_S_Neg _ -> char '-'
456 MO_U_Quot _ -> char '/'
457 MO_U_Rem _ -> char '%'
459 -- Signed comparisons (floating-point comparisons also use these)
460 -- & Unsigned comparisons
461 MO_S_Ge _ -> ptext SLIT(">=")
462 MO_S_Le _ -> ptext SLIT("<=")
463 MO_S_Gt _ -> char '>'
464 MO_S_Lt _ -> char '<'
466 MO_U_Ge _ -> ptext SLIT(">=")
467 MO_U_Le _ -> ptext SLIT("<=")
468 MO_U_Gt _ -> char '>'
469 MO_U_Lt _ -> char '<'
471 -- Bitwise operations. Not all of these may be supported at all
472 -- sizes, and only integral MachReps are valid.
477 MO_Shl _ -> ptext SLIT("<<")
478 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
479 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
481 -- Conversions. Some of these will be NOPs.
482 -- Floating-point conversions use the signed variant.
483 -- We won't know to generate (void*) casts here, but maybe from
487 MO_U_Conv I8 I8 -> empty
488 MO_U_Conv I16 I16 -> empty
489 MO_U_Conv I32 I32 -> empty
490 MO_U_Conv I64 I64 -> empty
491 MO_U_Conv I128 I128 -> empty
492 MO_S_Conv I8 I8 -> empty
493 MO_S_Conv I16 I16 -> empty
494 MO_S_Conv I32 I32 -> empty
495 MO_S_Conv I64 I64 -> empty
496 MO_S_Conv I128 I128 -> empty
498 MO_U_Conv _from to -> parens (machRepCType to)
499 MO_S_Conv _from to -> parens (machRepSignedCType to)
501 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
503 signedOp :: MachOp -> Bool
504 signedOp (MO_S_Quot _) = True
505 signedOp (MO_S_Rem _) = True
506 signedOp (MO_S_Neg _) = True
507 signedOp (MO_S_Ge _) = True
508 signedOp (MO_S_Le _) = True
509 signedOp (MO_S_Gt _) = True
510 signedOp (MO_S_Lt _) = True
511 signedOp (MO_S_Shr _) = True
512 signedOp (MO_S_Conv _ _) = True
515 -- ---------------------------------------------------------------------
516 -- tend to be implemented by foreign calls
518 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
520 pprCallishMachOp_for_C mop
522 MO_F64_Pwr -> ptext SLIT("pow")
523 MO_F64_Sin -> ptext SLIT("sin")
524 MO_F64_Cos -> ptext SLIT("cos")
525 MO_F64_Tan -> ptext SLIT("tan")
526 MO_F64_Sinh -> ptext SLIT("sinh")
527 MO_F64_Cosh -> ptext SLIT("cosh")
528 MO_F64_Tanh -> ptext SLIT("tanh")
529 MO_F64_Asin -> ptext SLIT("asin")
530 MO_F64_Acos -> ptext SLIT("acos")
531 MO_F64_Atan -> ptext SLIT("atan")
532 MO_F64_Log -> ptext SLIT("log")
533 MO_F64_Exp -> ptext SLIT("exp")
534 MO_F64_Sqrt -> ptext SLIT("sqrt")
535 MO_F32_Pwr -> ptext SLIT("pow")
536 MO_F32_Sin -> ptext SLIT("sin")
537 MO_F32_Cos -> ptext SLIT("cos")
538 MO_F32_Tan -> ptext SLIT("tan")
539 MO_F32_Sinh -> ptext SLIT("sinh")
540 MO_F32_Cosh -> ptext SLIT("cosh")
541 MO_F32_Tanh -> ptext SLIT("tanh")
542 MO_F32_Asin -> ptext SLIT("asin")
543 MO_F32_Acos -> ptext SLIT("acos")
544 MO_F32_Atan -> ptext SLIT("atan")
545 MO_F32_Log -> ptext SLIT("log")
546 MO_F32_Exp -> ptext SLIT("exp")
547 MO_F32_Sqrt -> ptext SLIT("sqrt")
549 -- ---------------------------------------------------------------------
553 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
555 mkJMP_ i = ptext SLIT("JMP_") <> parens i
556 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
557 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
561 mkFB_ = ptext SLIT("FB_") -- function code begin
562 mkFE_ = ptext SLIT("FE_") -- function code end
564 -- from includes/Stg.h
566 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
568 mkC_ = ptext SLIT("(C_)") -- StgChar
569 mkW_ = ptext SLIT("(W_)") -- StgWord
570 mkP_ = ptext SLIT("(P_)") -- StgWord*
571 mkPP_ = ptext SLIT("(PP_)") -- P_*
572 mkI_ = ptext SLIT("(I_)") -- StgInt
573 mkA_ = ptext SLIT("(A_)") -- StgAddr
574 mkD_ = ptext SLIT("(D_)") -- const StgWord*
575 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
576 mkB_ = ptext SLIT("(B_)") -- StgByteArray
577 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
579 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
580 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
583 -- ---------------------------------------------------------------------
587 -- Generating assignments is what we're all about, here
589 pprAssign :: CmmReg -> CmmExpr -> SDoc
591 -- dest is a reg, rhs is a reg
592 pprAssign r1 (CmmReg r2)
593 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
594 || isPtrReg r1 && isPtrReg r2
595 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
597 -- dest is a reg, rhs is a CmmRegOff
598 pprAssign r1 (CmmRegOff r2 off)
599 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
600 || isPtrReg r1 && isPtrReg r2
601 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
603 off1 | isPtrReg r2 = off `shiftR` wordShift
606 (op,off') | off >= 0 = (char '+', off1)
607 | otherwise = (char '-', -off1)
609 -- dest is a reg, rhs is anything.
610 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
611 -- the lvalue elicits a warning from new GCC versions (3.4+).
614 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
615 | Just ty <- strangeRegType r1
616 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
618 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
620 -- ---------------------------------------------------------------------
624 | isStrangeTypeReg reg = mkW_ <> pprReg reg
625 | otherwise = pprReg reg
627 -- True if the register has type StgPtr in C, otherwise it has an
628 -- integer type. We need to take care with pointer arithmetic on registers
630 isPtrReg :: CmmReg -> Bool
631 isPtrReg (CmmLocal _) = False
632 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
634 isPtrGlobalReg :: GlobalReg -> Bool
635 isPtrGlobalReg (VanillaReg n) = True
636 isPtrGlobalReg Sp = True
637 isPtrGlobalReg Hp = True
638 isPtrGlobalReg HpLim = True
639 isPtrGlobalReg SpLim = True
640 isPtrGlobalReg _ = False
642 -- True if in C this register doesn't have the type given by
643 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
644 isStrangeTypeReg :: CmmReg -> Bool
645 isStrangeTypeReg (CmmLocal _) = False
646 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
648 isStrangeTypeGlobal :: GlobalReg -> Bool
649 isStrangeTypeGlobal CurrentTSO = True
650 isStrangeTypeGlobal CurrentNursery = True
651 isStrangeTypeGlobal BaseReg = True
652 isStrangeTypeGlobal r = isPtrGlobalReg r
654 strangeRegType :: CmmReg -> Maybe SDoc
655 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
656 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
657 strangeRegType _ = Nothing
659 -- pprReg just prints the register name.
661 pprReg :: CmmReg -> SDoc
663 CmmLocal local -> pprLocalReg local
664 CmmGlobal global -> pprGlobalReg global
666 pprAsPtrReg :: CmmReg -> SDoc
667 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
668 pprAsPtrReg other_reg = pprReg other_reg
670 pprGlobalReg :: GlobalReg -> SDoc
671 pprGlobalReg gr = case gr of
672 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
673 FloatReg n -> char 'F' <> int n
674 DoubleReg n -> char 'D' <> int n
675 LongReg n -> char 'L' <> int n
676 Sp -> ptext SLIT("Sp")
677 SpLim -> ptext SLIT("SpLim")
678 Hp -> ptext SLIT("Hp")
679 HpLim -> ptext SLIT("HpLim")
680 CurrentTSO -> ptext SLIT("CurrentTSO")
681 CurrentNursery -> ptext SLIT("CurrentNursery")
682 HpAlloc -> ptext SLIT("HpAlloc")
683 BaseReg -> ptext SLIT("BaseReg")
684 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
685 GCFun -> ptext SLIT("stg_gc_fun")
687 pprLocalReg :: LocalReg -> SDoc
688 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
690 -- -----------------------------------------------------------------------------
693 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
694 -> Maybe [GlobalReg] -> SDoc
696 pprCall ppr_fn cconv results args vols
697 | not (is_cish cconv)
698 = panic "pprForeignCall: unknown calling convention"
702 ptext SLIT("CALLER_SAVE_SYSTEM") $$
703 hcat [ ppr_results results, ppr_fn,
704 parens (commafy (map pprArg args)), semi ] $$
705 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
708 ppr_results [] = empty
709 ppr_results [(one,hint)]
710 = pprReg one <> ptext SLIT(" = ")
711 <> pprUnHint hint (cmmRegRep one)
712 ppr_results _other = panic "pprCall: multiple results"
714 pprArg (expr, PtrHint)
715 = cCast (ptext SLIT("void *")) expr
716 -- see comment by machRepHintCType below
717 pprArg (expr, SignedHint)
718 = cCast (machRepSignedCType (cmmExprRep expr)) expr
719 pprArg (expr, _other)
722 pprUnHint PtrHint rep = parens (machRepCType rep)
723 pprUnHint SignedHint rep = parens (machRepCType rep)
724 pprUnHint _ _ = empty
726 save = save_restore SLIT("CALLER_SAVE")
727 restore = save_restore SLIT("CALLER_RESTORE")
729 -- Nothing says "I don't know what's live; save everything"
730 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
731 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
732 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
733 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
735 pprGlobalRegName :: GlobalReg -> SDoc
736 pprGlobalRegName gr = case gr of
737 VanillaReg n -> char 'R' <> int n -- without the .w suffix
740 -- Currently we only have these two calling conventions, but this might
741 -- change in the future...
742 is_cish CCallConv = True
743 is_cish StdCallConv = True
745 -- ---------------------------------------------------------------------
746 -- Find and print local and external declarations for a list of
749 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
750 pprTempAndExternDecls stmts
751 = (vcat (map pprTempDecl (eltsUFM temps)),
752 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
753 where (temps, lbls) = runTE (mapM_ te_BB stmts)
755 pprDataExterns :: [CmmStatic] -> SDoc
756 pprDataExterns statics
757 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
758 where (_, lbls) = runTE (mapM_ te_Static statics)
760 pprTempDecl :: LocalReg -> SDoc
761 pprTempDecl l@(LocalReg _uniq rep)
762 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
764 pprExternDecl :: Bool -> CLabel -> SDoc
765 pprExternDecl in_srt lbl
766 -- do not print anything for "known external" things
767 | not (needsCDecl lbl) = empty
769 hcat [ visibility, label_type (labelType lbl),
770 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
773 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
776 label_type CodeLabel = ptext SLIT("F_")
777 label_type DataLabel = ptext SLIT("I_")
780 | externallyVisibleCLabel lbl = char 'E'
781 | otherwise = char 'I'
784 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
785 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
787 instance Monad TE where
788 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
789 return a = TE $ \s -> (a, s)
791 te_lbl :: CLabel -> TE ()
792 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
794 te_temp :: LocalReg -> TE ()
795 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
797 runTE :: TE () -> TEState
798 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
800 te_Static :: CmmStatic -> TE ()
801 te_Static (CmmStaticLit lit) = te_Lit lit
802 te_Static _ = return ()
804 te_BB :: CmmBasicBlock -> TE ()
805 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
807 te_Lit :: CmmLit -> TE ()
808 te_Lit (CmmLabel l) = te_lbl l
809 te_Lit (CmmLabelOff l _) = te_lbl l
810 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
813 te_Stmt :: CmmStmt -> TE ()
814 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
815 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
816 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
817 mapM_ (te_Expr.fst) es
818 te_Stmt (CmmCondBranch e _) = te_Expr e
819 te_Stmt (CmmSwitch e _) = te_Expr e
820 te_Stmt (CmmJump e _) = te_Expr e
821 te_Stmt _ = return ()
823 te_Expr :: CmmExpr -> TE ()
824 te_Expr (CmmLit lit) = te_Lit lit
825 te_Expr (CmmLoad e _) = te_Expr e
826 te_Expr (CmmReg r) = te_Reg r
827 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
828 te_Expr (CmmRegOff r _) = te_Reg r
830 te_Reg :: CmmReg -> TE ()
831 te_Reg (CmmLocal l) = te_temp l
835 -- ---------------------------------------------------------------------
836 -- C types for MachReps
838 cCast :: SDoc -> CmmExpr -> SDoc
839 cCast ty expr = parens ty <> pprExpr1 expr
841 -- This is for finding the types of foreign call arguments. For a pointer
842 -- argument, we always cast the argument to (void *), to avoid warnings from
844 machRepHintCType :: MachRep -> MachHint -> SDoc
845 machRepHintCType rep PtrHint = ptext SLIT("void *")
846 machRepHintCType rep SignedHint = machRepSignedCType rep
847 machRepHintCType rep _other = machRepCType rep
849 machRepPtrCType :: MachRep -> SDoc
850 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
851 | otherwise = machRepCType r <> char '*'
853 machRepCType :: MachRep -> SDoc
854 machRepCType r | r == wordRep = ptext SLIT("W_")
855 | otherwise = sized_type
856 where sized_type = case r of
857 I8 -> ptext SLIT("StgWord8")
858 I16 -> ptext SLIT("StgWord16")
859 I32 -> ptext SLIT("StgWord32")
860 I64 -> ptext SLIT("StgWord64")
861 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
862 F64 -> ptext SLIT("StgDouble")
863 _ -> panic "machRepCType"
865 machRepSignedCType :: MachRep -> SDoc
866 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
867 | otherwise = sized_type
868 where sized_type = case r of
869 I8 -> ptext SLIT("StgInt8")
870 I16 -> ptext SLIT("StgInt16")
871 I32 -> ptext SLIT("StgInt32")
872 I64 -> ptext SLIT("StgInt64")
873 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
874 F64 -> ptext SLIT("StgDouble")
875 _ -> panic "machRepCType"
877 -- ---------------------------------------------------------------------
878 -- print strings as valid C strings
880 -- Assumes it contains only characters '\0'..'\xFF'!
881 pprFSInCStyle :: FastString -> SDoc
882 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
884 pprStringInCStyle :: String -> SDoc
885 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
887 charToC :: Char -> String
888 charToC '\"' = "\\\""
889 charToC '\'' = "\\\'"
890 charToC '\\' = "\\\\"
891 charToC c | c >= ' ' && c <= '~' = [c]
892 | c > '\xFF' = panic ("charToC "++show c)
894 chr (ord '0' + ord c `div` 64),
895 chr (ord '0' + ord c `div` 8 `mod` 8),
896 chr (ord '0' + ord c `mod` 8)]
899 -- ---------------------------------------------------------------------------
900 -- Initialising static objects with floating-point numbers. We can't
901 -- just emit the floating point number, because C will cast it to an int
902 -- by rounding it. We want the actual bit-representation of the float.
904 -- This is a hack to turn the floating point numbers into ints that we
905 -- can safely initialise to static locations.
908 | machRepByteWidth F64 == 2 * wORD_SIZE = True
909 | machRepByteWidth F64 == wORD_SIZE = False
910 | otherwise = panic "big_doubles"
912 #if __GLASGOW_HASKELL__ >= 504
913 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
914 newFloatArray = newArray_
916 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
917 newDoubleArray = newArray_
919 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
920 castFloatToIntArray = castSTUArray
922 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
923 castDoubleToIntArray = castSTUArray
925 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
926 writeFloatArray = writeArray
928 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
929 writeDoubleArray = writeArray
931 readIntArray :: STUArray s Int Int -> Int -> ST s Int
932 readIntArray = readArray
936 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
937 castFloatToIntArray = return
939 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
940 castDoubleToIntArray = return
944 -- floats are always 1 word
945 floatToWord :: Rational -> CmmLit
948 arr <- newFloatArray ((0::Int),0)
949 writeFloatArray arr 0 (fromRational r)
950 arr' <- castFloatToIntArray arr
951 i <- readIntArray arr' 0
952 return (CmmInt (toInteger i) wordRep)
955 doubleToWords :: Rational -> [CmmLit]
957 | big_doubles -- doubles are 2 words
959 arr <- newDoubleArray ((0::Int),1)
960 writeDoubleArray arr 0 (fromRational r)
961 arr' <- castDoubleToIntArray arr
962 i1 <- readIntArray arr' 0
963 i2 <- readIntArray arr' 1
964 return [ CmmInt (toInteger i1) wordRep
965 , CmmInt (toInteger i2) wordRep
968 | otherwise -- doubles are 1 word
970 arr <- newDoubleArray ((0::Int),0)
971 writeDoubleArray arr 0 (fromRational r)
972 arr' <- castDoubleToIntArray arr
973 i <- readIntArray arr' 0
974 return [ CmmInt (toInteger i) wordRep ]
977 -- ---------------------------------------------------------------------------
981 wordShift = machRepLogWidth wordRep
983 commafy :: [SDoc] -> SDoc
984 commafy xs = hsep $ punctuate comma xs
986 -- Print in C hex format: 0x13fa
987 pprHexVal :: Integer -> MachRep -> SDoc
988 pprHexVal 0 _ = ptext SLIT("0x0")
990 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
991 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
993 -- type suffix for literals:
994 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
995 -- signed values for doing signed operations, but at all other
996 -- times values are unsigned. This also helps eliminate occasional
997 -- warnings about integer overflow from gcc.
999 -- on 32-bit platforms, add "ULL" to 64-bit literals
1000 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1001 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1002 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1003 repsuffix _ = char 'U'
1008 (q,r) = w' `quotRem` 16
1009 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1010 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))