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 )
41 import StaticFlags ( opt_Unregisterised )
44 import Data.List ( intersperse, groupBy )
45 import Data.Bits ( shiftR )
46 import Char ( ord, chr )
49 import Data.Word ( Word8 )
52 import PprCmm () -- instances only
56 #if __GLASGOW_HASKELL__ >= 504
61 -- --------------------------------------------------------------------------
64 pprCs :: DynFlags -> [Cmm] -> SDoc
66 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
69 | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
72 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
73 writeCs dflags handle cmms
74 = printForC handle (pprCs dflags cmms)
76 -- --------------------------------------------------------------------------
77 -- Now do some real work
79 -- for fun, we could call cmmToCmm over the tops...
83 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
88 pprTop :: CmmTop -> SDoc
89 pprTop (CmmProc info clbl _params blocks) =
91 then pprDataExterns info $$
92 pprWordArray (entryLblToInfoLbl clbl) info
96 -- the first block doesn't get a label:
97 (BasicBlock _ stmts : rest) -> vcat [
100 (if (externallyVisibleCLabel clbl)
101 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
104 nest 8 (vcat (map pprStmt stmts)) $$
105 vcat (map pprBBlock rest),
110 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
113 -- Chunks of static data.
115 -- We only handle (a) arrays of word-sized things and (b) strings.
117 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
119 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
120 ptext SLIT("[] = "), pprStringInCStyle str, semi
123 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
125 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
126 brackets (int size), semi
129 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
130 pprDataExterns lits $$
131 pprWordArray lbl lits
133 -- these shouldn't appear?
134 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
137 -- --------------------------------------------------------------------------
138 -- BasicBlocks are self-contained entities: they always end in a jump.
140 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
141 -- as many jumps as possible into fall throughs.
144 pprBBlock :: CmmBasicBlock -> SDoc
145 pprBBlock (BasicBlock lbl stmts) =
147 pprTrace "pprC.pprBBlock: curious empty code block for"
148 (pprBlockId lbl) empty
150 nest 4 (pprBlockId lbl <> colon) $$
151 nest 8 (vcat (map pprStmt stmts))
153 -- --------------------------------------------------------------------------
154 -- Info tables. Just arrays of words.
155 -- See codeGen/ClosureInfo, and nativeGen/PprMach
157 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
159 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
160 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
161 $$ nest 8 (commafy (pprStatics ds))
165 -- has to be static, if it isn't globally visible
167 pprLocalness :: CLabel -> SDoc
168 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
171 -- --------------------------------------------------------------------------
175 pprStmt :: CmmStmt -> SDoc
177 pprStmt stmt = case stmt of
179 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
181 CmmAssign dest src -> pprAssign dest src
184 | rep == I64 && wordRep /= I64
185 -> ptext SLIT("ASSIGN_Word64") <>
186 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
188 | rep == F64 && wordRep /= I64
189 -> ptext SLIT("ASSIGN_DBL") <>
190 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
193 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
197 CmmCall (CmmForeignCall fn cconv) results args volatile ->
198 -- Controversial: leave this out for now.
201 pprCall ppr_fn cconv results args volatile
204 CmmLit (CmmLabel lbl) -> pprCLabel lbl
205 _other -> parens (cCast (pprCFunType cconv results args) fn)
206 -- for a dynamic call, cast the expression to
207 -- a function of the right type (we hope).
209 -- we #undef a function before calling it: the FFI is supposed to be
210 -- an interface specifically to C, not to C+CPP. For one thing, this
211 -- makes the via-C route more compatible with the NCG. If macros
212 -- are being used for optimisation, then inline functions are probably
214 pprUndef (CmmLit (CmmLabel lbl)) =
215 ptext SLIT("#undef") <+> pprCLabel lbl
218 CmmCall (CmmPrim op) results args volatile ->
219 pprCall ppr_fn CCallConv results args volatile
221 ppr_fn = pprCallishMachOp_for_C op
223 CmmBranch ident -> pprBranch ident
224 CmmCondBranch expr ident -> pprCondBranch expr ident
225 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
226 CmmSwitch arg ids -> pprSwitch arg ids
228 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
229 pprCFunType cconv ress args
232 parens (text (ccallConvAttribute cconv) <> char '*'),
233 parens (commafy (map arg_type args))
236 res_type [] = ptext SLIT("void")
237 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
239 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
241 -- ---------------------------------------------------------------------
242 -- unconditional branches
243 pprBranch :: BlockId -> SDoc
244 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
247 -- ---------------------------------------------------------------------
248 -- conditional branches to local labels
249 pprCondBranch :: CmmExpr -> BlockId -> SDoc
250 pprCondBranch expr ident
251 = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
252 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
255 -- ---------------------------------------------------------------------
256 -- a local table branch
258 -- we find the fall-through cases
260 -- N.B. we remove Nothing's from the list of branches, as they are
261 -- 'undefined'. However, they may be defined one day, so we better
262 -- document this behaviour.
264 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
265 pprSwitch e maybe_ids
266 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
267 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
269 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
270 4 (vcat ( map caseify pairs2 )))
274 sndEq (_,x) (_,y) = x == y
277 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
280 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
281 ptext SLIT("/* fall through */") ]
284 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
285 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
287 -- ---------------------------------------------------------------------
291 -- C Types: the invariant is that the C expression generated by
295 -- has a type in C which is also given by
297 -- machRepCType (cmmExprRep e)
299 -- (similar invariants apply to the rest of the pretty printer).
301 pprExpr :: CmmExpr -> SDoc
302 pprExpr e = case e of
303 CmmLit lit -> pprLit lit
305 CmmLoad e I64 | wordRep /= I64
306 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
308 CmmLoad e F64 | wordRep /= I64
309 -> ptext SLIT("PK_DBL") <> parens (mkP_ <> pprExpr1 e)
311 CmmLoad (CmmReg r) rep
312 | isPtrReg r && rep == wordRep
313 -> char '*' <> pprAsPtrReg r
315 CmmLoad (CmmRegOff r 0) rep
316 | isPtrReg r && rep == wordRep
317 -> char '*' <> pprAsPtrReg r
319 CmmLoad (CmmRegOff r off) rep
320 | isPtrReg r && rep == wordRep
321 -- ToDo: check that the offset is a word multiple?
322 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
326 char '*' <> parens (cCast (machRepPtrCType rep) expr)
328 CmmReg reg -> pprCastReg reg
329 CmmRegOff reg 0 -> pprCastReg reg
332 | i > 0 -> pprRegOff (char '+') i
333 | otherwise -> pprRegOff (char '-') (-i)
335 pprRegOff op i' = pprCastReg reg <> op <> int i'
337 CmmMachOp mop args -> pprMachOpApp mop args
339 pprExpr1 :: CmmExpr -> SDoc
340 pprExpr1 (CmmLit lit) = pprLit1 lit
341 pprExpr1 e@(CmmReg _reg) = pprExpr e
342 pprExpr1 other = parens (pprExpr other)
344 -- --------------------------------------------------------------------------
345 -- MachOp applications
347 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
351 = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
352 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
353 isMulMayOfloOp (MO_S_MulMayOflo _) = True
354 isMulMayOfloOp _ = False
356 pprMachOpApp mop args
359 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
362 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
364 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
367 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
368 | otherwise = pprExpr1 e
370 -- --------------------------------------------------------------------------
373 pprLit :: CmmLit -> SDoc
374 pprLit lit = case lit of
375 CmmInt i rep -> pprHexVal i rep
376 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
377 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
378 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
379 CmmLabelDiffOff clbl1 clbl2 i
381 -- * the lit must occur in the info table clbl2
382 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
383 -- The Mangler is expected to convert any reference to an SRT,
384 -- a slow entry point or a large bitmap
385 -- from an info table to an offset.
386 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
388 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
390 pprLit1 :: CmmLit -> SDoc
391 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
392 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
393 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
394 pprLit1 other = pprLit other
396 -- ---------------------------------------------------------------------------
399 pprStatics :: [CmmStatic] -> [SDoc]
401 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
402 = pprLit1 (floatToWord f) : pprStatics rest
403 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
404 = map pprLit1 (doubleToWords f) ++ pprStatics rest
405 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
406 | machRepByteWidth I32 == wORD_SIZE
407 #ifdef WORDS_BIGENDIAN
408 = pprStatics (CmmStaticLit (CmmInt q I32) :
409 CmmStaticLit (CmmInt r I32) : rest)
411 = pprStatics (CmmStaticLit (CmmInt r I32) :
412 CmmStaticLit (CmmInt q I32) : rest)
414 where r = i .&. 0xffffffff
416 pprStatics (CmmStaticLit lit : rest)
417 = pprLit1 lit : pprStatics rest
418 pprStatics (other : rest)
419 = pprPanic "pprWord" (pprStatic other)
421 pprStatic :: CmmStatic -> SDoc
422 pprStatic s = case s of
424 CmmStaticLit lit -> nest 4 (pprLit lit)
425 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
426 CmmDataLabel clbl -> pprCLabel clbl <> colon
427 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
429 -- these should be inlined, like the old .hc
430 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
433 -- ---------------------------------------------------------------------------
436 pprBlockId :: BlockId -> SDoc
437 pprBlockId b = char '_' <> ppr (getUnique b)
439 -- --------------------------------------------------------------------------
440 -- Print a MachOp in a way suitable for emitting via C.
443 pprMachOp_for_C :: MachOp -> SDoc
445 pprMachOp_for_C mop = case mop of
447 -- Integer operations
450 MO_Eq _ -> ptext SLIT("==")
451 MO_Ne _ -> ptext SLIT("!=")
454 MO_S_Quot _ -> char '/'
455 MO_S_Rem _ -> char '%'
456 MO_S_Neg _ -> char '-'
458 MO_U_Quot _ -> char '/'
459 MO_U_Rem _ -> char '%'
461 -- Signed comparisons (floating-point comparisons also use these)
462 -- & Unsigned comparisons
463 MO_S_Ge _ -> ptext SLIT(">=")
464 MO_S_Le _ -> ptext SLIT("<=")
465 MO_S_Gt _ -> char '>'
466 MO_S_Lt _ -> char '<'
468 MO_U_Ge _ -> ptext SLIT(">=")
469 MO_U_Le _ -> ptext SLIT("<=")
470 MO_U_Gt _ -> char '>'
471 MO_U_Lt _ -> char '<'
473 -- Bitwise operations. Not all of these may be supported at all
474 -- sizes, and only integral MachReps are valid.
479 MO_Shl _ -> ptext SLIT("<<")
480 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
481 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
483 -- Conversions. Some of these will be NOPs.
484 -- Floating-point conversions use the signed variant.
485 -- We won't know to generate (void*) casts here, but maybe from
489 MO_U_Conv I8 I8 -> empty
490 MO_U_Conv I16 I16 -> empty
491 MO_U_Conv I32 I32 -> empty
492 MO_U_Conv I64 I64 -> empty
493 MO_U_Conv I128 I128 -> empty
494 MO_S_Conv I8 I8 -> empty
495 MO_S_Conv I16 I16 -> empty
496 MO_S_Conv I32 I32 -> empty
497 MO_S_Conv I64 I64 -> empty
498 MO_S_Conv I128 I128 -> empty
500 MO_U_Conv _from to -> parens (machRepCType to)
501 MO_S_Conv _from to -> parens (machRepSignedCType to)
503 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
505 signedOp :: MachOp -> Bool
506 signedOp (MO_S_Quot _) = True
507 signedOp (MO_S_Rem _) = True
508 signedOp (MO_S_Neg _) = True
509 signedOp (MO_S_Ge _) = True
510 signedOp (MO_S_Le _) = True
511 signedOp (MO_S_Gt _) = True
512 signedOp (MO_S_Lt _) = True
513 signedOp (MO_S_Shr _) = True
514 signedOp (MO_S_Conv _ _) = True
517 -- ---------------------------------------------------------------------
518 -- tend to be implemented by foreign calls
520 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
522 pprCallishMachOp_for_C mop
524 MO_F64_Pwr -> ptext SLIT("pow")
525 MO_F64_Sin -> ptext SLIT("sin")
526 MO_F64_Cos -> ptext SLIT("cos")
527 MO_F64_Tan -> ptext SLIT("tan")
528 MO_F64_Sinh -> ptext SLIT("sinh")
529 MO_F64_Cosh -> ptext SLIT("cosh")
530 MO_F64_Tanh -> ptext SLIT("tanh")
531 MO_F64_Asin -> ptext SLIT("asin")
532 MO_F64_Acos -> ptext SLIT("acos")
533 MO_F64_Atan -> ptext SLIT("atan")
534 MO_F64_Log -> ptext SLIT("log")
535 MO_F64_Exp -> ptext SLIT("exp")
536 MO_F64_Sqrt -> ptext SLIT("sqrt")
537 MO_F32_Pwr -> ptext SLIT("powf")
538 MO_F32_Sin -> ptext SLIT("sinf")
539 MO_F32_Cos -> ptext SLIT("cosf")
540 MO_F32_Tan -> ptext SLIT("tanf")
541 MO_F32_Sinh -> ptext SLIT("sinhf")
542 MO_F32_Cosh -> ptext SLIT("coshf")
543 MO_F32_Tanh -> ptext SLIT("tanhf")
544 MO_F32_Asin -> ptext SLIT("asinf")
545 MO_F32_Acos -> ptext SLIT("acosf")
546 MO_F32_Atan -> ptext SLIT("atanf")
547 MO_F32_Log -> ptext SLIT("logf")
548 MO_F32_Exp -> ptext SLIT("expf")
549 MO_F32_Sqrt -> ptext SLIT("sqrtf")
550 MO_WriteBarrier -> ptext SLIT("write_barrier")
552 -- ---------------------------------------------------------------------
556 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
558 mkJMP_ i = ptext SLIT("JMP_") <> parens i
559 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
560 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
564 mkFB_ = ptext SLIT("FB_") -- function code begin
565 mkFE_ = ptext SLIT("FE_") -- function code end
567 -- from includes/Stg.h
569 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
571 mkC_ = ptext SLIT("(C_)") -- StgChar
572 mkW_ = ptext SLIT("(W_)") -- StgWord
573 mkP_ = ptext SLIT("(P_)") -- StgWord*
574 mkPP_ = ptext SLIT("(PP_)") -- P_*
575 mkI_ = ptext SLIT("(I_)") -- StgInt
576 mkA_ = ptext SLIT("(A_)") -- StgAddr
577 mkD_ = ptext SLIT("(D_)") -- const StgWord*
578 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
579 mkB_ = ptext SLIT("(B_)") -- StgByteArray
580 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
582 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
583 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
586 -- ---------------------------------------------------------------------
590 -- Generating assignments is what we're all about, here
592 pprAssign :: CmmReg -> CmmExpr -> SDoc
594 -- dest is a reg, rhs is a reg
595 pprAssign r1 (CmmReg r2)
596 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
597 || isPtrReg r1 && isPtrReg r2
598 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
600 -- dest is a reg, rhs is a CmmRegOff
601 pprAssign r1 (CmmRegOff r2 off)
602 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
603 || isPtrReg r1 && isPtrReg r2
604 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
606 off1 | isPtrReg r2 = off `shiftR` wordShift
609 (op,off') | off >= 0 = (char '+', off1)
610 | otherwise = (char '-', -off1)
612 -- dest is a reg, rhs is anything.
613 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
614 -- the lvalue elicits a warning from new GCC versions (3.4+).
617 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
618 | Just ty <- strangeRegType r1
619 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
621 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
623 -- ---------------------------------------------------------------------
627 | isStrangeTypeReg reg = mkW_ <> pprReg reg
628 | otherwise = pprReg reg
630 -- True if the register has type StgPtr in C, otherwise it has an
631 -- integer type. We need to take care with pointer arithmetic on registers
633 isPtrReg :: CmmReg -> Bool
634 isPtrReg (CmmLocal _) = False
635 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
637 isPtrGlobalReg :: GlobalReg -> Bool
638 isPtrGlobalReg (VanillaReg n) = True
639 isPtrGlobalReg Sp = True
640 isPtrGlobalReg Hp = True
641 isPtrGlobalReg HpLim = True
642 isPtrGlobalReg SpLim = True
643 isPtrGlobalReg _ = False
645 -- True if in C this register doesn't have the type given by
646 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
647 isStrangeTypeReg :: CmmReg -> Bool
648 isStrangeTypeReg (CmmLocal _) = False
649 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
651 isStrangeTypeGlobal :: GlobalReg -> Bool
652 isStrangeTypeGlobal CurrentTSO = True
653 isStrangeTypeGlobal CurrentNursery = True
654 isStrangeTypeGlobal BaseReg = True
655 isStrangeTypeGlobal r = isPtrGlobalReg r
657 strangeRegType :: CmmReg -> Maybe SDoc
658 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
659 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
660 strangeRegType (CmmGlobal BaseReg) = Just (ptext SLIT("struct StgRegTable_ *"))
661 strangeRegType _ = Nothing
663 -- pprReg just prints the register name.
665 pprReg :: CmmReg -> SDoc
667 CmmLocal local -> pprLocalReg local
668 CmmGlobal global -> pprGlobalReg global
670 pprAsPtrReg :: CmmReg -> SDoc
671 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
672 pprAsPtrReg other_reg = pprReg other_reg
674 pprGlobalReg :: GlobalReg -> SDoc
675 pprGlobalReg gr = case gr of
676 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
677 FloatReg n -> char 'F' <> int n
678 DoubleReg n -> char 'D' <> int n
679 LongReg n -> char 'L' <> int n
680 Sp -> ptext SLIT("Sp")
681 SpLim -> ptext SLIT("SpLim")
682 Hp -> ptext SLIT("Hp")
683 HpLim -> ptext SLIT("HpLim")
684 CurrentTSO -> ptext SLIT("CurrentTSO")
685 CurrentNursery -> ptext SLIT("CurrentNursery")
686 HpAlloc -> ptext SLIT("HpAlloc")
687 BaseReg -> ptext SLIT("BaseReg")
688 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
689 GCFun -> ptext SLIT("stg_gc_fun")
691 pprLocalReg :: LocalReg -> SDoc
692 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
694 -- -----------------------------------------------------------------------------
697 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
698 -> Maybe [GlobalReg] -> SDoc
700 pprCall ppr_fn cconv results args vols
701 | not (is_cish cconv)
702 = panic "pprCall: unknown calling convention"
706 ptext SLIT("CALLER_SAVE_SYSTEM") $$
707 #if x86_64_TARGET_ARCH
708 -- HACK around gcc optimisations.
709 -- x86_64 needs a __DISCARD__() here, to create a barrier between
710 -- putting the arguments into temporaries and passing the arguments
711 -- to the callee, because the argument expressions may refer to
712 -- machine registers that are also used for passing arguments in the
713 -- C calling convention.
714 (if (not opt_Unregisterised)
715 then ptext SLIT("__DISCARD__();")
718 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi $$
719 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
722 ppr_assign [] rhs = rhs
723 ppr_assign [(reg@(CmmGlobal BaseReg), hint)] rhs
724 | Just ty <- strangeRegType reg
725 = ptext SLIT("ASSIGN_BaseReg") <> parens (parens ty <> rhs)
726 -- BaseReg is special, sometimes it isn't an lvalue and we
727 -- can't assign to it.
728 ppr_assign [(one,hint)] rhs
729 | Just ty <- strangeRegType one
730 = pprReg one <> ptext SLIT(" = ") <> parens ty <> rhs
732 = pprReg one <> ptext SLIT(" = ")
733 <> pprUnHint hint (cmmRegRep one) <> rhs
734 ppr_assign _other _rhs = panic "pprCall: multiple results"
736 pprArg (expr, PtrHint)
737 = cCast (ptext SLIT("void *")) expr
738 -- see comment by machRepHintCType below
739 pprArg (expr, SignedHint)
740 = cCast (machRepSignedCType (cmmExprRep expr)) expr
741 pprArg (expr, _other)
744 pprUnHint PtrHint rep = parens (machRepCType rep)
745 pprUnHint SignedHint rep = parens (machRepCType rep)
746 pprUnHint _ _ = empty
748 save = save_restore SLIT("CALLER_SAVE")
749 restore = save_restore SLIT("CALLER_RESTORE")
751 -- Nothing says "I don't know what's live; save everything"
752 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
753 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
754 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
755 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
757 pprGlobalRegName :: GlobalReg -> SDoc
758 pprGlobalRegName gr = case gr of
759 VanillaReg n -> char 'R' <> int n -- without the .w suffix
762 -- Currently we only have these two calling conventions, but this might
763 -- change in the future...
764 is_cish CCallConv = True
765 is_cish StdCallConv = True
767 -- ---------------------------------------------------------------------
768 -- Find and print local and external declarations for a list of
771 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
772 pprTempAndExternDecls stmts
773 = (vcat (map pprTempDecl (eltsUFM temps)),
774 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
775 where (temps, lbls) = runTE (mapM_ te_BB stmts)
777 pprDataExterns :: [CmmStatic] -> SDoc
778 pprDataExterns statics
779 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
780 where (_, lbls) = runTE (mapM_ te_Static statics)
782 pprTempDecl :: LocalReg -> SDoc
783 pprTempDecl l@(LocalReg _uniq rep)
784 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
786 pprExternDecl :: Bool -> CLabel -> SDoc
787 pprExternDecl in_srt lbl
788 -- do not print anything for "known external" things
789 | not (needsCDecl lbl) = empty
791 hcat [ visibility, label_type (labelType lbl),
792 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
795 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
798 label_type CodeLabel = ptext SLIT("F_")
799 label_type DataLabel = ptext SLIT("I_")
802 | externallyVisibleCLabel lbl = char 'E'
803 | otherwise = char 'I'
806 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
807 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
809 instance Monad TE where
810 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
811 return a = TE $ \s -> (a, s)
813 te_lbl :: CLabel -> TE ()
814 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
816 te_temp :: LocalReg -> TE ()
817 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
819 runTE :: TE () -> TEState
820 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
822 te_Static :: CmmStatic -> TE ()
823 te_Static (CmmStaticLit lit) = te_Lit lit
824 te_Static _ = return ()
826 te_BB :: CmmBasicBlock -> TE ()
827 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
829 te_Lit :: CmmLit -> TE ()
830 te_Lit (CmmLabel l) = te_lbl l
831 te_Lit (CmmLabelOff l _) = te_lbl l
832 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
835 te_Stmt :: CmmStmt -> TE ()
836 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
837 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
838 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
839 mapM_ (te_Expr.fst) es
840 te_Stmt (CmmCondBranch e _) = te_Expr e
841 te_Stmt (CmmSwitch e _) = te_Expr e
842 te_Stmt (CmmJump e _) = te_Expr e
843 te_Stmt _ = return ()
845 te_Expr :: CmmExpr -> TE ()
846 te_Expr (CmmLit lit) = te_Lit lit
847 te_Expr (CmmLoad e _) = te_Expr e
848 te_Expr (CmmReg r) = te_Reg r
849 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
850 te_Expr (CmmRegOff r _) = te_Reg r
852 te_Reg :: CmmReg -> TE ()
853 te_Reg (CmmLocal l) = te_temp l
857 -- ---------------------------------------------------------------------
858 -- C types for MachReps
860 cCast :: SDoc -> CmmExpr -> SDoc
861 cCast ty expr = parens ty <> pprExpr1 expr
863 -- This is for finding the types of foreign call arguments. For a pointer
864 -- argument, we always cast the argument to (void *), to avoid warnings from
866 machRepHintCType :: MachRep -> MachHint -> SDoc
867 machRepHintCType rep PtrHint = ptext SLIT("void *")
868 machRepHintCType rep SignedHint = machRepSignedCType rep
869 machRepHintCType rep _other = machRepCType rep
871 machRepPtrCType :: MachRep -> SDoc
872 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
873 | otherwise = machRepCType r <> char '*'
875 machRepCType :: MachRep -> SDoc
876 machRepCType r | r == wordRep = ptext SLIT("W_")
877 | otherwise = sized_type
878 where sized_type = case r of
879 I8 -> ptext SLIT("StgWord8")
880 I16 -> ptext SLIT("StgWord16")
881 I32 -> ptext SLIT("StgWord32")
882 I64 -> ptext SLIT("StgWord64")
883 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
884 F64 -> ptext SLIT("StgDouble")
885 _ -> panic "machRepCType"
887 machRepSignedCType :: MachRep -> SDoc
888 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
889 | otherwise = sized_type
890 where sized_type = case r of
891 I8 -> ptext SLIT("StgInt8")
892 I16 -> ptext SLIT("StgInt16")
893 I32 -> ptext SLIT("StgInt32")
894 I64 -> ptext SLIT("StgInt64")
895 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
896 F64 -> ptext SLIT("StgDouble")
897 _ -> panic "machRepCType"
899 -- ---------------------------------------------------------------------
900 -- print strings as valid C strings
902 pprStringInCStyle :: [Word8] -> SDoc
903 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
905 charToC :: Word8 -> String
907 case chr (fromIntegral w) of
911 c | c >= ' ' && c <= '~' -> [c]
912 | otherwise -> ['\\',
913 chr (ord '0' + ord c `div` 64),
914 chr (ord '0' + ord c `div` 8 `mod` 8),
915 chr (ord '0' + ord c `mod` 8)]
917 -- ---------------------------------------------------------------------------
918 -- Initialising static objects with floating-point numbers. We can't
919 -- just emit the floating point number, because C will cast it to an int
920 -- by rounding it. We want the actual bit-representation of the float.
922 -- This is a hack to turn the floating point numbers into ints that we
923 -- can safely initialise to static locations.
926 | machRepByteWidth F64 == 2 * wORD_SIZE = True
927 | machRepByteWidth F64 == wORD_SIZE = False
928 | otherwise = panic "big_doubles"
930 #if __GLASGOW_HASKELL__ >= 504
931 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
932 newFloatArray = newArray_
934 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
935 newDoubleArray = newArray_
937 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
938 castFloatToIntArray = castSTUArray
940 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
941 castDoubleToIntArray = castSTUArray
943 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
944 writeFloatArray = writeArray
946 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
947 writeDoubleArray = writeArray
949 readIntArray :: STUArray s Int Int -> Int -> ST s Int
950 readIntArray = readArray
954 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
955 castFloatToIntArray = return
957 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
958 castDoubleToIntArray = return
962 -- floats are always 1 word
963 floatToWord :: Rational -> CmmLit
966 arr <- newFloatArray ((0::Int),0)
967 writeFloatArray arr 0 (fromRational r)
968 arr' <- castFloatToIntArray arr
969 i <- readIntArray arr' 0
970 return (CmmInt (toInteger i) wordRep)
973 doubleToWords :: Rational -> [CmmLit]
975 | big_doubles -- doubles are 2 words
977 arr <- newDoubleArray ((0::Int),1)
978 writeDoubleArray arr 0 (fromRational r)
979 arr' <- castDoubleToIntArray arr
980 i1 <- readIntArray arr' 0
981 i2 <- readIntArray arr' 1
982 return [ CmmInt (toInteger i1) wordRep
983 , CmmInt (toInteger i2) wordRep
986 | otherwise -- doubles are 1 word
988 arr <- newDoubleArray ((0::Int),0)
989 writeDoubleArray arr 0 (fromRational r)
990 arr' <- castDoubleToIntArray arr
991 i <- readIntArray arr' 0
992 return [ CmmInt (toInteger i) wordRep ]
995 -- ---------------------------------------------------------------------------
999 wordShift = machRepLogWidth wordRep
1001 commafy :: [SDoc] -> SDoc
1002 commafy xs = hsep $ punctuate comma xs
1004 -- Print in C hex format: 0x13fa
1005 pprHexVal :: Integer -> MachRep -> SDoc
1006 pprHexVal 0 _ = ptext SLIT("0x0")
1008 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
1009 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
1011 -- type suffix for literals:
1012 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1013 -- signed values for doing signed operations, but at all other
1014 -- times values are unsigned. This also helps eliminate occasional
1015 -- warnings about integer overflow from gcc.
1017 -- on 32-bit platforms, add "ULL" to 64-bit literals
1018 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1019 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1020 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1021 repsuffix _ = char 'U'
1026 (q,r) = w' `quotRem` 16
1027 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1028 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))