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