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