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