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
359 | Just ty <- machOpNeedsCast mop
360 = ty <> parens (pprMachOpApp' mop args)
362 = pprMachOpApp' mop args
364 -- Comparisons in C have type 'int', but we want type W_ (this is what
365 -- resultRepOfMachOp says). The other C operations inherit their type
366 -- from their operands, so no casting is required.
367 machOpNeedsCast :: MachOp -> Maybe SDoc
369 | isComparisonMachOp mop = Just mkW_
370 | otherwise = Nothing
372 pprMachOpApp' mop args
375 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
378 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
380 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
383 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
384 | otherwise = pprExpr1 e
386 -- --------------------------------------------------------------------------
389 pprLit :: CmmLit -> SDoc
390 pprLit lit = case lit of
391 CmmInt i rep -> pprHexVal i rep
392 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
393 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
394 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
395 CmmLabelDiffOff clbl1 clbl2 i
397 -- * the lit must occur in the info table clbl2
398 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
399 -- The Mangler is expected to convert any reference to an SRT,
400 -- a slow entry point or a large bitmap
401 -- from an info table to an offset.
402 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
404 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
406 pprLit1 :: CmmLit -> SDoc
407 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
408 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
409 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
410 pprLit1 other = pprLit other
412 -- ---------------------------------------------------------------------------
415 pprStatics :: [CmmStatic] -> [SDoc]
417 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
418 = pprLit1 (floatToWord f) : pprStatics rest
419 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
420 = map pprLit1 (doubleToWords f) ++ pprStatics rest
421 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
422 | machRepByteWidth I32 == wORD_SIZE
423 #ifdef WORDS_BIGENDIAN
424 = pprStatics (CmmStaticLit (CmmInt q I32) :
425 CmmStaticLit (CmmInt r I32) : rest)
427 = pprStatics (CmmStaticLit (CmmInt r I32) :
428 CmmStaticLit (CmmInt q I32) : rest)
430 where r = i .&. 0xffffffff
432 pprStatics (CmmStaticLit lit : rest)
433 = pprLit1 lit : pprStatics rest
434 pprStatics (other : rest)
435 = pprPanic "pprWord" (pprStatic other)
437 pprStatic :: CmmStatic -> SDoc
438 pprStatic s = case s of
440 CmmStaticLit lit -> nest 4 (pprLit lit)
441 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
442 CmmDataLabel clbl -> pprCLabel clbl <> colon
443 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
445 -- these should be inlined, like the old .hc
446 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
449 -- ---------------------------------------------------------------------------
452 pprBlockId :: BlockId -> SDoc
453 pprBlockId b = char '_' <> ppr (getUnique b)
455 -- --------------------------------------------------------------------------
456 -- Print a MachOp in a way suitable for emitting via C.
459 pprMachOp_for_C :: MachOp -> SDoc
461 pprMachOp_for_C mop = case mop of
463 -- Integer operations
466 MO_Eq _ -> ptext SLIT("==")
467 MO_Ne _ -> ptext SLIT("!=")
470 MO_S_Quot _ -> char '/'
471 MO_S_Rem _ -> char '%'
472 MO_S_Neg _ -> char '-'
474 MO_U_Quot _ -> char '/'
475 MO_U_Rem _ -> char '%'
477 -- Signed comparisons (floating-point comparisons also use these)
478 -- & Unsigned comparisons
479 MO_S_Ge _ -> ptext SLIT(">=")
480 MO_S_Le _ -> ptext SLIT("<=")
481 MO_S_Gt _ -> char '>'
482 MO_S_Lt _ -> char '<'
484 MO_U_Ge _ -> ptext SLIT(">=")
485 MO_U_Le _ -> ptext SLIT("<=")
486 MO_U_Gt _ -> char '>'
487 MO_U_Lt _ -> char '<'
489 -- Bitwise operations. Not all of these may be supported at all
490 -- sizes, and only integral MachReps are valid.
495 MO_Shl _ -> ptext SLIT("<<")
496 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
497 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
499 -- Conversions. Some of these will be NOPs.
500 -- Floating-point conversions use the signed variant.
501 -- We won't know to generate (void*) casts here, but maybe from
505 MO_U_Conv I8 I8 -> empty
506 MO_U_Conv I16 I16 -> empty
507 MO_U_Conv I32 I32 -> empty
508 MO_U_Conv I64 I64 -> empty
509 MO_U_Conv I128 I128 -> empty
510 MO_S_Conv I8 I8 -> empty
511 MO_S_Conv I16 I16 -> empty
512 MO_S_Conv I32 I32 -> empty
513 MO_S_Conv I64 I64 -> empty
514 MO_S_Conv I128 I128 -> empty
516 MO_U_Conv _from to -> parens (machRepCType to)
517 MO_S_Conv _from to -> parens (machRepSignedCType to)
519 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
521 signedOp :: MachOp -> Bool
522 signedOp (MO_S_Quot _) = True
523 signedOp (MO_S_Rem _) = True
524 signedOp (MO_S_Neg _) = True
525 signedOp (MO_S_Ge _) = True
526 signedOp (MO_S_Le _) = True
527 signedOp (MO_S_Gt _) = True
528 signedOp (MO_S_Lt _) = True
529 signedOp (MO_S_Shr _) = True
530 signedOp (MO_S_Conv _ _) = True
533 -- ---------------------------------------------------------------------
534 -- tend to be implemented by foreign calls
536 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
538 pprCallishMachOp_for_C mop
540 MO_F64_Pwr -> ptext SLIT("pow")
541 MO_F64_Sin -> ptext SLIT("sin")
542 MO_F64_Cos -> ptext SLIT("cos")
543 MO_F64_Tan -> ptext SLIT("tan")
544 MO_F64_Sinh -> ptext SLIT("sinh")
545 MO_F64_Cosh -> ptext SLIT("cosh")
546 MO_F64_Tanh -> ptext SLIT("tanh")
547 MO_F64_Asin -> ptext SLIT("asin")
548 MO_F64_Acos -> ptext SLIT("acos")
549 MO_F64_Atan -> ptext SLIT("atan")
550 MO_F64_Log -> ptext SLIT("log")
551 MO_F64_Exp -> ptext SLIT("exp")
552 MO_F64_Sqrt -> ptext SLIT("sqrt")
553 MO_F32_Pwr -> ptext SLIT("powf")
554 MO_F32_Sin -> ptext SLIT("sinf")
555 MO_F32_Cos -> ptext SLIT("cosf")
556 MO_F32_Tan -> ptext SLIT("tanf")
557 MO_F32_Sinh -> ptext SLIT("sinhf")
558 MO_F32_Cosh -> ptext SLIT("coshf")
559 MO_F32_Tanh -> ptext SLIT("tanhf")
560 MO_F32_Asin -> ptext SLIT("asinf")
561 MO_F32_Acos -> ptext SLIT("acosf")
562 MO_F32_Atan -> ptext SLIT("atanf")
563 MO_F32_Log -> ptext SLIT("logf")
564 MO_F32_Exp -> ptext SLIT("expf")
565 MO_F32_Sqrt -> ptext SLIT("sqrtf")
566 MO_WriteBarrier -> ptext SLIT("write_barrier")
568 -- ---------------------------------------------------------------------
572 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
574 mkJMP_ i = ptext SLIT("JMP_") <> parens i
575 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
576 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
580 mkFB_ = ptext SLIT("FB_") -- function code begin
581 mkFE_ = ptext SLIT("FE_") -- function code end
583 -- from includes/Stg.h
585 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
587 mkC_ = ptext SLIT("(C_)") -- StgChar
588 mkW_ = ptext SLIT("(W_)") -- StgWord
589 mkP_ = ptext SLIT("(P_)") -- StgWord*
590 mkPP_ = ptext SLIT("(PP_)") -- P_*
591 mkI_ = ptext SLIT("(I_)") -- StgInt
592 mkA_ = ptext SLIT("(A_)") -- StgAddr
593 mkD_ = ptext SLIT("(D_)") -- const StgWord*
594 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
595 mkB_ = ptext SLIT("(B_)") -- StgByteArray
596 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
598 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
599 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
602 -- ---------------------------------------------------------------------
606 -- Generating assignments is what we're all about, here
608 pprAssign :: CmmReg -> CmmExpr -> SDoc
610 -- dest is a reg, rhs is a reg
611 pprAssign r1 (CmmReg r2)
612 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
613 || isPtrReg r1 && isPtrReg r2
614 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
616 -- dest is a reg, rhs is a CmmRegOff
617 pprAssign r1 (CmmRegOff r2 off)
618 | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
619 || isPtrReg r1 && isPtrReg r2
620 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
622 off1 | isPtrReg r2 = off `shiftR` wordShift
625 (op,off') | off >= 0 = (char '+', off1)
626 | otherwise = (char '-', -off1)
628 -- dest is a reg, rhs is anything.
629 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
630 -- the lvalue elicits a warning from new GCC versions (3.4+).
633 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
634 | Just ty <- strangeRegType r1
635 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
637 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
639 -- ---------------------------------------------------------------------
643 | isStrangeTypeReg reg = mkW_ <> pprReg reg
644 | otherwise = pprReg reg
646 -- True if the register has type StgPtr in C, otherwise it has an
647 -- integer type. We need to take care with pointer arithmetic on registers
649 isPtrReg :: CmmReg -> Bool
650 isPtrReg (CmmLocal _) = False
651 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
653 isPtrGlobalReg :: GlobalReg -> Bool
654 isPtrGlobalReg (VanillaReg n) = True
655 isPtrGlobalReg Sp = True
656 isPtrGlobalReg Hp = True
657 isPtrGlobalReg HpLim = True
658 isPtrGlobalReg SpLim = True
659 isPtrGlobalReg _ = False
661 -- True if in C this register doesn't have the type given by
662 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
663 isStrangeTypeReg :: CmmReg -> Bool
664 isStrangeTypeReg (CmmLocal _) = False
665 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
667 isStrangeTypeGlobal :: GlobalReg -> Bool
668 isStrangeTypeGlobal CurrentTSO = True
669 isStrangeTypeGlobal CurrentNursery = True
670 isStrangeTypeGlobal BaseReg = True
671 isStrangeTypeGlobal r = isPtrGlobalReg r
673 strangeRegType :: CmmReg -> Maybe SDoc
674 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
675 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
676 strangeRegType (CmmGlobal BaseReg) = Just (ptext SLIT("struct StgRegTable_ *"))
677 strangeRegType _ = Nothing
679 -- pprReg just prints the register name.
681 pprReg :: CmmReg -> SDoc
683 CmmLocal local -> pprLocalReg local
684 CmmGlobal global -> pprGlobalReg global
686 pprAsPtrReg :: CmmReg -> SDoc
687 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
688 pprAsPtrReg other_reg = pprReg other_reg
690 pprGlobalReg :: GlobalReg -> SDoc
691 pprGlobalReg gr = case gr of
692 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
693 FloatReg n -> char 'F' <> int n
694 DoubleReg n -> char 'D' <> int n
695 LongReg n -> char 'L' <> int n
696 Sp -> ptext SLIT("Sp")
697 SpLim -> ptext SLIT("SpLim")
698 Hp -> ptext SLIT("Hp")
699 HpLim -> ptext SLIT("HpLim")
700 CurrentTSO -> ptext SLIT("CurrentTSO")
701 CurrentNursery -> ptext SLIT("CurrentNursery")
702 HpAlloc -> ptext SLIT("HpAlloc")
703 BaseReg -> ptext SLIT("BaseReg")
704 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
705 GCFun -> ptext SLIT("stg_gc_fun")
707 pprLocalReg :: LocalReg -> SDoc
708 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
710 -- -----------------------------------------------------------------------------
713 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
714 -> Maybe [GlobalReg] -> SDoc
716 pprCall ppr_fn cconv results args vols
717 | not (is_cish cconv)
718 = panic "pprCall: unknown calling convention"
722 ptext SLIT("CALLER_SAVE_SYSTEM") $$
723 #if x86_64_TARGET_ARCH
724 -- HACK around gcc optimisations.
725 -- x86_64 needs a __DISCARD__() here, to create a barrier between
726 -- putting the arguments into temporaries and passing the arguments
727 -- to the callee, because the argument expressions may refer to
728 -- machine registers that are also used for passing arguments in the
729 -- C calling convention.
730 (if (not opt_Unregisterised)
731 then ptext SLIT("__DISCARD__();")
734 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi $$
735 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
738 ppr_assign [] rhs = rhs
739 ppr_assign [(reg@(CmmGlobal BaseReg), hint)] rhs
740 | Just ty <- strangeRegType reg
741 = ptext SLIT("ASSIGN_BaseReg") <> parens (parens ty <> rhs)
742 -- BaseReg is special, sometimes it isn't an lvalue and we
743 -- can't assign to it.
744 ppr_assign [(one,hint)] rhs
745 | Just ty <- strangeRegType one
746 = pprReg one <> ptext SLIT(" = ") <> parens ty <> rhs
748 = pprReg one <> ptext SLIT(" = ")
749 <> pprUnHint hint (cmmRegRep one) <> rhs
750 ppr_assign _other _rhs = panic "pprCall: multiple results"
752 pprArg (expr, PtrHint)
753 = cCast (ptext SLIT("void *")) expr
754 -- see comment by machRepHintCType below
755 pprArg (expr, SignedHint)
756 = cCast (machRepSignedCType (cmmExprRep expr)) expr
757 pprArg (expr, _other)
760 pprUnHint PtrHint rep = parens (machRepCType rep)
761 pprUnHint SignedHint rep = parens (machRepCType rep)
762 pprUnHint _ _ = empty
764 save = save_restore SLIT("CALLER_SAVE")
765 restore = save_restore SLIT("CALLER_RESTORE")
767 -- Nothing says "I don't know what's live; save everything"
768 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
769 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
770 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
771 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
773 pprGlobalRegName :: GlobalReg -> SDoc
774 pprGlobalRegName gr = case gr of
775 VanillaReg n -> char 'R' <> int n -- without the .w suffix
778 -- Currently we only have these two calling conventions, but this might
779 -- change in the future...
780 is_cish CCallConv = True
781 is_cish StdCallConv = True
783 -- ---------------------------------------------------------------------
784 -- Find and print local and external declarations for a list of
787 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
788 pprTempAndExternDecls stmts
789 = (vcat (map pprTempDecl (eltsUFM temps)),
790 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
791 where (temps, lbls) = runTE (mapM_ te_BB stmts)
793 pprDataExterns :: [CmmStatic] -> SDoc
794 pprDataExterns statics
795 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
796 where (_, lbls) = runTE (mapM_ te_Static statics)
798 pprTempDecl :: LocalReg -> SDoc
799 pprTempDecl l@(LocalReg _uniq rep)
800 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
802 pprExternDecl :: Bool -> CLabel -> SDoc
803 pprExternDecl in_srt lbl
804 -- do not print anything for "known external" things
805 | not (needsCDecl lbl) = empty
807 hcat [ visibility, label_type (labelType lbl),
808 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
811 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
814 label_type CodeLabel = ptext SLIT("F_")
815 label_type DataLabel = ptext SLIT("I_")
818 | externallyVisibleCLabel lbl = char 'E'
819 | otherwise = char 'I'
822 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
823 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
825 instance Monad TE where
826 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
827 return a = TE $ \s -> (a, s)
829 te_lbl :: CLabel -> TE ()
830 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
832 te_temp :: LocalReg -> TE ()
833 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
835 runTE :: TE () -> TEState
836 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
838 te_Static :: CmmStatic -> TE ()
839 te_Static (CmmStaticLit lit) = te_Lit lit
840 te_Static _ = return ()
842 te_BB :: CmmBasicBlock -> TE ()
843 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
845 te_Lit :: CmmLit -> TE ()
846 te_Lit (CmmLabel l) = te_lbl l
847 te_Lit (CmmLabelOff l _) = te_lbl l
848 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
851 te_Stmt :: CmmStmt -> TE ()
852 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
853 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
854 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
855 mapM_ (te_Expr.fst) es
856 te_Stmt (CmmCondBranch e _) = te_Expr e
857 te_Stmt (CmmSwitch e _) = te_Expr e
858 te_Stmt (CmmJump e _) = te_Expr e
859 te_Stmt _ = return ()
861 te_Expr :: CmmExpr -> TE ()
862 te_Expr (CmmLit lit) = te_Lit lit
863 te_Expr (CmmLoad e _) = te_Expr e
864 te_Expr (CmmReg r) = te_Reg r
865 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
866 te_Expr (CmmRegOff r _) = te_Reg r
868 te_Reg :: CmmReg -> TE ()
869 te_Reg (CmmLocal l) = te_temp l
873 -- ---------------------------------------------------------------------
874 -- C types for MachReps
876 cCast :: SDoc -> CmmExpr -> SDoc
877 cCast ty expr = parens ty <> pprExpr1 expr
879 -- This is for finding the types of foreign call arguments. For a pointer
880 -- argument, we always cast the argument to (void *), to avoid warnings from
882 machRepHintCType :: MachRep -> MachHint -> SDoc
883 machRepHintCType rep PtrHint = ptext SLIT("void *")
884 machRepHintCType rep SignedHint = machRepSignedCType rep
885 machRepHintCType rep _other = machRepCType rep
887 machRepPtrCType :: MachRep -> SDoc
888 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
889 | otherwise = machRepCType r <> char '*'
891 machRepCType :: MachRep -> SDoc
892 machRepCType r | r == wordRep = ptext SLIT("W_")
893 | otherwise = sized_type
894 where sized_type = case r of
895 I8 -> ptext SLIT("StgWord8")
896 I16 -> ptext SLIT("StgWord16")
897 I32 -> ptext SLIT("StgWord32")
898 I64 -> ptext SLIT("StgWord64")
899 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
900 F64 -> ptext SLIT("StgDouble")
901 _ -> panic "machRepCType"
903 machRepSignedCType :: MachRep -> SDoc
904 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
905 | otherwise = sized_type
906 where sized_type = case r of
907 I8 -> ptext SLIT("StgInt8")
908 I16 -> ptext SLIT("StgInt16")
909 I32 -> ptext SLIT("StgInt32")
910 I64 -> ptext SLIT("StgInt64")
911 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
912 F64 -> ptext SLIT("StgDouble")
913 _ -> panic "machRepCType"
915 -- ---------------------------------------------------------------------
916 -- print strings as valid C strings
918 pprStringInCStyle :: [Word8] -> SDoc
919 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
921 charToC :: Word8 -> String
923 case chr (fromIntegral w) of
927 c | c >= ' ' && c <= '~' -> [c]
928 | otherwise -> ['\\',
929 chr (ord '0' + ord c `div` 64),
930 chr (ord '0' + ord c `div` 8 `mod` 8),
931 chr (ord '0' + ord c `mod` 8)]
933 -- ---------------------------------------------------------------------------
934 -- Initialising static objects with floating-point numbers. We can't
935 -- just emit the floating point number, because C will cast it to an int
936 -- by rounding it. We want the actual bit-representation of the float.
938 -- This is a hack to turn the floating point numbers into ints that we
939 -- can safely initialise to static locations.
942 | machRepByteWidth F64 == 2 * wORD_SIZE = True
943 | machRepByteWidth F64 == wORD_SIZE = False
944 | otherwise = panic "big_doubles"
946 #if __GLASGOW_HASKELL__ >= 504
947 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
948 newFloatArray = newArray_
950 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
951 newDoubleArray = newArray_
953 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
954 castFloatToIntArray = castSTUArray
956 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
957 castDoubleToIntArray = castSTUArray
959 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
960 writeFloatArray = writeArray
962 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
963 writeDoubleArray = writeArray
965 readIntArray :: STUArray s Int Int -> Int -> ST s Int
966 readIntArray = readArray
970 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
971 castFloatToIntArray = return
973 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
974 castDoubleToIntArray = return
978 -- floats are always 1 word
979 floatToWord :: Rational -> CmmLit
982 arr <- newFloatArray ((0::Int),0)
983 writeFloatArray arr 0 (fromRational r)
984 arr' <- castFloatToIntArray arr
985 i <- readIntArray arr' 0
986 return (CmmInt (toInteger i) wordRep)
989 doubleToWords :: Rational -> [CmmLit]
991 | big_doubles -- doubles are 2 words
993 arr <- newDoubleArray ((0::Int),1)
994 writeDoubleArray arr 0 (fromRational r)
995 arr' <- castDoubleToIntArray arr
996 i1 <- readIntArray arr' 0
997 i2 <- readIntArray arr' 1
998 return [ CmmInt (toInteger i1) wordRep
999 , CmmInt (toInteger i2) wordRep
1002 | otherwise -- doubles are 1 word
1004 arr <- newDoubleArray ((0::Int),0)
1005 writeDoubleArray arr 0 (fromRational r)
1006 arr' <- castDoubleToIntArray arr
1007 i <- readIntArray arr' 0
1008 return [ CmmInt (toInteger i) wordRep ]
1011 -- ---------------------------------------------------------------------------
1015 wordShift = machRepLogWidth wordRep
1017 commafy :: [SDoc] -> SDoc
1018 commafy xs = hsep $ punctuate comma xs
1020 -- Print in C hex format: 0x13fa
1021 pprHexVal :: Integer -> MachRep -> SDoc
1022 pprHexVal 0 _ = ptext SLIT("0x0")
1024 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
1025 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
1027 -- type suffix for literals:
1028 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1029 -- signed values for doing signed operations, but at all other
1030 -- times values are unsigned. This also helps eliminate occasional
1031 -- warnings about integer overflow from gcc.
1033 -- on 32-bit platforms, add "ULL" to 64-bit literals
1034 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1035 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1036 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1037 repsuffix _ = char 'U'
1042 (q,r) = w' `quotRem` 16
1043 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1044 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))