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