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