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