1 -----------------------------------------------------------------------------
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
5 -- (c) The University of Glasgow 2004-2006
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"
50 import PprCmm () -- instances only
54 #if __GLASGOW_HASKELL__ >= 504
57 import Control.Monad.ST
59 #if x86_64_TARGET_ARCH
60 import StaticFlags ( opt_Unregisterised )
63 -- --------------------------------------------------------------------------
66 pprCs :: DynFlags -> [Cmm] -> SDoc
68 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
71 | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
74 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
75 writeCs dflags handle cmms
76 = printForC handle (pprCs dflags cmms)
78 -- --------------------------------------------------------------------------
79 -- Now do some real work
81 -- for fun, we could call cmmToCmm over the tops...
85 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
90 pprTop :: CmmTop -> SDoc
91 pprTop (CmmProc info clbl _params blocks) =
93 then pprDataExterns info $$
94 pprWordArray (entryLblToInfoLbl clbl) info
98 -- the first block doesn't get a label:
99 (BasicBlock _ stmts : rest) -> vcat [
102 (if (externallyVisibleCLabel clbl)
103 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
106 nest 8 (vcat (map pprStmt stmts)) $$
107 vcat (map pprBBlock rest),
112 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
115 -- Chunks of static data.
117 -- We only handle (a) arrays of word-sized things and (b) strings.
119 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
121 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
122 ptext SLIT("[] = "), pprStringInCStyle str, semi
125 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
127 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
128 brackets (int size), semi
131 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
132 pprDataExterns lits $$
133 pprWordArray lbl lits
135 -- these shouldn't appear?
136 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
139 -- --------------------------------------------------------------------------
140 -- BasicBlocks are self-contained entities: they always end in a jump.
142 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
143 -- as many jumps as possible into fall throughs.
146 pprBBlock :: CmmBasicBlock -> SDoc
147 pprBBlock (BasicBlock lbl stmts) =
149 pprTrace "pprC.pprBBlock: curious empty code block for"
150 (pprBlockId lbl) empty
152 nest 4 (pprBlockId lbl <> colon) $$
153 nest 8 (vcat (map pprStmt stmts))
155 -- --------------------------------------------------------------------------
156 -- Info tables. Just arrays of words.
157 -- See codeGen/ClosureInfo, and nativeGen/PprMach
159 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
161 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
162 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
163 $$ nest 8 (commafy (pprStatics ds))
167 -- has to be static, if it isn't globally visible
169 pprLocalness :: CLabel -> SDoc
170 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
173 -- --------------------------------------------------------------------------
177 pprStmt :: CmmStmt -> SDoc
179 pprStmt stmt = case stmt of
181 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
183 CmmAssign dest src -> pprAssign dest src
186 | rep == I64 && wordRep /= I64
187 -> ptext SLIT("ASSIGN_Word64") <>
188 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
190 | rep == F64 && wordRep /= I64
191 -> ptext SLIT("ASSIGN_DBL") <>
192 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
195 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
199 CmmCall (CmmForeignCall fn cconv) results args volatile ->
200 -- Controversial: leave this out for now.
203 pprCall ppr_fn cconv results args volatile
206 CmmLit (CmmLabel lbl) -> pprCLabel lbl
207 _other -> parens (cCast (pprCFunType cconv results args) fn)
208 -- for a dynamic call, cast the expression to
209 -- a function of the right type (we hope).
211 -- we #undef a function before calling it: the FFI is supposed to be
212 -- an interface specifically to C, not to C+CPP. For one thing, this
213 -- makes the via-C route more compatible with the NCG. If macros
214 -- are being used for optimisation, then inline functions are probably
216 pprUndef (CmmLit (CmmLabel lbl)) =
217 ptext SLIT("#undef") <+> pprCLabel lbl
220 CmmCall (CmmPrim op) results args volatile ->
221 pprCall ppr_fn CCallConv results args volatile
223 ppr_fn = pprCallishMachOp_for_C op
225 CmmBranch ident -> pprBranch ident
226 CmmCondBranch expr ident -> pprCondBranch expr ident
227 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
228 CmmSwitch arg ids -> pprSwitch arg ids
230 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
231 pprCFunType cconv ress args
234 parens (text (ccallConvAttribute cconv) <> char '*'),
235 parens (commafy (map arg_type args))
238 res_type [] = ptext SLIT("void")
239 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
241 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
243 -- ---------------------------------------------------------------------
244 -- unconditional branches
245 pprBranch :: BlockId -> SDoc
246 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
249 -- ---------------------------------------------------------------------
250 -- conditional branches to local labels
251 pprCondBranch :: CmmExpr -> BlockId -> SDoc
252 pprCondBranch expr ident
253 = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
254 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
257 -- ---------------------------------------------------------------------
258 -- a local table branch
260 -- we find the fall-through cases
262 -- N.B. we remove Nothing's from the list of branches, as they are
263 -- 'undefined'. However, they may be defined one day, so we better
264 -- document this behaviour.
266 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
267 pprSwitch e maybe_ids
268 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
269 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
271 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
272 4 (vcat ( map caseify pairs2 )))
276 sndEq (_,x) (_,y) = x == y
279 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
282 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
283 ptext SLIT("/* fall through */") ]
286 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
287 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
289 -- ---------------------------------------------------------------------
293 -- C Types: the invariant is that the C expression generated by
297 -- has a type in C which is also given by
299 -- machRepCType (cmmExprRep e)
301 -- (similar invariants apply to the rest of the pretty printer).
303 pprExpr :: CmmExpr -> SDoc
304 pprExpr e = case e of
305 CmmLit lit -> pprLit lit
307 CmmLoad e I64 | wordRep /= I64
308 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
310 CmmLoad e F64 | wordRep /= I64
311 -> ptext SLIT("PK_DBL") <> parens (mkP_ <> pprExpr1 e)
313 CmmLoad (CmmReg r) rep
314 | isPtrReg r && rep == wordRep
315 -> char '*' <> pprAsPtrReg r
317 CmmLoad (CmmRegOff r 0) rep
318 | isPtrReg r && rep == wordRep
319 -> char '*' <> pprAsPtrReg r
321 CmmLoad (CmmRegOff r off) rep
322 | isPtrReg r && rep == wordRep
323 -- ToDo: check that the offset is a word multiple?
324 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
328 char '*' <> parens (cCast (machRepPtrCType rep) expr)
330 CmmReg reg -> pprCastReg reg
331 CmmRegOff reg 0 -> pprCastReg reg
334 | i > 0 -> pprRegOff (char '+') i
335 | otherwise -> pprRegOff (char '-') (-i)
337 pprRegOff op i' = pprCastReg reg <> op <> int i'
339 CmmMachOp mop args -> pprMachOpApp mop args
341 pprExpr1 :: CmmExpr -> SDoc
342 pprExpr1 (CmmLit lit) = pprLit1 lit
343 pprExpr1 e@(CmmReg _reg) = pprExpr e
344 pprExpr1 other = parens (pprExpr other)
346 -- --------------------------------------------------------------------------
347 -- MachOp applications
349 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
353 = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
354 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
355 isMulMayOfloOp (MO_S_MulMayOflo _) = True
356 isMulMayOfloOp _ = False
358 pprMachOpApp mop args
361 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
364 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
366 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
369 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
370 | otherwise = pprExpr1 e
372 -- --------------------------------------------------------------------------
375 pprLit :: CmmLit -> SDoc
376 pprLit lit = case lit of
377 CmmInt i rep -> pprHexVal i rep
378 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
379 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
380 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
381 CmmLabelDiffOff clbl1 clbl2 i
383 -- * the lit must occur in the info table clbl2
384 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
385 -- The Mangler is expected to convert any reference to an SRT,
386 -- a slow entry point or a large bitmap
387 -- from an info table to an offset.
388 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
390 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
392 pprLit1 :: CmmLit -> SDoc
393 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
394 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
395 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
396 pprLit1 other = pprLit other
398 -- ---------------------------------------------------------------------------
401 pprStatics :: [CmmStatic] -> [SDoc]
403 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
404 = pprLit1 (floatToWord f) : pprStatics rest
405 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
406 = map pprLit1 (doubleToWords f) ++ pprStatics rest
407 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
408 | machRepByteWidth I32 == wORD_SIZE
409 #ifdef WORDS_BIGENDIAN
410 = pprStatics (CmmStaticLit (CmmInt q I32) :
411 CmmStaticLit (CmmInt r I32) : rest)
413 = pprStatics (CmmStaticLit (CmmInt r I32) :
414 CmmStaticLit (CmmInt q I32) : rest)
416 where r = i .&. 0xffffffff
418 pprStatics (CmmStaticLit lit : rest)
419 = pprLit1 lit : pprStatics rest
420 pprStatics (other : rest)
421 = pprPanic "pprWord" (pprStatic other)
423 pprStatic :: CmmStatic -> SDoc
424 pprStatic s = case s of
426 CmmStaticLit lit -> nest 4 (pprLit lit)
427 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
428 CmmDataLabel clbl -> pprCLabel clbl <> colon
429 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
431 -- these should be inlined, like the old .hc
432 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
435 -- ---------------------------------------------------------------------------
438 pprBlockId :: BlockId -> SDoc
439 pprBlockId b = char '_' <> ppr (getUnique b)
441 -- --------------------------------------------------------------------------
442 -- Print a MachOp in a way suitable for emitting via C.
445 pprMachOp_for_C :: MachOp -> SDoc
447 pprMachOp_for_C mop = case mop of
449 -- Integer operations
452 MO_Eq _ -> ptext SLIT("==")
453 MO_Ne _ -> ptext SLIT("!=")
456 MO_S_Quot _ -> char '/'
457 MO_S_Rem _ -> char '%'
458 MO_S_Neg _ -> char '-'
460 MO_U_Quot _ -> char '/'
461 MO_U_Rem _ -> char '%'
463 -- Signed comparisons (floating-point comparisons also use these)
464 -- & Unsigned comparisons
465 MO_S_Ge _ -> ptext SLIT(">=")
466 MO_S_Le _ -> ptext SLIT("<=")
467 MO_S_Gt _ -> char '>'
468 MO_S_Lt _ -> char '<'
470 MO_U_Ge _ -> ptext SLIT(">=")
471 MO_U_Le _ -> ptext SLIT("<=")
472 MO_U_Gt _ -> char '>'
473 MO_U_Lt _ -> char '<'
475 -- Bitwise operations. Not all of these may be supported at all
476 -- sizes, and only integral MachReps are valid.
481 MO_Shl _ -> ptext SLIT("<<")
482 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
483 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
485 -- Conversions. Some of these will be NOPs.
486 -- Floating-point conversions use the signed variant.
487 -- We won't know to generate (void*) casts here, but maybe from
491 MO_U_Conv I8 I8 -> empty
492 MO_U_Conv I16 I16 -> empty
493 MO_U_Conv I32 I32 -> empty
494 MO_U_Conv I64 I64 -> empty
495 MO_U_Conv I128 I128 -> empty
496 MO_S_Conv I8 I8 -> empty
497 MO_S_Conv I16 I16 -> empty
498 MO_S_Conv I32 I32 -> empty
499 MO_S_Conv I64 I64 -> empty
500 MO_S_Conv I128 I128 -> empty
502 MO_U_Conv _from to -> parens (machRepCType to)
503 MO_S_Conv _from to -> parens (machRepSignedCType to)
505 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
507 signedOp :: MachOp -> Bool
508 signedOp (MO_S_Quot _) = True
509 signedOp (MO_S_Rem _) = True
510 signedOp (MO_S_Neg _) = True
511 signedOp (MO_S_Ge _) = True
512 signedOp (MO_S_Le _) = True
513 signedOp (MO_S_Gt _) = True
514 signedOp (MO_S_Lt _) = True
515 signedOp (MO_S_Shr _) = True
516 signedOp (MO_S_Conv _ _) = True
519 -- ---------------------------------------------------------------------
520 -- tend to be implemented by foreign calls
522 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
524 pprCallishMachOp_for_C mop
526 MO_F64_Pwr -> ptext SLIT("pow")
527 MO_F64_Sin -> ptext SLIT("sin")
528 MO_F64_Cos -> ptext SLIT("cos")
529 MO_F64_Tan -> ptext SLIT("tan")
530 MO_F64_Sinh -> ptext SLIT("sinh")
531 MO_F64_Cosh -> ptext SLIT("cosh")
532 MO_F64_Tanh -> ptext SLIT("tanh")
533 MO_F64_Asin -> ptext SLIT("asin")
534 MO_F64_Acos -> ptext SLIT("acos")
535 MO_F64_Atan -> ptext SLIT("atan")
536 MO_F64_Log -> ptext SLIT("log")
537 MO_F64_Exp -> ptext SLIT("exp")
538 MO_F64_Sqrt -> ptext SLIT("sqrt")
539 MO_F32_Pwr -> ptext SLIT("powf")
540 MO_F32_Sin -> ptext SLIT("sinf")
541 MO_F32_Cos -> ptext SLIT("cosf")
542 MO_F32_Tan -> ptext SLIT("tanf")
543 MO_F32_Sinh -> ptext SLIT("sinhf")
544 MO_F32_Cosh -> ptext SLIT("coshf")
545 MO_F32_Tanh -> ptext SLIT("tanhf")
546 MO_F32_Asin -> ptext SLIT("asinf")
547 MO_F32_Acos -> ptext SLIT("acosf")
548 MO_F32_Atan -> ptext SLIT("atanf")
549 MO_F32_Log -> ptext SLIT("logf")
550 MO_F32_Exp -> ptext SLIT("expf")
551 MO_F32_Sqrt -> ptext SLIT("sqrtf")
552 MO_WriteBarrier -> ptext SLIT("write_barrier")
554 -- ---------------------------------------------------------------------
558 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
560 mkJMP_ i = ptext SLIT("JMP_") <> parens i
561 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
562 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
566 mkFB_ = ptext SLIT("FB_") -- function code begin
567 mkFE_ = ptext SLIT("FE_") -- function code end
569 -- from includes/Stg.h
571 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
573 mkC_ = ptext SLIT("(C_)") -- StgChar
574 mkW_ = ptext SLIT("(W_)") -- StgWord
575 mkP_ = ptext SLIT("(P_)") -- StgWord*
576 mkPP_ = ptext SLIT("(PP_)") -- P_*
577 mkI_ = ptext SLIT("(I_)") -- StgInt
578 mkA_ = ptext SLIT("(A_)") -- StgAddr
579 mkD_ = ptext SLIT("(D_)") -- const StgWord*
580 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
581 mkB_ = ptext SLIT("(B_)") -- StgByteArray
582 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
584 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
585 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
588 -- ---------------------------------------------------------------------
592 -- Generating assignments is what we're all about, here
594 pprAssign :: CmmReg -> CmmExpr -> SDoc
596 -- dest is a reg, rhs is a reg
597 pprAssign r1 (CmmReg r2)
598 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
599 || isPtrReg r1 && isPtrReg r2
600 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
602 -- dest is a reg, rhs is a CmmRegOff
603 pprAssign r1 (CmmRegOff r2 off)
604 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
605 || isPtrReg r1 && isPtrReg r2
606 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
608 off1 | isPtrReg r2 = off `shiftR` wordShift
611 (op,off') | off >= 0 = (char '+', off1)
612 | otherwise = (char '-', -off1)
614 -- dest is a reg, rhs is anything.
615 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
616 -- the lvalue elicits a warning from new GCC versions (3.4+).
619 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
620 | Just ty <- strangeRegType r1
621 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
623 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
625 -- ---------------------------------------------------------------------
629 | isStrangeTypeReg reg = mkW_ <> pprReg reg
630 | otherwise = pprReg reg
632 -- True if the register has type StgPtr in C, otherwise it has an
633 -- integer type. We need to take care with pointer arithmetic on registers
635 isPtrReg :: CmmReg -> Bool
636 isPtrReg (CmmLocal _) = False
637 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
639 isPtrGlobalReg :: GlobalReg -> Bool
640 isPtrGlobalReg (VanillaReg n) = True
641 isPtrGlobalReg Sp = True
642 isPtrGlobalReg Hp = True
643 isPtrGlobalReg HpLim = True
644 isPtrGlobalReg SpLim = True
645 isPtrGlobalReg _ = False
647 -- True if in C this register doesn't have the type given by
648 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
649 isStrangeTypeReg :: CmmReg -> Bool
650 isStrangeTypeReg (CmmLocal _) = False
651 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
653 isStrangeTypeGlobal :: GlobalReg -> Bool
654 isStrangeTypeGlobal CurrentTSO = True
655 isStrangeTypeGlobal CurrentNursery = True
656 isStrangeTypeGlobal BaseReg = True
657 isStrangeTypeGlobal r = isPtrGlobalReg r
659 strangeRegType :: CmmReg -> Maybe SDoc
660 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
661 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
662 strangeRegType (CmmGlobal BaseReg) = Just (ptext SLIT("struct StgRegTable_ *"))
663 strangeRegType _ = Nothing
665 -- pprReg just prints the register name.
667 pprReg :: CmmReg -> SDoc
669 CmmLocal local -> pprLocalReg local
670 CmmGlobal global -> pprGlobalReg global
672 pprAsPtrReg :: CmmReg -> SDoc
673 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
674 pprAsPtrReg other_reg = pprReg other_reg
676 pprGlobalReg :: GlobalReg -> SDoc
677 pprGlobalReg gr = case gr of
678 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
679 FloatReg n -> char 'F' <> int n
680 DoubleReg n -> char 'D' <> int n
681 LongReg n -> char 'L' <> int n
682 Sp -> ptext SLIT("Sp")
683 SpLim -> ptext SLIT("SpLim")
684 Hp -> ptext SLIT("Hp")
685 HpLim -> ptext SLIT("HpLim")
686 CurrentTSO -> ptext SLIT("CurrentTSO")
687 CurrentNursery -> ptext SLIT("CurrentNursery")
688 HpAlloc -> ptext SLIT("HpAlloc")
689 BaseReg -> ptext SLIT("BaseReg")
690 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
691 GCFun -> ptext SLIT("stg_gc_fun")
693 pprLocalReg :: LocalReg -> SDoc
694 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
696 -- -----------------------------------------------------------------------------
699 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
700 -> Maybe [GlobalReg] -> SDoc
702 pprCall ppr_fn cconv results args vols
703 | not (is_cish cconv)
704 = panic "pprCall: unknown calling convention"
708 ptext SLIT("CALLER_SAVE_SYSTEM") $$
709 #if x86_64_TARGET_ARCH
710 -- HACK around gcc optimisations.
711 -- x86_64 needs a __DISCARD__() here, to create a barrier between
712 -- putting the arguments into temporaries and passing the arguments
713 -- to the callee, because the argument expressions may refer to
714 -- machine registers that are also used for passing arguments in the
715 -- C calling convention.
716 (if (not opt_Unregisterised)
717 then ptext SLIT("__DISCARD__();")
720 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi $$
721 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
724 ppr_assign [] rhs = rhs
725 ppr_assign [(reg@(CmmGlobal BaseReg), hint)] rhs
726 | Just ty <- strangeRegType reg
727 = ptext SLIT("ASSIGN_BaseReg") <> parens (parens ty <> rhs)
728 -- BaseReg is special, sometimes it isn't an lvalue and we
729 -- can't assign to it.
730 ppr_assign [(one,hint)] rhs
731 | Just ty <- strangeRegType one
732 = pprReg one <> ptext SLIT(" = ") <> parens ty <> rhs
734 = pprReg one <> ptext SLIT(" = ")
735 <> pprUnHint hint (cmmRegRep one) <> rhs
736 ppr_assign _other _rhs = panic "pprCall: multiple results"
738 pprArg (expr, PtrHint)
739 = cCast (ptext SLIT("void *")) expr
740 -- see comment by machRepHintCType below
741 pprArg (expr, SignedHint)
742 = cCast (machRepSignedCType (cmmExprRep expr)) expr
743 pprArg (expr, _other)
746 pprUnHint PtrHint rep = parens (machRepCType rep)
747 pprUnHint SignedHint rep = parens (machRepCType rep)
748 pprUnHint _ _ = empty
750 save = save_restore SLIT("CALLER_SAVE")
751 restore = save_restore SLIT("CALLER_RESTORE")
753 -- Nothing says "I don't know what's live; save everything"
754 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
755 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
756 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
757 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
759 pprGlobalRegName :: GlobalReg -> SDoc
760 pprGlobalRegName gr = case gr of
761 VanillaReg n -> char 'R' <> int n -- without the .w suffix
764 -- Currently we only have these two calling conventions, but this might
765 -- change in the future...
766 is_cish CCallConv = True
767 is_cish StdCallConv = True
769 -- ---------------------------------------------------------------------
770 -- Find and print local and external declarations for a list of
773 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
774 pprTempAndExternDecls stmts
775 = (vcat (map pprTempDecl (eltsUFM temps)),
776 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
777 where (temps, lbls) = runTE (mapM_ te_BB stmts)
779 pprDataExterns :: [CmmStatic] -> SDoc
780 pprDataExterns statics
781 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
782 where (_, lbls) = runTE (mapM_ te_Static statics)
784 pprTempDecl :: LocalReg -> SDoc
785 pprTempDecl l@(LocalReg _uniq rep)
786 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
788 pprExternDecl :: Bool -> CLabel -> SDoc
789 pprExternDecl in_srt lbl
790 -- do not print anything for "known external" things
791 | not (needsCDecl lbl) = empty
793 hcat [ visibility, label_type (labelType lbl),
794 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
797 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
800 label_type CodeLabel = ptext SLIT("F_")
801 label_type DataLabel = ptext SLIT("I_")
804 | externallyVisibleCLabel lbl = char 'E'
805 | otherwise = char 'I'
808 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
809 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
811 instance Monad TE where
812 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
813 return a = TE $ \s -> (a, s)
815 te_lbl :: CLabel -> TE ()
816 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
818 te_temp :: LocalReg -> TE ()
819 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
821 runTE :: TE () -> TEState
822 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
824 te_Static :: CmmStatic -> TE ()
825 te_Static (CmmStaticLit lit) = te_Lit lit
826 te_Static _ = return ()
828 te_BB :: CmmBasicBlock -> TE ()
829 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
831 te_Lit :: CmmLit -> TE ()
832 te_Lit (CmmLabel l) = te_lbl l
833 te_Lit (CmmLabelOff l _) = te_lbl l
834 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
837 te_Stmt :: CmmStmt -> TE ()
838 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
839 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
840 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
841 mapM_ (te_Expr.fst) es
842 te_Stmt (CmmCondBranch e _) = te_Expr e
843 te_Stmt (CmmSwitch e _) = te_Expr e
844 te_Stmt (CmmJump e _) = te_Expr e
845 te_Stmt _ = return ()
847 te_Expr :: CmmExpr -> TE ()
848 te_Expr (CmmLit lit) = te_Lit lit
849 te_Expr (CmmLoad e _) = te_Expr e
850 te_Expr (CmmReg r) = te_Reg r
851 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
852 te_Expr (CmmRegOff r _) = te_Reg r
854 te_Reg :: CmmReg -> TE ()
855 te_Reg (CmmLocal l) = te_temp l
859 -- ---------------------------------------------------------------------
860 -- C types for MachReps
862 cCast :: SDoc -> CmmExpr -> SDoc
863 cCast ty expr = parens ty <> pprExpr1 expr
865 -- This is for finding the types of foreign call arguments. For a pointer
866 -- argument, we always cast the argument to (void *), to avoid warnings from
868 machRepHintCType :: MachRep -> MachHint -> SDoc
869 machRepHintCType rep PtrHint = ptext SLIT("void *")
870 machRepHintCType rep SignedHint = machRepSignedCType rep
871 machRepHintCType rep _other = machRepCType rep
873 machRepPtrCType :: MachRep -> SDoc
874 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
875 | otherwise = machRepCType r <> char '*'
877 machRepCType :: MachRep -> SDoc
878 machRepCType r | r == wordRep = ptext SLIT("W_")
879 | otherwise = sized_type
880 where sized_type = case r of
881 I8 -> ptext SLIT("StgWord8")
882 I16 -> ptext SLIT("StgWord16")
883 I32 -> ptext SLIT("StgWord32")
884 I64 -> ptext SLIT("StgWord64")
885 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
886 F64 -> ptext SLIT("StgDouble")
887 _ -> panic "machRepCType"
889 machRepSignedCType :: MachRep -> SDoc
890 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
891 | otherwise = sized_type
892 where sized_type = case r of
893 I8 -> ptext SLIT("StgInt8")
894 I16 -> ptext SLIT("StgInt16")
895 I32 -> ptext SLIT("StgInt32")
896 I64 -> ptext SLIT("StgInt64")
897 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
898 F64 -> ptext SLIT("StgDouble")
899 _ -> panic "machRepCType"
901 -- ---------------------------------------------------------------------
902 -- print strings as valid C strings
904 pprStringInCStyle :: [Word8] -> SDoc
905 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
907 charToC :: Word8 -> String
909 case chr (fromIntegral w) of
913 c | c >= ' ' && c <= '~' -> [c]
914 | otherwise -> ['\\',
915 chr (ord '0' + ord c `div` 64),
916 chr (ord '0' + ord c `div` 8 `mod` 8),
917 chr (ord '0' + ord c `mod` 8)]
919 -- ---------------------------------------------------------------------------
920 -- Initialising static objects with floating-point numbers. We can't
921 -- just emit the floating point number, because C will cast it to an int
922 -- by rounding it. We want the actual bit-representation of the float.
924 -- This is a hack to turn the floating point numbers into ints that we
925 -- can safely initialise to static locations.
928 | machRepByteWidth F64 == 2 * wORD_SIZE = True
929 | machRepByteWidth F64 == wORD_SIZE = False
930 | otherwise = panic "big_doubles"
932 #if __GLASGOW_HASKELL__ >= 504
933 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
934 newFloatArray = newArray_
936 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
937 newDoubleArray = newArray_
939 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
940 castFloatToIntArray = castSTUArray
942 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
943 castDoubleToIntArray = castSTUArray
945 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
946 writeFloatArray = writeArray
948 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
949 writeDoubleArray = writeArray
951 readIntArray :: STUArray s Int Int -> Int -> ST s Int
952 readIntArray = readArray
956 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
957 castFloatToIntArray = return
959 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
960 castDoubleToIntArray = return
964 -- floats are always 1 word
965 floatToWord :: Rational -> CmmLit
968 arr <- newFloatArray ((0::Int),0)
969 writeFloatArray arr 0 (fromRational r)
970 arr' <- castFloatToIntArray arr
971 i <- readIntArray arr' 0
972 return (CmmInt (toInteger i) wordRep)
975 doubleToWords :: Rational -> [CmmLit]
977 | big_doubles -- doubles are 2 words
979 arr <- newDoubleArray ((0::Int),1)
980 writeDoubleArray arr 0 (fromRational r)
981 arr' <- castDoubleToIntArray arr
982 i1 <- readIntArray arr' 0
983 i2 <- readIntArray arr' 1
984 return [ CmmInt (toInteger i1) wordRep
985 , CmmInt (toInteger i2) wordRep
988 | otherwise -- doubles are 1 word
990 arr <- newDoubleArray ((0::Int),0)
991 writeDoubleArray arr 0 (fromRational r)
992 arr' <- castDoubleToIntArray arr
993 i <- readIntArray arr' 0
994 return [ CmmInt (toInteger i) wordRep ]
997 -- ---------------------------------------------------------------------------
1001 wordShift = machRepLogWidth wordRep
1003 commafy :: [SDoc] -> SDoc
1004 commafy xs = hsep $ punctuate comma xs
1006 -- Print in C hex format: 0x13fa
1007 pprHexVal :: Integer -> MachRep -> SDoc
1008 pprHexVal 0 _ = ptext SLIT("0x0")
1010 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
1011 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
1013 -- type suffix for literals:
1014 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1015 -- signed values for doing signed operations, but at all other
1016 -- times values are unsigned. This also helps eliminate occasional
1017 -- warnings about integer overflow from gcc.
1019 -- on 32-bit platforms, add "ULL" to 64-bit literals
1020 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1021 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1022 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1023 repsuffix _ = char 'U'
1028 (q,r) = w' `quotRem` 16
1029 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1030 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))