2 -- The above warning supression flag is a temporary kludge.
3 -- While working on this module you are encouraged to remove it and fix
4 -- any warnings in the module. See
5 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
8 -----------------------------------------------------------------------------
10 -- Pretty-printing of Cmm as C, suitable for feeding gcc
12 -- (c) The University of Glasgow 2004-2006
14 -----------------------------------------------------------------------------
17 -- Print Cmm as real C, for -fvia-C
19 -- See wiki:Commentary/Compiler/Backends/PprC
21 -- This is simpler than the old PprAbsC, because Cmm is "macro-expanded"
22 -- relative to the old AbstractC, and many oddities/decorations have
23 -- disappeared from the data type.
26 -- ToDo: save/restore volatile registers around calls.
33 #include "HsVersions.h"
37 import PprCmm () -- Instances only
61 import Control.Monad.ST
63 #if x86_64_TARGET_ARCH
64 import StaticFlags ( opt_Unregisterised )
67 #if defined(alpha_TARGET_ARCH) || defined(mips_TARGET_ARCH) || defined(mipsel_TARGET_ARCH) || defined(arm_TARGET_ARCH)
68 #define BEWARE_LOAD_STORE_ALIGNMENT
71 -- --------------------------------------------------------------------------
74 pprCs :: DynFlags -> [RawCmm] -> SDoc
76 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
79 | dopt Opt_SplitObjs dflags = ptext (sLit "__STG_SPLIT_MARKER")
82 writeCs :: DynFlags -> Handle -> [RawCmm] -> IO ()
83 writeCs dflags handle cmms
84 = printForC handle (pprCs dflags cmms)
86 -- --------------------------------------------------------------------------
87 -- Now do some real work
89 -- for fun, we could call cmmToCmm over the tops...
92 pprC :: RawCmm -> SDoc
93 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
98 pprTop :: RawCmmTop -> SDoc
99 pprTop (CmmProc info clbl _params (ListGraph blocks)) =
101 then pprDataExterns info $$
102 pprWordArray (entryLblToInfoLbl clbl) info
106 -- the first block doesn't get a label:
107 (BasicBlock _ stmts : rest) -> vcat [
110 (if (externallyVisibleCLabel clbl)
111 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
114 nest 8 (vcat (map pprStmt stmts)) $$
115 vcat (map pprBBlock rest),
120 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
123 -- Chunks of static data.
125 -- We only handle (a) arrays of word-sized things and (b) strings.
127 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
129 pprLocalness lbl, ptext (sLit "char "), pprCLabel lbl,
130 ptext (sLit "[] = "), pprStringInCStyle str, semi
133 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
135 pprLocalness lbl, ptext (sLit "char "), pprCLabel lbl,
136 brackets (int size), semi
139 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
140 pprDataExterns lits $$
141 pprWordArray lbl lits
143 -- these shouldn't appear?
144 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
146 -- --------------------------------------------------------------------------
147 -- BasicBlocks are self-contained entities: they always end in a jump.
149 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
150 -- as many jumps as possible into fall throughs.
153 pprBBlock :: CmmBasicBlock -> SDoc
154 pprBBlock (BasicBlock lbl stmts) =
156 pprTrace "pprC.pprBBlock: curious empty code block for"
157 (pprBlockId lbl) empty
159 nest 4 (pprBlockId lbl <> colon) $$
160 nest 8 (vcat (map pprStmt stmts))
162 -- --------------------------------------------------------------------------
163 -- Info tables. Just arrays of words.
164 -- See codeGen/ClosureInfo, and nativeGen/PprMach
166 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
168 = hcat [ pprLocalness lbl, ptext (sLit "StgWord")
169 , space, pprCLabel lbl, ptext (sLit "[] = {") ]
170 $$ nest 8 (commafy (pprStatics ds))
174 -- has to be static, if it isn't globally visible
176 pprLocalness :: CLabel -> SDoc
177 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext (sLit "static ")
180 -- --------------------------------------------------------------------------
184 pprStmt :: CmmStmt -> SDoc
186 pprStmt stmt = case stmt of
188 CmmComment s -> (hang (ptext (sLit "/*")) 3 (ftext s)) $$ ptext (sLit "*/")
190 CmmAssign dest src -> pprAssign dest src
193 | rep == I64 && wordRep /= I64
194 -> ptext (sLit "ASSIGN_Word64") <>
195 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
197 | rep == F64 && wordRep /= I64
198 -> ptext (sLit "ASSIGN_DBL") <>
199 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
202 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
206 CmmCall (CmmCallee fn cconv) results args safety _ret ->
208 pprCall ppr_fn cconv results args safety
210 ppr_fn = parens (cCast (pprCFunType (char '*') cconv results args) fn)
212 -- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
215 CmmLit (CmmLabel lbl) | not (isMathFun lbl) ->
216 ptext (sLit ";EI_(") <+> pprCLabel lbl <> char ')' <> semi
217 -- we declare all called functions as data labels,
218 -- and then cast them to the right type when calling.
219 -- This is because the label might already have a
220 -- declaration as a data label in the same file,
221 -- e.g. Foreign.Marshal.Alloc declares 'free' as
222 -- both a data label and a function label.
225 -- for a dynamic call, no declaration is necessary.
227 CmmCall (CmmPrim op) results args safety _ret ->
228 pprCall ppr_fn CCallConv results args safety
230 ppr_fn = pprCallishMachOp_for_C op
232 CmmBranch ident -> pprBranch ident
233 CmmCondBranch expr ident -> pprCondBranch expr ident
234 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
235 CmmSwitch arg ids -> pprSwitch arg ids
237 pprCFunType :: SDoc -> CCallConv -> CmmFormals -> CmmActuals -> SDoc
238 pprCFunType ppr_fn cconv ress args
240 parens (text (ccallConvAttribute cconv) <> ppr_fn) <>
241 parens (commafy (map arg_type args))
243 res_type [] = ptext (sLit "void")
244 res_type [CmmKinded one hint] = machRepHintCType (localRegRep one) hint
246 arg_type (CmmKinded expr hint) = machRepHintCType (cmmExprRep expr) hint
248 -- ---------------------------------------------------------------------
249 -- unconditional branches
250 pprBranch :: BlockId -> SDoc
251 pprBranch ident = ptext (sLit "goto") <+> pprBlockId ident <> semi
254 -- ---------------------------------------------------------------------
255 -- conditional branches to local labels
256 pprCondBranch :: CmmExpr -> BlockId -> SDoc
257 pprCondBranch expr ident
258 = hsep [ ptext (sLit "if") , parens(pprExpr expr) ,
259 ptext (sLit "goto") , (pprBlockId ident) <> semi ]
262 -- ---------------------------------------------------------------------
263 -- a local table branch
265 -- we find the fall-through cases
267 -- N.B. we remove Nothing's from the list of branches, as they are
268 -- 'undefined'. However, they may be defined one day, so we better
269 -- document this behaviour.
271 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
272 pprSwitch e maybe_ids
273 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
274 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
276 (hang (ptext (sLit "switch") <+> parens ( pprExpr e ) <+> lbrace)
277 4 (vcat ( map caseify pairs2 )))
281 sndEq (_,x) (_,y) = x == y
284 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
287 hsep [ ptext (sLit "case") , pprHexVal ix wordRep <> colon ,
288 ptext (sLit "/* fall through */") ]
291 hsep [ ptext (sLit "case") , pprHexVal ix wordRep <> colon ,
292 ptext (sLit "goto") , (pprBlockId ident) <> semi ]
294 -- ---------------------------------------------------------------------
298 -- C Types: the invariant is that the C expression generated by
302 -- has a type in C which is also given by
304 -- machRepCType (cmmExprRep e)
306 -- (similar invariants apply to the rest of the pretty printer).
308 pprExpr :: CmmExpr -> SDoc
309 pprExpr e = case e of
310 CmmLit lit -> pprLit lit
312 CmmLoad e I64 | wordRep /= I64
313 -> ptext (sLit "PK_Word64") <> parens (mkP_ <> pprExpr1 e)
315 CmmLoad e F64 | wordRep /= I64
316 -> ptext (sLit "PK_DBL") <> parens (mkP_ <> pprExpr1 e)
318 CmmLoad (CmmReg r) rep
319 | isPtrReg r && rep == wordRep
320 -> char '*' <> pprAsPtrReg r
322 CmmLoad (CmmRegOff r 0) rep
323 | isPtrReg r && rep == wordRep
324 -> char '*' <> pprAsPtrReg r
326 CmmLoad (CmmRegOff r off) rep
327 | isPtrReg r && rep == wordRep && (off `rem` wORD_SIZE == 0)
328 -- ToDo: check that the offset is a word multiple?
329 -- (For tagging to work, I had to avoid unaligned loads. --ARY)
330 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
336 CmmReg reg -> pprCastReg reg
337 CmmRegOff reg 0 -> pprCastReg reg
340 | i > 0 -> pprRegOff (char '+') i
341 | otherwise -> pprRegOff (char '-') (-i)
343 pprRegOff op i' = pprCastReg reg <> op <> int i'
345 CmmMachOp mop args -> pprMachOpApp mop args
347 pprExpr1 :: CmmExpr -> SDoc
348 pprExpr1 (CmmLit lit) = pprLit1 lit
349 pprExpr1 e@(CmmReg _reg) = pprExpr e
350 pprExpr1 other = parens (pprExpr other)
352 -- --------------------------------------------------------------------------
353 -- MachOp applications
355 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
359 = ptext (sLit "mulIntMayOflo") <> parens (commafy (map pprExpr args))
360 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
361 isMulMayOfloOp (MO_S_MulMayOflo _) = True
362 isMulMayOfloOp _ = False
364 pprMachOpApp mop args
365 | Just ty <- machOpNeedsCast mop
366 = ty <> parens (pprMachOpApp' mop args)
368 = pprMachOpApp' mop args
370 -- Comparisons in C have type 'int', but we want type W_ (this is what
371 -- resultRepOfMachOp says). The other C operations inherit their type
372 -- from their operands, so no casting is required.
373 machOpNeedsCast :: MachOp -> Maybe SDoc
375 | isComparisonMachOp mop = Just mkW_
376 | otherwise = Nothing
378 pprMachOpApp' mop args
381 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
384 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
386 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
389 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
390 | otherwise = pprExpr1 e
392 -- --------------------------------------------------------------------------
395 pprLit :: CmmLit -> SDoc
396 pprLit lit = case lit of
397 CmmInt i rep -> pprHexVal i rep
399 CmmFloat f rep -> parens (machRepCType rep) <> str
400 where d = fromRational f :: Double
401 str | isInfinite d && d < 0 = ptext (sLit "-INFINITY")
402 | isInfinite d = ptext (sLit "INFINITY")
403 | isNaN d = ptext (sLit "NAN")
404 | otherwise = text (show d)
405 -- these constants come from <math.h>
408 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
409 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
410 CmmLabelDiffOff clbl1 clbl2 i
412 -- * the lit must occur in the info table clbl2
413 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
414 -- The Mangler is expected to convert any reference to an SRT,
415 -- a slow entry point or a large bitmap
416 -- from an info table to an offset.
417 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
419 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
421 pprLit1 :: CmmLit -> SDoc
422 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
423 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
424 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
425 pprLit1 other = pprLit other
427 -- ---------------------------------------------------------------------------
430 pprStatics :: [CmmStatic] -> [SDoc]
432 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
433 -- floats are padded to a word, see #1852
434 | wORD_SIZE == 8, CmmStaticLit (CmmInt 0 I32) : rest' <- rest
435 = pprLit1 (floatToWord f) : pprStatics rest'
437 = pprLit1 (floatToWord f) : pprStatics rest
439 = pprPanic "pprStatics: float" (vcat (map (\(CmmStaticLit l) -> ppr (cmmLitRep l)) rest))
440 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
441 = map pprLit1 (doubleToWords f) ++ pprStatics rest
442 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
443 | machRepByteWidth I32 == wORD_SIZE
444 #ifdef WORDS_BIGENDIAN
445 = pprStatics (CmmStaticLit (CmmInt q I32) :
446 CmmStaticLit (CmmInt r I32) : rest)
448 = pprStatics (CmmStaticLit (CmmInt r I32) :
449 CmmStaticLit (CmmInt q I32) : rest)
451 where r = i .&. 0xffffffff
453 pprStatics (CmmStaticLit (CmmInt i rep) : rest)
454 | machRepByteWidth rep /= wORD_SIZE
455 = panic "pprStatics: cannot emit a non-word-sized static literal"
456 pprStatics (CmmStaticLit lit : rest)
457 = pprLit1 lit : pprStatics rest
458 pprStatics (other : rest)
459 = pprPanic "pprWord" (pprStatic other)
461 pprStatic :: CmmStatic -> SDoc
462 pprStatic s = case s of
464 CmmStaticLit lit -> nest 4 (pprLit lit)
465 CmmAlign i -> nest 4 (ptext (sLit "/* align */") <+> int i)
466 CmmDataLabel clbl -> pprCLabel clbl <> colon
467 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
469 -- these should be inlined, like the old .hc
470 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
473 -- ---------------------------------------------------------------------------
476 pprBlockId :: BlockId -> SDoc
477 pprBlockId b = char '_' <> ppr (getUnique b)
479 -- --------------------------------------------------------------------------
480 -- Print a MachOp in a way suitable for emitting via C.
483 pprMachOp_for_C :: MachOp -> SDoc
485 pprMachOp_for_C mop = case mop of
487 -- Integer operations
490 MO_Eq _ -> ptext (sLit "==")
491 MO_Ne _ -> ptext (sLit "!=")
494 MO_S_Quot _ -> char '/'
495 MO_S_Rem _ -> char '%'
496 MO_S_Neg _ -> char '-'
498 MO_U_Quot _ -> char '/'
499 MO_U_Rem _ -> char '%'
501 -- Signed comparisons (floating-point comparisons also use these)
502 -- & Unsigned comparisons
503 MO_S_Ge _ -> ptext (sLit ">=")
504 MO_S_Le _ -> ptext (sLit "<=")
505 MO_S_Gt _ -> char '>'
506 MO_S_Lt _ -> char '<'
508 MO_U_Ge _ -> ptext (sLit ">=")
509 MO_U_Le _ -> ptext (sLit "<=")
510 MO_U_Gt _ -> char '>'
511 MO_U_Lt _ -> char '<'
513 -- Bitwise operations. Not all of these may be supported at all
514 -- sizes, and only integral MachReps are valid.
519 MO_Shl _ -> ptext (sLit "<<")
520 MO_U_Shr _ -> ptext (sLit ">>") -- unsigned shift right
521 MO_S_Shr _ -> ptext (sLit ">>") -- signed shift right
523 -- Conversions. Some of these will be NOPs.
524 -- Floating-point conversions use the signed variant.
525 -- We won't know to generate (void*) casts here, but maybe from
529 MO_U_Conv I8 I8 -> empty
530 MO_U_Conv I16 I16 -> empty
531 MO_U_Conv I32 I32 -> empty
532 MO_U_Conv I64 I64 -> empty
533 MO_U_Conv I128 I128 -> empty
534 MO_S_Conv I8 I8 -> empty
535 MO_S_Conv I16 I16 -> empty
536 MO_S_Conv I32 I32 -> empty
537 MO_S_Conv I64 I64 -> empty
538 MO_S_Conv I128 I128 -> empty
540 MO_U_Conv _from to -> parens (machRepCType to)
541 MO_S_Conv _from to -> parens (machRepSignedCType to)
543 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
545 signedOp :: MachOp -> Bool
546 signedOp (MO_S_Quot _) = True
547 signedOp (MO_S_Rem _) = True
548 signedOp (MO_S_Neg _) = True
549 signedOp (MO_S_Ge _) = True
550 signedOp (MO_S_Le _) = True
551 signedOp (MO_S_Gt _) = True
552 signedOp (MO_S_Lt _) = True
553 signedOp (MO_S_Shr _) = True
554 signedOp (MO_S_Conv _ _) = True
557 -- ---------------------------------------------------------------------
558 -- tend to be implemented by foreign calls
560 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
562 pprCallishMachOp_for_C mop
564 MO_F64_Pwr -> ptext (sLit "pow")
565 MO_F64_Sin -> ptext (sLit "sin")
566 MO_F64_Cos -> ptext (sLit "cos")
567 MO_F64_Tan -> ptext (sLit "tan")
568 MO_F64_Sinh -> ptext (sLit "sinh")
569 MO_F64_Cosh -> ptext (sLit "cosh")
570 MO_F64_Tanh -> ptext (sLit "tanh")
571 MO_F64_Asin -> ptext (sLit "asin")
572 MO_F64_Acos -> ptext (sLit "acos")
573 MO_F64_Atan -> ptext (sLit "atan")
574 MO_F64_Log -> ptext (sLit "log")
575 MO_F64_Exp -> ptext (sLit "exp")
576 MO_F64_Sqrt -> ptext (sLit "sqrt")
577 MO_F32_Pwr -> ptext (sLit "powf")
578 MO_F32_Sin -> ptext (sLit "sinf")
579 MO_F32_Cos -> ptext (sLit "cosf")
580 MO_F32_Tan -> ptext (sLit "tanf")
581 MO_F32_Sinh -> ptext (sLit "sinhf")
582 MO_F32_Cosh -> ptext (sLit "coshf")
583 MO_F32_Tanh -> ptext (sLit "tanhf")
584 MO_F32_Asin -> ptext (sLit "asinf")
585 MO_F32_Acos -> ptext (sLit "acosf")
586 MO_F32_Atan -> ptext (sLit "atanf")
587 MO_F32_Log -> ptext (sLit "logf")
588 MO_F32_Exp -> ptext (sLit "expf")
589 MO_F32_Sqrt -> ptext (sLit "sqrtf")
590 MO_WriteBarrier -> ptext (sLit "write_barrier")
592 -- ---------------------------------------------------------------------
596 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
598 mkJMP_ i = ptext (sLit "JMP_") <> parens i
599 mkFN_ i = ptext (sLit "FN_") <> parens i -- externally visible function
600 mkIF_ i = ptext (sLit "IF_") <> parens i -- locally visible
604 mkFB_ = ptext (sLit "FB_") -- function code begin
605 mkFE_ = ptext (sLit "FE_") -- function code end
607 -- from includes/Stg.h
609 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
611 mkC_ = ptext (sLit "(C_)") -- StgChar
612 mkW_ = ptext (sLit "(W_)") -- StgWord
613 mkP_ = ptext (sLit "(P_)") -- StgWord*
614 mkPP_ = ptext (sLit "(PP_)") -- P_*
615 mkI_ = ptext (sLit "(I_)") -- StgInt
616 mkA_ = ptext (sLit "(A_)") -- StgAddr
617 mkD_ = ptext (sLit "(D_)") -- const StgWord*
618 mkF_ = ptext (sLit "(F_)") -- StgFunPtr
619 mkB_ = ptext (sLit "(B_)") -- StgByteArray
620 mkL_ = ptext (sLit "(L_)") -- StgClosurePtr
622 mkLI_ = ptext (sLit "(LI_)") -- StgInt64
623 mkLW_ = ptext (sLit "(LW_)") -- StgWord64
626 -- ---------------------------------------------------------------------
630 -- Generating assignments is what we're all about, here
632 pprAssign :: CmmReg -> CmmExpr -> SDoc
634 -- dest is a reg, rhs is a reg
635 pprAssign r1 (CmmReg r2)
636 | isPtrReg r1 && isPtrReg r2
637 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
639 -- dest is a reg, rhs is a CmmRegOff
640 pprAssign r1 (CmmRegOff r2 off)
641 | isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE == 0)
642 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
644 off1 = off `shiftR` wordShift
646 (op,off') | off >= 0 = (char '+', off1)
647 | otherwise = (char '-', -off1)
649 -- dest is a reg, rhs is anything.
650 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
651 -- the lvalue elicits a warning from new GCC versions (3.4+).
653 | isFixedPtrReg r1 = mkAssign (mkP_ <> pprExpr1 r2)
654 | Just ty <- strangeRegType r1 = mkAssign (parens ty <> pprExpr1 r2)
655 | otherwise = mkAssign (pprExpr r2)
656 where mkAssign x = if r1 == CmmGlobal BaseReg
657 then ptext (sLit "ASSIGN_BaseReg") <> parens x <> semi
658 else pprReg r1 <> ptext (sLit " = ") <> x <> semi
660 -- ---------------------------------------------------------------------
664 | isStrangeTypeReg reg = mkW_ <> pprReg reg
665 | otherwise = pprReg reg
667 -- True if (pprReg reg) will give an expression with type StgPtr. We
668 -- need to take care with pointer arithmetic on registers with type
670 isFixedPtrReg :: CmmReg -> Bool
671 isFixedPtrReg (CmmLocal _) = False
672 isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
674 -- True if (pprAsPtrReg reg) will give an expression with type StgPtr
675 isPtrReg :: CmmReg -> Bool
676 isPtrReg (CmmLocal _) = False
677 isPtrReg (CmmGlobal (VanillaReg n)) = True -- if we print via pprAsPtrReg
678 isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg
680 -- True if this global reg has type StgPtr
681 isFixedPtrGlobalReg :: GlobalReg -> Bool
682 isFixedPtrGlobalReg Sp = True
683 isFixedPtrGlobalReg Hp = True
684 isFixedPtrGlobalReg HpLim = True
685 isFixedPtrGlobalReg SpLim = True
686 isFixedPtrGlobalReg _ = False
688 -- True if in C this register doesn't have the type given by
689 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
690 isStrangeTypeReg :: CmmReg -> Bool
691 isStrangeTypeReg (CmmLocal _) = False
692 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
694 isStrangeTypeGlobal :: GlobalReg -> Bool
695 isStrangeTypeGlobal CurrentTSO = True
696 isStrangeTypeGlobal CurrentNursery = True
697 isStrangeTypeGlobal BaseReg = True
698 isStrangeTypeGlobal r = isFixedPtrGlobalReg r
700 strangeRegType :: CmmReg -> Maybe SDoc
701 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext (sLit "struct StgTSO_ *"))
702 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext (sLit "struct bdescr_ *"))
703 strangeRegType (CmmGlobal BaseReg) = Just (ptext (sLit "struct StgRegTable_ *"))
704 strangeRegType _ = Nothing
706 -- pprReg just prints the register name.
708 pprReg :: CmmReg -> SDoc
710 CmmLocal local -> pprLocalReg local
711 CmmGlobal global -> pprGlobalReg global
713 pprAsPtrReg :: CmmReg -> SDoc
714 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext (sLit ".p")
715 pprAsPtrReg other_reg = pprReg other_reg
717 pprGlobalReg :: GlobalReg -> SDoc
718 pprGlobalReg gr = case gr of
719 VanillaReg n -> char 'R' <> int n <> ptext (sLit ".w")
720 FloatReg n -> char 'F' <> int n
721 DoubleReg n -> char 'D' <> int n
722 LongReg n -> char 'L' <> int n
723 Sp -> ptext (sLit "Sp")
724 SpLim -> ptext (sLit "SpLim")
725 Hp -> ptext (sLit "Hp")
726 HpLim -> ptext (sLit "HpLim")
727 CurrentTSO -> ptext (sLit "CurrentTSO")
728 CurrentNursery -> ptext (sLit "CurrentNursery")
729 HpAlloc -> ptext (sLit "HpAlloc")
730 BaseReg -> ptext (sLit "BaseReg")
731 GCEnter1 -> ptext (sLit "stg_gc_enter_1")
732 GCFun -> ptext (sLit "stg_gc_fun")
734 pprLocalReg :: LocalReg -> SDoc
735 pprLocalReg (LocalReg uniq _ _) = char '_' <> ppr uniq
737 -- -----------------------------------------------------------------------------
740 pprCall :: SDoc -> CCallConv -> CmmFormals -> CmmActuals -> CmmSafety
743 pprCall ppr_fn cconv results args _
744 | not (is_cish cconv)
745 = panic "pprCall: unknown calling convention"
749 #if x86_64_TARGET_ARCH
750 -- HACK around gcc optimisations.
751 -- x86_64 needs a __DISCARD__() here, to create a barrier between
752 -- putting the arguments into temporaries and passing the arguments
753 -- to the callee, because the argument expressions may refer to
754 -- machine registers that are also used for passing arguments in the
755 -- C calling convention.
756 (if (not opt_Unregisterised)
757 then ptext (sLit "__DISCARD__();")
760 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi
762 ppr_assign [] rhs = rhs
763 ppr_assign [CmmKinded one hint] rhs
764 = pprLocalReg one <> ptext (sLit " = ")
765 <> pprUnHint hint (localRegRep one) <> rhs
766 ppr_assign _other _rhs = panic "pprCall: multiple results"
768 pprArg (CmmKinded expr hint)
769 | hint `elem` [PtrHint,SignedHint]
770 = cCast (machRepHintCType (cmmExprRep expr) hint) expr
771 -- see comment by machRepHintCType below
772 pprArg (CmmKinded expr _other)
775 pprUnHint PtrHint rep = parens (machRepCType rep)
776 pprUnHint SignedHint rep = parens (machRepCType rep)
777 pprUnHint _ _ = empty
779 pprGlobalRegName :: GlobalReg -> SDoc
780 pprGlobalRegName gr = case gr of
781 VanillaReg n -> char 'R' <> int n -- without the .w suffix
784 -- Currently we only have these two calling conventions, but this might
785 -- change in the future...
786 is_cish CCallConv = True
787 is_cish StdCallConv = True
789 -- ---------------------------------------------------------------------
790 -- Find and print local and external declarations for a list of
793 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
794 pprTempAndExternDecls stmts
795 = (vcat (map pprTempDecl (uniqSetToList temps)),
796 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
797 where (temps, lbls) = runTE (mapM_ te_BB stmts)
799 pprDataExterns :: [CmmStatic] -> SDoc
800 pprDataExterns statics
801 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
802 where (_, lbls) = runTE (mapM_ te_Static statics)
804 pprTempDecl :: LocalReg -> SDoc
805 pprTempDecl l@(LocalReg _ rep _)
806 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
808 pprExternDecl :: Bool -> CLabel -> SDoc
809 pprExternDecl in_srt lbl
810 -- do not print anything for "known external" things
811 | not (needsCDecl lbl) = empty
813 hcat [ visibility, label_type (labelType lbl),
814 lparen, pprCLabel lbl, text ");" ]
816 label_type CodeLabel = ptext (sLit "F_")
817 label_type DataLabel = ptext (sLit "I_")
820 | externallyVisibleCLabel lbl = char 'E'
821 | otherwise = char 'I'
824 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
825 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
827 instance Monad TE where
828 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
829 return a = TE $ \s -> (a, s)
831 te_lbl :: CLabel -> TE ()
832 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
834 te_temp :: LocalReg -> TE ()
835 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
837 runTE :: TE () -> TEState
838 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
840 te_Static :: CmmStatic -> TE ()
841 te_Static (CmmStaticLit lit) = te_Lit lit
842 te_Static _ = return ()
844 te_BB :: CmmBasicBlock -> TE ()
845 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
847 te_Lit :: CmmLit -> TE ()
848 te_Lit (CmmLabel l) = te_lbl l
849 te_Lit (CmmLabelOff l _) = te_lbl l
850 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
853 te_Stmt :: CmmStmt -> TE ()
854 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
855 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
856 te_Stmt (CmmCall _ rs es _ _) = mapM_ (te_temp.kindlessCmm) rs >>
857 mapM_ (te_Expr.kindlessCmm) es
858 te_Stmt (CmmCondBranch e _) = te_Expr e
859 te_Stmt (CmmSwitch e _) = te_Expr e
860 te_Stmt (CmmJump e _) = te_Expr e
861 te_Stmt _ = return ()
863 te_Expr :: CmmExpr -> TE ()
864 te_Expr (CmmLit lit) = te_Lit lit
865 te_Expr (CmmLoad e _) = te_Expr e
866 te_Expr (CmmReg r) = te_Reg r
867 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
868 te_Expr (CmmRegOff r _) = te_Reg r
870 te_Reg :: CmmReg -> TE ()
871 te_Reg (CmmLocal l) = te_temp l
875 -- ---------------------------------------------------------------------
876 -- C types for MachReps
878 cCast :: SDoc -> CmmExpr -> SDoc
879 cCast ty expr = parens ty <> pprExpr1 expr
881 cLoad :: CmmExpr -> MachRep -> SDoc
882 #ifdef BEWARE_LOAD_STORE_ALIGNMENT
884 let decl = machRepCType rep <+> ptext (sLit "x") <> semi
885 struct = ptext (sLit "struct") <+> braces (decl)
886 packed_attr = ptext (sLit "__attribute__((packed))")
887 cast = parens (struct <+> packed_attr <> char '*')
888 in parens (cast <+> pprExpr1 expr) <> ptext (sLit "->x")
890 cLoad expr rep = char '*' <> parens (cCast (machRepPtrCType rep) expr)
893 -- This is for finding the types of foreign call arguments. For a pointer
894 -- argument, we always cast the argument to (void *), to avoid warnings from
896 machRepHintCType :: MachRep -> MachHint -> SDoc
897 machRepHintCType rep PtrHint = ptext (sLit "void *")
898 machRepHintCType rep SignedHint = machRepSignedCType rep
899 machRepHintCType rep _other = machRepCType rep
901 machRepPtrCType :: MachRep -> SDoc
902 machRepPtrCType r | r == wordRep = ptext (sLit "P_")
903 | otherwise = machRepCType r <> char '*'
905 machRepCType :: MachRep -> SDoc
906 machRepCType r | r == wordRep = ptext (sLit "W_")
907 | otherwise = sized_type
908 where sized_type = case r of
909 I8 -> ptext (sLit "StgWord8")
910 I16 -> ptext (sLit "StgWord16")
911 I32 -> ptext (sLit "StgWord32")
912 I64 -> ptext (sLit "StgWord64")
913 F32 -> ptext (sLit "StgFloat") -- ToDo: correct?
914 F64 -> ptext (sLit "StgDouble")
915 _ -> panic "machRepCType"
917 machRepSignedCType :: MachRep -> SDoc
918 machRepSignedCType r | r == wordRep = ptext (sLit "I_")
919 | otherwise = sized_type
920 where sized_type = case r of
921 I8 -> ptext (sLit "StgInt8")
922 I16 -> ptext (sLit "StgInt16")
923 I32 -> ptext (sLit "StgInt32")
924 I64 -> ptext (sLit "StgInt64")
925 F32 -> ptext (sLit "StgFloat") -- ToDo: correct?
926 F64 -> ptext (sLit "StgDouble")
927 _ -> panic "machRepCType"
929 -- ---------------------------------------------------------------------
930 -- print strings as valid C strings
932 pprStringInCStyle :: [Word8] -> SDoc
933 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
935 charToC :: Word8 -> String
937 case chr (fromIntegral w) of
941 c | c >= ' ' && c <= '~' -> [c]
942 | otherwise -> ['\\',
943 chr (ord '0' + ord c `div` 64),
944 chr (ord '0' + ord c `div` 8 `mod` 8),
945 chr (ord '0' + ord c `mod` 8)]
947 -- ---------------------------------------------------------------------------
948 -- Initialising static objects with floating-point numbers. We can't
949 -- just emit the floating point number, because C will cast it to an int
950 -- by rounding it. We want the actual bit-representation of the float.
952 -- This is a hack to turn the floating point numbers into ints that we
953 -- can safely initialise to static locations.
956 | machRepByteWidth F64 == 2 * wORD_SIZE = True
957 | machRepByteWidth F64 == wORD_SIZE = False
958 | otherwise = panic "big_doubles"
960 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
961 castFloatToIntArray = castSTUArray
963 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
964 castDoubleToIntArray = castSTUArray
966 -- floats are always 1 word
967 floatToWord :: Rational -> CmmLit
970 arr <- newArray_ ((0::Int),0)
971 writeArray arr 0 (fromRational r)
972 arr' <- castFloatToIntArray arr
973 i <- readArray arr' 0
974 return (CmmInt (toInteger i) wordRep)
977 doubleToWords :: Rational -> [CmmLit]
979 | big_doubles -- doubles are 2 words
981 arr <- newArray_ ((0::Int),1)
982 writeArray arr 0 (fromRational r)
983 arr' <- castDoubleToIntArray arr
984 i1 <- readArray arr' 0
985 i2 <- readArray arr' 1
986 return [ CmmInt (toInteger i1) wordRep
987 , CmmInt (toInteger i2) wordRep
990 | otherwise -- doubles are 1 word
992 arr <- newArray_ ((0::Int),0)
993 writeArray arr 0 (fromRational r)
994 arr' <- castDoubleToIntArray arr
995 i <- readArray arr' 0
996 return [ CmmInt (toInteger i) wordRep ]
999 -- ---------------------------------------------------------------------------
1003 wordShift = machRepLogWidth wordRep
1005 commafy :: [SDoc] -> SDoc
1006 commafy xs = hsep $ punctuate comma xs
1008 -- Print in C hex format: 0x13fa
1009 pprHexVal :: Integer -> MachRep -> SDoc
1010 pprHexVal 0 _ = ptext (sLit "0x0")
1012 | w < 0 = parens (char '-' <> ptext (sLit "0x") <> go (-w) <> repsuffix rep)
1013 | otherwise = ptext (sLit "0x") <> go w <> repsuffix rep
1015 -- type suffix for literals:
1016 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1017 -- signed values for doing signed operations, but at all other
1018 -- times values are unsigned. This also helps eliminate occasional
1019 -- warnings about integer overflow from gcc.
1021 -- on 32-bit platforms, add "ULL" to 64-bit literals
1022 repsuffix I64 | wORD_SIZE == 4 = ptext (sLit "ULL")
1023 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1024 repsuffix I64 | cINT_SIZE == 4 = ptext (sLit "UL")
1025 repsuffix _ = char 'U'
1030 (q,r) = w' `quotRem` 16
1031 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1032 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))