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