76b1f43f2977cf9a4a270c8c09d6b9a90d15a4a5
[ghc-hetmet.git] / ghc / compiler / absCSyn / PprAbsC.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[PprAbsC]{Pretty-printing Abstract~C}
7 %*                                                                      *
8 %************************************************************************
9
10 \begin{code}
11 module PprAbsC (
12         writeRealC,
13         dumpRealC,
14         pprAmode,
15         pprMagicId
16     ) where
17
18 #include "HsVersions.h"
19
20 import IO       ( Handle )
21
22 import PrimRep 
23 import AbsCSyn
24 import ClosureInfo
25 import AbsCUtils        ( getAmodeRep, nonemptyAbsC,
26                           mixedPtrLocn, mixedTypeLocn
27                         )
28
29 import ForeignCall      ( CCallSpec(..), CCallTarget(..), playSafe,
30                           playThreadSafe, ccallConvAttribute,
31                           ForeignCall(..), DNCallSpec(..),
32                           DNType(..), DNKind(..) )
33 import CLabel           ( externallyVisibleCLabel,
34                           needsCDecl, pprCLabel, mkClosureLabel,
35                           mkReturnInfoLabel, mkReturnPtLabel, mkClosureTblLabel,
36                           CLabel, CLabelType(..), labelType, labelDynamic
37                         )
38
39 import CmdLineOpts      ( opt_SccProfilingOn, opt_GranMacros )
40 import CostCentre       ( pprCostCentreDecl, pprCostCentreStackDecl )
41
42 import Costs            ( costs, addrModeCosts, CostRes(..), Side(..) )
43 import CStrings         ( pprCLabelString )
44 import FiniteMap        ( addToFM, emptyFM, lookupFM, FiniteMap )
45 import Literal          ( Literal(..) )
46 import TyCon            ( tyConDataCons )
47 import Name             ( NamedThing(..) )
48 import Maybes           ( catMaybes )
49 import PrimOp           ( primOpNeedsWrapper )
50 import MachOp           ( MachOp(..) )
51 import PrimRep          ( isFloatingRep, PrimRep(..), getPrimRepSize )
52 import Unique           ( pprUnique, Unique{-instance NamedThing-} )
53 import UniqSet          ( emptyUniqSet, elementOfUniqSet,
54                           addOneToUniqSet, UniqSet
55                         )
56 import StgSyn           ( StgOp(..) )
57 import Outputable
58 import FastString
59 import Util             ( lengthExceeds )
60
61 #if __GLASGOW_HASKELL__ >= 504
62 import Data.Array.ST
63 #endif
64
65 #ifdef DEBUG
66 import Util             ( listLengthCmp )
67 #endif
68
69 import Maybe            ( isJust )
70 import GLAEXTS
71 import MONAD_ST
72
73 infixr 9 `thenTE`
74 \end{code}
75
76 For spitting out the costs of an abstract~C expression, @writeRealC@
77 now not only prints the C~code of the @absC@ arg but also adds a macro
78 call to a cost evaluation function @GRAN_EXEC@. For that,
79 @pprAbsC@ has a new ``costs'' argument.  %% HWL
80
81 \begin{code}
82 {-
83 writeRealC :: Handle -> AbstractC -> IO ()
84 writeRealC handle absC
85      -- avoid holding on to the whole of absC in the !Gransim case.
86      if opt_GranMacros
87         then printForCFast fp (pprAbsC absC (costs absC))
88         else printForCFast fp (pprAbsC absC (panic "costs"))
89              --printForC handle (pprAbsC absC (panic "costs"))
90 dumpRealC :: AbstractC -> SDoc
91 dumpRealC absC = pprAbsC absC (costs absC)
92 -}
93
94 writeRealC :: Handle -> AbstractC -> IO ()
95 --writeRealC handle absC = 
96 -- _scc_ "writeRealC" 
97 -- printDoc LeftMode handle (pprAbsC absC (costs absC))
98
99 writeRealC handle absC
100  | opt_GranMacros = _scc_ "writeRealC" printForC handle $ 
101                                        pprCode CStyle (pprAbsC absC (costs absC))
102  | otherwise      = _scc_ "writeRealC" printForC handle $
103                                        pprCode CStyle (pprAbsC absC (panic "costs"))
104
105 dumpRealC :: AbstractC -> SDoc
106 dumpRealC absC
107  | opt_GranMacros = pprCode CStyle (pprAbsC absC (costs absC))
108  | otherwise      = pprCode CStyle (pprAbsC absC (panic "costs"))
109
110 \end{code}
111
112 This emits the macro,  which is used in GrAnSim  to compute the total costs
113 from a cost 5 tuple. %%  HWL
114
115 \begin{code}
116 emitMacro :: CostRes -> SDoc
117
118 emitMacro _ | not opt_GranMacros = empty
119
120 emitMacro (Cost (i,b,l,s,f))
121   = hcat [ ptext SLIT("GRAN_EXEC"), char '(',
122                           int i, comma, int b, comma, int l, comma,
123                           int s, comma, int f, pp_paren_semi ]
124
125 pp_paren_semi = text ");"
126 \end{code}
127
128 New type: Now pprAbsC also takes the costs for evaluating the Abstract C
129 code as an argument (that's needed when spitting out the GRAN_EXEC macro
130 which must be done before the return i.e. inside absC code)   HWL
131
132 \begin{code}
133 pprAbsC :: AbstractC -> CostRes -> SDoc
134 pprAbsC AbsCNop _ = empty
135 pprAbsC (AbsCStmts s1 s2) c = ($$) (pprAbsC s1 c) (pprAbsC s2 c)
136
137 pprAbsC (CAssign dest src) _ = pprAssign (getAmodeRep dest) dest src
138
139 pprAbsC (CJump target) c
140   = ($$) (hcat [emitMacro c {-WDP:, text "/* <--++  CJump */"-} ])
141              (hcat [ text jmp_lit, pprAmode target, pp_paren_semi ])
142
143 pprAbsC (CFallThrough target) c
144   = ($$) (hcat [emitMacro c {-WDP:, text "/* <--++  CFallThrough */"-} ])
145              (hcat [ text jmp_lit, pprAmode target, pp_paren_semi ])
146
147 -- --------------------------------------------------------------------------
148 -- Spit out GRAN_EXEC macro immediately before the return                 HWL
149
150 pprAbsC (CReturn am return_info)  c
151   = ($$) (hcat [emitMacro c {-WDP:, text "/* <----  CReturn */"-} ])
152              (hcat [text jmp_lit, target, pp_paren_semi ])
153   where
154    target = case return_info of
155         DirectReturn -> hcat [ptext SLIT("ENTRY_CODE"), lparen,
156                               pprAmode am, rparen]
157         DynamicVectoredReturn am' -> mk_vector (pprAmode am')
158         StaticVectoredReturn n -> mk_vector (int n)     -- Always positive
159    mk_vector x = hcat [ptext SLIT("RET_VEC"), char '(', pprAmode am, comma,
160                        x, rparen ]
161
162 pprAbsC (CSplitMarker) _ = ptext SLIT("__STG_SPLIT_MARKER")
163
164 -- we optimise various degenerate cases of CSwitches.
165
166 -- --------------------------------------------------------------------------
167 -- Assume: CSwitch is also end of basic block
168 --         costs function yields nullCosts for whole switch
169 --         ==> inherited costs c are those of basic block up to switch
170 --         ==> inherit c + costs for the corresponding branch
171 --                                                                       HWL
172 -- --------------------------------------------------------------------------
173
174 pprAbsC (CSwitch discrim [] deflt) c
175   = pprAbsC deflt (c + costs deflt)
176     -- Empty alternative list => no costs for discrim as nothing cond. here HWL
177
178 pprAbsC (CSwitch discrim [(tag,alt_code)] deflt) c -- only one alt
179   = case (nonemptyAbsC deflt) of
180       Nothing ->                -- one alt and no default
181                  pprAbsC alt_code (c + costs alt_code)
182                  -- Nothing conditional in here either  HWL
183
184       Just dc ->                -- make it an "if"
185                  do_if_stmt discrim tag alt_code dc c
186
187 -- What problem is the re-ordering trying to solve ?
188 pprAbsC (CSwitch discrim [(tag1@(MachInt i1), alt_code1),
189                           (tag2@(MachInt i2), alt_code2)] deflt) c
190   | empty_deflt && ((i1 == 0 && i2 == 1) || (i1 == 1 && i2 == 0))
191   = if (i1 == 0) then
192         do_if_stmt discrim tag1 alt_code1 alt_code2 c
193     else
194         do_if_stmt discrim tag2 alt_code2 alt_code1 c
195   where
196     empty_deflt = not (isJust (nonemptyAbsC deflt))
197
198 pprAbsC (CSwitch discrim alts deflt) c -- general case
199   | isFloatingRep (getAmodeRep discrim)
200     = pprAbsC (foldr ( \ a -> CSwitch discrim [a]) deflt alts) c
201   | otherwise
202     = vcat [
203         hcat [text "switch (", pp_discrim, text ") {"],
204         nest 2 (vcat (map ppr_alt alts)),
205         (case (nonemptyAbsC deflt) of
206            Nothing -> empty
207            Just dc ->
208             nest 2 (vcat [ptext SLIT("default:"),
209                                   pprAbsC dc (c + switch_head_cost
210                                                     + costs dc),
211                                   ptext SLIT("break;")])),
212         char '}' ]
213   where
214     pp_discrim
215       = pprAmode discrim
216
217     ppr_alt (lit, absC)
218       = vcat [ hcat [ptext SLIT("case "), pprBasicLit lit, char ':'],
219                    nest 2 (($$) (pprAbsC absC (c + switch_head_cost + costs absC))
220                                        (ptext SLIT("break;"))) ]
221
222     -- Costs for addressing header of switch and cond. branching        -- HWL
223     switch_head_cost = addrModeCosts discrim Rhs + (Cost (0, 1, 0, 0, 0))
224
225 pprAbsC stmt@(COpStmt results (StgFCallOp fcall uniq) args vol_regs) _
226   = pprFCall fcall uniq args results vol_regs
227
228 pprAbsC stmt@(COpStmt results (StgPrimOp op) args vol_regs) _
229   = let
230         non_void_args = grab_non_void_amodes args
231         non_void_results = grab_non_void_amodes results
232         -- if just one result, we print in the obvious "assignment" style;
233         -- if 0 or many results, we emit a macro call, w/ the results
234         -- followed by the arguments.  The macro presumably knows which
235         -- are which :-)
236
237         the_op = ppr_op_call non_void_results non_void_args
238                 -- liveness mask is *in* the non_void_args
239     in
240     if primOpNeedsWrapper op then
241         case (ppr_vol_regs vol_regs) of { (pp_saves, pp_restores) ->
242         vcat [  pp_saves,
243                 the_op,
244                 pp_restores
245              ]
246         }
247     else
248         the_op
249   where
250     ppr_op_call results args
251       = hcat [ ppr op, lparen,
252         hcat (punctuate comma (map ppr_op_result results)),
253         if null results || null args then empty else comma,
254         hcat (punctuate comma (map pprAmode args)),
255         pp_paren_semi ]
256
257     ppr_op_result r = ppr_amode r
258       -- primop macros do their own casting of result;
259       -- hence we can toss the provided cast...
260
261 -- NEW CASES FOR EXPANDED PRIMOPS
262
263 pprAbsC stmt@(CMachOpStmt res mop [arg1,arg2] maybe_vols) _
264   = let prefix_fn = mop `elem` [MO_Dbl_Pwr, MO_Flt_Pwr, MO_NatS_MulMayOflo]
265     in
266     case ppr_maybe_vol_regs maybe_vols of {(saves,restores) ->
267     saves $$
268     hcat (
269        [ppr_amode res, equals]
270        ++ (if prefix_fn 
271            then [pprMachOp_for_C mop, parens (pprAmode arg1 <> comma <> pprAmode arg2)]
272            else [pprAmode arg1, pprMachOp_for_C mop, pprAmode arg2])
273        ++ [semi]
274     )
275     $$ restores
276     }
277
278 pprAbsC stmt@(CMachOpStmt res mop [arg1] maybe_vols) _
279   = case ppr_maybe_vol_regs maybe_vols of {(saves,restores) ->
280     saves $$
281     hcat [ppr_amode res, equals, 
282           pprMachOp_for_C mop, parens (pprAmode arg1),
283           semi]
284     $$ restores
285     }
286
287 pprAbsC stmt@(CSequential stuff) c
288   = vcat (map (flip pprAbsC c) stuff)
289
290 -- end of NEW CASES FOR EXPANDED PRIMOPS
291
292 pprAbsC stmt@(CSRT lbl closures) c
293   = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
294          pp_exts
295       $$ ptext SLIT("SRT") <> lparen <> pprCLabel lbl <> rparen
296       $$ nest 2 (hcat (punctuate comma (map pp_closure_lbl closures)))
297          <> ptext SLIT("};")
298   }
299
300 pprAbsC stmt@(CBitmap liveness@(Liveness lbl size mask)) c
301   = pprWordArray lbl (mkWordCLit (fromIntegral size) : bitmapAddrModes mask)
302
303 pprAbsC stmt@(CSRTDesc desc_lbl srt_lbl off len bitmap) c
304   = pprWordArray desc_lbl (
305         CAddr (CIndex (CLbl srt_lbl DataPtrRep) (mkIntCLit off) WordRep) :
306         mkWordCLit (fromIntegral len) :
307         bitmapAddrModes bitmap
308      )
309
310 pprAbsC (CSimultaneous abs_c) c
311   = hcat [ptext SLIT("{{"), pprAbsC abs_c c, ptext SLIT("}}")]
312
313 pprAbsC (CCheck macro as code) c
314   = hcat [ptext (cCheckMacroText macro), lparen,
315        hcat (punctuate comma (map ppr_amode as)), comma,
316        pprAbsC code c, pp_paren_semi
317     ]
318 pprAbsC (CMacroStmt macro as) _
319   = hcat [ptext (cStmtMacroText macro), lparen,
320         hcat (punctuate comma (map ppr_amode as)),pp_paren_semi] -- no casting
321 pprAbsC (CCallProfCtrMacro op as) _
322   = hcat [ftext op, lparen,
323         hcat (punctuate comma (map ppr_amode as)),pp_paren_semi]
324 pprAbsC (CCallProfCCMacro op as) _
325   = hcat [ftext op, lparen,
326         hcat (punctuate comma (map ppr_amode as)),pp_paren_semi]
327 pprAbsC stmt@(CCallTypedef is_tdef (CCallSpec op_str cconv _) uniq results args) _
328   =  hsep [ ptext (if is_tdef then SLIT("typedef") else SLIT("extern"))
329           , ccall_res_ty
330           , fun_nm
331           , parens (hsep (punctuate comma ccall_decl_ty_args))
332           ] <> semi
333     where
334     {-
335       In the non-casm case, to ensure that we're entering the given external
336       entry point using the correct calling convention, we have to do the following:
337
338         - When entering via a function pointer (the `dynamic' case) using the specified
339           calling convention, we emit a typedefn declaration attributed with the
340           calling convention to use together with the result and parameter types we're
341           assuming. Coerce the function pointer to this type and go.
342
343         - to enter the function at a given code label, we emit an extern declaration
344           for the label here, stating the calling convention together with result and
345           argument types we're assuming. 
346
347           The C compiler will hopefully use this extern declaration to good effect,
348           reporting any discrepancies between our extern decl and any other that
349           may be in scope.
350     
351           Re: calling convention, notice that gcc (2.8.1 and egcs-1.0.2) will for
352           the external function `foo' use the calling convention of the first `foo'
353           prototype it encounters (nor does it complain about conflicting attribute
354           declarations). The consequence of this is that you cannot override the
355           calling convention of `foo' using an extern declaration (you'd have to use
356           a typedef), but why you would want to do such a thing in the first place
357           is totally beyond me.
358           
359           ToDo: petition the gcc folks to add code to warn about conflicting attribute
360           declarations.
361
362     -}
363
364      fun_nm
365        | is_tdef   = parens (text (ccallConvAttribute cconv) <+> char '*' <> ccall_fun_ty)
366        | otherwise = text (ccallConvAttribute cconv) <+> ccall_fun_ty
367
368      ccall_fun_ty = 
369         case op_str of
370           DynamicTarget  -> ptext SLIT("_ccall_fun_ty") <> ppr uniq
371           StaticTarget x -> pprCLabelString x
372
373      ccall_res_ty = 
374        case non_void_results of
375           []       -> ptext SLIT("void")
376           [amode]  -> ppr (getAmodeRep amode)
377           _        -> panic "pprAbsC{CCallTypedef}: ccall_res_ty"
378
379      ccall_decl_ty_args 
380        | is_tdef   = tail ccall_arg_tys
381        | otherwise = ccall_arg_tys
382
383      ccall_arg_tys      = map (ppr . getAmodeRep) non_void_args
384
385       -- the first argument will be the "I/O world" token (a VoidRep)
386       -- all others should be non-void
387      non_void_args =
388         let nvas = init args
389         in ASSERT (all non_void nvas) nvas
390
391       -- there will usually be two results: a (void) state which we
392       -- should ignore and a (possibly void) result.
393      non_void_results =
394         let nvrs = grab_non_void_amodes results
395         in ASSERT (listLengthCmp nvrs 1 /= GT) nvrs
396
397 pprAbsC (CCodeBlock lbl abs_C) _
398   = if not (isJust(nonemptyAbsC abs_C)) then
399         pprTrace "pprAbsC: curious empty code block for" (pprCLabel lbl) empty
400     else
401     case (pprTempAndExternDecls abs_C) of { (pp_temps, pp_exts) ->
402     vcat [
403         empty,
404         pp_exts, 
405         hcat [text (if (externallyVisibleCLabel lbl)
406                           then "FN_("   -- abbreviations to save on output
407                           else "IF_("),
408                    pprCLabel lbl, text ") {"],
409
410         pp_temps,
411
412         nest 8 (ptext SLIT("FB_")),
413         nest 8 (pprAbsC abs_C (costs abs_C)),
414         nest 8 (ptext SLIT("FE_")),
415         char '}',
416         char ' ' ]
417     }
418
419
420 pprAbsC (CInitHdr cl_info amode cost_centre size) _
421   = hcat [ ptext SLIT("SET_HDR_"), char '(',
422                 ppr_amode amode, comma,
423                 pprCLabelAddr info_lbl, comma,
424                 if_profiling (pprAmode cost_centre), comma,
425                 if_profiling (int size),
426                 pp_paren_semi ]
427   where
428     info_lbl    = infoTableLabelFromCI cl_info
429
430
431 pprAbsC stmt@(CStaticClosure closure_lbl cl_info cost_centre amodes) _
432   = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
433     vcat [
434         pp_exts,
435         hcat [
436                 ptext SLIT("SET_STATIC_HDR"), char '(',
437                 pprCLabel closure_lbl,                          comma,
438                 pprCLabel info_lbl,                             comma,
439                 if_profiling (pprAmode cost_centre),            comma,
440                 ppLocalness closure_lbl,                        comma,
441                 ppLocalnessMacro True{-include dyn-} info_lbl,
442                 char ')'
443                 ],
444         nest 2 (ppr_payload amodes),
445         ptext SLIT("};") ]
446     }
447   where
448     info_lbl    = infoTableLabelFromCI cl_info
449
450     ppr_payload [] = empty
451     ppr_payload ls = 
452         comma <+> 
453           (braces $ hsep $ punctuate comma $
454            map (text "(L_)" <>) (foldr ppr_item [] ls))
455
456     ppr_item item rest
457       | rep == VoidRep   = rest
458       | rep == FloatRep  = ppr_amode (floatToWord item) : rest
459       | rep == DoubleRep = map ppr_amode (doubleToWords item) ++ rest
460       | otherwise        = ppr_amode item : rest
461       where 
462         rep  = getAmodeRep item
463
464 pprAbsC stmt@(CClosureInfoAndCode cl_info entry) _
465   =  pprWordArray info_lbl (mkInfoTable cl_info)
466   $$ let stuff = CCodeBlock entry_lbl entry in
467      pprAbsC stuff (costs stuff)
468   where
469         entry_lbl = entryLabelFromCI cl_info
470         info_lbl  = infoTableLabelFromCI cl_info
471
472 pprAbsC stmt@(CClosureTbl tycon) _
473   = vcat (
474         ptext SLIT("CLOSURE_TBL") <> 
475            lparen <> pprCLabel (mkClosureTblLabel tycon) <> rparen :
476         punctuate comma (
477            map (pp_closure_lbl . mkClosureLabel . getName) (tyConDataCons tycon)
478         )
479    ) $$ ptext SLIT("};")
480
481 pprAbsC stmt@(CRetDirect uniq code srt liveness) _
482   =  pprWordArray info_lbl (mkRetInfoTable entry_lbl srt liveness)
483   $$ let stuff = CCodeBlock entry_lbl code in
484      pprAbsC stuff (costs stuff)
485   where
486      info_lbl  = mkReturnInfoLabel uniq
487      entry_lbl = mkReturnPtLabel uniq
488
489 pprAbsC stmt@(CRetVector lbl amodes srt liveness) _
490   = pprWordArray lbl (mkVecInfoTable amodes srt liveness)
491
492 pprAbsC stmt@(CModuleInitBlock plain_lbl lbl code) _
493   = vcat [
494         ptext SLIT("START_MOD_INIT") <> 
495             parens (pprCLabel plain_lbl <> comma <> pprCLabel lbl),
496         case (pprTempAndExternDecls stmt) of { (_, pp_exts) -> pp_exts },
497         pprAbsC code (costs code),
498         hcat [ptext SLIT("END_MOD_INIT"), lparen, rparen]
499     ]
500
501 pprAbsC (CCostCentreDecl is_local cc) _ = pprCostCentreDecl is_local cc
502 pprAbsC (CCostCentreStackDecl ccs)    _ = pprCostCentreStackDecl ccs
503 \end{code}
504
505 Info tables... just arrays of words (the translation is done in
506 ClosureInfo).
507
508 \begin{code}
509 pprWordArray lbl amodes
510   = (case snd (initTE (ppr_decls_Amodes amodes)) of
511         Just pp -> pp
512         Nothing -> empty)
513   $$ hcat [ ppLocalness lbl, ptext SLIT("StgWord "), 
514             pprCLabel lbl, ptext SLIT("[] = {") ]
515   $$ hcat (punctuate comma (map (castToWord.pprAmode) amodes))
516   $$ ptext SLIT("};")
517
518 castToWord s = text "(W_)(" <> s <> char ')'
519 \end{code}
520
521 \begin{code}
522 -- Print a CMachOp in a way suitable for emitting via C.
523 pprMachOp_for_C MO_Nat_Add       = char '+'
524 pprMachOp_for_C MO_Nat_Sub       = char '-'
525 pprMachOp_for_C MO_Nat_Eq        = text "==" 
526 pprMachOp_for_C MO_Nat_Ne        = text "!="
527
528 pprMachOp_for_C MO_NatS_Ge       = text ">="
529 pprMachOp_for_C MO_NatS_Le       = text "<="
530 pprMachOp_for_C MO_NatS_Gt       = text ">"
531 pprMachOp_for_C MO_NatS_Lt       = text "<"
532
533 pprMachOp_for_C MO_NatU_Ge       = text ">="
534 pprMachOp_for_C MO_NatU_Le       = text "<="
535 pprMachOp_for_C MO_NatU_Gt       = text ">"
536 pprMachOp_for_C MO_NatU_Lt       = text "<"
537
538 pprMachOp_for_C MO_NatS_Mul      = char '*'
539 pprMachOp_for_C MO_NatS_MulMayOflo = text "mulIntMayOflo"
540 pprMachOp_for_C MO_NatS_Quot     = char '/'
541 pprMachOp_for_C MO_NatS_Rem      = char '%'
542 pprMachOp_for_C MO_NatS_Neg      = char '-'
543
544 pprMachOp_for_C MO_NatU_Mul      = char '*'
545 pprMachOp_for_C MO_NatU_Quot     = char '/'
546 pprMachOp_for_C MO_NatU_Rem      = char '%'
547
548 pprMachOp_for_C MO_Nat_And       = text "&"
549 pprMachOp_for_C MO_Nat_Or        = text "|"
550 pprMachOp_for_C MO_Nat_Xor       = text "^"
551 pprMachOp_for_C MO_Nat_Not       = text "~"
552 pprMachOp_for_C MO_Nat_Shl       = text "<<"
553 pprMachOp_for_C MO_Nat_Shr       = text ">>"
554 pprMachOp_for_C MO_Nat_Sar       = text ">>"
555
556 pprMachOp_for_C MO_32U_Eq        = text "=="
557 pprMachOp_for_C MO_32U_Ne        = text "!="
558 pprMachOp_for_C MO_32U_Ge        = text ">="
559 pprMachOp_for_C MO_32U_Le        = text "<="
560 pprMachOp_for_C MO_32U_Gt        = text ">"
561 pprMachOp_for_C MO_32U_Lt        = text "<"
562
563 pprMachOp_for_C MO_Dbl_Eq        = text "=="
564 pprMachOp_for_C MO_Dbl_Ne        = text "!="
565 pprMachOp_for_C MO_Dbl_Ge        = text ">="
566 pprMachOp_for_C MO_Dbl_Le        = text "<="
567 pprMachOp_for_C MO_Dbl_Gt        = text ">"
568 pprMachOp_for_C MO_Dbl_Lt        = text "<"
569
570 pprMachOp_for_C MO_Dbl_Add       = text "+"
571 pprMachOp_for_C MO_Dbl_Sub       = text "-"
572 pprMachOp_for_C MO_Dbl_Mul       = text "*"
573 pprMachOp_for_C MO_Dbl_Div       = text "/"
574 pprMachOp_for_C MO_Dbl_Pwr       = text "pow"
575
576 pprMachOp_for_C MO_Dbl_Sin       = text "sin"
577 pprMachOp_for_C MO_Dbl_Cos       = text "cos"
578 pprMachOp_for_C MO_Dbl_Tan       = text "tan"
579 pprMachOp_for_C MO_Dbl_Sinh      = text "sinh"
580 pprMachOp_for_C MO_Dbl_Cosh      = text "cosh"
581 pprMachOp_for_C MO_Dbl_Tanh      = text "tanh"
582 pprMachOp_for_C MO_Dbl_Asin      = text "asin"
583 pprMachOp_for_C MO_Dbl_Acos      = text "acos"
584 pprMachOp_for_C MO_Dbl_Atan      = text "atan"
585 pprMachOp_for_C MO_Dbl_Log       = text "log"
586 pprMachOp_for_C MO_Dbl_Exp       = text "exp"
587 pprMachOp_for_C MO_Dbl_Sqrt      = text "sqrt"
588 pprMachOp_for_C MO_Dbl_Neg       = text "-"
589
590 pprMachOp_for_C MO_Flt_Add       = text "+"
591 pprMachOp_for_C MO_Flt_Sub       = text "-"
592 pprMachOp_for_C MO_Flt_Mul       = text "*"
593 pprMachOp_for_C MO_Flt_Div       = text "/"
594 pprMachOp_for_C MO_Flt_Pwr       = text "pow"
595
596 pprMachOp_for_C MO_Flt_Eq        = text "=="
597 pprMachOp_for_C MO_Flt_Ne        = text "!="
598 pprMachOp_for_C MO_Flt_Ge        = text ">="
599 pprMachOp_for_C MO_Flt_Le        = text "<="
600 pprMachOp_for_C MO_Flt_Gt        = text ">"
601 pprMachOp_for_C MO_Flt_Lt        = text "<"
602
603 pprMachOp_for_C MO_Flt_Sin       = text "sin"
604 pprMachOp_for_C MO_Flt_Cos       = text "cos"
605 pprMachOp_for_C MO_Flt_Tan       = text "tan"
606 pprMachOp_for_C MO_Flt_Sinh      = text "sinh"
607 pprMachOp_for_C MO_Flt_Cosh      = text "cosh"
608 pprMachOp_for_C MO_Flt_Tanh      = text "tanh"
609 pprMachOp_for_C MO_Flt_Asin      = text "asin"
610 pprMachOp_for_C MO_Flt_Acos      = text "acos"
611 pprMachOp_for_C MO_Flt_Atan      = text "atan"
612 pprMachOp_for_C MO_Flt_Log       = text "log"
613 pprMachOp_for_C MO_Flt_Exp       = text "exp"
614 pprMachOp_for_C MO_Flt_Sqrt      = text "sqrt"
615 pprMachOp_for_C MO_Flt_Neg       = text "-"
616
617 pprMachOp_for_C MO_32U_to_NatS   = text "(StgInt)"
618 pprMachOp_for_C MO_NatS_to_32U   = text "(StgWord32)"
619
620 pprMachOp_for_C MO_NatS_to_Dbl   = text "(StgDouble)"
621 pprMachOp_for_C MO_Dbl_to_NatS   = text "(StgInt)"
622
623 pprMachOp_for_C MO_NatS_to_Flt   = text "(StgFloat)"
624 pprMachOp_for_C MO_Flt_to_NatS   = text "(StgInt)"
625
626 pprMachOp_for_C MO_NatS_to_NatU  = text "(StgWord)"
627 pprMachOp_for_C MO_NatU_to_NatS  = text "(StgInt)"
628
629 pprMachOp_for_C MO_NatS_to_NatP  = text "(void*)"
630 pprMachOp_for_C MO_NatP_to_NatS  = text "(StgInt)"
631 pprMachOp_for_C MO_NatU_to_NatP  = text "(void*)"
632 pprMachOp_for_C MO_NatP_to_NatU  = text "(StgWord)"
633
634 pprMachOp_for_C MO_Dbl_to_Flt    = text "(StgFloat)"
635 pprMachOp_for_C MO_Flt_to_Dbl    = text "(StgDouble)"
636
637 pprMachOp_for_C MO_8S_to_NatS    = text "(StgInt8)(StgInt)"
638 pprMachOp_for_C MO_16S_to_NatS   = text "(StgInt16)(StgInt)"
639 pprMachOp_for_C MO_32S_to_NatS   = text "(StgInt32)(StgInt)"
640
641 pprMachOp_for_C MO_8U_to_NatU    = text "(StgWord8)(StgWord)"
642 pprMachOp_for_C MO_16U_to_NatU   = text "(StgWord16)(StgWord)"
643 pprMachOp_for_C MO_32U_to_NatU   = text "(StgWord32)(StgWord)"
644
645 pprMachOp_for_C MO_8U_to_32U     = text "(StgWord32)"
646 pprMachOp_for_C MO_32U_to_8U     = text "(StgWord8)"
647
648
649 ppLocalness lbl
650   = if (externallyVisibleCLabel lbl) 
651                 then empty 
652                 else ptext SLIT("static ")
653
654 -- Horrible macros for declaring the types and locality of labels (see
655 -- StgMacros.h).
656
657 ppLocalnessMacro include_dyn_prefix clabel =
658      hcat [
659         visiblity_prefix,
660         dyn_prefix,
661         case label_type of
662           ClosureType        -> ptext SLIT("C_")
663           CodeType           -> ptext SLIT("F_")
664           InfoTblType        -> ptext SLIT("I_")
665           RetInfoTblType     -> ptext SLIT("RI_")
666           ClosureTblType     -> ptext SLIT("CP_")
667           DataType           -> ptext SLIT("D_")
668      ]
669   where
670    is_visible = externallyVisibleCLabel clabel
671    label_type = labelType clabel
672
673    visiblity_prefix
674      | is_visible = char 'E'
675      | otherwise  = char 'I'
676
677    dyn_prefix
678      | include_dyn_prefix && labelDynamic clabel = char 'D'
679      | otherwise                                 = empty
680
681 \end{code}
682
683 \begin{code}
684 jmp_lit = "JMP_("
685
686 grab_non_void_amodes amodes
687   = filter non_void amodes
688
689 non_void amode
690   = case (getAmodeRep amode) of
691       VoidRep -> False
692       k -> True
693 \end{code}
694
695 \begin{code}
696 ppr_maybe_vol_regs :: Maybe [MagicId] -> (SDoc, SDoc)
697 ppr_maybe_vol_regs Nothing
698    = (empty, empty)
699 ppr_maybe_vol_regs (Just vrs)
700    = case ppr_vol_regs vrs of
701         (saves, restores) 
702            -> (pp_basic_saves $$ saves,
703                pp_basic_restores $$ restores)
704
705 ppr_vol_regs :: [MagicId] -> (SDoc, SDoc)
706
707 ppr_vol_regs [] = (empty, empty)
708 ppr_vol_regs (VoidReg:rs) = ppr_vol_regs rs
709 ppr_vol_regs (r:rs)
710   = let pp_reg = case r of
711                     VanillaReg pk n -> pprVanillaReg n
712                     _ -> pprMagicId r
713         (more_saves, more_restores) = ppr_vol_regs rs
714     in
715     (($$) ((<>) (ptext SLIT("CALLER_SAVE_"))    pp_reg) more_saves,
716      ($$) ((<>) (ptext SLIT("CALLER_RESTORE_")) pp_reg) more_restores)
717
718 -- pp_basic_{saves,restores}: The BaseReg, Sp, Hp and
719 -- HpLim (see StgRegs.lh) may need to be saved/restored around CCalls,
720 -- depending on the platform.  (The "volatile regs" stuff handles all
721 -- other registers.)  Just be *sure* BaseReg is OK before trying to do
722 -- anything else. The correct sequence of saves&restores are
723 -- encoded by the CALLER_*_SYSTEM macros.
724 pp_basic_saves    = ptext SLIT("CALLER_SAVE_SYSTEM")
725 pp_basic_restores = ptext SLIT("CALLER_RESTORE_SYSTEM")
726 \end{code}
727
728 \begin{code}
729 pp_closure_lbl lbl
730       | labelDynamic lbl = text "DLL_SRT_ENTRY" <> parens (pprCLabel lbl)
731       | otherwise        = char '&' <> pprCLabel lbl
732 \end{code}
733
734 \begin{code}
735 if_profiling pretty
736   = if  opt_SccProfilingOn
737     then pretty
738     else char '0' -- leave it out!
739 -- ---------------------------------------------------------------------------
740 -- Changes for GrAnSim:
741 --  draw costs for computation in head of if into both branches;
742 --  as no abstractC data structure is given for the head, one is constructed
743 --  guessing unknown values and fed into the costs function
744 -- ---------------------------------------------------------------------------
745
746 do_if_stmt discrim tag alt_code deflt c
747    = let
748        cond = hcat [ pprAmode discrim
749                    , ptext SLIT(" == ")
750                    , tcast
751                    , pprAmode (CLit tag)
752                    ]
753         -- to be absolutely sure that none of the 
754         -- conversion rules hit, e.g.,
755         --
756         --     minInt is different to (int)minInt
757         --
758         -- in C (when minInt is a number not a constant
759         --  expression which evaluates to it.)
760         -- 
761        tcast = case tag of
762                    MachInt _  -> ptext SLIT("(I_)")
763                    _          -> empty
764      in
765      ppr_if_stmt cond
766                  alt_code deflt
767                  (addrModeCosts discrim Rhs) c
768
769 ppr_if_stmt pp_pred then_part else_part discrim_costs c
770   = vcat [
771       hcat [text "if (", pp_pred, text ") {"],
772       nest 8 (pprAbsC then_part         (c + discrim_costs +
773                                         (Cost (0, 2, 0, 0, 0)) +
774                                         costs then_part)),
775       (case nonemptyAbsC else_part of Nothing -> empty; Just _ -> text "} else {"),
776       nest 8 (pprAbsC else_part  (c + discrim_costs +
777                                         (Cost (0, 1, 0, 0, 0)) +
778                                         costs else_part)),
779       char '}' ]
780     {- Total costs = inherited costs (before if) + costs for accessing discrim
781                      + costs for cond branch ( = (0, 1, 0, 0, 0) )
782                      + costs for that alternative
783     -}
784 \end{code}
785
786 Historical note: this used to be two separate cases -- one for `ccall'
787 and one for `casm'.  To get round a potential limitation to only 10
788 arguments, the numbering of arguments in @process_casm@ was beefed up a
789 bit. ADR
790
791 Some rough notes on generating code for @CCallOp@:
792
793 1) Evaluate all arguments and stuff them into registers. (done elsewhere)
794 2) Save any essential registers (heap, stack, etc).
795
796    ToDo: If stable pointers are in use, these must be saved in a place
797    where the runtime system can get at them so that the Stg world can
798    be restarted during the call.
799
800 3) Save any temporary registers that are currently in use.
801 4) Do the call, putting result into a local variable
802 5) Restore essential registers
803 6) Restore temporaries
804
805    (This happens after restoration of essential registers because we
806    might need the @Base@ register to access all the others correctly.)
807
808    Otherwise, copy local variable into result register.
809
810 8) If ccall (not casm), declare the function being called as extern so
811    that C knows if it returns anything other than an int.
812
813 \begin{pseudocode}
814 { ResultType _ccall_result;
815   basic_saves;
816   saves;
817   _ccall_result = f( args );
818   basic_restores;
819   restores;
820
821   return_reg = _ccall_result;
822 }
823 \end{pseudocode}
824
825 Amendment to the above: if we can GC, we have to:
826
827 * make sure we save all our registers away where the garbage collector
828   can get at them.
829 * be sure that there are no live registers or we're in trouble.
830   (This can cause problems if you try something foolish like passing
831    an array or a foreign obj to a _ccall_GC_ thing.)
832 * increment/decrement the @inCCallGC@ counter before/after the call so
833   that the runtime check that PerformGC is being used sensibly will work.
834
835 \begin{code}
836 pprFCall call uniq args results vol_regs
837   = case call of
838       CCall (CCallSpec target _cconv safety) ->
839         vcat [ char '{',
840                 declare_local_vars,   -- local var for *result*
841                 vcat local_arg_decls,
842                 makeCall target safety 
843                          (process_casm local_vars pp_non_void_args (call_str target)),
844                 assign_results,
845               char '}'
846              ]
847       DNCall (DNCallSpec isStatic kind assem nm argTys resTy) ->
848          let
849           resultVar = "_ccall_result"
850           hasAssemArg = isStatic || kind == DNConstructor
851           invokeOp  = 
852             case kind of
853               DNMethod 
854                 | isStatic  -> "DN_invokeStatic"
855                 | otherwise -> "DN_invokeMethod"
856               DNField
857                 | isStatic ->
858                    if resTy == DNUnit 
859                     then "DN_setStatic"
860                     else "DN_getStatic"
861                 | otherwise ->
862                    if resTy == DNUnit 
863                     then "DN_setField"
864                     else "DN_getField"
865               DNConstructor -> "DN_createObject"
866
867           (methArrDecl, methArrInit, methArrName, methArrLen) 
868             | null argTys = (empty, empty, text "NULL", text "0")
869             | otherwise   = 
870               ( text "DotnetArg __meth_args[" <> int (length argTys) <> text "];"
871               , vcat (zipWith3 (\ idx arg argTy -> 
872                                  text "__meth_args[" <> int idx <> text "].arg." <> text (toDotnetArgField argTy) <> equals <> ppr_amode arg <> semi $$
873                                  text "__meth_args[" <> int idx <> text "].arg_type=" <> text (toDotnetTy argTy) <> semi)
874                                [0..]
875                                non_void_args
876                                argTys)
877               , text "__meth_args"
878               , int (length non_void_args)
879               )
880          in
881          vcat [ char '{',
882                   declare_local_vars,
883                   vcat local_arg_decls,
884                   vcat [ methArrDecl
885                        , methArrInit
886                        , text "_ccall_result1 =" <+> text invokeOp <> parens (
887                           hcat (punctuate comma $
888                                      (if hasAssemArg then
889                                         ((if null assem then 
890                                             text "NULL" 
891                                          else 
892                                             doubleQuotes (text assem)):)
893                                       else
894                                          id) $
895                                      [ doubleQuotes $ text nm
896                                      , methArrName
897                                      , methArrLen
898                                      , text (toDotnetTy resTy)
899                                      , text "(void*)&" <> text resultVar 
900                                      ])) <> semi
901                         ],
902                   assign_results,
903                 char '}'
904                ]
905   where
906     (pp_saves, pp_restores) = ppr_vol_regs vol_regs
907     
908     makeCall target safety theCall = 
909         vcat [ pp_save_context, theCall, pp_restore_context ]
910      where
911       (pp_save_context, pp_restore_context)
912         | playSafe safety = ( text "{ I_" <+> ppr_uniq_token <> 
913                                 text "; SUSPEND_THREAD" <> parens thread_macro_args <> semi
914                             , text "RESUME_THREAD" <> parens thread_macro_args <> text ";}"
915                             )
916         | otherwise = ( pp_basic_saves $$ pp_saves,
917                         pp_basic_restores $$ pp_restores)
918            where
919             thread_macro_args = ppr_uniq_token <> comma <+> 
920                                 text "rts" <> ppr (playThreadSafe safety)
921             ppr_uniq_token = text "tok_" <> ppr uniq
922
923
924     non_void_args = 
925         let nvas = init args
926         in ASSERT2 ( all non_void nvas, ppr call <+> hsep (map pprAmode args) )
927         nvas
928     -- the last argument will be the "I/O world" token (a VoidRep)
929     -- all others should be non-void
930
931     non_void_results =
932         let nvrs = grab_non_void_amodes results
933         in ASSERT (forDotnet || listLengthCmp nvrs 1 /= GT) nvrs
934     -- there will usually be two results: a (void) state which we
935     -- should ignore and a (possibly void) result.
936
937     (local_arg_decls, pp_non_void_args)
938       = unzip [ ppr_casm_arg a i | (a,i) <- non_void_args `zip` [1..] ]
939
940     (declare_local_vars, local_vars, assign_results)
941       = ppr_casm_results non_void_results forDotnet
942
943     forDotnet
944       = case call of
945           DNCall{} -> True
946           _ -> False
947
948     call_str tgt 
949       = case tgt of
950           StaticTarget fn -> mk_ccall_str (pprCLabelString fn) ccall_args
951           DynamicTarget   -> mk_ccall_str dyn_fun              (tail ccall_args)
952
953     ccall_args = zipWith (\ _ i -> char '%' <> int i) non_void_args [0..]
954     dyn_fun    = parens (parens (ptext SLIT("_ccall_fun_ty") <> ppr uniq) <> text "%0")
955                                                  
956
957     -- Remainder only used for ccall
958     mk_ccall_str fun_name ccall_fun_args = showSDoc
959         (hcat [
960                 if null non_void_results
961                   then empty
962                   else text "%r = ",
963                 lparen, fun_name, lparen,
964                   hcat (punctuate comma ccall_fun_args),
965                 text "));"
966         ])
967
968 toDotnetTy :: DNType -> String
969 toDotnetTy x = 
970   case x of 
971     DNByte -> "Dotnet_Byte"
972     DNBool -> "Dotnet_Bool"
973     DNChar -> "Dotnet_Char"
974     DNDouble -> "Dotnet_Double"
975     DNFloat  -> "Dotnet_Float"
976     DNInt    -> "Dotnet_Int"
977     DNInt8   -> "Dotnet_Int8"
978     DNInt16  -> "Dotnet_Int16"
979     DNInt32  -> "Dotnet_Int32"
980     DNInt64  -> "Dotnet_Int64"
981     DNWord8  -> "Dotnet_Word8"
982     DNWord16 -> "Dotnet_Word16"
983     DNWord32 -> "Dotnet_Word32"
984     DNWord64 -> "Dotnet_Word64"
985     DNPtr    -> "Dotnet_Ptr"
986     DNUnit   -> "Dotnet_Unit"
987     DNObject -> "Dotnet_Object"
988     DNString -> "Dotnet_String"
989
990 toDotnetArgField :: DNType -> String
991 toDotnetArgField x = 
992   case x of 
993     DNByte -> "arg_byte"
994     DNBool -> "arg_bool"
995     DNChar -> "arg_char"
996     DNDouble -> "arg_double"
997     DNFloat  -> "arg_float"
998     DNInt    -> "arg_int"
999     DNInt8   -> "arg_int8"
1000     DNInt16  -> "arg_int16"
1001     DNInt32  -> "arg_int32"
1002     DNInt64  -> "arg_int64"
1003     DNWord8  -> "arg_word8"
1004     DNWord16 -> "arg_word16"
1005     DNWord32 -> "arg_word32"
1006     DNWord64 -> "arg_word64"
1007     DNPtr    -> "arg_ptr"
1008     DNUnit   -> "arg_ptr" -- can't happen
1009     DNObject -> "arg_obj"
1010     DNString -> "arg_str"
1011
1012 ppr_casm_arg :: CAddrMode -> Int -> (SDoc, SDoc)
1013     -- (a) decl and assignment, (b) local var to be used later
1014
1015 ppr_casm_arg amode a_num
1016   = let
1017         a_kind   = getAmodeRep amode
1018         pp_amode = pprAmode amode
1019         pp_kind  = pprPrimKind a_kind
1020
1021         local_var  = (<>) (ptext SLIT("_ccall_arg")) (int a_num)
1022
1023         declare_local_var
1024           = hcat [ pp_kind, space, local_var, equals, pp_amode, semi ]
1025     in
1026     (declare_local_var, local_var)
1027 \end{code}
1028
1029 For l-values, the critical questions are:
1030
1031 1) Are there any results at all?
1032
1033    We only allow zero or one results.
1034
1035 \begin{code}
1036 ppr_casm_results
1037         :: [CAddrMode]  -- list of results (length <= 1)
1038         -> Bool         -- True => multiple results OK.
1039         ->
1040         ( SDoc,         -- declaration of any local vars
1041           [SDoc],       -- list of result vars (same length as results)
1042           SDoc )        -- assignment (if any) of results in local var to registers
1043
1044 ppr_casm_results [] _
1045   = (empty, [], empty)  -- no results
1046
1047 ppr_casm_results (r:rs) multiResultsOK
1048   | not multiResultsOK && not (null rs) = panic "ppr_casm_results: ccall/casm with many results"
1049   | otherwise
1050   = foldr (\ (a,b,c) (as,bs,cs) -> (a $$ as, b ++ bs, c $$ cs))
1051           (empty,[],empty)
1052           (zipWith pprRes (r:rs) ("" : map show [(1::Int)..]))
1053     where
1054       pprRes r suf = (declare_local_var, [local_var], assign_result)
1055        where
1056         result_reg = ppr_amode r
1057         r_kind     = getAmodeRep r
1058
1059         local_var  = ptext SLIT("_ccall_result") <> text suf
1060
1061         (result_type, assign_result)
1062           = (pprPrimKind r_kind,
1063              hcat [ result_reg, equals, local_var, semi ])
1064
1065         declare_local_var = hcat [ result_type, space, local_var, semi ]
1066
1067 \end{code}
1068
1069
1070 Note the sneaky way _the_ result is represented by a list so that we
1071 can complain if it's used twice.
1072
1073 ToDo: Any chance of giving line numbers when process-casm fails?
1074       Or maybe we should do a check _much earlier_ in compiler. ADR
1075
1076 \begin{code}
1077 process_casm :: [SDoc]          -- results (length <= 1)
1078              -> [SDoc]          -- arguments
1079              -> String          -- format string (with embedded %'s)
1080              -> SDoc            -- code being generated
1081
1082 process_casm results args string = process results args string
1083  where
1084   process []    _ "" = empty
1085   process (_:_) _ "" = error ("process_casm: non-void result not assigned while processing _casm_ \"" ++ 
1086                               string ++ 
1087                               "\"\n(Try changing result type to IO ()\n")
1088
1089   process ress args ('%':cs)
1090     = case cs of
1091         [] ->
1092             error ("process_casm: lonely % while processing _casm_ \"" ++ string ++ "\".\n")
1093
1094         ('%':css) ->
1095             char '%' <> process ress args css
1096
1097         ('r':css)  ->
1098           case ress of
1099             []  -> error ("process_casm: no result to match %r while processing _casm_ \"" ++ string ++ "\".\nTry deleting %r or changing result type from PrimIO ()\n")
1100             [r] -> r <> (process [] args css)
1101             _   -> panic ("process_casm: casm with many results while processing _casm_ \"" ++ string ++ "\".\n")
1102
1103         other ->
1104           let
1105                 read_int :: ReadS Int
1106                 read_int = reads
1107           in
1108           case (read_int other) of
1109             [(num,css)] ->
1110                   if num >= 0 && args `lengthExceeds` num
1111                   then parens (args !! num) <> process ress args css
1112                   else error ("process_casm: no such arg #:"++(show num)++" while processing \"" ++ string ++ "\".\n")
1113             _ -> error ("process_casm: not %<num> while processing _casm_ \"" ++ string ++ "\".\n")
1114
1115   process ress args (other_c:cs)
1116     = char other_c <> process ress args cs
1117 \end{code}
1118
1119 %************************************************************************
1120 %*                                                                      *
1121 \subsection[a2r-assignments]{Assignments}
1122 %*                                                                      *
1123 %************************************************************************
1124
1125 Printing assignments is a little tricky because of type coercion.
1126
1127 First of all, the kind of the thing being assigned can be gotten from
1128 the destination addressing mode.  (It should be the same as the kind
1129 of the source addressing mode.)  If the kind of the assignment is of
1130 @VoidRep@, then don't generate any code at all.
1131
1132 \begin{code}
1133 pprAssign :: PrimRep -> CAddrMode -> CAddrMode -> SDoc
1134
1135 pprAssign VoidRep dest src = empty
1136 \end{code}
1137
1138 Special treatment for floats and doubles, to avoid unwanted conversions.
1139
1140 \begin{code}
1141 pprAssign FloatRep dest@(CVal reg_rel _) src
1142   = hcat [ ptext SLIT("ASSIGN_FLT((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1143
1144 pprAssign DoubleRep dest@(CVal reg_rel _) src
1145   = hcat [ ptext SLIT("ASSIGN_DBL((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1146
1147 pprAssign Int64Rep dest@(CVal reg_rel _) src
1148   = hcat [ ptext SLIT("ASSIGN_Int64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1149 pprAssign Word64Rep dest@(CVal reg_rel _) src
1150   = hcat [ ptext SLIT("ASSIGN_Word64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1151 \end{code}
1152
1153 Lastly, the question is: will the C compiler think the types of the
1154 two sides of the assignment match?
1155
1156         We assume that the types will match if neither side is a
1157         @CVal@ addressing mode for any register which can point into
1158         the heap or stack.
1159
1160 Why?  Because the heap and stack are used to store miscellaneous
1161 things, whereas the temporaries, registers, etc., are only used for
1162 things of fixed type.
1163
1164 \begin{code}
1165 pprAssign kind (CReg (VanillaReg _ dest)) (CReg (VanillaReg _ src))
1166   = hcat [ pprVanillaReg dest, equals,
1167                 pprVanillaReg src, semi ]
1168
1169 pprAssign kind dest src
1170   | mixedTypeLocn dest
1171     -- Add in a cast to StgWord (a.k.a. W_) iff the destination is mixed
1172   = hcat [ ppr_amode dest, equals,
1173                 text "(W_)(",   -- Here is the cast
1174                 ppr_amode src, pp_paren_semi ]
1175
1176 pprAssign kind dest src
1177   | mixedPtrLocn dest && getAmodeRep src /= PtrRep
1178     -- Add in a cast to StgPtr (a.k.a. P_) iff the destination is mixed
1179   = hcat [ ppr_amode dest, equals,
1180                 text "(P_)(",   -- Here is the cast
1181                 ppr_amode src, pp_paren_semi ]
1182
1183 pprAssign kind other_dest src
1184   = hcat [ ppr_amode other_dest, equals,
1185                 pprAmode  src, semi ]
1186 \end{code}
1187
1188
1189 %************************************************************************
1190 %*                                                                      *
1191 \subsection[a2r-CAddrModes]{Addressing modes}
1192 %*                                                                      *
1193 %************************************************************************
1194
1195 @pprAmode@ is used to print r-values (which may need casts), whereas
1196 @ppr_amode@ is used for l-values {\em and} as a help function for
1197 @pprAmode@.
1198
1199 \begin{code}
1200 pprAmode, ppr_amode :: CAddrMode -> SDoc
1201 \end{code}
1202
1203 For reasons discussed above under assignments, @CVal@ modes need
1204 to be treated carefully.  First come special cases for floats and doubles,
1205 similar to those in @pprAssign@:
1206
1207 (NB: @PK_FLT@ and @PK_DBL@ require the {\em address} of the value in
1208 question.)
1209
1210 \begin{code}
1211 pprAmode (CVal reg_rel FloatRep)
1212   = hcat [ text "PK_FLT((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1213 pprAmode (CVal reg_rel DoubleRep)
1214   = hcat [ text "PK_DBL((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1215 pprAmode (CVal reg_rel Int64Rep)
1216   = hcat [ text "PK_Int64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1217 pprAmode (CVal reg_rel Word64Rep)
1218   = hcat [ text "PK_Word64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1219 \end{code}
1220
1221 Next comes the case where there is some other cast need, and the
1222 no-cast case:
1223
1224 \begin{code}
1225 pprAmode amode
1226   | mixedTypeLocn amode
1227   = parens (hcat [ pprPrimKind (getAmodeRep amode), ptext SLIT(")("),
1228                 ppr_amode amode ])
1229   | otherwise   -- No cast needed
1230   = ppr_amode amode
1231 \end{code}
1232
1233 When we have an indirection through a CIndex, we have to be careful to
1234 get the type casts right.  
1235
1236 this amode:
1237
1238         CVal (CIndex kind1 base offset) kind2
1239
1240 means (in C speak): 
1241         
1242         *(kind2 *)((kind1 *)base + offset)
1243
1244 That is, the indexing is done in units of kind1, but the resulting
1245 amode has kind2.
1246
1247 \begin{code}
1248 ppr_amode (CVal reg_rel@(CIndex _ _ _) kind)
1249   = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1250         (pp_reg, Nothing)     -> panic "ppr_amode: CIndex"
1251         (pp_reg, Just offset) -> 
1252            hcat [ char '*', parens (pprPrimKind kind <> char '*'),
1253                   parens (pp_reg <> char '+' <> offset) ]
1254 \end{code}
1255
1256 Now the rest of the cases for ``workhorse'' @ppr_amode@:
1257
1258 \begin{code}
1259 ppr_amode (CVal reg_rel _)
1260   = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1261         (pp_reg, Nothing)     -> (<>)  (char '*') pp_reg
1262         (pp_reg, Just offset) -> hcat [ pp_reg, brackets offset ]
1263
1264 ppr_amode (CAddr reg_rel)
1265   = case (pprRegRelative True{-sign wanted-} reg_rel) of
1266         (pp_reg, Nothing)     -> pp_reg
1267         (pp_reg, Just offset) -> pp_reg <> offset
1268
1269 ppr_amode (CReg magic_id) = pprMagicId magic_id
1270
1271 ppr_amode (CTemp uniq kind) = char '_' <> pprUnique uniq <> char '_'
1272
1273 ppr_amode (CLbl lbl kind) = pprCLabelAddr lbl 
1274
1275 ppr_amode (CCharLike ch)
1276   = hcat [ptext SLIT("CHARLIKE_CLOSURE"), char '(', pprAmode ch, rparen ]
1277 ppr_amode (CIntLike int)
1278   = hcat [ptext SLIT("INTLIKE_CLOSURE"), char '(', pprAmode int, rparen ]
1279
1280 ppr_amode (CLit lit) = pprBasicLit lit
1281
1282 ppr_amode (CJoinPoint _)
1283   = panic "ppr_amode: CJoinPoint"
1284
1285 ppr_amode (CMacroExpr pk macro as)
1286   = parens (ptext (cExprMacroText macro) <> 
1287             parens (hcat (punctuate comma (map pprAmode as))))
1288 \end{code}
1289
1290 \begin{code}
1291 cExprMacroText ENTRY_CODE               = SLIT("ENTRY_CODE")
1292 cExprMacroText ARG_TAG                  = SLIT("ARG_TAG")
1293 cExprMacroText GET_TAG                  = SLIT("GET_TAG")
1294 cExprMacroText CCS_HDR                  = SLIT("CCS_HDR")
1295 cExprMacroText BYTE_ARR_CTS             = SLIT("BYTE_ARR_CTS")
1296 cExprMacroText PTRS_ARR_CTS             = SLIT("PTRS_ARR_CTS")
1297 cExprMacroText ForeignObj_CLOSURE_DATA  = SLIT("ForeignObj_CLOSURE_DATA")
1298
1299 cStmtMacroText UPD_CAF                  = SLIT("UPD_CAF")
1300 cStmtMacroText UPD_BH_UPDATABLE         = SLIT("UPD_BH_UPDATABLE")
1301 cStmtMacroText UPD_BH_SINGLE_ENTRY      = SLIT("UPD_BH_SINGLE_ENTRY")
1302 cStmtMacroText PUSH_UPD_FRAME           = SLIT("PUSH_UPD_FRAME")
1303 cStmtMacroText SET_TAG                  = SLIT("SET_TAG")
1304 cStmtMacroText DATA_TO_TAGZH            = SLIT("dataToTagzh")
1305 cStmtMacroText REGISTER_FOREIGN_EXPORT  = SLIT("REGISTER_FOREIGN_EXPORT")
1306 cStmtMacroText REGISTER_IMPORT          = SLIT("REGISTER_IMPORT")
1307 cStmtMacroText REGISTER_DIMPORT         = SLIT("REGISTER_DIMPORT")
1308 cStmtMacroText GRAN_FETCH               = SLIT("GRAN_FETCH")
1309 cStmtMacroText GRAN_RESCHEDULE          = SLIT("GRAN_RESCHEDULE")
1310 cStmtMacroText GRAN_FETCH_AND_RESCHEDULE= SLIT("GRAN_FETCH_AND_RESCHEDULE")
1311 cStmtMacroText THREAD_CONTEXT_SWITCH    = SLIT("THREAD_CONTEXT_SWITCH")
1312 cStmtMacroText GRAN_YIELD               = SLIT("GRAN_YIELD")
1313
1314 cCheckMacroText HP_CHK_NP               = SLIT("HP_CHK_NP")
1315 cCheckMacroText STK_CHK_NP              = SLIT("STK_CHK_NP")
1316 cCheckMacroText HP_STK_CHK_NP           = SLIT("HP_STK_CHK_NP")
1317 cCheckMacroText HP_CHK_FUN              = SLIT("HP_CHK_FUN")
1318 cCheckMacroText STK_CHK_FUN             = SLIT("STK_CHK_FUN")
1319 cCheckMacroText HP_STK_CHK_FUN          = SLIT("HP_STK_CHK_FUN")
1320 cCheckMacroText HP_CHK_NOREGS           = SLIT("HP_CHK_NOREGS")
1321 cCheckMacroText HP_CHK_UNPT_R1          = SLIT("HP_CHK_UNPT_R1")
1322 cCheckMacroText HP_CHK_UNBX_R1          = SLIT("HP_CHK_UNBX_R1")
1323 cCheckMacroText HP_CHK_F1               = SLIT("HP_CHK_F1")
1324 cCheckMacroText HP_CHK_D1               = SLIT("HP_CHK_D1")
1325 cCheckMacroText HP_CHK_L1               = SLIT("HP_CHK_L1")
1326 cCheckMacroText HP_CHK_UNBX_TUPLE       = SLIT("HP_CHK_UNBX_TUPLE")
1327 \end{code}
1328
1329 %************************************************************************
1330 %*                                                                      *
1331 \subsection[ppr-liveness-masks]{Liveness Masks}
1332 %*                                                                      *
1333 %************************************************************************
1334
1335 \begin{code}
1336 bitmapAddrModes [] = [mkWordCLit 0]
1337 bitmapAddrModes xs = map mkWordCLit xs
1338 \end{code}
1339
1340 %************************************************************************
1341 %*                                                                      *
1342 \subsection[a2r-MagicIds]{Magic ids}
1343 %*                                                                      *
1344 %************************************************************************
1345
1346 @pprRegRelative@ returns a pair of the @Doc@ for the register
1347 (some casting may be required), and a @Maybe Doc@ for the offset
1348 (zero offset gives a @Nothing@).
1349
1350 \begin{code}
1351 addPlusSign :: Bool -> SDoc -> SDoc
1352 addPlusSign False p = p
1353 addPlusSign True  p = (<>) (char '+') p
1354
1355 pprSignedInt :: Bool -> Int -> Maybe SDoc       -- Nothing => 0
1356 pprSignedInt sign_wanted n
1357  = if n == 0 then Nothing else
1358    if n > 0  then Just (addPlusSign sign_wanted (int n))
1359    else           Just (int n)
1360
1361 pprRegRelative :: Bool          -- True <=> Print leading plus sign (if +ve)
1362                -> RegRelative
1363                -> (SDoc, Maybe SDoc)
1364
1365 pprRegRelative sign_wanted (SpRel off)
1366   = (pprMagicId Sp, pprSignedInt sign_wanted (I# off))
1367
1368 pprRegRelative sign_wanted r@(HpRel o)
1369   = let pp_Hp    = pprMagicId Hp; off = I# o
1370     in
1371     if off == 0 then
1372         (pp_Hp, Nothing)
1373     else
1374         (pp_Hp, Just ((<>) (char '-') (int off)))
1375
1376 pprRegRelative sign_wanted (NodeRel o)
1377   = let pp_Node = pprMagicId node; off = I# o
1378     in
1379     if off == 0 then
1380         (pp_Node, Nothing)
1381     else
1382         (pp_Node, Just (addPlusSign sign_wanted (int off)))
1383
1384 pprRegRelative sign_wanted (CIndex base offset kind)
1385   = ( hcat [text "((", pprPrimKind kind, text " *)(", ppr_amode base, text "))"]
1386     , Just (hcat [if sign_wanted then char '+' else empty,
1387             text "(I_)(", ppr_amode offset, ptext SLIT(")")])
1388     )
1389 \end{code}
1390
1391 @pprMagicId@ just prints the register name.  @VanillaReg@ registers are
1392 represented by a discriminated union (@StgUnion@), so we use the @PrimRep@
1393 to select the union tag.
1394
1395 \begin{code}
1396 pprMagicId :: MagicId -> SDoc
1397
1398 pprMagicId BaseReg                  = ptext SLIT("BaseReg")
1399 pprMagicId (VanillaReg pk n)
1400                                     = hcat [ pprVanillaReg n, char '.',
1401                                                   pprUnionTag pk ]
1402 pprMagicId (FloatReg  n)            = ptext SLIT("F") <> int (I# n)
1403 pprMagicId (DoubleReg n)            = ptext SLIT("D") <> int (I# n)
1404 pprMagicId (LongReg _ n)            = ptext SLIT("L") <> int (I# n)
1405 pprMagicId Sp                       = ptext SLIT("Sp")
1406 pprMagicId SpLim                    = ptext SLIT("SpLim")
1407 pprMagicId Hp                       = ptext SLIT("Hp")
1408 pprMagicId HpLim                    = ptext SLIT("HpLim")
1409 pprMagicId CurCostCentre            = ptext SLIT("CCCS")
1410 pprMagicId VoidReg                  = ptext SLIT("VoidReg")
1411
1412 pprVanillaReg :: Int# -> SDoc
1413 pprVanillaReg n = char 'R' <> int (I# n)
1414
1415 pprUnionTag :: PrimRep -> SDoc
1416
1417 pprUnionTag PtrRep              = char 'p'
1418 pprUnionTag CodePtrRep          = ptext SLIT("fp")
1419 pprUnionTag DataPtrRep          = char 'd'
1420 pprUnionTag RetRep              = char 'p'
1421 pprUnionTag CostCentreRep       = panic "pprUnionTag:CostCentre?"
1422
1423 pprUnionTag CharRep             = char 'c'
1424 pprUnionTag Int8Rep             = ptext SLIT("i8")
1425 pprUnionTag IntRep              = char 'i'
1426 pprUnionTag WordRep             = char 'w'
1427 pprUnionTag Int32Rep            = char 'i'
1428 pprUnionTag Word32Rep           = char 'w'
1429 pprUnionTag AddrRep             = char 'a'
1430 pprUnionTag FloatRep            = char 'f'
1431 pprUnionTag DoubleRep           = panic "pprUnionTag:Double?"
1432
1433 pprUnionTag StablePtrRep        = char 'p'
1434
1435 pprUnionTag _                   = panic "pprUnionTag:Odd kind"
1436 \end{code}
1437
1438
1439 Find and print local and external declarations for a list of
1440 Abstract~C statements.
1441 \begin{code}
1442 pprTempAndExternDecls :: AbstractC -> (SDoc{-temps-}, SDoc{-externs-})
1443 pprTempAndExternDecls AbsCNop = (empty, empty)
1444
1445 pprTempAndExternDecls (AbsCStmts stmt1 stmt2)
1446   = initTE (ppr_decls_AbsC stmt1        `thenTE` \ (t_p1, e_p1) ->
1447             ppr_decls_AbsC stmt2        `thenTE` \ (t_p2, e_p2) ->
1448             case (catMaybes [t_p1, t_p2])        of { real_temps ->
1449             case (catMaybes [e_p1, e_p2])        of { real_exts ->
1450             returnTE (vcat real_temps, vcat real_exts) }}
1451            )
1452
1453 pprTempAndExternDecls other_stmt
1454   = initTE (ppr_decls_AbsC other_stmt `thenTE` \ (maybe_t, maybe_e) ->
1455             returnTE (
1456                 case maybe_t of
1457                   Nothing -> empty
1458                   Just pp -> pp,
1459
1460                 case maybe_e of
1461                   Nothing -> empty
1462                   Just pp -> pp )
1463            )
1464
1465 pprBasicLit :: Literal -> SDoc
1466 pprPrimKind :: PrimRep -> SDoc
1467
1468 pprBasicLit  lit = ppr lit
1469 pprPrimKind  k   = ppr k
1470 \end{code}
1471
1472
1473 %************************************************************************
1474 %*                                                                      *
1475 \subsection[a2r-monad]{Monadery}
1476 %*                                                                      *
1477 %************************************************************************
1478
1479 We need some monadery to keep track of temps and externs we have already
1480 printed.  This info must be threaded right through the Abstract~C, so
1481 it's most convenient to hide it in this monad.
1482
1483 WDP 95/02: Switched from \tr{([Unique], [CLabel])} to
1484 \tr{(UniqSet, CLabelSet)}.  Allegedly for efficiency.
1485
1486 \begin{code}
1487 type CLabelSet = FiniteMap CLabel (){-any type will do-}
1488 emptyCLabelSet = emptyFM
1489 x `elementOfCLabelSet` labs
1490   = case (lookupFM labs x) of { Just _ -> True; Nothing -> False }
1491
1492 addToCLabelSet set x = addToFM set x ()
1493
1494 type TEenv = (UniqSet Unique, CLabelSet)
1495
1496 type TeM result =  TEenv -> (TEenv, result)
1497
1498 initTE :: TeM a -> a
1499 initTE sa
1500   = case sa (emptyUniqSet, emptyCLabelSet) of { (_, result) ->
1501     result }
1502
1503 {-# INLINE thenTE #-}
1504 {-# INLINE returnTE #-}
1505
1506 thenTE :: TeM a -> (a -> TeM b) -> TeM b
1507 thenTE a b u
1508   = case a u        of { (u_1, result_of_a) ->
1509     b result_of_a u_1 }
1510
1511 mapTE :: (a -> TeM b) -> [a] -> TeM [b]
1512 mapTE f []     = returnTE []
1513 mapTE f (x:xs)
1514   = f x         `thenTE` \ r  ->
1515     mapTE f xs  `thenTE` \ rs ->
1516     returnTE (r : rs)
1517
1518 returnTE :: a -> TeM a
1519 returnTE result env = (env, result)
1520
1521 -- these next two check whether the thing is already
1522 -- recorded, and THEN THEY RECORD IT
1523 -- (subsequent calls will return False for the same uniq/label)
1524
1525 tempSeenTE :: Unique -> TeM Bool
1526 tempSeenTE uniq env@(seen_uniqs, seen_labels)
1527   = if (uniq `elementOfUniqSet` seen_uniqs)
1528     then (env, True)
1529     else ((addOneToUniqSet seen_uniqs uniq,
1530           seen_labels),
1531           False)
1532
1533 labelSeenTE :: CLabel -> TeM Bool
1534 labelSeenTE lbl env@(seen_uniqs, seen_labels)
1535   = if (lbl `elementOfCLabelSet` seen_labels)
1536     then (env, True)
1537     else ((seen_uniqs,
1538           addToCLabelSet seen_labels lbl),
1539           False)
1540 \end{code}
1541
1542 \begin{code}
1543 pprTempDecl :: Unique -> PrimRep -> SDoc
1544 pprTempDecl uniq kind
1545   = hcat [ pprPrimKind kind, space, char '_', pprUnique uniq, ptext SLIT("_;") ]
1546
1547 pprExternDecl :: Bool -> CLabel -> SDoc
1548 pprExternDecl in_srt clabel
1549   | not (needsCDecl clabel) = empty -- do not print anything for "known external" things
1550   | otherwise               = 
1551         hcat [ ppLocalnessMacro (not in_srt) clabel, 
1552                lparen, dyn_wrapper (pprCLabel clabel), pp_paren_semi ]
1553  where
1554   dyn_wrapper d
1555     | in_srt && labelDynamic clabel = text "DLL_IMPORT_DATA_VAR" <> parens d
1556     | otherwise                     = d
1557
1558 \end{code}
1559
1560 \begin{code}
1561 ppr_decls_AbsC :: AbstractC -> TeM (Maybe SDoc{-temps-}, Maybe SDoc{-externs-})
1562
1563 ppr_decls_AbsC AbsCNop          = returnTE (Nothing, Nothing)
1564
1565 ppr_decls_AbsC (AbsCStmts stmts_1 stmts_2)
1566   = ppr_decls_AbsC stmts_1  `thenTE` \ p1 ->
1567     ppr_decls_AbsC stmts_2  `thenTE` \ p2 ->
1568     returnTE (maybe_vcat [p1, p2])
1569
1570 ppr_decls_AbsC (CSplitMarker) = returnTE (Nothing, Nothing)
1571
1572 ppr_decls_AbsC (CAssign dest source)
1573   = ppr_decls_Amode dest    `thenTE` \ p1 ->
1574     ppr_decls_Amode source  `thenTE` \ p2 ->
1575     returnTE (maybe_vcat [p1, p2])
1576
1577 ppr_decls_AbsC (CJump target) = ppr_decls_Amode target
1578
1579 ppr_decls_AbsC (CFallThrough target) = ppr_decls_Amode target
1580
1581 ppr_decls_AbsC (CReturn target _) = ppr_decls_Amode target
1582
1583 ppr_decls_AbsC (CSwitch discrim alts deflt)
1584   = ppr_decls_Amode discrim     `thenTE` \ pdisc ->
1585     mapTE ppr_alt_stuff alts    `thenTE` \ palts  ->
1586     ppr_decls_AbsC deflt        `thenTE` \ pdeflt ->
1587     returnTE (maybe_vcat (pdisc:pdeflt:palts))
1588   where
1589     ppr_alt_stuff (_, absC) = ppr_decls_AbsC absC
1590
1591 ppr_decls_AbsC (CCodeBlock lbl absC)
1592   = ppr_decls_AbsC absC
1593
1594 ppr_decls_AbsC (CInitHdr cl_info reg_rel cost_centre _)
1595         -- ToDo: strictly speaking, should chk "cost_centre" amode
1596   = labelSeenTE info_lbl     `thenTE` \  label_seen ->
1597     returnTE (Nothing,
1598               if label_seen then
1599                   Nothing
1600               else
1601                   Just (pprExternDecl False{-not in an SRT decl-} info_lbl))
1602   where
1603     info_lbl = infoTableLabelFromCI cl_info
1604
1605 ppr_decls_AbsC (CMachOpStmt res _ args _) = ppr_decls_Amodes (res : args)
1606 ppr_decls_AbsC (COpStmt results _ args _) = ppr_decls_Amodes (results ++ args)
1607
1608 ppr_decls_AbsC (CSimultaneous abc)        = ppr_decls_AbsC abc
1609
1610 ppr_decls_AbsC (CSequential abcs) 
1611   = mapTE ppr_decls_AbsC abcs   `thenTE` \ t_and_e_s ->
1612     returnTE (maybe_vcat t_and_e_s)
1613
1614 ppr_decls_AbsC (CCheck              _ amodes code) = 
1615      ppr_decls_Amodes amodes `thenTE` \p1 ->
1616      ppr_decls_AbsC code     `thenTE` \p2 ->
1617      returnTE (maybe_vcat [p1,p2])
1618
1619 ppr_decls_AbsC (CMacroStmt          _ amodes)   = ppr_decls_Amodes amodes
1620
1621 ppr_decls_AbsC (CCallProfCtrMacro   _ amodes)   = ppr_decls_Amodes [] -- *****!!!
1622   -- you get some nasty re-decls of stdio.h if you compile
1623   -- the prelude while looking inside those amodes;
1624   -- no real reason to, anyway.
1625 ppr_decls_AbsC (CCallProfCCMacro    _ amodes)   = ppr_decls_Amodes amodes
1626
1627 ppr_decls_AbsC (CStaticClosure _ closure_info cost_centre amodes)
1628         -- ToDo: strictly speaking, should chk "cost_centre" amode
1629   = ppr_decls_Amodes amodes
1630
1631 ppr_decls_AbsC (CClosureInfoAndCode cl_info entry)
1632   = ppr_decls_Amodes [entry_lbl]                `thenTE` \ p1 ->
1633     ppr_decls_AbsC entry                        `thenTE` \ p2 ->
1634     returnTE (maybe_vcat [p1, p2])
1635   where
1636     entry_lbl = CLbl (entryLabelFromCI cl_info) CodePtrRep
1637
1638 ppr_decls_AbsC (CSRT _ closure_lbls)
1639   = mapTE labelSeenTE closure_lbls              `thenTE` \ seen ->
1640     returnTE (Nothing, 
1641               if and seen then Nothing
1642                 else Just (vcat [ pprExternDecl True{-in SRT decl-} l
1643                                 | (l,False) <- zip closure_lbls seen ]))
1644
1645 ppr_decls_AbsC (CRetDirect     _ code _ _)   = ppr_decls_AbsC code
1646 ppr_decls_AbsC (CRetVector _ amodes _ _)     = ppr_decls_Amodes amodes
1647 ppr_decls_AbsC (CModuleInitBlock _ _ code)   = ppr_decls_AbsC code
1648
1649 ppr_decls_AbsC (_) = returnTE (Nothing, Nothing)
1650 \end{code}
1651
1652 \begin{code}
1653 ppr_decls_Amode :: CAddrMode -> TeM (Maybe SDoc, Maybe SDoc)
1654 ppr_decls_Amode (CVal  (CIndex base offset _) _) = ppr_decls_Amodes [base,offset]
1655 ppr_decls_Amode (CAddr (CIndex base offset _))   = ppr_decls_Amodes [base,offset]
1656 ppr_decls_Amode (CVal _ _)      = returnTE (Nothing, Nothing)
1657 ppr_decls_Amode (CAddr _)       = returnTE (Nothing, Nothing)
1658 ppr_decls_Amode (CReg _)        = returnTE (Nothing, Nothing)
1659 ppr_decls_Amode (CLit _)        = returnTE (Nothing, Nothing)
1660
1661 -- CIntLike must be a literal -- no decls
1662 ppr_decls_Amode (CIntLike int)  = returnTE (Nothing, Nothing)
1663
1664 -- CCharLike too
1665 ppr_decls_Amode (CCharLike char) = returnTE (Nothing, Nothing)
1666
1667 -- now, the only place where we actually print temps/externs...
1668 ppr_decls_Amode (CTemp uniq kind)
1669   = case kind of
1670       VoidRep -> returnTE (Nothing, Nothing)
1671       other ->
1672         tempSeenTE uniq `thenTE` \ temp_seen ->
1673         returnTE
1674           (if temp_seen then Nothing else Just (pprTempDecl uniq kind), Nothing)
1675
1676 ppr_decls_Amode (CLbl lbl VoidRep)
1677   = returnTE (Nothing, Nothing)
1678
1679 ppr_decls_Amode (CLbl lbl kind)
1680   = labelSeenTE lbl `thenTE` \ label_seen ->
1681     returnTE (Nothing,
1682               if label_seen then Nothing else Just (pprExternDecl False{-not in an SRT decl-} lbl))
1683
1684 ppr_decls_Amode (CMacroExpr _ _ amodes)
1685   = ppr_decls_Amodes amodes
1686
1687 ppr_decls_Amode other = returnTE (Nothing, Nothing)
1688
1689
1690 maybe_vcat :: [(Maybe SDoc, Maybe SDoc)] -> (Maybe SDoc, Maybe SDoc)
1691 maybe_vcat ps
1692   = case (unzip ps)     of { (ts, es) ->
1693     case (catMaybes ts) of { real_ts  ->
1694     case (catMaybes es) of { real_es  ->
1695     (if (null real_ts) then Nothing else Just (vcat real_ts),
1696      if (null real_es) then Nothing else Just (vcat real_es))
1697     } } }
1698 \end{code}
1699
1700 \begin{code}
1701 ppr_decls_Amodes :: [CAddrMode] -> TeM (Maybe SDoc, Maybe SDoc)
1702 ppr_decls_Amodes amodes
1703   = mapTE ppr_decls_Amode amodes `thenTE` \ ps ->
1704     returnTE ( maybe_vcat ps )
1705 \end{code}
1706
1707 Print out a C Label where you want the *address* of the label, not the
1708 object it refers to.  The distinction is important when the label may
1709 refer to a C structure (info tables and closures, for instance).
1710
1711 When just generating a declaration for the label, use pprCLabel.
1712
1713 \begin{code}
1714 pprCLabelAddr :: CLabel -> SDoc
1715 pprCLabelAddr clabel =
1716   case labelType clabel of
1717      InfoTblType    -> addr_of_label
1718      RetInfoTblType -> addr_of_label
1719      ClosureType    -> addr_of_label
1720      VecTblType     -> addr_of_label
1721      DataType       -> addr_of_label
1722
1723      _              -> pp_label
1724   where
1725     addr_of_label = ptext SLIT("(P_)&") <> pp_label
1726     pp_label = pprCLabel clabel
1727 \end{code}
1728
1729 -----------------------------------------------------------------------------
1730 Initialising static objects with floating-point numbers.  We can't
1731 just emit the floating point number, because C will cast it to an int
1732 by rounding it.  We want the actual bit-representation of the float.
1733
1734 This is a hack to turn the floating point numbers into ints that we
1735 can safely initialise to static locations.
1736
1737 \begin{code}
1738 big_doubles = (getPrimRepSize DoubleRep) /= 1
1739
1740 #if __GLASGOW_HASKELL__ >= 504
1741 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
1742 newFloatArray = newArray_
1743
1744 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
1745 newDoubleArray = newArray_
1746
1747 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
1748 castFloatToIntArray = castSTUArray
1749
1750 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
1751 castDoubleToIntArray = castSTUArray
1752
1753 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
1754 writeFloatArray = writeArray
1755
1756 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
1757 writeDoubleArray = writeArray
1758
1759 readIntArray :: STUArray s Int Int -> Int -> ST s Int
1760 readIntArray = readArray
1761
1762 #else
1763
1764 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
1765 castFloatToIntArray = return
1766
1767 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
1768 castDoubleToIntArray = return
1769
1770 #endif
1771
1772 -- floats are always 1 word
1773 floatToWord :: CAddrMode -> CAddrMode
1774 floatToWord (CLit (MachFloat r))
1775   = runST (do
1776         arr <- newFloatArray ((0::Int),0)
1777         writeFloatArray arr 0 (fromRational r)
1778         arr' <- castFloatToIntArray arr
1779         i <- readIntArray arr' 0
1780         return (CLit (MachInt (toInteger i)))
1781     )
1782
1783 doubleToWords :: CAddrMode -> [CAddrMode]
1784 doubleToWords (CLit (MachDouble r))
1785   | big_doubles                         -- doubles are 2 words
1786   = runST (do
1787         arr <- newDoubleArray ((0::Int),1)
1788         writeDoubleArray arr 0 (fromRational r)
1789         arr' <- castDoubleToIntArray arr
1790         i1 <- readIntArray arr' 0
1791         i2 <- readIntArray arr' 1
1792         return [ CLit (MachInt (toInteger i1))
1793                , CLit (MachInt (toInteger i2))
1794                ]
1795     )
1796   | otherwise                           -- doubles are 1 word
1797   = runST (do
1798         arr <- newDoubleArray ((0::Int),0)
1799         writeDoubleArray arr 0 (fromRational r)
1800         arr' <- castDoubleToIntArray arr
1801         i <- readIntArray arr' 0
1802         return [ CLit (MachInt (toInteger i)) ]
1803     )
1804 \end{code}