00c8a7349bb2a39d06cfa9d574d319227bd328e1
[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           target    = StaticTarget (mkFastString nm)
850           resultVar = "_ccall_result"
851           
852           hasAssemArg = isStatic || kind == DNConstructor
853           invokeOp  = 
854             case kind of
855               DNMethod 
856                 | isStatic  -> "DN_invokeStatic"
857                 | otherwise -> "DN_invokeMethod"
858               DNField
859                 | isStatic ->
860                    if resTy == DNUnit 
861                     then "DN_setStatic"
862                     else "DN_getStatic"
863                 | otherwise ->
864                    if resTy == DNUnit 
865                     then "DN_setField"
866                     else "DN_getField"
867               DNConstructor -> "DN_createObject"
868
869           (methArrDecl, methArrInit, methArrName, methArrLen) 
870             | null argTys = (empty, empty, text "NULL", text "0")
871             | otherwise   = 
872               ( text "DotnetArg __meth_args[" <> int (length argTys) <> text "];"
873               , vcat (zipWith3 (\ idx arg argTy -> 
874                                  text "__meth_args[" <> int idx <> text "].arg." <> text (toDotnetArgField argTy) <> equals <> ppr_amode arg <> semi $$
875                                  text "__meth_args[" <> int idx <> text "].arg_type=" <> text (toDotnetTy argTy) <> semi)
876                                [0..]
877                                non_void_args
878                                argTys)
879               , text "__meth_args"
880               , int (length non_void_args)
881               )
882          in
883          vcat [ char '{',
884                   declare_local_vars,
885                   vcat local_arg_decls,
886                   vcat [ methArrDecl
887                        , methArrInit
888                        , text "_ccall_result1 =" <+> text invokeOp <> parens (
889                           hcat (punctuate comma $
890                                      (if hasAssemArg then
891                                         ((if null assem then 
892                                             text "NULL" 
893                                          else 
894                                             doubleQuotes (text assem)):)
895                                       else
896                                          id) $
897                                      [ doubleQuotes $ text nm
898                                      , methArrName
899                                      , methArrLen
900                                      , text (toDotnetTy resTy)
901                                      , text "(void*)&" <> text resultVar 
902                                      ])) <> semi
903                         ],
904                   assign_results,
905                 char '}'
906                ]
907   where
908     (pp_saves, pp_restores) = ppr_vol_regs vol_regs
909     
910     makeCall target safety theCall = 
911         vcat [ pp_save_context, theCall, pp_restore_context ]
912      where
913       (pp_save_context, pp_restore_context)
914         | playSafe safety = ( text "{ I_" <+> ppr_uniq_token <> 
915                                 text "; SUSPEND_THREAD" <> parens thread_macro_args <> semi
916                             , text "RESUME_THREAD" <> parens thread_macro_args <> text ";}"
917                             )
918         | otherwise = ( pp_basic_saves $$ pp_saves,
919                         pp_basic_restores $$ pp_restores)
920            where
921             thread_macro_args = ppr_uniq_token <> comma <+> 
922                                 text "rts" <> ppr (playThreadSafe safety)
923             ppr_uniq_token = text "tok_" <> ppr uniq
924
925
926     non_void_args = 
927         let nvas = init args
928         in ASSERT2 ( all non_void nvas, ppr call <+> hsep (map pprAmode args) )
929         nvas
930     -- the last argument will be the "I/O world" token (a VoidRep)
931     -- all others should be non-void
932
933     non_void_results =
934         let nvrs = grab_non_void_amodes results
935         in ASSERT (forDotnet || listLengthCmp nvrs 1 /= GT) nvrs
936     -- there will usually be two results: a (void) state which we
937     -- should ignore and a (possibly void) result.
938
939     (local_arg_decls, pp_non_void_args)
940       = unzip [ ppr_casm_arg a i | (a,i) <- non_void_args `zip` [1..] ]
941
942     (declare_local_vars, local_vars, assign_results)
943       = ppr_casm_results non_void_results forDotnet
944
945     forDotnet
946       = case call of
947           DNCall{} -> True
948           _ -> False
949
950     call_str tgt 
951       = case tgt of
952           CasmTarget str  -> unpackFS str
953           StaticTarget fn -> mk_ccall_str (pprCLabelString fn) ccall_args
954           DynamicTarget   -> mk_ccall_str dyn_fun              (tail ccall_args)
955
956     ccall_args = zipWith (\ _ i -> char '%' <> int i) non_void_args [0..]
957     dyn_fun    = parens (parens (ptext SLIT("_ccall_fun_ty") <> ppr uniq) <> text "%0")
958                                                  
959
960     -- Remainder only used for ccall
961     mk_ccall_str fun_name ccall_fun_args = showSDoc
962         (hcat [
963                 if null non_void_results
964                   then empty
965                   else text "%r = ",
966                 lparen, fun_name, lparen,
967                   hcat (punctuate comma ccall_fun_args),
968                 text "));"
969         ])
970
971 toDotnetTy :: DNType -> String
972 toDotnetTy x = 
973   case x of 
974     DNByte -> "Dotnet_Byte"
975     DNBool -> "Dotnet_Bool"
976     DNChar -> "Dotnet_Char"
977     DNDouble -> "Dotnet_Double"
978     DNFloat  -> "Dotnet_Float"
979     DNInt    -> "Dotnet_Int"
980     DNInt8   -> "Dotnet_Int8"
981     DNInt16  -> "Dotnet_Int16"
982     DNInt32  -> "Dotnet_Int32"
983     DNInt64  -> "Dotnet_Int64"
984     DNWord8  -> "Dotnet_Word8"
985     DNWord16 -> "Dotnet_Word16"
986     DNWord32 -> "Dotnet_Word32"
987     DNWord64 -> "Dotnet_Word64"
988     DNPtr    -> "Dotnet_Ptr"
989     DNUnit   -> "Dotnet_Unit"
990     DNObject -> "Dotnet_Object"
991     DNString -> "Dotnet_String"
992
993 toDotnetArgField :: DNType -> String
994 toDotnetArgField x = 
995   case x of 
996     DNByte -> "arg_byte"
997     DNBool -> "arg_bool"
998     DNChar -> "arg_char"
999     DNDouble -> "arg_double"
1000     DNFloat  -> "arg_float"
1001     DNInt    -> "arg_int"
1002     DNInt8   -> "arg_int8"
1003     DNInt16  -> "arg_int16"
1004     DNInt32  -> "arg_int32"
1005     DNInt64  -> "arg_int64"
1006     DNWord8  -> "arg_word8"
1007     DNWord16 -> "arg_word16"
1008     DNWord32 -> "arg_word32"
1009     DNWord64 -> "arg_word64"
1010     DNPtr    -> "arg_ptr"
1011     DNUnit   -> "arg_ptr" -- can't happen
1012     DNObject -> "arg_obj"
1013     DNString -> "arg_str"
1014
1015 ppr_casm_arg :: CAddrMode -> Int -> (SDoc, SDoc)
1016     -- (a) decl and assignment, (b) local var to be used later
1017
1018 ppr_casm_arg amode a_num
1019   = let
1020         a_kind   = getAmodeRep amode
1021         pp_amode = pprAmode amode
1022         pp_kind  = pprPrimKind a_kind
1023
1024         local_var  = (<>) (ptext SLIT("_ccall_arg")) (int a_num)
1025
1026         declare_local_var
1027           = hcat [ pp_kind, space, local_var, equals, pp_amode, semi ]
1028     in
1029     (declare_local_var, local_var)
1030 \end{code}
1031
1032 For l-values, the critical questions are:
1033
1034 1) Are there any results at all?
1035
1036    We only allow zero or one results.
1037
1038 \begin{code}
1039 ppr_casm_results
1040         :: [CAddrMode]  -- list of results (length <= 1)
1041         -> Bool         -- True => multiple results OK.
1042         ->
1043         ( SDoc,         -- declaration of any local vars
1044           [SDoc],       -- list of result vars (same length as results)
1045           SDoc )        -- assignment (if any) of results in local var to registers
1046
1047 ppr_casm_results [] _
1048   = (empty, [], empty)  -- no results
1049
1050 ppr_casm_results (r:rs) multiResultsOK
1051   | not multiResultsOK && not (null rs) = panic "ppr_casm_results: ccall/casm with many results"
1052   | otherwise
1053   = foldr (\ (a,b,c) (as,bs,cs) -> (a $$ as, b ++ bs, c $$ cs))
1054           (empty,[],empty)
1055           (zipWith pprRes (r:rs) ("" : map show [(1::Int)..]))
1056     where
1057       pprRes r suf = (declare_local_var, [local_var], assign_result)
1058        where
1059         result_reg = ppr_amode r
1060         r_kind     = getAmodeRep r
1061
1062         local_var  = ptext SLIT("_ccall_result") <> text suf
1063
1064         (result_type, assign_result)
1065           = (pprPrimKind r_kind,
1066              hcat [ result_reg, equals, local_var, semi ])
1067
1068         declare_local_var = hcat [ result_type, space, local_var, semi ]
1069
1070 \end{code}
1071
1072
1073 Note the sneaky way _the_ result is represented by a list so that we
1074 can complain if it's used twice.
1075
1076 ToDo: Any chance of giving line numbers when process-casm fails?
1077       Or maybe we should do a check _much earlier_ in compiler. ADR
1078
1079 \begin{code}
1080 process_casm :: [SDoc]          -- results (length <= 1)
1081              -> [SDoc]          -- arguments
1082              -> String          -- format string (with embedded %'s)
1083              -> SDoc            -- code being generated
1084
1085 process_casm results args string = process results args string
1086  where
1087   process []    _ "" = empty
1088   process (_:_) _ "" = error ("process_casm: non-void result not assigned while processing _casm_ \"" ++ 
1089                               string ++ 
1090                               "\"\n(Try changing result type to IO ()\n")
1091
1092   process ress args ('%':cs)
1093     = case cs of
1094         [] ->
1095             error ("process_casm: lonely % while processing _casm_ \"" ++ string ++ "\".\n")
1096
1097         ('%':css) ->
1098             char '%' <> process ress args css
1099
1100         ('r':css)  ->
1101           case ress of
1102             []  -> error ("process_casm: no result to match %r while processing _casm_ \"" ++ string ++ "\".\nTry deleting %r or changing result type from PrimIO ()\n")
1103             [r] -> r <> (process [] args css)
1104             _   -> panic ("process_casm: casm with many results while processing _casm_ \"" ++ string ++ "\".\n")
1105
1106         other ->
1107           let
1108                 read_int :: ReadS Int
1109                 read_int = reads
1110           in
1111           case (read_int other) of
1112             [(num,css)] ->
1113                   if num >= 0 && args `lengthExceeds` num
1114                   then parens (args !! num) <> process ress args css
1115                   else error ("process_casm: no such arg #:"++(show num)++" while processing \"" ++ string ++ "\".\n")
1116             _ -> error ("process_casm: not %<num> while processing _casm_ \"" ++ string ++ "\".\n")
1117
1118   process ress args (other_c:cs)
1119     = char other_c <> process ress args cs
1120 \end{code}
1121
1122 %************************************************************************
1123 %*                                                                      *
1124 \subsection[a2r-assignments]{Assignments}
1125 %*                                                                      *
1126 %************************************************************************
1127
1128 Printing assignments is a little tricky because of type coercion.
1129
1130 First of all, the kind of the thing being assigned can be gotten from
1131 the destination addressing mode.  (It should be the same as the kind
1132 of the source addressing mode.)  If the kind of the assignment is of
1133 @VoidRep@, then don't generate any code at all.
1134
1135 \begin{code}
1136 pprAssign :: PrimRep -> CAddrMode -> CAddrMode -> SDoc
1137
1138 pprAssign VoidRep dest src = empty
1139 \end{code}
1140
1141 Special treatment for floats and doubles, to avoid unwanted conversions.
1142
1143 \begin{code}
1144 pprAssign FloatRep dest@(CVal reg_rel _) src
1145   = hcat [ ptext SLIT("ASSIGN_FLT((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1146
1147 pprAssign DoubleRep dest@(CVal reg_rel _) src
1148   = hcat [ ptext SLIT("ASSIGN_DBL((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1149
1150 pprAssign Int64Rep dest@(CVal reg_rel _) src
1151   = hcat [ ptext SLIT("ASSIGN_Int64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1152 pprAssign Word64Rep dest@(CVal reg_rel _) src
1153   = hcat [ ptext SLIT("ASSIGN_Word64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1154 \end{code}
1155
1156 Lastly, the question is: will the C compiler think the types of the
1157 two sides of the assignment match?
1158
1159         We assume that the types will match if neither side is a
1160         @CVal@ addressing mode for any register which can point into
1161         the heap or stack.
1162
1163 Why?  Because the heap and stack are used to store miscellaneous
1164 things, whereas the temporaries, registers, etc., are only used for
1165 things of fixed type.
1166
1167 \begin{code}
1168 pprAssign kind (CReg (VanillaReg _ dest)) (CReg (VanillaReg _ src))
1169   = hcat [ pprVanillaReg dest, equals,
1170                 pprVanillaReg src, semi ]
1171
1172 pprAssign kind dest src
1173   | mixedTypeLocn dest
1174     -- Add in a cast to StgWord (a.k.a. W_) iff the destination is mixed
1175   = hcat [ ppr_amode dest, equals,
1176                 text "(W_)(",   -- Here is the cast
1177                 ppr_amode src, pp_paren_semi ]
1178
1179 pprAssign kind dest src
1180   | mixedPtrLocn dest && getAmodeRep src /= PtrRep
1181     -- Add in a cast to StgPtr (a.k.a. P_) iff the destination is mixed
1182   = hcat [ ppr_amode dest, equals,
1183                 text "(P_)(",   -- Here is the cast
1184                 ppr_amode src, pp_paren_semi ]
1185
1186 pprAssign kind other_dest src
1187   = hcat [ ppr_amode other_dest, equals,
1188                 pprAmode  src, semi ]
1189 \end{code}
1190
1191
1192 %************************************************************************
1193 %*                                                                      *
1194 \subsection[a2r-CAddrModes]{Addressing modes}
1195 %*                                                                      *
1196 %************************************************************************
1197
1198 @pprAmode@ is used to print r-values (which may need casts), whereas
1199 @ppr_amode@ is used for l-values {\em and} as a help function for
1200 @pprAmode@.
1201
1202 \begin{code}
1203 pprAmode, ppr_amode :: CAddrMode -> SDoc
1204 \end{code}
1205
1206 For reasons discussed above under assignments, @CVal@ modes need
1207 to be treated carefully.  First come special cases for floats and doubles,
1208 similar to those in @pprAssign@:
1209
1210 (NB: @PK_FLT@ and @PK_DBL@ require the {\em address} of the value in
1211 question.)
1212
1213 \begin{code}
1214 pprAmode (CVal reg_rel FloatRep)
1215   = hcat [ text "PK_FLT((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1216 pprAmode (CVal reg_rel DoubleRep)
1217   = hcat [ text "PK_DBL((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1218 pprAmode (CVal reg_rel Int64Rep)
1219   = hcat [ text "PK_Int64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1220 pprAmode (CVal reg_rel Word64Rep)
1221   = hcat [ text "PK_Word64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1222 \end{code}
1223
1224 Next comes the case where there is some other cast need, and the
1225 no-cast case:
1226
1227 \begin{code}
1228 pprAmode amode
1229   | mixedTypeLocn amode
1230   = parens (hcat [ pprPrimKind (getAmodeRep amode), ptext SLIT(")("),
1231                 ppr_amode amode ])
1232   | otherwise   -- No cast needed
1233   = ppr_amode amode
1234 \end{code}
1235
1236 When we have an indirection through a CIndex, we have to be careful to
1237 get the type casts right.  
1238
1239 this amode:
1240
1241         CVal (CIndex kind1 base offset) kind2
1242
1243 means (in C speak): 
1244         
1245         *(kind2 *)((kind1 *)base + offset)
1246
1247 That is, the indexing is done in units of kind1, but the resulting
1248 amode has kind2.
1249
1250 \begin{code}
1251 ppr_amode (CVal reg_rel@(CIndex _ _ _) kind)
1252   = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1253         (pp_reg, Nothing)     -> panic "ppr_amode: CIndex"
1254         (pp_reg, Just offset) -> 
1255            hcat [ char '*', parens (pprPrimKind kind <> char '*'),
1256                   parens (pp_reg <> char '+' <> offset) ]
1257 \end{code}
1258
1259 Now the rest of the cases for ``workhorse'' @ppr_amode@:
1260
1261 \begin{code}
1262 ppr_amode (CVal reg_rel _)
1263   = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1264         (pp_reg, Nothing)     -> (<>)  (char '*') pp_reg
1265         (pp_reg, Just offset) -> hcat [ pp_reg, brackets offset ]
1266
1267 ppr_amode (CAddr reg_rel)
1268   = case (pprRegRelative True{-sign wanted-} reg_rel) of
1269         (pp_reg, Nothing)     -> pp_reg
1270         (pp_reg, Just offset) -> pp_reg <> offset
1271
1272 ppr_amode (CReg magic_id) = pprMagicId magic_id
1273
1274 ppr_amode (CTemp uniq kind) = char '_' <> pprUnique uniq <> char '_'
1275
1276 ppr_amode (CLbl lbl kind) = pprCLabelAddr lbl 
1277
1278 ppr_amode (CCharLike ch)
1279   = hcat [ptext SLIT("CHARLIKE_CLOSURE"), char '(', pprAmode ch, rparen ]
1280 ppr_amode (CIntLike int)
1281   = hcat [ptext SLIT("INTLIKE_CLOSURE"), char '(', pprAmode int, rparen ]
1282
1283 ppr_amode (CLit lit) = pprBasicLit lit
1284
1285 ppr_amode (CJoinPoint _)
1286   = panic "ppr_amode: CJoinPoint"
1287
1288 ppr_amode (CMacroExpr pk macro as)
1289   = parens (ptext (cExprMacroText macro) <> 
1290             parens (hcat (punctuate comma (map pprAmode as))))
1291 \end{code}
1292
1293 \begin{code}
1294 cExprMacroText ENTRY_CODE               = SLIT("ENTRY_CODE")
1295 cExprMacroText ARG_TAG                  = SLIT("ARG_TAG")
1296 cExprMacroText GET_TAG                  = SLIT("GET_TAG")
1297 cExprMacroText UPD_FRAME_UPDATEE        = SLIT("UPD_FRAME_UPDATEE")
1298 cExprMacroText CCS_HDR                  = SLIT("CCS_HDR")
1299 cExprMacroText BYTE_ARR_CTS             = SLIT("BYTE_ARR_CTS")
1300 cExprMacroText PTRS_ARR_CTS             = SLIT("PTRS_ARR_CTS")
1301 cExprMacroText ForeignObj_CLOSURE_DATA  = SLIT("ForeignObj_CLOSURE_DATA")
1302
1303 cStmtMacroText UPD_CAF                  = SLIT("UPD_CAF")
1304 cStmtMacroText UPD_BH_UPDATABLE         = SLIT("UPD_BH_UPDATABLE")
1305 cStmtMacroText UPD_BH_SINGLE_ENTRY      = SLIT("UPD_BH_SINGLE_ENTRY")
1306 cStmtMacroText PUSH_UPD_FRAME           = SLIT("PUSH_UPD_FRAME")
1307 cStmtMacroText SET_TAG                  = SLIT("SET_TAG")
1308 cStmtMacroText DATA_TO_TAGZH            = SLIT("dataToTagzh")
1309 cStmtMacroText AWAKEN_BQ_CLOSURE        = SLIT("AWAKEN_BQ_CLOSURE")
1310 cStmtMacroText REGISTER_FOREIGN_EXPORT  = SLIT("REGISTER_FOREIGN_EXPORT")
1311 cStmtMacroText REGISTER_IMPORT          = SLIT("REGISTER_IMPORT")
1312 cStmtMacroText REGISTER_DIMPORT         = SLIT("REGISTER_DIMPORT")
1313 cStmtMacroText GRAN_FETCH               = SLIT("GRAN_FETCH")
1314 cStmtMacroText GRAN_RESCHEDULE          = SLIT("GRAN_RESCHEDULE")
1315 cStmtMacroText GRAN_FETCH_AND_RESCHEDULE= SLIT("GRAN_FETCH_AND_RESCHEDULE")
1316 cStmtMacroText THREAD_CONTEXT_SWITCH    = SLIT("THREAD_CONTEXT_SWITCH")
1317 cStmtMacroText GRAN_YIELD               = SLIT("GRAN_YIELD")
1318
1319 cCheckMacroText HP_CHK_NP               = SLIT("HP_CHK_NP")
1320 cCheckMacroText STK_CHK_NP              = SLIT("STK_CHK_NP")
1321 cCheckMacroText HP_STK_CHK_NP           = SLIT("HP_STK_CHK_NP")
1322 cCheckMacroText HP_CHK_FUN              = SLIT("HP_CHK_FUN")
1323 cCheckMacroText STK_CHK_FUN             = SLIT("STK_CHK_FUN")
1324 cCheckMacroText HP_STK_CHK_FUN          = SLIT("HP_STK_CHK_FUN")
1325 cCheckMacroText HP_CHK_NOREGS           = SLIT("HP_CHK_NOREGS")
1326 cCheckMacroText HP_CHK_UNPT_R1          = SLIT("HP_CHK_UNPT_R1")
1327 cCheckMacroText HP_CHK_UNBX_R1          = SLIT("HP_CHK_UNBX_R1")
1328 cCheckMacroText HP_CHK_F1               = SLIT("HP_CHK_F1")
1329 cCheckMacroText HP_CHK_D1               = SLIT("HP_CHK_D1")
1330 cCheckMacroText HP_CHK_L1               = SLIT("HP_CHK_L1")
1331 cCheckMacroText HP_CHK_UNBX_TUPLE       = SLIT("HP_CHK_UNBX_TUPLE")
1332 \end{code}
1333
1334 %************************************************************************
1335 %*                                                                      *
1336 \subsection[ppr-liveness-masks]{Liveness Masks}
1337 %*                                                                      *
1338 %************************************************************************
1339
1340 \begin{code}
1341 bitmapAddrModes [] = [mkWordCLit 0]
1342 bitmapAddrModes xs = map mkWordCLit xs
1343 \end{code}
1344
1345 %************************************************************************
1346 %*                                                                      *
1347 \subsection[a2r-MagicIds]{Magic ids}
1348 %*                                                                      *
1349 %************************************************************************
1350
1351 @pprRegRelative@ returns a pair of the @Doc@ for the register
1352 (some casting may be required), and a @Maybe Doc@ for the offset
1353 (zero offset gives a @Nothing@).
1354
1355 \begin{code}
1356 addPlusSign :: Bool -> SDoc -> SDoc
1357 addPlusSign False p = p
1358 addPlusSign True  p = (<>) (char '+') p
1359
1360 pprSignedInt :: Bool -> Int -> Maybe SDoc       -- Nothing => 0
1361 pprSignedInt sign_wanted n
1362  = if n == 0 then Nothing else
1363    if n > 0  then Just (addPlusSign sign_wanted (int n))
1364    else           Just (int n)
1365
1366 pprRegRelative :: Bool          -- True <=> Print leading plus sign (if +ve)
1367                -> RegRelative
1368                -> (SDoc, Maybe SDoc)
1369
1370 pprRegRelative sign_wanted (SpRel off)
1371   = (pprMagicId Sp, pprSignedInt sign_wanted (I# off))
1372
1373 pprRegRelative sign_wanted r@(HpRel o)
1374   = let pp_Hp    = pprMagicId Hp; off = I# o
1375     in
1376     if off == 0 then
1377         (pp_Hp, Nothing)
1378     else
1379         (pp_Hp, Just ((<>) (char '-') (int off)))
1380
1381 pprRegRelative sign_wanted (NodeRel o)
1382   = let pp_Node = pprMagicId node; off = I# o
1383     in
1384     if off == 0 then
1385         (pp_Node, Nothing)
1386     else
1387         (pp_Node, Just (addPlusSign sign_wanted (int off)))
1388
1389 pprRegRelative sign_wanted (CIndex base offset kind)
1390   = ( hcat [text "((", pprPrimKind kind, text " *)(", ppr_amode base, text "))"]
1391     , Just (hcat [if sign_wanted then char '+' else empty,
1392             text "(I_)(", ppr_amode offset, ptext SLIT(")")])
1393     )
1394 \end{code}
1395
1396 @pprMagicId@ just prints the register name.  @VanillaReg@ registers are
1397 represented by a discriminated union (@StgUnion@), so we use the @PrimRep@
1398 to select the union tag.
1399
1400 \begin{code}
1401 pprMagicId :: MagicId -> SDoc
1402
1403 pprMagicId BaseReg                  = ptext SLIT("BaseReg")
1404 pprMagicId (VanillaReg pk n)
1405                                     = hcat [ pprVanillaReg n, char '.',
1406                                                   pprUnionTag pk ]
1407 pprMagicId (FloatReg  n)            = ptext SLIT("F") <> int (I# n)
1408 pprMagicId (DoubleReg n)            = ptext SLIT("D") <> int (I# n)
1409 pprMagicId (LongReg _ n)            = ptext SLIT("L") <> int (I# n)
1410 pprMagicId Sp                       = ptext SLIT("Sp")
1411 pprMagicId SpLim                    = ptext SLIT("SpLim")
1412 pprMagicId Hp                       = ptext SLIT("Hp")
1413 pprMagicId HpLim                    = ptext SLIT("HpLim")
1414 pprMagicId CurCostCentre            = ptext SLIT("CCCS")
1415 pprMagicId VoidReg                  = ptext SLIT("VoidReg")
1416
1417 pprVanillaReg :: Int# -> SDoc
1418 pprVanillaReg n = char 'R' <> int (I# n)
1419
1420 pprUnionTag :: PrimRep -> SDoc
1421
1422 pprUnionTag PtrRep              = char 'p'
1423 pprUnionTag CodePtrRep          = ptext SLIT("fp")
1424 pprUnionTag DataPtrRep          = char 'd'
1425 pprUnionTag RetRep              = char 'p'
1426 pprUnionTag CostCentreRep       = panic "pprUnionTag:CostCentre?"
1427
1428 pprUnionTag CharRep             = char 'c'
1429 pprUnionTag Int8Rep             = ptext SLIT("i8")
1430 pprUnionTag IntRep              = char 'i'
1431 pprUnionTag WordRep             = char 'w'
1432 pprUnionTag Int32Rep            = char 'i'
1433 pprUnionTag Word32Rep           = char 'w'
1434 pprUnionTag AddrRep             = char 'a'
1435 pprUnionTag FloatRep            = char 'f'
1436 pprUnionTag DoubleRep           = panic "pprUnionTag:Double?"
1437
1438 pprUnionTag StablePtrRep        = char 'p'
1439
1440 pprUnionTag _                   = panic "pprUnionTag:Odd kind"
1441 \end{code}
1442
1443
1444 Find and print local and external declarations for a list of
1445 Abstract~C statements.
1446 \begin{code}
1447 pprTempAndExternDecls :: AbstractC -> (SDoc{-temps-}, SDoc{-externs-})
1448 pprTempAndExternDecls AbsCNop = (empty, empty)
1449
1450 pprTempAndExternDecls (AbsCStmts stmt1 stmt2)
1451   = initTE (ppr_decls_AbsC stmt1        `thenTE` \ (t_p1, e_p1) ->
1452             ppr_decls_AbsC stmt2        `thenTE` \ (t_p2, e_p2) ->
1453             case (catMaybes [t_p1, t_p2])        of { real_temps ->
1454             case (catMaybes [e_p1, e_p2])        of { real_exts ->
1455             returnTE (vcat real_temps, vcat real_exts) }}
1456            )
1457
1458 pprTempAndExternDecls other_stmt
1459   = initTE (ppr_decls_AbsC other_stmt `thenTE` \ (maybe_t, maybe_e) ->
1460             returnTE (
1461                 case maybe_t of
1462                   Nothing -> empty
1463                   Just pp -> pp,
1464
1465                 case maybe_e of
1466                   Nothing -> empty
1467                   Just pp -> pp )
1468            )
1469
1470 pprBasicLit :: Literal -> SDoc
1471 pprPrimKind :: PrimRep -> SDoc
1472
1473 pprBasicLit  lit = ppr lit
1474 pprPrimKind  k   = ppr k
1475 \end{code}
1476
1477
1478 %************************************************************************
1479 %*                                                                      *
1480 \subsection[a2r-monad]{Monadery}
1481 %*                                                                      *
1482 %************************************************************************
1483
1484 We need some monadery to keep track of temps and externs we have already
1485 printed.  This info must be threaded right through the Abstract~C, so
1486 it's most convenient to hide it in this monad.
1487
1488 WDP 95/02: Switched from \tr{([Unique], [CLabel])} to
1489 \tr{(UniqSet, CLabelSet)}.  Allegedly for efficiency.
1490
1491 \begin{code}
1492 type CLabelSet = FiniteMap CLabel (){-any type will do-}
1493 emptyCLabelSet = emptyFM
1494 x `elementOfCLabelSet` labs
1495   = case (lookupFM labs x) of { Just _ -> True; Nothing -> False }
1496
1497 addToCLabelSet set x = addToFM set x ()
1498
1499 type TEenv = (UniqSet Unique, CLabelSet)
1500
1501 type TeM result =  TEenv -> (TEenv, result)
1502
1503 initTE :: TeM a -> a
1504 initTE sa
1505   = case sa (emptyUniqSet, emptyCLabelSet) of { (_, result) ->
1506     result }
1507
1508 {-# INLINE thenTE #-}
1509 {-# INLINE returnTE #-}
1510
1511 thenTE :: TeM a -> (a -> TeM b) -> TeM b
1512 thenTE a b u
1513   = case a u        of { (u_1, result_of_a) ->
1514     b result_of_a u_1 }
1515
1516 mapTE :: (a -> TeM b) -> [a] -> TeM [b]
1517 mapTE f []     = returnTE []
1518 mapTE f (x:xs)
1519   = f x         `thenTE` \ r  ->
1520     mapTE f xs  `thenTE` \ rs ->
1521     returnTE (r : rs)
1522
1523 returnTE :: a -> TeM a
1524 returnTE result env = (env, result)
1525
1526 -- these next two check whether the thing is already
1527 -- recorded, and THEN THEY RECORD IT
1528 -- (subsequent calls will return False for the same uniq/label)
1529
1530 tempSeenTE :: Unique -> TeM Bool
1531 tempSeenTE uniq env@(seen_uniqs, seen_labels)
1532   = if (uniq `elementOfUniqSet` seen_uniqs)
1533     then (env, True)
1534     else ((addOneToUniqSet seen_uniqs uniq,
1535           seen_labels),
1536           False)
1537
1538 labelSeenTE :: CLabel -> TeM Bool
1539 labelSeenTE lbl env@(seen_uniqs, seen_labels)
1540   = if (lbl `elementOfCLabelSet` seen_labels)
1541     then (env, True)
1542     else ((seen_uniqs,
1543           addToCLabelSet seen_labels lbl),
1544           False)
1545 \end{code}
1546
1547 \begin{code}
1548 pprTempDecl :: Unique -> PrimRep -> SDoc
1549 pprTempDecl uniq kind
1550   = hcat [ pprPrimKind kind, space, char '_', pprUnique uniq, ptext SLIT("_;") ]
1551
1552 pprExternDecl :: Bool -> CLabel -> SDoc
1553 pprExternDecl in_srt clabel
1554   | not (needsCDecl clabel) = empty -- do not print anything for "known external" things
1555   | otherwise               = 
1556         hcat [ ppLocalnessMacro (not in_srt) clabel, 
1557                lparen, dyn_wrapper (pprCLabel clabel), pp_paren_semi ]
1558  where
1559   dyn_wrapper d
1560     | in_srt && labelDynamic clabel = text "DLL_IMPORT_DATA_VAR" <> parens d
1561     | otherwise                     = d
1562
1563 \end{code}
1564
1565 \begin{code}
1566 ppr_decls_AbsC :: AbstractC -> TeM (Maybe SDoc{-temps-}, Maybe SDoc{-externs-})
1567
1568 ppr_decls_AbsC AbsCNop          = returnTE (Nothing, Nothing)
1569
1570 ppr_decls_AbsC (AbsCStmts stmts_1 stmts_2)
1571   = ppr_decls_AbsC stmts_1  `thenTE` \ p1 ->
1572     ppr_decls_AbsC stmts_2  `thenTE` \ p2 ->
1573     returnTE (maybe_vcat [p1, p2])
1574
1575 ppr_decls_AbsC (CSplitMarker) = returnTE (Nothing, Nothing)
1576
1577 ppr_decls_AbsC (CAssign dest source)
1578   = ppr_decls_Amode dest    `thenTE` \ p1 ->
1579     ppr_decls_Amode source  `thenTE` \ p2 ->
1580     returnTE (maybe_vcat [p1, p2])
1581
1582 ppr_decls_AbsC (CJump target) = ppr_decls_Amode target
1583
1584 ppr_decls_AbsC (CFallThrough target) = ppr_decls_Amode target
1585
1586 ppr_decls_AbsC (CReturn target _) = ppr_decls_Amode target
1587
1588 ppr_decls_AbsC (CSwitch discrim alts deflt)
1589   = ppr_decls_Amode discrim     `thenTE` \ pdisc ->
1590     mapTE ppr_alt_stuff alts    `thenTE` \ palts  ->
1591     ppr_decls_AbsC deflt        `thenTE` \ pdeflt ->
1592     returnTE (maybe_vcat (pdisc:pdeflt:palts))
1593   where
1594     ppr_alt_stuff (_, absC) = ppr_decls_AbsC absC
1595
1596 ppr_decls_AbsC (CCodeBlock lbl absC)
1597   = ppr_decls_AbsC absC
1598
1599 ppr_decls_AbsC (CInitHdr cl_info reg_rel cost_centre _)
1600         -- ToDo: strictly speaking, should chk "cost_centre" amode
1601   = labelSeenTE info_lbl     `thenTE` \  label_seen ->
1602     returnTE (Nothing,
1603               if label_seen then
1604                   Nothing
1605               else
1606                   Just (pprExternDecl False{-not in an SRT decl-} info_lbl))
1607   where
1608     info_lbl = infoTableLabelFromCI cl_info
1609
1610 ppr_decls_AbsC (CMachOpStmt res _ args _) = ppr_decls_Amodes (res : args)
1611 ppr_decls_AbsC (COpStmt results _ args _) = ppr_decls_Amodes (results ++ args)
1612
1613 ppr_decls_AbsC (CSimultaneous abc)        = ppr_decls_AbsC abc
1614
1615 ppr_decls_AbsC (CSequential abcs) 
1616   = mapTE ppr_decls_AbsC abcs   `thenTE` \ t_and_e_s ->
1617     returnTE (maybe_vcat t_and_e_s)
1618
1619 ppr_decls_AbsC (CCheck              _ amodes code) = 
1620      ppr_decls_Amodes amodes `thenTE` \p1 ->
1621      ppr_decls_AbsC code     `thenTE` \p2 ->
1622      returnTE (maybe_vcat [p1,p2])
1623
1624 ppr_decls_AbsC (CMacroStmt          _ amodes)   = ppr_decls_Amodes amodes
1625
1626 ppr_decls_AbsC (CCallProfCtrMacro   _ amodes)   = ppr_decls_Amodes [] -- *****!!!
1627   -- you get some nasty re-decls of stdio.h if you compile
1628   -- the prelude while looking inside those amodes;
1629   -- no real reason to, anyway.
1630 ppr_decls_AbsC (CCallProfCCMacro    _ amodes)   = ppr_decls_Amodes amodes
1631
1632 ppr_decls_AbsC (CStaticClosure _ closure_info cost_centre amodes)
1633         -- ToDo: strictly speaking, should chk "cost_centre" amode
1634   = ppr_decls_Amodes amodes
1635
1636 ppr_decls_AbsC (CClosureInfoAndCode cl_info entry)
1637   = ppr_decls_Amodes [entry_lbl]                `thenTE` \ p1 ->
1638     ppr_decls_AbsC entry                        `thenTE` \ p2 ->
1639     returnTE (maybe_vcat [p1, p2])
1640   where
1641     entry_lbl = CLbl (entryLabelFromCI cl_info) CodePtrRep
1642
1643 ppr_decls_AbsC (CSRT _ closure_lbls)
1644   = mapTE labelSeenTE closure_lbls              `thenTE` \ seen ->
1645     returnTE (Nothing, 
1646               if and seen then Nothing
1647                 else Just (vcat [ pprExternDecl True{-in SRT decl-} l
1648                                 | (l,False) <- zip closure_lbls seen ]))
1649
1650 ppr_decls_AbsC (CRetDirect     _ code _ _)   = ppr_decls_AbsC code
1651 ppr_decls_AbsC (CRetVector _ amodes _ _)     = ppr_decls_Amodes amodes
1652 ppr_decls_AbsC (CModuleInitBlock _ _ code)   = ppr_decls_AbsC code
1653
1654 ppr_decls_AbsC (_) = returnTE (Nothing, Nothing)
1655 \end{code}
1656
1657 \begin{code}
1658 ppr_decls_Amode :: CAddrMode -> TeM (Maybe SDoc, Maybe SDoc)
1659 ppr_decls_Amode (CVal  (CIndex base offset _) _) = ppr_decls_Amodes [base,offset]
1660 ppr_decls_Amode (CAddr (CIndex base offset _))   = ppr_decls_Amodes [base,offset]
1661 ppr_decls_Amode (CVal _ _)      = returnTE (Nothing, Nothing)
1662 ppr_decls_Amode (CAddr _)       = returnTE (Nothing, Nothing)
1663 ppr_decls_Amode (CReg _)        = returnTE (Nothing, Nothing)
1664 ppr_decls_Amode (CLit _)        = returnTE (Nothing, Nothing)
1665
1666 -- CIntLike must be a literal -- no decls
1667 ppr_decls_Amode (CIntLike int)  = returnTE (Nothing, Nothing)
1668
1669 -- CCharLike too
1670 ppr_decls_Amode (CCharLike char) = returnTE (Nothing, Nothing)
1671
1672 -- now, the only place where we actually print temps/externs...
1673 ppr_decls_Amode (CTemp uniq kind)
1674   = case kind of
1675       VoidRep -> returnTE (Nothing, Nothing)
1676       other ->
1677         tempSeenTE uniq `thenTE` \ temp_seen ->
1678         returnTE
1679           (if temp_seen then Nothing else Just (pprTempDecl uniq kind), Nothing)
1680
1681 ppr_decls_Amode (CLbl lbl VoidRep)
1682   = returnTE (Nothing, Nothing)
1683
1684 ppr_decls_Amode (CLbl lbl kind)
1685   = labelSeenTE lbl `thenTE` \ label_seen ->
1686     returnTE (Nothing,
1687               if label_seen then Nothing else Just (pprExternDecl False{-not in an SRT decl-} lbl))
1688
1689 ppr_decls_Amode (CMacroExpr _ _ amodes)
1690   = ppr_decls_Amodes amodes
1691
1692 ppr_decls_Amode other = returnTE (Nothing, Nothing)
1693
1694
1695 maybe_vcat :: [(Maybe SDoc, Maybe SDoc)] -> (Maybe SDoc, Maybe SDoc)
1696 maybe_vcat ps
1697   = case (unzip ps)     of { (ts, es) ->
1698     case (catMaybes ts) of { real_ts  ->
1699     case (catMaybes es) of { real_es  ->
1700     (if (null real_ts) then Nothing else Just (vcat real_ts),
1701      if (null real_es) then Nothing else Just (vcat real_es))
1702     } } }
1703 \end{code}
1704
1705 \begin{code}
1706 ppr_decls_Amodes :: [CAddrMode] -> TeM (Maybe SDoc, Maybe SDoc)
1707 ppr_decls_Amodes amodes
1708   = mapTE ppr_decls_Amode amodes `thenTE` \ ps ->
1709     returnTE ( maybe_vcat ps )
1710 \end{code}
1711
1712 Print out a C Label where you want the *address* of the label, not the
1713 object it refers to.  The distinction is important when the label may
1714 refer to a C structure (info tables and closures, for instance).
1715
1716 When just generating a declaration for the label, use pprCLabel.
1717
1718 \begin{code}
1719 pprCLabelAddr :: CLabel -> SDoc
1720 pprCLabelAddr clabel =
1721   case labelType clabel of
1722      InfoTblType    -> addr_of_label
1723      RetInfoTblType -> addr_of_label
1724      ClosureType    -> addr_of_label
1725      VecTblType     -> addr_of_label
1726      DataType       -> addr_of_label
1727
1728      _              -> pp_label
1729   where
1730     addr_of_label = ptext SLIT("(P_)&") <> pp_label
1731     pp_label = pprCLabel clabel
1732 \end{code}
1733
1734 -----------------------------------------------------------------------------
1735 Initialising static objects with floating-point numbers.  We can't
1736 just emit the floating point number, because C will cast it to an int
1737 by rounding it.  We want the actual bit-representation of the float.
1738
1739 This is a hack to turn the floating point numbers into ints that we
1740 can safely initialise to static locations.
1741
1742 \begin{code}
1743 big_doubles = (getPrimRepSize DoubleRep) /= 1
1744
1745 #if __GLASGOW_HASKELL__ >= 504
1746 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
1747 newFloatArray = newArray_
1748
1749 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
1750 newDoubleArray = newArray_
1751
1752 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
1753 castFloatToIntArray = castSTUArray
1754
1755 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
1756 castDoubleToIntArray = castSTUArray
1757
1758 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
1759 writeFloatArray = writeArray
1760
1761 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
1762 writeDoubleArray = writeArray
1763
1764 readIntArray :: STUArray s Int Int -> Int -> ST s Int
1765 readIntArray = readArray
1766
1767 #else
1768
1769 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
1770 castFloatToIntArray = return
1771
1772 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
1773 castDoubleToIntArray = return
1774
1775 #endif
1776
1777 -- floats are always 1 word
1778 floatToWord :: CAddrMode -> CAddrMode
1779 floatToWord (CLit (MachFloat r))
1780   = runST (do
1781         arr <- newFloatArray ((0::Int),0)
1782         writeFloatArray arr 0 (fromRational r)
1783         arr' <- castFloatToIntArray arr
1784         i <- readIntArray arr' 0
1785         return (CLit (MachInt (toInteger i)))
1786     )
1787
1788 doubleToWords :: CAddrMode -> [CAddrMode]
1789 doubleToWords (CLit (MachDouble r))
1790   | big_doubles                         -- doubles are 2 words
1791   = runST (do
1792         arr <- newDoubleArray ((0::Int),1)
1793         writeDoubleArray arr 0 (fromRational r)
1794         arr' <- castDoubleToIntArray arr
1795         i1 <- readIntArray arr' 0
1796         i2 <- readIntArray arr' 1
1797         return [ CLit (MachInt (toInteger i1))
1798                , CLit (MachInt (toInteger i2))
1799                ]
1800     )
1801   | otherwise                           -- doubles are 1 word
1802   = runST (do
1803         arr <- newDoubleArray ((0::Int),0)
1804         writeDoubleArray arr 0 (fromRational r)
1805         arr' <- castDoubleToIntArray arr
1806         i <- readIntArray arr' 0
1807         return [ CLit (MachInt (toInteger i)) ]
1808     )
1809 \end{code}