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