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