2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %************************************************************************
6 \section[PprAbsC]{Pretty-printing Abstract~C}
8 %************************************************************************
18 #include "HsVersions.h"
24 import AbsCUtils ( getAmodeRep, nonemptyAbsC,
25 mixedPtrLocn, mixedTypeLocn
28 import Constants ( mIN_UPD_SIZE )
29 import CallConv ( callConvAttribute )
30 import CLabel ( externallyVisibleCLabel,
31 needsCDecl, pprCLabel,
32 mkReturnInfoLabel, mkReturnPtLabel, mkClosureTblLabel,
33 mkClosureLabel, mkErrorStdEntryLabel,
34 CLabel, CLabelType(..), labelType, labelDynamic
37 import CmdLineOpts ( opt_SccProfilingOn, opt_GranMacros )
38 import CostCentre ( pprCostCentreDecl, pprCostCentreStackDecl )
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 ( DataCon{-instance NamedThing-}, dataConWrapId )
47 import Maybes ( maybeToBool, catMaybes )
48 import PrimOp ( primOpNeedsWrapper, pprPrimOp, pprCCallOp,
49 PrimOp(..), CCall(..), CCallTarget(..), isDynamicTarget )
50 import PrimRep ( isFloatingRep, PrimRep(..), getPrimRepSize, showPrimRep )
51 import SMRep ( pprSMRep )
52 import Unique ( pprUnique, Unique{-instance NamedThing-} )
53 import UniqSet ( emptyUniqSet, elementOfUniqSet,
54 addOneToUniqSet, UniqSet
56 import StgSyn ( SRT(..) )
57 import BitSet ( intBS )
60 import Util ( nOfThem )
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
75 writeRealC :: Handle -> AbstractC -> IO ()
76 writeRealC handle absC
77 -- avoid holding on to the whole of absC in the !Gransim case.
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)
86 writeRealC :: Handle -> AbstractC -> IO ()
87 --writeRealC handle absC =
89 -- printDoc LeftMode handle (pprAbsC absC (costs absC))
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"))
97 dumpRealC :: AbstractC -> SDoc
99 | opt_GranMacros = pprCode CStyle (pprAbsC absC (costs absC))
100 | otherwise = pprCode CStyle (pprAbsC absC (panic "costs"))
104 This emits the macro, which is used in GrAnSim to compute the total costs
105 from a cost 5 tuple. %% HWL
108 emitMacro :: CostRes -> SDoc
110 emitMacro _ | not opt_GranMacros = empty
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 ]
117 pp_paren_semi = text ");"
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
125 pprAbsC :: AbstractC -> CostRes -> SDoc
126 pprAbsC AbsCNop _ = empty
127 pprAbsC (AbsCStmts s1 s2) c = ($$) (pprAbsC s1 c) (pprAbsC s2 c)
129 pprAbsC (CAssign dest src) _ = pprAssign (getAmodeRep dest) dest src
131 pprAbsC (CJump target) c
132 = ($$) (hcat [emitMacro c {-WDP:, text "/* <--++ CJump */"-} ])
133 (hcat [ text jmp_lit, pprAmode target, pp_paren_semi ])
135 pprAbsC (CFallThrough target) c
136 = ($$) (hcat [emitMacro c {-WDP:, text "/* <--++ CFallThrough */"-} ])
137 (hcat [ text jmp_lit, pprAmode target, pp_paren_semi ])
139 -- --------------------------------------------------------------------------
140 -- Spit out GRAN_EXEC macro immediately before the return HWL
142 pprAbsC (CReturn am return_info) c
143 = ($$) (hcat [emitMacro c {-WDP:, text "/* <---- CReturn */"-} ])
144 (hcat [text jmp_lit, target, pp_paren_semi ])
146 target = case return_info of
147 DirectReturn -> hcat [ptext SLIT("ENTRY_CODE"), lparen,
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,
154 pprAbsC (CSplitMarker) _ = ptext SLIT("__STG_SPLIT_MARKER")
156 -- we optimise various degenerate cases of CSwitches.
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
164 -- --------------------------------------------------------------------------
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
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
176 Just dc -> -- make it an "if"
177 do_if_stmt discrim tag alt_code dc c
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))
184 do_if_stmt discrim tag1 alt_code1 alt_code2 c
186 do_if_stmt discrim tag2 alt_code2 alt_code1 c
188 empty_deflt = not (maybeToBool (nonemptyAbsC deflt))
190 pprAbsC (CSwitch discrim alts deflt) c -- general case
191 | isFloatingRep (getAmodeRep discrim)
192 = pprAbsC (foldr ( \ a -> CSwitch discrim [a]) deflt alts) c
195 hcat [text "switch (", pp_discrim, text ") {"],
196 nest 2 (vcat (map ppr_alt alts)),
197 (case (nonemptyAbsC deflt) of
200 nest 2 (vcat [ptext SLIT("default:"),
201 pprAbsC dc (c + switch_head_cost
203 ptext SLIT("break;")])),
210 = vcat [ hcat [ptext SLIT("case "), pprBasicLit lit, char ':'],
211 nest 2 (($$) (pprAbsC absC (c + switch_head_cost + costs absC))
212 (ptext SLIT("break;"))) ]
214 -- Costs for addressing header of switch and cond. branching -- HWL
215 switch_head_cost = addrModeCosts discrim Rhs + (Cost (0, 1, 0, 0, 0))
217 pprAbsC stmt@(COpStmt results (CCallOp ccall) args vol_regs) _
218 = pprCCall ccall args results vol_regs
220 pprAbsC stmt@(COpStmt results op args vol_regs) _
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
229 the_op = ppr_op_call non_void_results non_void_args
230 -- liveness mask is *in* the non_void_args
232 if primOpNeedsWrapper op then
233 case (ppr_vol_regs vol_regs) of { (pp_saves, pp_restores) ->
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)),
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...
253 pprAbsC stmt@(CSRT lbl closures) c
254 = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
256 $$ ptext SLIT("SRT") <> lparen <> pprCLabel lbl <> rparen
257 $$ nest 2 (hcat (punctuate comma (map pp_closure_lbl closures)))
261 pprAbsC stmt@(CBitmap lbl mask) c
263 hcat [ ptext SLIT("BITMAP"), lparen,
264 pprCLabel lbl, comma,
267 hcat (punctuate comma (map (int.intBS) mask)),
271 pprAbsC (CSimultaneous abs_c) c
272 = hcat [ptext SLIT("{{"), pprAbsC abs_c c, ptext SLIT("}}")]
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
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"))
292 , parens (hsep (punctuate comma ccall_decl_ty_args))
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:
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.
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.
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
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.
320 ToDo: petition the gcc folks to add code to warn about conflicting attribute
326 | is_tdef = parens (text (callConvAttribute cconv) <+> char '*' <> ccall_fun_ty)
327 | otherwise = text (callConvAttribute cconv) <+> ccall_fun_ty
331 DynamicTarget u -> ptext SLIT("_ccall_fun_ty") <> ppr u
332 StaticTarget x -> pprCLabelString x
335 case non_void_results of
336 [] -> ptext SLIT("void")
337 [amode] -> text (showPrimRep (getAmodeRep amode))
338 _ -> panic "pprAbsC{CCallTypedef}: ccall_res_ty"
341 | is_tdef = tail ccall_arg_tys
342 | otherwise = ccall_arg_tys
344 ccall_arg_tys = map (text.showPrimRep.getAmodeRep) non_void_args
346 -- the first argument will be the "I/O world" token (a VoidRep)
347 -- all others should be non-void
350 in ASSERT (all non_void nvas) nvas
352 -- there will usually be two results: a (void) state which we
353 -- should ignore and a (possibly void) result.
355 let nvrs = grab_non_void_amodes results
356 in ASSERT (length nvrs <= 1) nvrs
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
362 case (pprTempAndExternDecls abs_C) of { (pp_temps, pp_exts) ->
366 hcat [text (if (externallyVisibleCLabel lbl)
367 then "FN_(" -- abbreviations to save on output
369 pprCLabel lbl, text ") {"],
373 nest 8 (ptext SLIT("FB_")),
374 nest 8 (pprAbsC abs_C (costs abs_C)),
375 nest 8 (ptext SLIT("FE_")),
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),
388 info_lbl = infoTableLabelFromCI cl_info
390 pprAbsC stmt@(CStaticClosure closure_lbl cl_info cost_centre amodes) _
391 = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
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,
403 nest 2 (ppr_payload (amodes ++ padding_wds ++ static_link_field)),
407 info_lbl = infoTableLabelFromCI cl_info
409 ppr_payload [] = empty
410 ppr_payload ls = comma <+>
411 braces (hsep (punctuate comma (map ((text "(L_)" <>).ppr_item) ls)))
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
420 rep = getAmodeRep item
423 if not (closureUpdReqd cl_info) then
426 case max 0 (mIN_UPD_SIZE - length amodes) of { still_needed ->
427 nOfThem still_needed (mkIntCLit 0) } -- a bunch of 0s
430 | staticClosureNeedsLink cl_info = [mkIntCLit 0]
433 pprAbsC stmt@(CClosureInfoAndCode cl_info slow maybe_fast cl_descr) _
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
443 else empty ), char '(',
445 pprCLabel info_lbl, comma,
446 pprCLabel slow_lbl, comma,
447 pp_rest, {- ptrs,nptrs,[srt,]type,-} comma,
449 ppLocalness info_lbl, comma,
450 ppLocalnessMacro True{-include dyn-} slow_lbl, comma,
452 if_profiling pp_descr, comma,
453 if_profiling pp_type,
459 Just fast -> let stuff = CCodeBlock fast_lbl fast in
460 pprAbsC stuff (costs stuff)
463 info_lbl = infoTableLabelFromCI cl_info
464 fast_lbl = fastLabelFromCI cl_info
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))
473 maybe_selector = maybeSelectorInfo cl_info
474 is_selector = maybeToBool maybe_selector
475 (Just select_word_i) = maybe_selector
477 maybe_tag = closureSemiTag cl_info
478 is_constr = maybeToBool maybe_tag
479 (Just tag) = maybe_tag
481 needs_srt = infoTblNeedsSRT cl_info
482 srt = getSRTInfo cl_info
484 size = closureNonHdrSize cl_info
486 ptrs = closurePtrsSize cl_info
489 pp_rest | is_selector = int select_word_i
494 hcat [ int tag, comma ]
495 else if needs_srt then
500 type_str = pprSMRep (closureSMRep cl_info)
502 pp_descr = pprStringInCStyle cl_descr
503 pp_type = pprStringInCStyle (closureTypeDescr cl_info)
505 pprAbsC stmt@(CClosureTbl tycon) _
507 ptext SLIT("CLOSURE_TBL") <>
508 lparen <> pprCLabel (mkClosureTblLabel tycon) <> rparen :
510 map (pp_closure_lbl . mkClosureLabel . getName . dataConWrapId) (tyConDataCons tycon)
512 ) $$ ptext SLIT("};")
514 pprAbsC stmt@(CRetDirect uniq code srt liveness) _
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
531 info_lbl = mkReturnInfoLabel uniq
532 entry_lbl = mkReturnPtLabel uniq
534 pp_code = let stuff = CCodeBlock entry_lbl code in
535 pprAbsC stuff (costs stuff)
537 type_str = case liveness of
538 LvSmall _ -> SLIT("RET_SMALL")
539 LvLarge _ -> SLIT("RET_BIG")
541 pprAbsC stmt@(CRetVector lbl amodes srt liveness) _
542 = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
546 ptext SLIT("VEC_INFO_") <> int size,
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
554 nest 2 (sep (punctuate comma (map ppr_item amodes))),
560 ppr_item item = (<>) (text "(F_) ") (ppr_amode item)
563 type_str = case liveness of
564 LvSmall _ -> SLIT("RET_VEC_SMALL")
565 LvLarge _ -> SLIT("RET_VEC_BIG")
568 pprAbsC stmt@(CModuleInitBlock lbl code) _
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]
576 pprAbsC (CCostCentreDecl is_local cc) _ = pprCostCentreDecl is_local cc
577 pprAbsC (CCostCentreStackDecl ccs) _ = pprCostCentreStackDecl ccs
582 = if (externallyVisibleCLabel lbl)
584 else ptext SLIT("static ")
586 -- Horrible macros for declaring the types and locality of labels (see
589 ppLocalnessMacro include_dyn_prefix clabel =
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_")
601 is_visible = externallyVisibleCLabel clabel
602 label_type = labelType clabel
605 | is_visible = char 'E'
606 | otherwise = char 'I'
609 | include_dyn_prefix && labelDynamic clabel = char 'D'
617 grab_non_void_amodes amodes
618 = filter non_void amodes
621 = case (getAmodeRep amode) of
627 ppr_vol_regs :: [MagicId] -> (SDoc, SDoc)
629 ppr_vol_regs [] = (empty, empty)
630 ppr_vol_regs (VoidReg:rs) = ppr_vol_regs rs
632 = let pp_reg = case r of
633 VanillaReg pk n -> pprVanillaReg n
635 (more_saves, more_restores) = ppr_vol_regs rs
637 (($$) ((<>) (ptext SLIT("CALLER_SAVE_")) pp_reg) more_saves,
638 ($$) ((<>) (ptext SLIT("CALLER_RESTORE_")) pp_reg) more_restores)
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")
651 has_srt (_, NoSRT) = False
660 (lbl, SRT off len) ->
661 hcat [ pprCLabel lbl, comma,
668 | labelDynamic lbl = text "DLL_SRT_ENTRY" <> parens (pprCLabel lbl)
669 | otherwise = char '&' <> pprCLabel lbl
674 = if opt_SccProfilingOn
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 -- ---------------------------------------------------------------------------
684 do_if_stmt discrim tag alt_code deflt c
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)
690 (addrModeCosts discrim Rhs) c
692 cond = hcat [ pprAmode discrim
695 , pprAmode (CLit tag)
697 -- to be absolutely sure that none of the
698 -- conversion rules hit, e.g.,
700 -- minInt is different to (int)minInt
702 -- in C (when minInt is a number not a constant
703 -- expression which evaluates to it.)
705 tcast = case other of
706 MachInt _ -> ptext SLIT("(I_)")
711 (addrModeCosts discrim Rhs) c
713 ppr_if_stmt pp_pred then_part else_part discrim_costs c
715 hcat [text "if (", pp_pred, text ") {"],
716 nest 8 (pprAbsC then_part (c + discrim_costs +
717 (Cost (0, 2, 0, 0, 0)) +
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)) +
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
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
735 Some rough notes on generating code for @CCallOp@:
737 1) Evaluate all arguments and stuff them into registers. (done elsewhere)
738 2) Save any essential registers (heap, stack, etc).
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.
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
749 (This happens after restoration of essential registers because we
750 might need the @Base@ register to access all the others correctly.)
752 Otherwise, copy local variable into result register.
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.
758 { ResultType _ccall_result;
761 _ccall_result = f( args );
765 return_reg = _ccall_result;
769 Amendment to the above: if we can GC, we have to:
771 * make sure we save all our registers away where the garbage collector
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.
780 pprCCall call@(CCall op_str is_asm may_gc cconv) args results vol_regs
783 declare_local_vars, -- local var for *result*
784 vcat local_arg_decls,
786 process_casm local_vars pp_non_void_args casm_str,
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);}"
797 | otherwise = ( pp_basic_saves $$ pp_saves,
798 pp_basic_restores $$ pp_restores)
802 in ASSERT2 ( all non_void nvas, pprCCallOp call <+> hsep (map pprAmode args) )
804 -- the last argument will be the "I/O world" token (a VoidRep)
805 -- all others should be non-void
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.
813 (local_arg_decls, pp_non_void_args)
814 = unzip [ ppr_casm_arg a i | (a,i) <- non_void_args `zip` [1..] ]
816 (declare_local_vars, local_vars, assign_results)
817 = ppr_casm_results non_void_results
819 casm_str = if is_asm then _UNPK_ asm_str else ccall_str
820 StaticTarget asm_str = op_str -- Must be static if it's a casm
822 -- Remainder only used for ccall
824 fun_name = case op_str of
825 DynamicTarget u -> parens (parens (ptext SLIT("_ccall_fun_ty") <> ppr u) <> text "%0")
826 StaticTarget st -> pprCLabelString st
830 if null non_void_results
833 lparen, fun_name, lparen,
834 hcat (punctuate comma ccall_fun_args),
838 ccall_fun_args | isDynamicTarget op_str = tail ccall_args
839 | otherwise = ccall_args
841 ccall_args = zipWith (\ _ i -> char '%' <> int i) non_void_args [0..]
845 If the argument is a heap object, we need to reach inside and pull out
846 the bit the C world wants to see. The only heap objects which can be
847 passed are @Array@s and @ByteArray@s.
850 ppr_casm_arg :: CAddrMode -> Int -> (SDoc, SDoc)
851 -- (a) decl and assignment, (b) local var to be used later
853 ppr_casm_arg amode a_num
855 a_kind = getAmodeRep amode
856 pp_amode = pprAmode amode
857 pp_kind = pprPrimKind a_kind
859 local_var = (<>) (ptext SLIT("_ccall_arg")) (int a_num)
861 (arg_type, pp_amode2)
864 -- for array arguments, pass a pointer to the body of the array
865 -- (PTRS_ARR_CTS skips over all the header nonsense)
866 ArrayRep -> (pp_kind,
867 hcat [ptext SLIT("PTRS_ARR_CTS"),char '(', pp_amode, rparen])
868 ByteArrayRep -> (pp_kind,
869 hcat [ptext SLIT("BYTE_ARR_CTS"),char '(', pp_amode, rparen])
871 -- for ForeignObj, use FOREIGN_OBJ_DATA to fish out the contents.
872 ForeignObjRep -> (pp_kind,
873 hcat [ptext SLIT("ForeignObj_CLOSURE_DATA"),
874 char '(', pp_amode, char ')'])
876 other -> (pp_kind, pp_amode)
879 = hcat [ arg_type, space, local_var, equals, pp_amode2, semi ]
881 (declare_local_var, local_var)
884 For l-values, the critical questions are:
886 1) Are there any results at all?
888 We only allow zero or one results.
892 :: [CAddrMode] -- list of results (length <= 1)
894 ( SDoc, -- declaration of any local vars
895 [SDoc], -- list of result vars (same length as results)
896 SDoc ) -- assignment (if any) of results in local var to registers
899 = (empty, [], empty) -- no results
903 result_reg = ppr_amode r
904 r_kind = getAmodeRep r
906 local_var = ptext SLIT("_ccall_result")
908 (result_type, assign_result)
909 = (pprPrimKind r_kind,
910 hcat [ result_reg, equals, local_var, semi ])
912 declare_local_var = hcat [ result_type, space, local_var, semi ]
914 (declare_local_var, [local_var], assign_result)
917 = panic "ppr_casm_results: ccall/casm with many results"
921 Note the sneaky way _the_ result is represented by a list so that we
922 can complain if it's used twice.
924 ToDo: Any chance of giving line numbers when process-casm fails?
925 Or maybe we should do a check _much earlier_ in compiler. ADR
928 process_casm :: [SDoc] -- results (length <= 1)
929 -> [SDoc] -- arguments
930 -> String -- format string (with embedded %'s)
931 -> SDoc -- code being generated
933 process_casm results args string = process results args string
935 process [] _ "" = empty
936 process (_:_) _ "" = error ("process_casm: non-void result not assigned while processing _casm_ \"" ++
938 "\"\n(Try changing result type to IO ()\n")
940 process ress args ('%':cs)
943 error ("process_casm: lonely % while processing _casm_ \"" ++ string ++ "\".\n")
946 char '%' <> process ress args css
950 [] -> error ("process_casm: no result to match %r while processing _casm_ \"" ++ string ++ "\".\nTry deleting %r or changing result type from PrimIO ()\n")
951 [r] -> r <> (process [] args css)
952 _ -> panic ("process_casm: casm with many results while processing _casm_ \"" ++ string ++ "\".\n")
956 read_int :: ReadS Int
959 case (read_int other) of
961 if 0 <= num && num < length args
962 then parens (args !! num) <> process ress args css
963 else error ("process_casm: no such arg #:"++(show num)++" while processing \"" ++ string ++ "\".\n")
964 _ -> error ("process_casm: not %<num> while processing _casm_ \"" ++ string ++ "\".\n")
966 process ress args (other_c:cs)
967 = char other_c <> process ress args cs
970 %************************************************************************
972 \subsection[a2r-assignments]{Assignments}
974 %************************************************************************
976 Printing assignments is a little tricky because of type coercion.
978 First of all, the kind of the thing being assigned can be gotten from
979 the destination addressing mode. (It should be the same as the kind
980 of the source addressing mode.) If the kind of the assignment is of
981 @VoidRep@, then don't generate any code at all.
984 pprAssign :: PrimRep -> CAddrMode -> CAddrMode -> SDoc
986 pprAssign VoidRep dest src = empty
989 Special treatment for floats and doubles, to avoid unwanted conversions.
992 pprAssign FloatRep dest@(CVal reg_rel _) src
993 = hcat [ ptext SLIT("ASSIGN_FLT"),char '(', ppr_amode (CAddr reg_rel), comma, pprAmode src, pp_paren_semi ]
995 pprAssign DoubleRep dest@(CVal reg_rel _) src
996 = hcat [ ptext SLIT("ASSIGN_DBL"),char '(', ppr_amode (CAddr reg_rel), comma, pprAmode src, pp_paren_semi ]
998 pprAssign Int64Rep dest@(CVal reg_rel _) src
999 = hcat [ ptext SLIT("ASSIGN_Int64"),char '(', ppr_amode (CAddr reg_rel), comma, pprAmode src, pp_paren_semi ]
1000 pprAssign Word64Rep dest@(CVal reg_rel _) src
1001 = hcat [ ptext SLIT("ASSIGN_Word64"),char '(', ppr_amode (CAddr reg_rel), comma, pprAmode src, pp_paren_semi ]
1004 Lastly, the question is: will the C compiler think the types of the
1005 two sides of the assignment match?
1007 We assume that the types will match if neither side is a
1008 @CVal@ addressing mode for any register which can point into
1011 Why? Because the heap and stack are used to store miscellaneous
1012 things, whereas the temporaries, registers, etc., are only used for
1013 things of fixed type.
1016 pprAssign kind (CReg (VanillaReg _ dest)) (CReg (VanillaReg _ src))
1017 = hcat [ pprVanillaReg dest, equals,
1018 pprVanillaReg src, semi ]
1020 pprAssign kind dest src
1021 | mixedTypeLocn dest
1022 -- Add in a cast to StgWord (a.k.a. W_) iff the destination is mixed
1023 = hcat [ ppr_amode dest, equals,
1024 text "(W_)(", -- Here is the cast
1025 ppr_amode src, pp_paren_semi ]
1027 pprAssign kind dest src
1028 | mixedPtrLocn dest && getAmodeRep src /= PtrRep
1029 -- Add in a cast to StgPtr (a.k.a. P_) iff the destination is mixed
1030 = hcat [ ppr_amode dest, equals,
1031 text "(P_)(", -- Here is the cast
1032 ppr_amode src, pp_paren_semi ]
1034 pprAssign ByteArrayRep dest src
1036 -- Add in a cast iff the source is mixed
1037 = hcat [ ppr_amode dest, equals,
1038 text "(StgByteArray)(", -- Here is the cast
1039 ppr_amode src, pp_paren_semi ]
1041 pprAssign kind other_dest src
1042 = hcat [ ppr_amode other_dest, equals,
1043 pprAmode src, semi ]
1047 %************************************************************************
1049 \subsection[a2r-CAddrModes]{Addressing modes}
1051 %************************************************************************
1053 @pprAmode@ is used to print r-values (which may need casts), whereas
1054 @ppr_amode@ is used for l-values {\em and} as a help function for
1058 pprAmode, ppr_amode :: CAddrMode -> SDoc
1061 For reasons discussed above under assignments, @CVal@ modes need
1062 to be treated carefully. First come special cases for floats and doubles,
1063 similar to those in @pprAssign@:
1065 (NB: @PK_FLT@ and @PK_DBL@ require the {\em address} of the value in
1069 pprAmode (CVal reg_rel FloatRep)
1070 = hcat [ text "PK_FLT(", ppr_amode (CAddr reg_rel), rparen ]
1071 pprAmode (CVal reg_rel DoubleRep)
1072 = hcat [ text "PK_DBL(", ppr_amode (CAddr reg_rel), rparen ]
1073 pprAmode (CVal reg_rel Int64Rep)
1074 = hcat [ text "PK_Int64(", ppr_amode (CAddr reg_rel), rparen ]
1075 pprAmode (CVal reg_rel Word64Rep)
1076 = hcat [ text "PK_Word64(", ppr_amode (CAddr reg_rel), rparen ]
1079 Next comes the case where there is some other cast need, and the
1084 | mixedTypeLocn amode
1085 = parens (hcat [ pprPrimKind (getAmodeRep amode), ptext SLIT(")("),
1087 | otherwise -- No cast needed
1091 When we have an indirection through a CIndex, we have to be careful to
1092 get the type casts right.
1096 CVal (CIndex kind1 base offset) kind2
1100 *(kind2 *)((kind1 *)base + offset)
1102 That is, the indexing is done in units of kind1, but the resulting
1106 ppr_amode (CVal reg_rel@(CIndex _ _ _) kind)
1107 = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1108 (pp_reg, Nothing) -> panic "ppr_amode: CIndex"
1109 (pp_reg, Just offset) ->
1110 hcat [ char '*', parens (pprPrimKind kind <> char '*'),
1111 parens (pp_reg <> char '+' <> offset) ]
1114 Now the rest of the cases for ``workhorse'' @ppr_amode@:
1117 ppr_amode (CVal reg_rel _)
1118 = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1119 (pp_reg, Nothing) -> (<>) (char '*') pp_reg
1120 (pp_reg, Just offset) -> hcat [ pp_reg, brackets offset ]
1122 ppr_amode (CAddr reg_rel)
1123 = case (pprRegRelative True{-sign wanted-} reg_rel) of
1124 (pp_reg, Nothing) -> pp_reg
1125 (pp_reg, Just offset) -> (<>) pp_reg offset
1127 ppr_amode (CReg magic_id) = pprMagicId magic_id
1129 ppr_amode (CTemp uniq kind) = char '_' <> pprUnique uniq <> char '_'
1131 ppr_amode (CLbl lbl kind) = pprCLabelAddr lbl
1133 ppr_amode (CCharLike ch)
1134 = hcat [ptext SLIT("CHARLIKE_CLOSURE"), char '(', pprAmode ch, rparen ]
1135 ppr_amode (CIntLike int)
1136 = hcat [ptext SLIT("INTLIKE_CLOSURE"), char '(', pprAmode int, rparen ]
1138 ppr_amode (CLit lit) = pprBasicLit lit
1140 ppr_amode (CJoinPoint _)
1141 = panic "ppr_amode: CJoinPoint"
1143 ppr_amode (CMacroExpr pk macro as)
1144 = parens (ptext (cExprMacroText macro) <>
1145 parens (hcat (punctuate comma (map pprAmode as))))
1149 cExprMacroText ENTRY_CODE = SLIT("ENTRY_CODE")
1150 cExprMacroText ARG_TAG = SLIT("ARG_TAG")
1151 cExprMacroText GET_TAG = SLIT("GET_TAG")
1152 cExprMacroText UPD_FRAME_UPDATEE = SLIT("UPD_FRAME_UPDATEE")
1153 cExprMacroText CCS_HDR = SLIT("CCS_HDR")
1155 cStmtMacroText ARGS_CHK = SLIT("ARGS_CHK")
1156 cStmtMacroText ARGS_CHK_LOAD_NODE = SLIT("ARGS_CHK_LOAD_NODE")
1157 cStmtMacroText UPD_CAF = SLIT("UPD_CAF")
1158 cStmtMacroText UPD_BH_UPDATABLE = SLIT("UPD_BH_UPDATABLE")
1159 cStmtMacroText UPD_BH_SINGLE_ENTRY = SLIT("UPD_BH_SINGLE_ENTRY")
1160 cStmtMacroText PUSH_UPD_FRAME = SLIT("PUSH_UPD_FRAME")
1161 cStmtMacroText PUSH_SEQ_FRAME = SLIT("PUSH_SEQ_FRAME")
1162 cStmtMacroText UPDATE_SU_FROM_UPD_FRAME = SLIT("UPDATE_SU_FROM_UPD_FRAME")
1163 cStmtMacroText SET_TAG = SLIT("SET_TAG")
1164 cStmtMacroText REGISTER_FOREIGN_EXPORT = SLIT("REGISTER_FOREIGN_EXPORT")
1165 cStmtMacroText REGISTER_IMPORT = SLIT("REGISTER_IMPORT")
1166 cStmtMacroText REGISTER_DIMPORT = SLIT("REGISTER_DIMPORT")
1167 cStmtMacroText GRAN_FETCH = SLIT("GRAN_FETCH")
1168 cStmtMacroText GRAN_RESCHEDULE = SLIT("GRAN_RESCHEDULE")
1169 cStmtMacroText GRAN_FETCH_AND_RESCHEDULE= SLIT("GRAN_FETCH_AND_RESCHEDULE")
1170 cStmtMacroText THREAD_CONTEXT_SWITCH = SLIT("THREAD_CONTEXT_SWITCH")
1171 cStmtMacroText GRAN_YIELD = SLIT("GRAN_YIELD")
1173 cCheckMacroText HP_CHK_NP = SLIT("HP_CHK_NP")
1174 cCheckMacroText STK_CHK_NP = SLIT("STK_CHK_NP")
1175 cCheckMacroText HP_STK_CHK_NP = SLIT("HP_STK_CHK_NP")
1176 cCheckMacroText HP_CHK_SEQ_NP = SLIT("HP_CHK_SEQ_NP")
1177 cCheckMacroText HP_CHK = SLIT("HP_CHK")
1178 cCheckMacroText STK_CHK = SLIT("STK_CHK")
1179 cCheckMacroText HP_STK_CHK = SLIT("HP_STK_CHK")
1180 cCheckMacroText HP_CHK_NOREGS = SLIT("HP_CHK_NOREGS")
1181 cCheckMacroText HP_CHK_UNPT_R1 = SLIT("HP_CHK_UNPT_R1")
1182 cCheckMacroText HP_CHK_UNBX_R1 = SLIT("HP_CHK_UNBX_R1")
1183 cCheckMacroText HP_CHK_F1 = SLIT("HP_CHK_F1")
1184 cCheckMacroText HP_CHK_D1 = SLIT("HP_CHK_D1")
1185 cCheckMacroText HP_CHK_L1 = SLIT("HP_CHK_L1")
1186 cCheckMacroText HP_CHK_UT_ALT = SLIT("HP_CHK_UT_ALT")
1187 cCheckMacroText HP_CHK_GEN = SLIT("HP_CHK_GEN")
1190 %************************************************************************
1192 \subsection[ppr-liveness-masks]{Liveness Masks}
1194 %************************************************************************
1197 pp_liveness :: Liveness -> SDoc
1200 LvLarge lbl -> char '&' <> pprCLabel lbl
1201 LvSmall mask -- Avoid gcc bug when printing minInt
1202 | bitmap_int == minInt -> int (bitmap_int+1) <> text "-1"
1203 | otherwise -> int bitmap_int
1205 bitmap_int = intBS mask
1208 %************************************************************************
1210 \subsection[a2r-MagicIds]{Magic ids}
1212 %************************************************************************
1214 @pprRegRelative@ returns a pair of the @Doc@ for the register
1215 (some casting may be required), and a @Maybe Doc@ for the offset
1216 (zero offset gives a @Nothing@).
1219 addPlusSign :: Bool -> SDoc -> SDoc
1220 addPlusSign False p = p
1221 addPlusSign True p = (<>) (char '+') p
1223 pprSignedInt :: Bool -> Int -> Maybe SDoc -- Nothing => 0
1224 pprSignedInt sign_wanted n
1225 = if n == 0 then Nothing else
1226 if n > 0 then Just (addPlusSign sign_wanted (int n))
1229 pprRegRelative :: Bool -- True <=> Print leading plus sign (if +ve)
1231 -> (SDoc, Maybe SDoc)
1233 pprRegRelative sign_wanted (SpRel off)
1234 = (pprMagicId Sp, pprSignedInt sign_wanted (I# off))
1236 pprRegRelative sign_wanted r@(HpRel o)
1237 = let pp_Hp = pprMagicId Hp; off = I# o
1242 (pp_Hp, Just ((<>) (char '-') (int off)))
1244 pprRegRelative sign_wanted (NodeRel o)
1245 = let pp_Node = pprMagicId node; off = I# o
1250 (pp_Node, Just (addPlusSign sign_wanted (int off)))
1252 pprRegRelative sign_wanted (CIndex base offset kind)
1253 = ( hcat [text "((", pprPrimKind kind, text " *)(", ppr_amode base, text "))"]
1254 , Just (hcat [if sign_wanted then char '+' else empty,
1255 text "(I_)(", ppr_amode offset, ptext SLIT(")")])
1259 @pprMagicId@ just prints the register name. @VanillaReg@ registers are
1260 represented by a discriminated union (@StgUnion@), so we use the @PrimRep@
1261 to select the union tag.
1264 pprMagicId :: MagicId -> SDoc
1266 pprMagicId BaseReg = ptext SLIT("BaseReg")
1267 pprMagicId (VanillaReg pk n)
1268 = hcat [ pprVanillaReg n, char '.',
1270 pprMagicId (FloatReg n) = ptext SLIT("F") <> int (I# n)
1271 pprMagicId (DoubleReg n) = ptext SLIT("D") <> int (I# n)
1272 pprMagicId (LongReg _ n) = ptext SLIT("L") <> int (I# n)
1273 pprMagicId Sp = ptext SLIT("Sp")
1274 pprMagicId Su = ptext SLIT("Su")
1275 pprMagicId SpLim = ptext SLIT("SpLim")
1276 pprMagicId Hp = ptext SLIT("Hp")
1277 pprMagicId HpLim = ptext SLIT("HpLim")
1278 pprMagicId CurCostCentre = ptext SLIT("CCCS")
1279 pprMagicId VoidReg = panic "pprMagicId:VoidReg!"
1281 pprVanillaReg :: Int# -> SDoc
1282 pprVanillaReg n = char 'R' <> int (I# n)
1284 pprUnionTag :: PrimRep -> SDoc
1286 pprUnionTag PtrRep = char 'p'
1287 pprUnionTag CodePtrRep = ptext SLIT("fp")
1288 pprUnionTag DataPtrRep = char 'd'
1289 pprUnionTag RetRep = char 'p'
1290 pprUnionTag CostCentreRep = panic "pprUnionTag:CostCentre?"
1292 pprUnionTag CharRep = char 'c'
1293 pprUnionTag Int8Rep = ptext SLIT("i8")
1294 pprUnionTag IntRep = char 'i'
1295 pprUnionTag WordRep = char 'w'
1296 pprUnionTag AddrRep = char 'a'
1297 pprUnionTag FloatRep = char 'f'
1298 pprUnionTag DoubleRep = panic "pprUnionTag:Double?"
1300 pprUnionTag StablePtrRep = char 'p'
1301 pprUnionTag StableNameRep = char 'p'
1302 pprUnionTag WeakPtrRep = char 'p'
1303 pprUnionTag ForeignObjRep = char 'p'
1304 pprUnionTag PrimPtrRep = char 'p'
1306 pprUnionTag ThreadIdRep = char 't'
1308 pprUnionTag ArrayRep = char 'p'
1309 pprUnionTag ByteArrayRep = char 'b'
1310 pprUnionTag BCORep = char 'p'
1312 pprUnionTag _ = panic "pprUnionTag:Odd kind"
1316 Find and print local and external declarations for a list of
1317 Abstract~C statements.
1319 pprTempAndExternDecls :: AbstractC -> (SDoc{-temps-}, SDoc{-externs-})
1320 pprTempAndExternDecls AbsCNop = (empty, empty)
1322 pprTempAndExternDecls (AbsCStmts stmt1 stmt2)
1323 = initTE (ppr_decls_AbsC stmt1 `thenTE` \ (t_p1, e_p1) ->
1324 ppr_decls_AbsC stmt2 `thenTE` \ (t_p2, e_p2) ->
1325 case (catMaybes [t_p1, t_p2]) of { real_temps ->
1326 case (catMaybes [e_p1, e_p2]) of { real_exts ->
1327 returnTE (vcat real_temps, vcat real_exts) }}
1330 pprTempAndExternDecls other_stmt
1331 = initTE (ppr_decls_AbsC other_stmt `thenTE` \ (maybe_t, maybe_e) ->
1342 pprBasicLit :: Literal -> SDoc
1343 pprPrimKind :: PrimRep -> SDoc
1345 pprBasicLit lit = ppr lit
1346 pprPrimKind k = ppr k
1350 %************************************************************************
1352 \subsection[a2r-monad]{Monadery}
1354 %************************************************************************
1356 We need some monadery to keep track of temps and externs we have already
1357 printed. This info must be threaded right through the Abstract~C, so
1358 it's most convenient to hide it in this monad.
1360 WDP 95/02: Switched from \tr{([Unique], [CLabel])} to
1361 \tr{(UniqSet, CLabelSet)}. Allegedly for efficiency.
1364 type CLabelSet = FiniteMap CLabel (){-any type will do-}
1365 emptyCLabelSet = emptyFM
1366 x `elementOfCLabelSet` labs
1367 = case (lookupFM labs x) of { Just _ -> True; Nothing -> False }
1369 addToCLabelSet set x = addToFM set x ()
1371 type TEenv = (UniqSet Unique, CLabelSet)
1373 type TeM result = TEenv -> (TEenv, result)
1375 initTE :: TeM a -> a
1377 = case sa (emptyUniqSet, emptyCLabelSet) of { (_, result) ->
1380 {-# INLINE thenTE #-}
1381 {-# INLINE returnTE #-}
1383 thenTE :: TeM a -> (a -> TeM b) -> TeM b
1385 = case a u of { (u_1, result_of_a) ->
1388 mapTE :: (a -> TeM b) -> [a] -> TeM [b]
1389 mapTE f [] = returnTE []
1391 = f x `thenTE` \ r ->
1392 mapTE f xs `thenTE` \ rs ->
1395 returnTE :: a -> TeM a
1396 returnTE result env = (env, result)
1398 -- these next two check whether the thing is already
1399 -- recorded, and THEN THEY RECORD IT
1400 -- (subsequent calls will return False for the same uniq/label)
1402 tempSeenTE :: Unique -> TeM Bool
1403 tempSeenTE uniq env@(seen_uniqs, seen_labels)
1404 = if (uniq `elementOfUniqSet` seen_uniqs)
1406 else ((addOneToUniqSet seen_uniqs uniq,
1410 labelSeenTE :: CLabel -> TeM Bool
1411 labelSeenTE lbl env@(seen_uniqs, seen_labels)
1412 = if (lbl `elementOfCLabelSet` seen_labels)
1415 addToCLabelSet seen_labels lbl),
1420 pprTempDecl :: Unique -> PrimRep -> SDoc
1421 pprTempDecl uniq kind
1422 = hcat [ pprPrimKind kind, space, char '_', pprUnique uniq, ptext SLIT("_;") ]
1424 pprExternDecl :: Bool -> CLabel -> SDoc
1425 pprExternDecl in_srt clabel
1426 | not (needsCDecl clabel) = empty -- do not print anything for "known external" things
1428 hcat [ ppLocalnessMacro (not in_srt) clabel,
1429 lparen, dyn_wrapper (pprCLabel clabel), pp_paren_semi ]
1432 | in_srt && labelDynamic clabel = text "DLL_IMPORT_DATA_VAR" <> parens d
1438 ppr_decls_AbsC :: AbstractC -> TeM (Maybe SDoc{-temps-}, Maybe SDoc{-externs-})
1440 ppr_decls_AbsC AbsCNop = returnTE (Nothing, Nothing)
1442 ppr_decls_AbsC (AbsCStmts stmts_1 stmts_2)
1443 = ppr_decls_AbsC stmts_1 `thenTE` \ p1 ->
1444 ppr_decls_AbsC stmts_2 `thenTE` \ p2 ->
1445 returnTE (maybe_vcat [p1, p2])
1447 ppr_decls_AbsC (CSplitMarker) = returnTE (Nothing, Nothing)
1449 ppr_decls_AbsC (CAssign dest source)
1450 = ppr_decls_Amode dest `thenTE` \ p1 ->
1451 ppr_decls_Amode source `thenTE` \ p2 ->
1452 returnTE (maybe_vcat [p1, p2])
1454 ppr_decls_AbsC (CJump target) = ppr_decls_Amode target
1456 ppr_decls_AbsC (CFallThrough target) = ppr_decls_Amode target
1458 ppr_decls_AbsC (CReturn target _) = ppr_decls_Amode target
1460 ppr_decls_AbsC (CSwitch discrim alts deflt)
1461 = ppr_decls_Amode discrim `thenTE` \ pdisc ->
1462 mapTE ppr_alt_stuff alts `thenTE` \ palts ->
1463 ppr_decls_AbsC deflt `thenTE` \ pdeflt ->
1464 returnTE (maybe_vcat (pdisc:pdeflt:palts))
1466 ppr_alt_stuff (_, absC) = ppr_decls_AbsC absC
1468 ppr_decls_AbsC (CCodeBlock lbl absC)
1469 = ppr_decls_AbsC absC
1471 ppr_decls_AbsC (CInitHdr cl_info reg_rel cost_centre)
1472 -- ToDo: strictly speaking, should chk "cost_centre" amode
1473 = labelSeenTE info_lbl `thenTE` \ label_seen ->
1478 Just (pprExternDecl False{-not in an SRT decl-} info_lbl))
1480 info_lbl = infoTableLabelFromCI cl_info
1482 ppr_decls_AbsC (COpStmt results _ args _) = ppr_decls_Amodes (results ++ args)
1483 ppr_decls_AbsC (CSimultaneous abc) = ppr_decls_AbsC abc
1485 ppr_decls_AbsC (CCheck _ amodes code) =
1486 ppr_decls_Amodes amodes `thenTE` \p1 ->
1487 ppr_decls_AbsC code `thenTE` \p2 ->
1488 returnTE (maybe_vcat [p1,p2])
1490 ppr_decls_AbsC (CMacroStmt _ amodes) = ppr_decls_Amodes amodes
1492 ppr_decls_AbsC (CCallProfCtrMacro _ amodes) = ppr_decls_Amodes [] -- *****!!!
1493 -- you get some nasty re-decls of stdio.h if you compile
1494 -- the prelude while looking inside those amodes;
1495 -- no real reason to, anyway.
1496 ppr_decls_AbsC (CCallProfCCMacro _ amodes) = ppr_decls_Amodes amodes
1498 ppr_decls_AbsC (CStaticClosure closure_lbl closure_info cost_centre amodes)
1499 -- ToDo: strictly speaking, should chk "cost_centre" amode
1500 = ppr_decls_Amodes amodes
1502 ppr_decls_AbsC (CClosureInfoAndCode cl_info slow maybe_fast _)
1503 = ppr_decls_Amodes [entry_lbl] `thenTE` \ p1 ->
1504 ppr_decls_AbsC slow `thenTE` \ p2 ->
1506 Nothing -> returnTE (Nothing, Nothing)
1507 Just fast -> ppr_decls_AbsC fast) `thenTE` \ p3 ->
1508 returnTE (maybe_vcat [p1, p2, p3])
1510 entry_lbl = CLbl slow_lbl CodePtrRep
1511 slow_lbl = case (nonemptyAbsC slow) of
1512 Nothing -> mkErrorStdEntryLabel
1513 Just _ -> entryLabelFromCI cl_info
1515 ppr_decls_AbsC (CSRT _ closure_lbls)
1516 = mapTE labelSeenTE closure_lbls `thenTE` \ seen ->
1518 if and seen then Nothing
1519 else Just (vcat [ pprExternDecl True{-in SRT decl-} l
1520 | (l,False) <- zip closure_lbls seen ]))
1522 ppr_decls_AbsC (CRetDirect _ code _ _) = ppr_decls_AbsC code
1523 ppr_decls_AbsC (CRetVector _ amodes _ _) = ppr_decls_Amodes amodes
1524 ppr_decls_AbsC (CModuleInitBlock _ code) = ppr_decls_AbsC code
1526 ppr_decls_AbsC (_) = returnTE (Nothing, Nothing)
1530 ppr_decls_Amode :: CAddrMode -> TeM (Maybe SDoc, Maybe SDoc)
1531 ppr_decls_Amode (CVal (CIndex base offset _) _) = ppr_decls_Amodes [base,offset]
1532 ppr_decls_Amode (CAddr (CIndex base offset _)) = ppr_decls_Amodes [base,offset]
1533 ppr_decls_Amode (CVal _ _) = returnTE (Nothing, Nothing)
1534 ppr_decls_Amode (CAddr _) = returnTE (Nothing, Nothing)
1535 ppr_decls_Amode (CReg _) = returnTE (Nothing, Nothing)
1536 ppr_decls_Amode (CLit _) = returnTE (Nothing, Nothing)
1538 -- CIntLike must be a literal -- no decls
1539 ppr_decls_Amode (CIntLike int) = returnTE (Nothing, Nothing)
1542 ppr_decls_Amode (CCharLike char) = returnTE (Nothing, Nothing)
1544 -- now, the only place where we actually print temps/externs...
1545 ppr_decls_Amode (CTemp uniq kind)
1547 VoidRep -> returnTE (Nothing, Nothing)
1549 tempSeenTE uniq `thenTE` \ temp_seen ->
1551 (if temp_seen then Nothing else Just (pprTempDecl uniq kind), Nothing)
1553 ppr_decls_Amode (CLbl lbl VoidRep)
1554 = returnTE (Nothing, Nothing)
1556 ppr_decls_Amode (CLbl lbl kind)
1557 = labelSeenTE lbl `thenTE` \ label_seen ->
1559 if label_seen then Nothing else Just (pprExternDecl False{-not in an SRT decl-} lbl))
1561 ppr_decls_Amode (CMacroExpr _ _ amodes)
1562 = ppr_decls_Amodes amodes
1564 ppr_decls_Amode other = returnTE (Nothing, Nothing)
1567 maybe_vcat :: [(Maybe SDoc, Maybe SDoc)] -> (Maybe SDoc, Maybe SDoc)
1569 = case (unzip ps) of { (ts, es) ->
1570 case (catMaybes ts) of { real_ts ->
1571 case (catMaybes es) of { real_es ->
1572 (if (null real_ts) then Nothing else Just (vcat real_ts),
1573 if (null real_es) then Nothing else Just (vcat real_es))
1578 ppr_decls_Amodes :: [CAddrMode] -> TeM (Maybe SDoc, Maybe SDoc)
1579 ppr_decls_Amodes amodes
1580 = mapTE ppr_decls_Amode amodes `thenTE` \ ps ->
1581 returnTE ( maybe_vcat ps )
1584 Print out a C Label where you want the *address* of the label, not the
1585 object it refers to. The distinction is important when the label may
1586 refer to a C structure (info tables and closures, for instance).
1588 When just generating a declaration for the label, use pprCLabel.
1591 pprCLabelAddr :: CLabel -> SDoc
1592 pprCLabelAddr clabel =
1593 case labelType clabel of
1594 InfoTblType -> addr_of_label
1595 ClosureType -> addr_of_label
1596 VecTblType -> addr_of_label
1599 addr_of_label = ptext SLIT("(P_)&") <> pp_label
1600 pp_label = pprCLabel clabel
1604 -----------------------------------------------------------------------------
1605 Initialising static objects with floating-point numbers. We can't
1606 just emit the floating point number, because C will cast it to an int
1607 by rounding it. We want the actual bit-representation of the float.
1609 This is a hack to turn the floating point numbers into ints that we
1610 can safely initialise to static locations.
1613 big_doubles = (getPrimRepSize DoubleRep) /= 1
1615 -- floatss are always 1 word
1616 floatToWord :: CAddrMode -> CAddrMode
1617 floatToWord (CLit (MachFloat r))
1619 arr <- newFloatArray ((0::Int),0)
1620 writeFloatArray arr 0 (fromRational r)
1621 i <- readIntArray arr 0
1622 return (CLit (MachInt (toInteger i)))
1625 doubleToWords :: CAddrMode -> [CAddrMode]
1626 doubleToWords (CLit (MachDouble r))
1627 | big_doubles -- doubles are 2 words
1629 arr <- newDoubleArray ((0::Int),1)
1630 writeDoubleArray arr 0 (fromRational r)
1631 i1 <- readIntArray arr 0
1632 i2 <- readIntArray arr 1
1633 return [ CLit (MachInt (toInteger i1))
1634 , CLit (MachInt (toInteger i2))
1637 | otherwise -- doubles are 1 word
1639 arr <- newDoubleArray ((0::Int),0)
1640 writeDoubleArray arr 0 (fromRational r)
1641 i <- readIntArray arr 0
1642 return [ CLit (MachInt (toInteger i)) ]