simplify the generated C a little by removing some casts.
[ghc-hetmet.git] / compiler / cmm / PprC.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
4 --
5 -- (c) The University of Glasgow 2004-2006
6 --
7 -----------------------------------------------------------------------------
8
9 --
10 -- Print Cmm as real C, for -fvia-C
11 --
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.
15 --
16
17 -- ToDo: save/restore volatile registers around calls.
18
19 module PprC (
20         writeCs,
21         pprStringInCStyle 
22   ) where
23
24 #include "HsVersions.h"
25
26 -- Cmm stuff
27 import Cmm
28 import CLabel
29 import MachOp
30 import ForeignCall
31
32 -- Utils
33 import DynFlags
34 import Unique
35 import UniqSet
36 import FiniteMap
37 import UniqFM
38 import FastString
39 import Outputable
40 import Constants
41
42 -- The rest
43 import Data.List
44 import Data.Bits
45 import Data.Char
46 import System.IO
47 import Data.Word
48
49 #ifdef DEBUG
50 import PprCmm           () -- instances only
51 -- import Debug.Trace
52 #endif
53
54 #if __GLASGOW_HASKELL__ >= 504
55 import Data.Array.ST
56 #endif
57 import Control.Monad.ST
58
59 #if x86_64_TARGET_ARCH
60 import StaticFlags      ( opt_Unregisterised )
61 #endif
62
63 -- --------------------------------------------------------------------------
64 -- Top level
65
66 pprCs :: DynFlags -> [Cmm] -> SDoc
67 pprCs dflags cmms
68  = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
69  where
70    split_marker
71      | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
72      | otherwise                 = empty
73
74 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
75 writeCs dflags handle cmms 
76   = printForC handle (pprCs dflags cmms)
77
78 -- --------------------------------------------------------------------------
79 -- Now do some real work
80 --
81 -- for fun, we could call cmmToCmm over the tops...
82 --
83
84 pprC :: Cmm -> SDoc
85 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
86
87 --
88 -- top level procs
89 -- 
90 pprTop :: CmmTop -> SDoc
91 pprTop (CmmProc info clbl _params blocks) =
92     (if not (null info)
93         then pprDataExterns info $$
94              pprWordArray (entryLblToInfoLbl clbl) info
95         else empty) $$
96     (case blocks of
97         [] -> empty
98          -- the first block doesn't get a label:
99         (BasicBlock _ stmts : rest) -> vcat [
100            text "",
101            extern_decls,
102            (if (externallyVisibleCLabel clbl)
103                     then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
104            nest 8 temp_decls,
105            nest 8 mkFB_,
106            nest 8 (vcat (map pprStmt stmts)) $$
107               vcat (map pprBBlock rest),
108            nest 8 mkFE_,
109            rbrace ]
110     )
111   where
112         (temp_decls, extern_decls) = pprTempAndExternDecls blocks 
113
114
115 -- Chunks of static data.
116
117 -- We only handle (a) arrays of word-sized things and (b) strings.
118
119 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) = 
120   hcat [
121     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
122     ptext SLIT("[] = "), pprStringInCStyle str, semi
123   ]
124
125 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) = 
126   hcat [
127     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
128     brackets (int size), semi
129   ]
130
131 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) = 
132   pprDataExterns lits $$
133   pprWordArray lbl lits  
134
135 -- these shouldn't appear?
136 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
137
138
139 -- --------------------------------------------------------------------------
140 -- BasicBlocks are self-contained entities: they always end in a jump.
141 --
142 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
143 -- as many jumps as possible into fall throughs.
144 --
145
146 pprBBlock :: CmmBasicBlock -> SDoc
147 pprBBlock (BasicBlock lbl stmts) = 
148     if null stmts then
149         pprTrace "pprC.pprBBlock: curious empty code block for" 
150                         (pprBlockId lbl) empty
151     else 
152         nest 4 (pprBlockId lbl <> colon) $$
153         nest 8 (vcat (map pprStmt stmts))
154
155 -- --------------------------------------------------------------------------
156 -- Info tables. Just arrays of words. 
157 -- See codeGen/ClosureInfo, and nativeGen/PprMach
158
159 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
160 pprWordArray lbl ds
161   = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
162          , space, pprCLabel lbl, ptext SLIT("[] = {") ] 
163     $$ nest 8 (commafy (pprStatics ds))
164     $$ ptext SLIT("};")
165
166 --
167 -- has to be static, if it isn't globally visible
168 --
169 pprLocalness :: CLabel -> SDoc
170 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
171                  | otherwise = empty
172
173 -- --------------------------------------------------------------------------
174 -- Statements.
175 --
176
177 pprStmt :: CmmStmt -> SDoc
178
179 pprStmt stmt = case stmt of
180     CmmNop       -> empty
181     CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
182
183     CmmAssign dest src -> pprAssign dest src
184
185     CmmStore  dest src
186         | rep == I64 && wordRep /= I64
187         -> ptext SLIT("ASSIGN_Word64") <> 
188                 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
189
190         | rep == F64 && wordRep /= I64
191         -> ptext SLIT("ASSIGN_DBL") <> 
192                 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
193
194         | otherwise
195         -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
196         where
197           rep = cmmExprRep src
198
199     CmmCall (CmmForeignCall fn cconv) results args volatile -> 
200         -- Controversial: leave this out for now.
201         -- pprUndef fn $$
202
203         pprCall ppr_fn cconv results args volatile
204         where
205         ppr_fn = case fn of
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).
210
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
215         -- better anyway.
216         pprUndef (CmmLit (CmmLabel lbl)) = 
217            ptext SLIT("#undef") <+> pprCLabel lbl
218         pprUndef _ = empty
219
220     CmmCall (CmmPrim op) results args volatile -> 
221         pprCall ppr_fn CCallConv results args volatile
222         where
223         ppr_fn = pprCallishMachOp_for_C op
224
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
229
230 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
231 pprCFunType cconv ress args
232   = hcat [
233         res_type ress,
234         parens (text (ccallConvAttribute cconv) <>  char '*'),
235         parens (commafy (map arg_type args))
236    ]
237   where
238         res_type [] = ptext SLIT("void")
239         res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
240
241         arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
242
243 -- ---------------------------------------------------------------------
244 -- unconditional branches
245 pprBranch :: BlockId -> SDoc
246 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
247
248
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 ]
255
256
257 -- ---------------------------------------------------------------------
258 -- a local table branch
259 --
260 -- we find the fall-through cases
261 --
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.
265 --
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 ]
270     in 
271         (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
272                 4 (vcat ( map caseify pairs2 )))
273         $$ rbrace
274
275   where
276     sndEq (_,x) (_,y) = x == y
277
278     -- fall through case
279     caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
280         where 
281         do_fallthrough ix =
282                  hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
283                         ptext SLIT("/* fall through */") ]
284
285         final_branch ix = 
286                 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
287                        ptext SLIT("goto") , (pprBlockId ident) <> semi ]
288
289 -- ---------------------------------------------------------------------
290 -- Expressions.
291 --
292
293 -- C Types: the invariant is that the C expression generated by
294 --
295 --      pprExpr e
296 --
297 -- has a type in C which is also given by
298 --
299 --      machRepCType (cmmExprRep e)
300 --
301 -- (similar invariants apply to the rest of the pretty printer).
302
303 pprExpr :: CmmExpr -> SDoc
304 pprExpr e = case e of
305     CmmLit lit -> pprLit lit
306
307     CmmLoad e I64 | wordRep /= I64
308         -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
309
310     CmmLoad e F64 | wordRep /= I64
311         -> ptext SLIT("PK_DBL") <> parens (mkP_ <> pprExpr1 e)
312
313     CmmLoad (CmmReg r) rep 
314         | isPtrReg r && rep == wordRep
315         -> char '*' <> pprAsPtrReg r
316
317     CmmLoad (CmmRegOff r 0) rep 
318         | isPtrReg r && rep == wordRep
319         -> char '*' <> pprAsPtrReg r
320
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))
325
326     CmmLoad expr rep ->
327         -- the general case:
328         char '*' <> parens (cCast (machRepPtrCType rep) expr)
329
330     CmmReg reg      -> pprCastReg reg
331     CmmRegOff reg 0 -> pprCastReg reg
332
333     CmmRegOff reg i
334         | i >  0    -> pprRegOff (char '+') i
335         | otherwise -> pprRegOff (char '-') (-i)
336       where
337         pprRegOff op i' = pprCastReg reg <> op <> int i'
338
339     CmmMachOp mop args -> pprMachOpApp mop args
340
341 pprExpr1 :: CmmExpr -> SDoc
342 pprExpr1 (CmmLit lit)     = pprLit1 lit
343 pprExpr1 e@(CmmReg _reg)  = pprExpr e
344 pprExpr1 other            = parens (pprExpr other)
345
346 -- --------------------------------------------------------------------------
347 -- MachOp applications
348
349 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
350
351 pprMachOpApp op args
352   | isMulMayOfloOp op
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
357
358 pprMachOpApp mop args
359   | Just ty <- machOpNeedsCast mop 
360   = ty <> parens (pprMachOpApp' mop args)
361   | otherwise
362   = pprMachOpApp' mop args
363
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
368 machOpNeedsCast mop
369   | isComparisonMachOp mop = Just mkW_
370   | otherwise              = Nothing
371
372 pprMachOpApp' mop args
373  = case args of
374     -- dyadic
375     [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
376
377     -- unary
378     [x]   -> pprMachOp_for_C mop <> parens (pprArg x)
379
380     _     -> panic "PprC.pprMachOp : machop with wrong number of args"
381
382   where
383     pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
384              | otherwise    = pprExpr1 e
385
386 -- --------------------------------------------------------------------------
387 -- Literals
388
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
396         -- WARNING:
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
403
404 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
405
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
411
412 -- ---------------------------------------------------------------------------
413 -- Static data
414
415 pprStatics :: [CmmStatic] -> [SDoc]
416 pprStatics [] = []
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)
426 #else
427   = pprStatics (CmmStaticLit (CmmInt r I32) : 
428                 CmmStaticLit (CmmInt q I32) : rest)
429 #endif
430   where r = i .&. 0xffffffff
431         q = i `shiftR` 32
432 pprStatics (CmmStaticLit lit : rest)
433   = pprLit1 lit : pprStatics rest
434 pprStatics (other : rest)
435   = pprPanic "pprWord" (pprStatic other)
436
437 pprStatic :: CmmStatic -> SDoc
438 pprStatic s = case s of
439
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))
444
445     -- these should be inlined, like the old .hc
446     CmmString s'       -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
447
448
449 -- ---------------------------------------------------------------------------
450 -- Block Ids
451
452 pprBlockId :: BlockId -> SDoc
453 pprBlockId b = char '_' <> ppr (getUnique b)
454
455 -- --------------------------------------------------------------------------
456 -- Print a MachOp in a way suitable for emitting via C.
457 --
458
459 pprMachOp_for_C :: MachOp -> SDoc
460
461 pprMachOp_for_C mop = case mop of 
462
463         -- Integer operations
464         MO_Add          _ -> char '+'
465         MO_Sub          _ -> char '-'
466         MO_Eq           _ -> ptext SLIT("==")
467         MO_Ne           _ -> ptext SLIT("!=")
468         MO_Mul          _ -> char '*'
469
470         MO_S_Quot       _ -> char '/'
471         MO_S_Rem        _ -> char '%'
472         MO_S_Neg        _ -> char '-'
473
474         MO_U_Quot       _ -> char '/'
475         MO_U_Rem        _ -> char '%'
476
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 '<'
483
484         MO_U_Ge         _ -> ptext SLIT(">=")
485         MO_U_Le         _ -> ptext SLIT("<=")
486         MO_U_Gt         _ -> char '>'
487         MO_U_Lt         _ -> char '<'
488
489         -- Bitwise operations.  Not all of these may be supported at all
490         -- sizes, and only integral MachReps are valid.
491         MO_And          _ -> char '&'
492         MO_Or           _ -> char '|'
493         MO_Xor          _ -> char '^'
494         MO_Not          _ -> char '~'
495         MO_Shl          _ -> ptext SLIT("<<")
496         MO_U_Shr        _ -> ptext SLIT(">>") -- unsigned shift right
497         MO_S_Shr        _ -> ptext SLIT(">>") -- signed shift right
498
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
502 -- context elsewhere
503
504 -- noop casts
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
515
516         MO_U_Conv _from to  -> parens (machRepCType to)
517         MO_S_Conv _from to  -> parens (machRepSignedCType to)
518
519         _ -> panic "PprC.pprMachOp_for_C: unknown machop"
520
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
531 signedOp _ = False
532
533 -- ---------------------------------------------------------------------
534 -- tend to be implemented by foreign calls
535
536 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
537
538 pprCallishMachOp_for_C mop 
539     = case mop of
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")
567
568 -- ---------------------------------------------------------------------
569 -- Useful #defines
570 --
571
572 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
573
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
577
578
579 mkFB_, mkFE_ :: SDoc
580 mkFB_ = ptext SLIT("FB_") -- function code begin
581 mkFE_ = ptext SLIT("FE_") -- function code end
582
583 -- from includes/Stg.h
584 --
585 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
586
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
597
598 mkLI_ = ptext SLIT("(LI_)")       -- StgInt64
599 mkLW_ = ptext SLIT("(LW_)")       -- StgWord64
600
601
602 -- ---------------------------------------------------------------------
603 --
604 -- Assignments
605 --
606 -- Generating assignments is what we're all about, here
607 --
608 pprAssign :: CmmReg -> CmmExpr -> SDoc
609
610 -- dest is a reg, rhs is a reg
611 pprAssign r1 (CmmReg r2)
612    | isPtrReg r1 && isPtrReg r2
613    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
614
615 -- dest is a reg, rhs is a CmmRegOff
616 pprAssign r1 (CmmRegOff r2 off)
617    | isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE == 0)
618    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
619   where
620         off1 = off `shiftR` wordShift
621
622         (op,off') | off >= 0  = (char '+', off1)
623                   | otherwise = (char '-', -off1)
624
625 -- dest is a reg, rhs is anything.
626 -- We can't cast the lvalue, so we have to cast the rhs if necessary.  Casting
627 -- the lvalue elicits a warning from new GCC versions (3.4+).
628 pprAssign r1 r2
629   | isFixedPtrReg r1
630   = pprReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
631   | Just ty <- strangeRegType r1
632   = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
633   | otherwise
634   = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
635
636 -- ---------------------------------------------------------------------
637 -- Registers
638
639 pprCastReg reg
640    | isStrangeTypeReg reg = mkW_ <> pprReg reg
641    | otherwise            = pprReg reg
642
643 -- True if (pprReg reg) will give an expression with type StgPtr.  We
644 -- need to take care with pointer arithmetic on registers with type
645 -- StgPtr.
646 isFixedPtrReg :: CmmReg -> Bool
647 isFixedPtrReg (CmmLocal _) = False
648 isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
649
650 -- True if (pprAsPtrReg reg) will give an expression with type StgPtr
651 isPtrReg :: CmmReg -> Bool
652 isPtrReg (CmmLocal _)               = False
653 isPtrReg (CmmGlobal (VanillaReg n)) = True -- if we print via pprAsPtrReg
654 isPtrReg (CmmGlobal reg)            = isFixedPtrGlobalReg reg
655
656 -- True if this global reg has type StgPtr
657 isFixedPtrGlobalReg :: GlobalReg -> Bool
658 isFixedPtrGlobalReg Sp          = True
659 isFixedPtrGlobalReg Hp          = True
660 isFixedPtrGlobalReg HpLim       = True
661 isFixedPtrGlobalReg SpLim       = True
662 isFixedPtrGlobalReg _           = False
663
664 -- True if in C this register doesn't have the type given by 
665 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
666 isStrangeTypeReg :: CmmReg -> Bool
667 isStrangeTypeReg (CmmLocal _)   = False
668 isStrangeTypeReg (CmmGlobal g)  = isStrangeTypeGlobal g
669
670 isStrangeTypeGlobal :: GlobalReg -> Bool
671 isStrangeTypeGlobal CurrentTSO          = True
672 isStrangeTypeGlobal CurrentNursery      = True
673 isStrangeTypeGlobal BaseReg             = True
674 isStrangeTypeGlobal r                   = isFixedPtrGlobalReg r
675
676 strangeRegType :: CmmReg -> Maybe SDoc
677 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
678 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
679 strangeRegType (CmmGlobal BaseReg) = Just (ptext SLIT("struct StgRegTable_ *"))
680 strangeRegType _ = Nothing
681
682 -- pprReg just prints the register name.
683 --
684 pprReg :: CmmReg -> SDoc
685 pprReg r = case r of
686         CmmLocal  local  -> pprLocalReg local
687         CmmGlobal global -> pprGlobalReg global
688                 
689 pprAsPtrReg :: CmmReg -> SDoc
690 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
691 pprAsPtrReg other_reg = pprReg other_reg
692
693 pprGlobalReg :: GlobalReg -> SDoc
694 pprGlobalReg gr = case gr of
695     VanillaReg n   -> char 'R' <> int n  <> ptext SLIT(".w")
696     FloatReg   n   -> char 'F' <> int n
697     DoubleReg  n   -> char 'D' <> int n
698     LongReg    n   -> char 'L' <> int n
699     Sp             -> ptext SLIT("Sp")
700     SpLim          -> ptext SLIT("SpLim")
701     Hp             -> ptext SLIT("Hp")
702     HpLim          -> ptext SLIT("HpLim")
703     CurrentTSO     -> ptext SLIT("CurrentTSO")
704     CurrentNursery -> ptext SLIT("CurrentNursery")
705     HpAlloc        -> ptext SLIT("HpAlloc")
706     BaseReg        -> ptext SLIT("BaseReg")
707     GCEnter1       -> ptext SLIT("stg_gc_enter_1")
708     GCFun          -> ptext SLIT("stg_gc_fun")
709
710 pprLocalReg :: LocalReg -> SDoc
711 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
712
713 -- -----------------------------------------------------------------------------
714 -- Foreign Calls
715
716 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
717         -> Maybe [GlobalReg] -> SDoc
718
719 pprCall ppr_fn cconv results args vols
720   | not (is_cish cconv)
721   = panic "pprCall: unknown calling convention"
722
723   | otherwise
724   = save vols $$
725     ptext SLIT("CALLER_SAVE_SYSTEM") $$
726 #if x86_64_TARGET_ARCH
727         -- HACK around gcc optimisations.
728         -- x86_64 needs a __DISCARD__() here, to create a barrier between
729         -- putting the arguments into temporaries and passing the arguments
730         -- to the callee, because the argument expressions may refer to
731         -- machine registers that are also used for passing arguments in the
732         -- C calling convention.
733     (if (not opt_Unregisterised) 
734         then ptext SLIT("__DISCARD__();") 
735         else empty) $$
736 #endif
737     ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi $$
738     ptext SLIT("CALLER_RESTORE_SYSTEM") $$
739     restore vols
740   where 
741      ppr_assign []           rhs = rhs
742      ppr_assign [(reg@(CmmGlobal BaseReg), hint)] rhs
743          | Just ty <- strangeRegType reg
744          = ptext SLIT("ASSIGN_BaseReg") <> parens (parens ty <> rhs)
745          -- BaseReg is special, sometimes it isn't an lvalue and we
746          -- can't assign to it.
747      ppr_assign [(one,hint)] rhs
748          | Just ty <- strangeRegType one
749          = pprReg one <> ptext SLIT(" = ") <> parens ty <> rhs
750          | otherwise
751          = pprReg one <> ptext SLIT(" = ")
752                  <> pprUnHint hint (cmmRegRep one) <> rhs
753      ppr_assign _other _rhs = panic "pprCall: multiple results"
754
755      pprArg (expr, PtrHint)
756         = cCast (ptext SLIT("void *")) expr
757         -- see comment by machRepHintCType below
758      pprArg (expr, SignedHint)
759         = cCast (machRepSignedCType (cmmExprRep expr)) expr
760      pprArg (expr, _other)
761         = pprExpr expr
762
763      pprUnHint PtrHint    rep = parens (machRepCType rep)
764      pprUnHint SignedHint rep = parens (machRepCType rep)
765      pprUnHint _          _   = empty
766
767      save    = save_restore SLIT("CALLER_SAVE")
768      restore = save_restore SLIT("CALLER_RESTORE")
769
770         -- Nothing says "I don't know what's live; save everything"
771         -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
772      save_restore txt Nothing     = ptext txt <> ptext SLIT("_USER")
773      save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
774         where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
775
776 pprGlobalRegName :: GlobalReg -> SDoc
777 pprGlobalRegName gr = case gr of
778     VanillaReg n   -> char 'R' <> int n  -- without the .w suffix
779     _              -> pprGlobalReg gr
780
781 -- Currently we only have these two calling conventions, but this might
782 -- change in the future...
783 is_cish CCallConv   = True
784 is_cish StdCallConv = True
785
786 -- ---------------------------------------------------------------------
787 -- Find and print local and external declarations for a list of
788 -- Cmm statements.
789 -- 
790 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
791 pprTempAndExternDecls stmts 
792   = (vcat (map pprTempDecl (eltsUFM temps)), 
793      vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
794   where (temps, lbls) = runTE (mapM_ te_BB stmts)
795
796 pprDataExterns :: [CmmStatic] -> SDoc
797 pprDataExterns statics
798   = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
799   where (_, lbls) = runTE (mapM_ te_Static statics)
800
801 pprTempDecl :: LocalReg -> SDoc
802 pprTempDecl l@(LocalReg _uniq rep)
803   = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
804
805 pprExternDecl :: Bool -> CLabel -> SDoc
806 pprExternDecl in_srt lbl
807   -- do not print anything for "known external" things
808   | not (needsCDecl lbl) = empty
809   | otherwise               = 
810         hcat [ visibility, label_type (labelType lbl), 
811                lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
812  where
813   dyn_wrapper d
814     | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
815     | otherwise                  = d
816
817   label_type CodeLabel = ptext SLIT("F_")
818   label_type DataLabel = ptext SLIT("I_")
819
820   visibility
821      | externallyVisibleCLabel lbl = char 'E'
822      | otherwise                   = char 'I'
823
824
825 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
826 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
827
828 instance Monad TE where
829    TE m >>= k  = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
830    return a    = TE $ \s -> (a, s)
831
832 te_lbl :: CLabel -> TE ()
833 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
834
835 te_temp :: LocalReg -> TE ()
836 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
837
838 runTE :: TE () -> TEState
839 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
840
841 te_Static :: CmmStatic -> TE ()
842 te_Static (CmmStaticLit lit) = te_Lit lit
843 te_Static _ = return ()
844
845 te_BB :: CmmBasicBlock -> TE ()
846 te_BB (BasicBlock _ ss)         = mapM_ te_Stmt ss
847
848 te_Lit :: CmmLit -> TE ()
849 te_Lit (CmmLabel l) = te_lbl l
850 te_Lit (CmmLabelOff l _) = te_lbl l
851 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
852 te_Lit _ = return ()
853
854 te_Stmt :: CmmStmt -> TE ()
855 te_Stmt (CmmAssign r e)         = te_Reg r >> te_Expr e
856 te_Stmt (CmmStore l r)          = te_Expr l >> te_Expr r
857 te_Stmt (CmmCall _ rs es _)     = mapM_ (te_Reg.fst) rs >>
858                                   mapM_ (te_Expr.fst) es
859 te_Stmt (CmmCondBranch e _)     = te_Expr e
860 te_Stmt (CmmSwitch e _)         = te_Expr e
861 te_Stmt (CmmJump e _)           = te_Expr e
862 te_Stmt _                       = return ()
863
864 te_Expr :: CmmExpr -> TE ()
865 te_Expr (CmmLit lit)            = te_Lit lit
866 te_Expr (CmmLoad e _)           = te_Expr e
867 te_Expr (CmmReg r)              = te_Reg r
868 te_Expr (CmmMachOp _ es)        = mapM_ te_Expr es
869 te_Expr (CmmRegOff r _)         = te_Reg r
870
871 te_Reg :: CmmReg -> TE ()
872 te_Reg (CmmLocal l) = te_temp l
873 te_Reg _            = return ()
874
875
876 -- ---------------------------------------------------------------------
877 -- C types for MachReps
878
879 cCast :: SDoc -> CmmExpr -> SDoc
880 cCast ty expr = parens ty <> pprExpr1 expr
881
882 -- This is for finding the types of foreign call arguments.  For a pointer
883 -- argument, we always cast the argument to (void *), to avoid warnings from
884 -- the C compiler.
885 machRepHintCType :: MachRep -> MachHint -> SDoc
886 machRepHintCType rep PtrHint    = ptext SLIT("void *")
887 machRepHintCType rep SignedHint = machRepSignedCType rep
888 machRepHintCType rep _other     = machRepCType rep
889
890 machRepPtrCType :: MachRep -> SDoc
891 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
892                   | otherwise    = machRepCType r <> char '*'
893
894 machRepCType :: MachRep -> SDoc
895 machRepCType r | r == wordRep = ptext SLIT("W_")
896                | otherwise    = sized_type
897   where sized_type = case r of
898                         I8      -> ptext SLIT("StgWord8")
899                         I16     -> ptext SLIT("StgWord16")
900                         I32     -> ptext SLIT("StgWord32")
901                         I64     -> ptext SLIT("StgWord64")
902                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
903                         F64     -> ptext SLIT("StgDouble")
904                         _  -> panic "machRepCType"
905
906 machRepSignedCType :: MachRep -> SDoc
907 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
908                      | otherwise    = sized_type
909   where sized_type = case r of
910                         I8      -> ptext SLIT("StgInt8")
911                         I16     -> ptext SLIT("StgInt16")
912                         I32     -> ptext SLIT("StgInt32")
913                         I64     -> ptext SLIT("StgInt64")
914                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
915                         F64     -> ptext SLIT("StgDouble")
916                         _ -> panic "machRepCType"
917
918 -- ---------------------------------------------------------------------
919 -- print strings as valid C strings
920
921 pprStringInCStyle :: [Word8] -> SDoc
922 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
923
924 charToC :: Word8 -> String
925 charToC w = 
926   case chr (fromIntegral w) of
927         '\"' -> "\\\""
928         '\'' -> "\\\'"
929         '\\' -> "\\\\"
930         c | c >= ' ' && c <= '~' -> [c]
931           | otherwise -> ['\\',
932                          chr (ord '0' + ord c `div` 64),
933                          chr (ord '0' + ord c `div` 8 `mod` 8),
934                          chr (ord '0' + ord c         `mod` 8)]
935
936 -- ---------------------------------------------------------------------------
937 -- Initialising static objects with floating-point numbers.  We can't
938 -- just emit the floating point number, because C will cast it to an int
939 -- by rounding it.  We want the actual bit-representation of the float.
940
941 -- This is a hack to turn the floating point numbers into ints that we
942 -- can safely initialise to static locations.
943
944 big_doubles 
945   | machRepByteWidth F64 == 2 * wORD_SIZE  = True
946   | machRepByteWidth F64 == wORD_SIZE      = False
947   | otherwise = panic "big_doubles"
948
949 #if __GLASGOW_HASKELL__ >= 504
950 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
951 newFloatArray = newArray_
952
953 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
954 newDoubleArray = newArray_
955
956 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
957 castFloatToIntArray = castSTUArray
958
959 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
960 castDoubleToIntArray = castSTUArray
961
962 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
963 writeFloatArray = writeArray
964
965 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
966 writeDoubleArray = writeArray
967
968 readIntArray :: STUArray s Int Int -> Int -> ST s Int
969 readIntArray = readArray
970
971 #else
972
973 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
974 castFloatToIntArray = return
975
976 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
977 castDoubleToIntArray = return
978
979 #endif
980
981 -- floats are always 1 word
982 floatToWord :: Rational -> CmmLit
983 floatToWord r
984   = runST (do
985         arr <- newFloatArray ((0::Int),0)
986         writeFloatArray arr 0 (fromRational r)
987         arr' <- castFloatToIntArray arr
988         i <- readIntArray arr' 0
989         return (CmmInt (toInteger i) wordRep)
990     )
991
992 doubleToWords :: Rational -> [CmmLit]
993 doubleToWords r
994   | big_doubles                         -- doubles are 2 words
995   = runST (do
996         arr <- newDoubleArray ((0::Int),1)
997         writeDoubleArray arr 0 (fromRational r)
998         arr' <- castDoubleToIntArray arr
999         i1 <- readIntArray arr' 0
1000         i2 <- readIntArray arr' 1
1001         return [ CmmInt (toInteger i1) wordRep
1002                , CmmInt (toInteger i2) wordRep
1003                ]
1004     )
1005   | otherwise                           -- doubles are 1 word
1006   = runST (do
1007         arr <- newDoubleArray ((0::Int),0)
1008         writeDoubleArray arr 0 (fromRational r)
1009         arr' <- castDoubleToIntArray arr
1010         i <- readIntArray arr' 0
1011         return [ CmmInt (toInteger i) wordRep ]
1012     )
1013
1014 -- ---------------------------------------------------------------------------
1015 -- Utils
1016
1017 wordShift :: Int
1018 wordShift = machRepLogWidth wordRep
1019
1020 commafy :: [SDoc] -> SDoc
1021 commafy xs = hsep $ punctuate comma xs
1022
1023 -- Print in C hex format: 0x13fa
1024 pprHexVal :: Integer -> MachRep -> SDoc
1025 pprHexVal 0 _ = ptext SLIT("0x0")
1026 pprHexVal w rep
1027   | w < 0     = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
1028   | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
1029   where
1030         -- type suffix for literals:
1031         -- Integer literals are unsigned in Cmm/C.  We explicitly cast to
1032         -- signed values for doing signed operations, but at all other
1033         -- times values are unsigned.  This also helps eliminate occasional
1034         -- warnings about integer overflow from gcc.
1035
1036         -- on 32-bit platforms, add "ULL" to 64-bit literals
1037       repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1038         -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1039       repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1040       repsuffix _ = char 'U'
1041       
1042       go 0 = empty
1043       go w' = go q <> dig
1044            where
1045              (q,r) = w' `quotRem` 16
1046              dig | r < 10    = char (chr (fromInteger r + ord '0'))
1047                  | otherwise = char (chr (fromInteger r - 10 + ord 'a'))
1048