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