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