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