2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %************************************************************************
6 \section[PprAbsC]{Pretty-printing Abstract~C}
8 %************************************************************************
18 #include "HsVersions.h"
25 import AbsCUtils ( getAmodeRep, nonemptyAbsC,
26 mixedPtrLocn, mixedTypeLocn
29 import ForeignCall ( CCallSpec(..), CCallTarget(..), playSafe,
30 playThreadSafe, ccallConvAttribute,
31 ForeignCall(..), DNCallSpec(..),
32 DNType(..), DNKind(..) )
33 import CLabel ( externallyVisibleCLabel,
34 needsCDecl, pprCLabel, mkClosureLabel,
35 mkReturnInfoLabel, mkReturnPtLabel, mkClosureTblLabel,
36 CLabel, CLabelType(..), labelType, labelDynamic
39 import CmdLineOpts ( opt_SccProfilingOn, opt_GranMacros )
40 import CostCentre ( pprCostCentreDecl, pprCostCentreStackDecl )
42 import Costs ( costs, addrModeCosts, CostRes(..), Side(..) )
43 import CStrings ( pprCLabelString )
44 import FiniteMap ( addToFM, emptyFM, lookupFM, FiniteMap )
45 import Literal ( Literal(..) )
46 import TyCon ( tyConDataCons )
47 import Name ( NamedThing(..) )
48 import Maybes ( catMaybes )
49 import PrimOp ( primOpNeedsWrapper )
50 import MachOp ( MachOp(..) )
51 import PrimRep ( isFloatingRep, PrimRep(..), getPrimRepSize )
52 import Unique ( pprUnique, Unique{-instance NamedThing-} )
53 import UniqSet ( emptyUniqSet, elementOfUniqSet,
54 addOneToUniqSet, UniqSet
56 import StgSyn ( StgOp(..) )
59 import Util ( lengthExceeds )
61 #if __GLASGOW_HASKELL__ >= 504
66 import Util ( listLengthCmp )
69 import Maybe ( isJust )
76 For spitting out the costs of an abstract~C expression, @writeRealC@
77 now not only prints the C~code of the @absC@ arg but also adds a macro
78 call to a cost evaluation function @GRAN_EXEC@. For that,
79 @pprAbsC@ has a new ``costs'' argument. %% HWL
83 writeRealC :: Handle -> AbstractC -> IO ()
84 writeRealC handle absC
85 -- avoid holding on to the whole of absC in the !Gransim case.
87 then printForCFast fp (pprAbsC absC (costs absC))
88 else printForCFast fp (pprAbsC absC (panic "costs"))
89 --printForC handle (pprAbsC absC (panic "costs"))
90 dumpRealC :: AbstractC -> SDoc
91 dumpRealC absC = pprAbsC absC (costs absC)
94 writeRealC :: Handle -> AbstractC -> IO ()
95 --writeRealC handle absC =
97 -- printDoc LeftMode handle (pprAbsC absC (costs absC))
99 writeRealC handle absC
100 | opt_GranMacros = _scc_ "writeRealC" printForC handle $
101 pprCode CStyle (pprAbsC absC (costs absC))
102 | otherwise = _scc_ "writeRealC" printForC handle $
103 pprCode CStyle (pprAbsC absC (panic "costs"))
105 dumpRealC :: AbstractC -> SDoc
107 | opt_GranMacros = pprCode CStyle (pprAbsC absC (costs absC))
108 | otherwise = pprCode CStyle (pprAbsC absC (panic "costs"))
112 This emits the macro, which is used in GrAnSim to compute the total costs
113 from a cost 5 tuple. %% HWL
116 emitMacro :: CostRes -> SDoc
118 emitMacro _ | not opt_GranMacros = empty
120 emitMacro (Cost (i,b,l,s,f))
121 = hcat [ ptext SLIT("GRAN_EXEC"), char '(',
122 int i, comma, int b, comma, int l, comma,
123 int s, comma, int f, pp_paren_semi ]
125 pp_paren_semi = text ");"
128 New type: Now pprAbsC also takes the costs for evaluating the Abstract C
129 code as an argument (that's needed when spitting out the GRAN_EXEC macro
130 which must be done before the return i.e. inside absC code) HWL
133 pprAbsC :: AbstractC -> CostRes -> SDoc
134 pprAbsC AbsCNop _ = empty
135 pprAbsC (AbsCStmts s1 s2) c = ($$) (pprAbsC s1 c) (pprAbsC s2 c)
137 pprAbsC (CAssign dest src) _ = pprAssign (getAmodeRep dest) dest src
139 pprAbsC (CJump target) c
140 = ($$) (hcat [emitMacro c {-WDP:, text "/* <--++ CJump */"-} ])
141 (hcat [ text jmp_lit, pprAmode target, pp_paren_semi ])
143 pprAbsC (CFallThrough target) c
144 = ($$) (hcat [emitMacro c {-WDP:, text "/* <--++ CFallThrough */"-} ])
145 (hcat [ text jmp_lit, pprAmode target, pp_paren_semi ])
147 -- --------------------------------------------------------------------------
148 -- Spit out GRAN_EXEC macro immediately before the return HWL
150 pprAbsC (CReturn am return_info) c
151 = ($$) (hcat [emitMacro c {-WDP:, text "/* <---- CReturn */"-} ])
152 (hcat [text jmp_lit, target, pp_paren_semi ])
154 target = case return_info of
155 DirectReturn -> hcat [ptext SLIT("ENTRY_CODE"), lparen,
157 DynamicVectoredReturn am' -> mk_vector (pprAmode am')
158 StaticVectoredReturn n -> mk_vector (int n) -- Always positive
159 mk_vector x = hcat [ptext SLIT("RET_VEC"), char '(', pprAmode am, comma,
162 pprAbsC (CSplitMarker) _ = ptext SLIT("__STG_SPLIT_MARKER")
164 -- we optimise various degenerate cases of CSwitches.
166 -- --------------------------------------------------------------------------
167 -- Assume: CSwitch is also end of basic block
168 -- costs function yields nullCosts for whole switch
169 -- ==> inherited costs c are those of basic block up to switch
170 -- ==> inherit c + costs for the corresponding branch
172 -- --------------------------------------------------------------------------
174 pprAbsC (CSwitch discrim [] deflt) c
175 = pprAbsC deflt (c + costs deflt)
176 -- Empty alternative list => no costs for discrim as nothing cond. here HWL
178 pprAbsC (CSwitch discrim [(tag,alt_code)] deflt) c -- only one alt
179 = case (nonemptyAbsC deflt) of
180 Nothing -> -- one alt and no default
181 pprAbsC alt_code (c + costs alt_code)
182 -- Nothing conditional in here either HWL
184 Just dc -> -- make it an "if"
185 do_if_stmt discrim tag alt_code dc c
187 -- What problem is the re-ordering trying to solve ?
188 pprAbsC (CSwitch discrim [(tag1@(MachInt i1), alt_code1),
189 (tag2@(MachInt i2), alt_code2)] deflt) c
190 | empty_deflt && ((i1 == 0 && i2 == 1) || (i1 == 1 && i2 == 0))
192 do_if_stmt discrim tag1 alt_code1 alt_code2 c
194 do_if_stmt discrim tag2 alt_code2 alt_code1 c
196 empty_deflt = not (isJust (nonemptyAbsC deflt))
198 pprAbsC (CSwitch discrim alts deflt) c -- general case
199 | isFloatingRep (getAmodeRep discrim)
200 = pprAbsC (foldr ( \ a -> CSwitch discrim [a]) deflt alts) c
203 hcat [text "switch (", pp_discrim, text ") {"],
204 nest 2 (vcat (map ppr_alt alts)),
205 (case (nonemptyAbsC deflt) of
208 nest 2 (vcat [ptext SLIT("default:"),
209 pprAbsC dc (c + switch_head_cost
211 ptext SLIT("break;")])),
218 = vcat [ hcat [ptext SLIT("case "), pprBasicLit lit, char ':'],
219 nest 2 (($$) (pprAbsC absC (c + switch_head_cost + costs absC))
220 (ptext SLIT("break;"))) ]
222 -- Costs for addressing header of switch and cond. branching -- HWL
223 switch_head_cost = addrModeCosts discrim Rhs + (Cost (0, 1, 0, 0, 0))
225 pprAbsC stmt@(COpStmt results (StgFCallOp fcall uniq) args vol_regs) _
226 = pprFCall fcall uniq args results vol_regs
228 pprAbsC stmt@(COpStmt results (StgPrimOp op) args vol_regs) _
230 non_void_args = grab_non_void_amodes args
231 non_void_results = grab_non_void_amodes results
232 -- if just one result, we print in the obvious "assignment" style;
233 -- if 0 or many results, we emit a macro call, w/ the results
234 -- followed by the arguments. The macro presumably knows which
237 the_op = ppr_op_call non_void_results non_void_args
238 -- liveness mask is *in* the non_void_args
240 if primOpNeedsWrapper op then
241 case (ppr_vol_regs vol_regs) of { (pp_saves, pp_restores) ->
250 ppr_op_call results args
251 = hcat [ ppr op, lparen,
252 hcat (punctuate comma (map ppr_op_result results)),
253 if null results || null args then empty else comma,
254 hcat (punctuate comma (map pprAmode args)),
257 ppr_op_result r = ppr_amode r
258 -- primop macros do their own casting of result;
259 -- hence we can toss the provided cast...
261 -- NEW CASES FOR EXPANDED PRIMOPS
263 pprAbsC stmt@(CMachOpStmt res mop [arg1,arg2] maybe_vols) _
264 = let prefix_fn = mop `elem` [MO_Dbl_Pwr, MO_Flt_Pwr, MO_NatS_MulMayOflo]
266 case ppr_maybe_vol_regs maybe_vols of {(saves,restores) ->
269 [ppr_amode res, equals]
271 then [pprMachOp_for_C mop, parens (pprAmode arg1 <> comma <> pprAmode arg2)]
272 else [pprAmode arg1, pprMachOp_for_C mop, pprAmode arg2])
278 pprAbsC stmt@(CMachOpStmt res mop [arg1] maybe_vols) _
279 = case ppr_maybe_vol_regs maybe_vols of {(saves,restores) ->
281 hcat [ppr_amode res, equals,
282 pprMachOp_for_C mop, parens (pprAmode arg1),
287 pprAbsC stmt@(CSequential stuff) c
288 = vcat (map (flip pprAbsC c) stuff)
290 -- end of NEW CASES FOR EXPANDED PRIMOPS
292 pprAbsC stmt@(CSRT lbl closures) c
293 = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
295 $$ ptext SLIT("SRT") <> lparen <> pprCLabel lbl <> rparen
296 $$ nest 2 (hcat (punctuate comma (map pp_closure_lbl closures)))
300 pprAbsC stmt@(CBitmap liveness@(Liveness lbl size mask)) c
301 = pprWordArray lbl (mkWordCLit (fromIntegral size) : bitmapAddrModes mask)
303 pprAbsC stmt@(CSRTDesc desc_lbl srt_lbl off len bitmap) c
304 = pprWordArray desc_lbl (
305 CAddr (CIndex (CLbl srt_lbl DataPtrRep) (mkIntCLit off) WordRep) :
306 mkWordCLit (fromIntegral len) :
307 bitmapAddrModes bitmap
310 pprAbsC (CSimultaneous abs_c) c
311 = hcat [ptext SLIT("{{"), pprAbsC abs_c c, ptext SLIT("}}")]
313 pprAbsC (CCheck macro as code) c
314 = hcat [ptext (cCheckMacroText macro), lparen,
315 hcat (punctuate comma (map ppr_amode as)), comma,
316 pprAbsC code c, pp_paren_semi
318 pprAbsC (CMacroStmt macro as) _
319 = hcat [ptext (cStmtMacroText macro), lparen,
320 hcat (punctuate comma (map ppr_amode as)),pp_paren_semi] -- no casting
321 pprAbsC (CCallProfCtrMacro op as) _
322 = hcat [ftext op, lparen,
323 hcat (punctuate comma (map ppr_amode as)),pp_paren_semi]
324 pprAbsC (CCallProfCCMacro op as) _
325 = hcat [ftext op, lparen,
326 hcat (punctuate comma (map ppr_amode as)),pp_paren_semi]
327 pprAbsC stmt@(CCallTypedef is_tdef (CCallSpec op_str cconv _) uniq results args) _
328 = hsep [ ptext (if is_tdef then SLIT("typedef") else SLIT("extern"))
331 , parens (hsep (punctuate comma ccall_decl_ty_args))
335 In the non-casm case, to ensure that we're entering the given external
336 entry point using the correct calling convention, we have to do the following:
338 - When entering via a function pointer (the `dynamic' case) using the specified
339 calling convention, we emit a typedefn declaration attributed with the
340 calling convention to use together with the result and parameter types we're
341 assuming. Coerce the function pointer to this type and go.
343 - to enter the function at a given code label, we emit an extern declaration
344 for the label here, stating the calling convention together with result and
345 argument types we're assuming.
347 The C compiler will hopefully use this extern declaration to good effect,
348 reporting any discrepancies between our extern decl and any other that
351 Re: calling convention, notice that gcc (2.8.1 and egcs-1.0.2) will for
352 the external function `foo' use the calling convention of the first `foo'
353 prototype it encounters (nor does it complain about conflicting attribute
354 declarations). The consequence of this is that you cannot override the
355 calling convention of `foo' using an extern declaration (you'd have to use
356 a typedef), but why you would want to do such a thing in the first place
357 is totally beyond me.
359 ToDo: petition the gcc folks to add code to warn about conflicting attribute
365 | is_tdef = parens (text (ccallConvAttribute cconv) <+> char '*' <> ccall_fun_ty)
366 | otherwise = text (ccallConvAttribute cconv) <+> ccall_fun_ty
370 DynamicTarget -> ptext SLIT("_ccall_fun_ty") <> ppr uniq
371 StaticTarget x -> pprCLabelString x
374 case non_void_results of
375 [] -> ptext SLIT("void")
376 [amode] -> ppr (getAmodeRep amode)
377 _ -> panic "pprAbsC{CCallTypedef}: ccall_res_ty"
380 | is_tdef = tail ccall_arg_tys
381 | otherwise = ccall_arg_tys
383 ccall_arg_tys = map (ppr . getAmodeRep) non_void_args
385 -- the first argument will be the "I/O world" token (a VoidRep)
386 -- all others should be non-void
389 in ASSERT (all non_void nvas) nvas
391 -- there will usually be two results: a (void) state which we
392 -- should ignore and a (possibly void) result.
394 let nvrs = grab_non_void_amodes results
395 in ASSERT (listLengthCmp nvrs 1 /= GT) nvrs
397 pprAbsC (CCodeBlock lbl abs_C) _
398 = if not (isJust(nonemptyAbsC abs_C)) then
399 pprTrace "pprAbsC: curious empty code block for" (pprCLabel lbl) empty
401 case (pprTempAndExternDecls abs_C) of { (pp_temps, pp_exts) ->
405 hcat [text (if (externallyVisibleCLabel lbl)
406 then "FN_(" -- abbreviations to save on output
408 pprCLabel lbl, text ") {"],
412 nest 8 (ptext SLIT("FB_")),
413 nest 8 (pprAbsC abs_C (costs abs_C)),
414 nest 8 (ptext SLIT("FE_")),
420 pprAbsC (CInitHdr cl_info amode cost_centre size) _
421 = hcat [ ptext SLIT("SET_HDR_"), char '(',
422 ppr_amode amode, comma,
423 pprCLabelAddr info_lbl, comma,
424 if_profiling (pprAmode cost_centre), comma,
425 if_profiling (int size),
428 info_lbl = infoTableLabelFromCI cl_info
431 pprAbsC stmt@(CStaticClosure closure_lbl cl_info cost_centre amodes) _
432 = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
436 ptext SLIT("SET_STATIC_HDR"), char '(',
437 pprCLabel closure_lbl, comma,
438 pprCLabel info_lbl, comma,
439 if_profiling (pprAmode cost_centre), comma,
440 ppLocalness closure_lbl, comma,
441 ppLocalnessMacro True{-include dyn-} info_lbl,
444 nest 2 (ppr_payload amodes),
448 info_lbl = infoTableLabelFromCI cl_info
450 ppr_payload [] = empty
453 (braces $ hsep $ punctuate comma $
454 map (text "(L_)" <>) (foldr ppr_item [] ls))
457 | rep == VoidRep = rest
458 | rep == FloatRep = ppr_amode (floatToWord item) : rest
459 | rep == DoubleRep = map ppr_amode (doubleToWords item) ++ rest
460 | otherwise = ppr_amode item : rest
462 rep = getAmodeRep item
464 pprAbsC stmt@(CClosureInfoAndCode cl_info entry) _
465 = pprWordArray info_lbl (mkInfoTable cl_info)
466 $$ let stuff = CCodeBlock entry_lbl entry in
467 pprAbsC stuff (costs stuff)
469 entry_lbl = entryLabelFromCI cl_info
470 info_lbl = infoTableLabelFromCI cl_info
472 pprAbsC stmt@(CClosureTbl tycon) _
474 ptext SLIT("CLOSURE_TBL") <>
475 lparen <> pprCLabel (mkClosureTblLabel tycon) <> rparen :
477 map (pp_closure_lbl . mkClosureLabel . getName) (tyConDataCons tycon)
479 ) $$ ptext SLIT("};")
481 pprAbsC stmt@(CRetDirect uniq code srt liveness) _
482 = pprWordArray info_lbl (mkRetInfoTable entry_lbl srt liveness)
483 $$ let stuff = CCodeBlock entry_lbl code in
484 pprAbsC stuff (costs stuff)
486 info_lbl = mkReturnInfoLabel uniq
487 entry_lbl = mkReturnPtLabel uniq
489 pprAbsC stmt@(CRetVector lbl amodes srt liveness) _
490 = pprWordArray lbl (mkVecInfoTable amodes srt liveness)
492 pprAbsC stmt@(CModuleInitBlock plain_lbl lbl code) _
494 ptext SLIT("START_MOD_INIT") <>
495 parens (pprCLabel plain_lbl <> comma <> pprCLabel lbl),
496 case (pprTempAndExternDecls stmt) of { (_, pp_exts) -> pp_exts },
497 pprAbsC code (costs code),
498 hcat [ptext SLIT("END_MOD_INIT"), lparen, rparen]
501 pprAbsC (CCostCentreDecl is_local cc) _ = pprCostCentreDecl is_local cc
502 pprAbsC (CCostCentreStackDecl ccs) _ = pprCostCentreStackDecl ccs
505 Info tables... just arrays of words (the translation is done in
509 pprWordArray lbl amodes
510 = (case snd (initTE (ppr_decls_Amodes amodes)) of
513 $$ hcat [ ppLocalness lbl, ptext SLIT("StgWord "),
514 pprCLabel lbl, ptext SLIT("[] = {") ]
515 $$ hcat (punctuate comma (map (castToWord.pprAmode) amodes))
518 castToWord s = text "(W_)(" <> s <> char ')'
522 -- Print a CMachOp in a way suitable for emitting via C.
523 pprMachOp_for_C MO_Nat_Add = char '+'
524 pprMachOp_for_C MO_Nat_Sub = char '-'
525 pprMachOp_for_C MO_Nat_Eq = text "=="
526 pprMachOp_for_C MO_Nat_Ne = text "!="
528 pprMachOp_for_C MO_NatS_Ge = text ">="
529 pprMachOp_for_C MO_NatS_Le = text "<="
530 pprMachOp_for_C MO_NatS_Gt = text ">"
531 pprMachOp_for_C MO_NatS_Lt = text "<"
533 pprMachOp_for_C MO_NatU_Ge = text ">="
534 pprMachOp_for_C MO_NatU_Le = text "<="
535 pprMachOp_for_C MO_NatU_Gt = text ">"
536 pprMachOp_for_C MO_NatU_Lt = text "<"
538 pprMachOp_for_C MO_NatS_Mul = char '*'
539 pprMachOp_for_C MO_NatS_MulMayOflo = text "mulIntMayOflo"
540 pprMachOp_for_C MO_NatS_Quot = char '/'
541 pprMachOp_for_C MO_NatS_Rem = char '%'
542 pprMachOp_for_C MO_NatS_Neg = char '-'
544 pprMachOp_for_C MO_NatU_Mul = char '*'
545 pprMachOp_for_C MO_NatU_Quot = char '/'
546 pprMachOp_for_C MO_NatU_Rem = char '%'
548 pprMachOp_for_C MO_Nat_And = text "&"
549 pprMachOp_for_C MO_Nat_Or = text "|"
550 pprMachOp_for_C MO_Nat_Xor = text "^"
551 pprMachOp_for_C MO_Nat_Not = text "~"
552 pprMachOp_for_C MO_Nat_Shl = text "<<"
553 pprMachOp_for_C MO_Nat_Shr = text ">>"
554 pprMachOp_for_C MO_Nat_Sar = text ">>"
556 pprMachOp_for_C MO_32U_Eq = text "=="
557 pprMachOp_for_C MO_32U_Ne = text "!="
558 pprMachOp_for_C MO_32U_Ge = text ">="
559 pprMachOp_for_C MO_32U_Le = text "<="
560 pprMachOp_for_C MO_32U_Gt = text ">"
561 pprMachOp_for_C MO_32U_Lt = text "<"
563 pprMachOp_for_C MO_Dbl_Eq = text "=="
564 pprMachOp_for_C MO_Dbl_Ne = text "!="
565 pprMachOp_for_C MO_Dbl_Ge = text ">="
566 pprMachOp_for_C MO_Dbl_Le = text "<="
567 pprMachOp_for_C MO_Dbl_Gt = text ">"
568 pprMachOp_for_C MO_Dbl_Lt = text "<"
570 pprMachOp_for_C MO_Dbl_Add = text "+"
571 pprMachOp_for_C MO_Dbl_Sub = text "-"
572 pprMachOp_for_C MO_Dbl_Mul = text "*"
573 pprMachOp_for_C MO_Dbl_Div = text "/"
574 pprMachOp_for_C MO_Dbl_Pwr = text "pow"
576 pprMachOp_for_C MO_Dbl_Sin = text "sin"
577 pprMachOp_for_C MO_Dbl_Cos = text "cos"
578 pprMachOp_for_C MO_Dbl_Tan = text "tan"
579 pprMachOp_for_C MO_Dbl_Sinh = text "sinh"
580 pprMachOp_for_C MO_Dbl_Cosh = text "cosh"
581 pprMachOp_for_C MO_Dbl_Tanh = text "tanh"
582 pprMachOp_for_C MO_Dbl_Asin = text "asin"
583 pprMachOp_for_C MO_Dbl_Acos = text "acos"
584 pprMachOp_for_C MO_Dbl_Atan = text "atan"
585 pprMachOp_for_C MO_Dbl_Log = text "log"
586 pprMachOp_for_C MO_Dbl_Exp = text "exp"
587 pprMachOp_for_C MO_Dbl_Sqrt = text "sqrt"
588 pprMachOp_for_C MO_Dbl_Neg = text "-"
590 pprMachOp_for_C MO_Flt_Add = text "+"
591 pprMachOp_for_C MO_Flt_Sub = text "-"
592 pprMachOp_for_C MO_Flt_Mul = text "*"
593 pprMachOp_for_C MO_Flt_Div = text "/"
594 pprMachOp_for_C MO_Flt_Pwr = text "pow"
596 pprMachOp_for_C MO_Flt_Eq = text "=="
597 pprMachOp_for_C MO_Flt_Ne = text "!="
598 pprMachOp_for_C MO_Flt_Ge = text ">="
599 pprMachOp_for_C MO_Flt_Le = text "<="
600 pprMachOp_for_C MO_Flt_Gt = text ">"
601 pprMachOp_for_C MO_Flt_Lt = text "<"
603 pprMachOp_for_C MO_Flt_Sin = text "sin"
604 pprMachOp_for_C MO_Flt_Cos = text "cos"
605 pprMachOp_for_C MO_Flt_Tan = text "tan"
606 pprMachOp_for_C MO_Flt_Sinh = text "sinh"
607 pprMachOp_for_C MO_Flt_Cosh = text "cosh"
608 pprMachOp_for_C MO_Flt_Tanh = text "tanh"
609 pprMachOp_for_C MO_Flt_Asin = text "asin"
610 pprMachOp_for_C MO_Flt_Acos = text "acos"
611 pprMachOp_for_C MO_Flt_Atan = text "atan"
612 pprMachOp_for_C MO_Flt_Log = text "log"
613 pprMachOp_for_C MO_Flt_Exp = text "exp"
614 pprMachOp_for_C MO_Flt_Sqrt = text "sqrt"
615 pprMachOp_for_C MO_Flt_Neg = text "-"
617 pprMachOp_for_C MO_32U_to_NatS = text "(StgInt)"
618 pprMachOp_for_C MO_NatS_to_32U = text "(StgWord32)"
620 pprMachOp_for_C MO_NatS_to_Dbl = text "(StgDouble)"
621 pprMachOp_for_C MO_Dbl_to_NatS = text "(StgInt)"
623 pprMachOp_for_C MO_NatS_to_Flt = text "(StgFloat)"
624 pprMachOp_for_C MO_Flt_to_NatS = text "(StgInt)"
626 pprMachOp_for_C MO_NatS_to_NatU = text "(StgWord)"
627 pprMachOp_for_C MO_NatU_to_NatS = text "(StgInt)"
629 pprMachOp_for_C MO_NatS_to_NatP = text "(void*)"
630 pprMachOp_for_C MO_NatP_to_NatS = text "(StgInt)"
631 pprMachOp_for_C MO_NatU_to_NatP = text "(void*)"
632 pprMachOp_for_C MO_NatP_to_NatU = text "(StgWord)"
634 pprMachOp_for_C MO_Dbl_to_Flt = text "(StgFloat)"
635 pprMachOp_for_C MO_Flt_to_Dbl = text "(StgDouble)"
637 pprMachOp_for_C MO_8S_to_NatS = text "(StgInt8)(StgInt)"
638 pprMachOp_for_C MO_16S_to_NatS = text "(StgInt16)(StgInt)"
639 pprMachOp_for_C MO_32S_to_NatS = text "(StgInt32)(StgInt)"
641 pprMachOp_for_C MO_8U_to_NatU = text "(StgWord8)(StgWord)"
642 pprMachOp_for_C MO_16U_to_NatU = text "(StgWord16)(StgWord)"
643 pprMachOp_for_C MO_32U_to_NatU = text "(StgWord32)(StgWord)"
645 pprMachOp_for_C MO_8U_to_32U = text "(StgWord32)"
646 pprMachOp_for_C MO_32U_to_8U = text "(StgWord8)"
650 = if (externallyVisibleCLabel lbl)
652 else ptext SLIT("static ")
654 -- Horrible macros for declaring the types and locality of labels (see
657 ppLocalnessMacro include_dyn_prefix clabel =
662 ClosureType -> ptext SLIT("C_")
663 CodeType -> ptext SLIT("F_")
664 InfoTblType -> ptext SLIT("I_")
665 RetInfoTblType -> ptext SLIT("RI_")
666 ClosureTblType -> ptext SLIT("CP_")
667 DataType -> ptext SLIT("D_")
670 is_visible = externallyVisibleCLabel clabel
671 label_type = labelType clabel
674 | is_visible = char 'E'
675 | otherwise = char 'I'
678 | include_dyn_prefix && labelDynamic clabel = char 'D'
686 grab_non_void_amodes amodes
687 = filter non_void amodes
690 = case (getAmodeRep amode) of
696 ppr_maybe_vol_regs :: Maybe [MagicId] -> (SDoc, SDoc)
697 ppr_maybe_vol_regs Nothing
699 ppr_maybe_vol_regs (Just vrs)
700 = case ppr_vol_regs vrs of
702 -> (pp_basic_saves $$ saves,
703 pp_basic_restores $$ restores)
705 ppr_vol_regs :: [MagicId] -> (SDoc, SDoc)
707 ppr_vol_regs [] = (empty, empty)
708 ppr_vol_regs (VoidReg:rs) = ppr_vol_regs rs
710 = let pp_reg = case r of
711 VanillaReg pk n -> pprVanillaReg n
713 (more_saves, more_restores) = ppr_vol_regs rs
715 (($$) ((<>) (ptext SLIT("CALLER_SAVE_")) pp_reg) more_saves,
716 ($$) ((<>) (ptext SLIT("CALLER_RESTORE_")) pp_reg) more_restores)
718 -- pp_basic_{saves,restores}: The BaseReg, Sp, Hp and
719 -- HpLim (see StgRegs.lh) may need to be saved/restored around CCalls,
720 -- depending on the platform. (The "volatile regs" stuff handles all
721 -- other registers.) Just be *sure* BaseReg is OK before trying to do
722 -- anything else. The correct sequence of saves&restores are
723 -- encoded by the CALLER_*_SYSTEM macros.
724 pp_basic_saves = ptext SLIT("CALLER_SAVE_SYSTEM")
725 pp_basic_restores = ptext SLIT("CALLER_RESTORE_SYSTEM")
730 | labelDynamic lbl = text "DLL_SRT_ENTRY" <> parens (pprCLabel lbl)
731 | otherwise = char '&' <> pprCLabel lbl
736 = if opt_SccProfilingOn
738 else char '0' -- leave it out!
739 -- ---------------------------------------------------------------------------
740 -- Changes for GrAnSim:
741 -- draw costs for computation in head of if into both branches;
742 -- as no abstractC data structure is given for the head, one is constructed
743 -- guessing unknown values and fed into the costs function
744 -- ---------------------------------------------------------------------------
746 do_if_stmt discrim tag alt_code deflt c
748 cond = hcat [ pprAmode discrim
751 , pprAmode (CLit tag)
753 -- to be absolutely sure that none of the
754 -- conversion rules hit, e.g.,
756 -- minInt is different to (int)minInt
758 -- in C (when minInt is a number not a constant
759 -- expression which evaluates to it.)
762 MachInt _ -> ptext SLIT("(I_)")
767 (addrModeCosts discrim Rhs) c
769 ppr_if_stmt pp_pred then_part else_part discrim_costs c
771 hcat [text "if (", pp_pred, text ") {"],
772 nest 8 (pprAbsC then_part (c + discrim_costs +
773 (Cost (0, 2, 0, 0, 0)) +
775 (case nonemptyAbsC else_part of Nothing -> empty; Just _ -> text "} else {"),
776 nest 8 (pprAbsC else_part (c + discrim_costs +
777 (Cost (0, 1, 0, 0, 0)) +
780 {- Total costs = inherited costs (before if) + costs for accessing discrim
781 + costs for cond branch ( = (0, 1, 0, 0, 0) )
782 + costs for that alternative
786 Historical note: this used to be two separate cases -- one for `ccall'
787 and one for `casm'. To get round a potential limitation to only 10
788 arguments, the numbering of arguments in @process_casm@ was beefed up a
791 Some rough notes on generating code for @CCallOp@:
793 1) Evaluate all arguments and stuff them into registers. (done elsewhere)
794 2) Save any essential registers (heap, stack, etc).
796 ToDo: If stable pointers are in use, these must be saved in a place
797 where the runtime system can get at them so that the Stg world can
798 be restarted during the call.
800 3) Save any temporary registers that are currently in use.
801 4) Do the call, putting result into a local variable
802 5) Restore essential registers
803 6) Restore temporaries
805 (This happens after restoration of essential registers because we
806 might need the @Base@ register to access all the others correctly.)
808 Otherwise, copy local variable into result register.
810 8) If ccall (not casm), declare the function being called as extern so
811 that C knows if it returns anything other than an int.
814 { ResultType _ccall_result;
817 _ccall_result = f( args );
821 return_reg = _ccall_result;
825 Amendment to the above: if we can GC, we have to:
827 * make sure we save all our registers away where the garbage collector
829 * be sure that there are no live registers or we're in trouble.
830 (This can cause problems if you try something foolish like passing
831 an array or a foreign obj to a _ccall_GC_ thing.)
832 * increment/decrement the @inCCallGC@ counter before/after the call so
833 that the runtime check that PerformGC is being used sensibly will work.
836 pprFCall call uniq args results vol_regs
838 CCall (CCallSpec target _cconv safety) ->
840 declare_local_vars, -- local var for *result*
841 vcat local_arg_decls,
842 makeCall target safety
843 (process_casm local_vars pp_non_void_args (call_str target)),
847 DNCall (DNCallSpec isStatic kind assem nm argTys resTy) ->
849 target = StaticTarget (mkFastString nm)
850 resultVar = "_ccall_result"
852 hasAssemArg = isStatic || kind == DNConstructor
856 | isStatic -> "DN_invokeStatic"
857 | otherwise -> "DN_invokeMethod"
867 DNConstructor -> "DN_createObject"
869 (methArrDecl, methArrInit, methArrName, methArrLen)
870 | null argTys = (empty, empty, text "NULL", text "0")
872 ( text "DotnetArg __meth_args[" <> int (length argTys) <> text "];"
873 , vcat (zipWith3 (\ idx arg argTy ->
874 text "__meth_args[" <> int idx <> text "].arg." <> text (toDotnetArgField argTy) <> equals <> ppr_amode arg <> semi $$
875 text "__meth_args[" <> int idx <> text "].arg_type=" <> text (toDotnetTy argTy) <> semi)
880 , int (length non_void_args)
885 vcat local_arg_decls,
888 , text "_ccall_result1 =" <+> text invokeOp <> parens (
889 hcat (punctuate comma $
894 doubleQuotes (text assem)):)
897 [ doubleQuotes $ text nm
900 , text (toDotnetTy resTy)
901 , text "(void*)&" <> text resultVar
908 (pp_saves, pp_restores) = ppr_vol_regs vol_regs
910 makeCall target safety theCall =
911 vcat [ pp_save_context, theCall, pp_restore_context ]
913 (pp_save_context, pp_restore_context)
914 | playSafe safety = ( text "{ I_" <+> ppr_uniq_token <>
915 text "; SUSPEND_THREAD" <> parens thread_macro_args <> semi
916 , text "RESUME_THREAD" <> parens thread_macro_args <> text ";}"
918 | otherwise = ( pp_basic_saves $$ pp_saves,
919 pp_basic_restores $$ pp_restores)
921 thread_macro_args = ppr_uniq_token <> comma <+>
922 text "rts" <> ppr (playThreadSafe safety)
923 ppr_uniq_token = text "tok_" <> ppr uniq
928 in ASSERT2 ( all non_void nvas, ppr call <+> hsep (map pprAmode args) )
930 -- the last argument will be the "I/O world" token (a VoidRep)
931 -- all others should be non-void
934 let nvrs = grab_non_void_amodes results
935 in ASSERT (forDotnet || listLengthCmp nvrs 1 /= GT) nvrs
936 -- there will usually be two results: a (void) state which we
937 -- should ignore and a (possibly void) result.
939 (local_arg_decls, pp_non_void_args)
940 = unzip [ ppr_casm_arg a i | (a,i) <- non_void_args `zip` [1..] ]
942 (declare_local_vars, local_vars, assign_results)
943 = ppr_casm_results non_void_results forDotnet
952 StaticTarget fn -> mk_ccall_str (pprCLabelString fn) ccall_args
953 DynamicTarget -> mk_ccall_str dyn_fun (tail ccall_args)
955 ccall_args = zipWith (\ _ i -> char '%' <> int i) non_void_args [0..]
956 dyn_fun = parens (parens (ptext SLIT("_ccall_fun_ty") <> ppr uniq) <> text "%0")
959 -- Remainder only used for ccall
960 mk_ccall_str fun_name ccall_fun_args = showSDoc
962 if null non_void_results
965 lparen, fun_name, lparen,
966 hcat (punctuate comma ccall_fun_args),
970 toDotnetTy :: DNType -> String
973 DNByte -> "Dotnet_Byte"
974 DNBool -> "Dotnet_Bool"
975 DNChar -> "Dotnet_Char"
976 DNDouble -> "Dotnet_Double"
977 DNFloat -> "Dotnet_Float"
978 DNInt -> "Dotnet_Int"
979 DNInt8 -> "Dotnet_Int8"
980 DNInt16 -> "Dotnet_Int16"
981 DNInt32 -> "Dotnet_Int32"
982 DNInt64 -> "Dotnet_Int64"
983 DNWord8 -> "Dotnet_Word8"
984 DNWord16 -> "Dotnet_Word16"
985 DNWord32 -> "Dotnet_Word32"
986 DNWord64 -> "Dotnet_Word64"
987 DNPtr -> "Dotnet_Ptr"
988 DNUnit -> "Dotnet_Unit"
989 DNObject -> "Dotnet_Object"
990 DNString -> "Dotnet_String"
992 toDotnetArgField :: DNType -> String
998 DNDouble -> "arg_double"
999 DNFloat -> "arg_float"
1001 DNInt8 -> "arg_int8"
1002 DNInt16 -> "arg_int16"
1003 DNInt32 -> "arg_int32"
1004 DNInt64 -> "arg_int64"
1005 DNWord8 -> "arg_word8"
1006 DNWord16 -> "arg_word16"
1007 DNWord32 -> "arg_word32"
1008 DNWord64 -> "arg_word64"
1010 DNUnit -> "arg_ptr" -- can't happen
1011 DNObject -> "arg_obj"
1012 DNString -> "arg_str"
1014 ppr_casm_arg :: CAddrMode -> Int -> (SDoc, SDoc)
1015 -- (a) decl and assignment, (b) local var to be used later
1017 ppr_casm_arg amode a_num
1019 a_kind = getAmodeRep amode
1020 pp_amode = pprAmode amode
1021 pp_kind = pprPrimKind a_kind
1023 local_var = (<>) (ptext SLIT("_ccall_arg")) (int a_num)
1026 = hcat [ pp_kind, space, local_var, equals, pp_amode, semi ]
1028 (declare_local_var, local_var)
1031 For l-values, the critical questions are:
1033 1) Are there any results at all?
1035 We only allow zero or one results.
1039 :: [CAddrMode] -- list of results (length <= 1)
1040 -> Bool -- True => multiple results OK.
1042 ( SDoc, -- declaration of any local vars
1043 [SDoc], -- list of result vars (same length as results)
1044 SDoc ) -- assignment (if any) of results in local var to registers
1046 ppr_casm_results [] _
1047 = (empty, [], empty) -- no results
1049 ppr_casm_results (r:rs) multiResultsOK
1050 | not multiResultsOK && not (null rs) = panic "ppr_casm_results: ccall/casm with many results"
1052 = foldr (\ (a,b,c) (as,bs,cs) -> (a $$ as, b ++ bs, c $$ cs))
1054 (zipWith pprRes (r:rs) ("" : map show [(1::Int)..]))
1056 pprRes r suf = (declare_local_var, [local_var], assign_result)
1058 result_reg = ppr_amode r
1059 r_kind = getAmodeRep r
1061 local_var = ptext SLIT("_ccall_result") <> text suf
1063 (result_type, assign_result)
1064 = (pprPrimKind r_kind,
1065 hcat [ result_reg, equals, local_var, semi ])
1067 declare_local_var = hcat [ result_type, space, local_var, semi ]
1072 Note the sneaky way _the_ result is represented by a list so that we
1073 can complain if it's used twice.
1075 ToDo: Any chance of giving line numbers when process-casm fails?
1076 Or maybe we should do a check _much earlier_ in compiler. ADR
1079 process_casm :: [SDoc] -- results (length <= 1)
1080 -> [SDoc] -- arguments
1081 -> String -- format string (with embedded %'s)
1082 -> SDoc -- code being generated
1084 process_casm results args string = process results args string
1086 process [] _ "" = empty
1087 process (_:_) _ "" = error ("process_casm: non-void result not assigned while processing _casm_ \"" ++
1089 "\"\n(Try changing result type to IO ()\n")
1091 process ress args ('%':cs)
1094 error ("process_casm: lonely % while processing _casm_ \"" ++ string ++ "\".\n")
1097 char '%' <> process ress args css
1101 [] -> error ("process_casm: no result to match %r while processing _casm_ \"" ++ string ++ "\".\nTry deleting %r or changing result type from PrimIO ()\n")
1102 [r] -> r <> (process [] args css)
1103 _ -> panic ("process_casm: casm with many results while processing _casm_ \"" ++ string ++ "\".\n")
1107 read_int :: ReadS Int
1110 case (read_int other) of
1112 if num >= 0 && args `lengthExceeds` num
1113 then parens (args !! num) <> process ress args css
1114 else error ("process_casm: no such arg #:"++(show num)++" while processing \"" ++ string ++ "\".\n")
1115 _ -> error ("process_casm: not %<num> while processing _casm_ \"" ++ string ++ "\".\n")
1117 process ress args (other_c:cs)
1118 = char other_c <> process ress args cs
1121 %************************************************************************
1123 \subsection[a2r-assignments]{Assignments}
1125 %************************************************************************
1127 Printing assignments is a little tricky because of type coercion.
1129 First of all, the kind of the thing being assigned can be gotten from
1130 the destination addressing mode. (It should be the same as the kind
1131 of the source addressing mode.) If the kind of the assignment is of
1132 @VoidRep@, then don't generate any code at all.
1135 pprAssign :: PrimRep -> CAddrMode -> CAddrMode -> SDoc
1137 pprAssign VoidRep dest src = empty
1140 Special treatment for floats and doubles, to avoid unwanted conversions.
1143 pprAssign FloatRep dest@(CVal reg_rel _) src
1144 = hcat [ ptext SLIT("ASSIGN_FLT((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1146 pprAssign DoubleRep dest@(CVal reg_rel _) src
1147 = hcat [ ptext SLIT("ASSIGN_DBL((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1149 pprAssign Int64Rep dest@(CVal reg_rel _) src
1150 = hcat [ ptext SLIT("ASSIGN_Int64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1151 pprAssign Word64Rep dest@(CVal reg_rel _) src
1152 = hcat [ ptext SLIT("ASSIGN_Word64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1155 Lastly, the question is: will the C compiler think the types of the
1156 two sides of the assignment match?
1158 We assume that the types will match if neither side is a
1159 @CVal@ addressing mode for any register which can point into
1162 Why? Because the heap and stack are used to store miscellaneous
1163 things, whereas the temporaries, registers, etc., are only used for
1164 things of fixed type.
1167 pprAssign kind (CReg (VanillaReg _ dest)) (CReg (VanillaReg _ src))
1168 = hcat [ pprVanillaReg dest, equals,
1169 pprVanillaReg src, semi ]
1171 pprAssign kind dest src
1172 | mixedTypeLocn dest
1173 -- Add in a cast to StgWord (a.k.a. W_) iff the destination is mixed
1174 = hcat [ ppr_amode dest, equals,
1175 text "(W_)(", -- Here is the cast
1176 ppr_amode src, pp_paren_semi ]
1178 pprAssign kind dest src
1179 | mixedPtrLocn dest && getAmodeRep src /= PtrRep
1180 -- Add in a cast to StgPtr (a.k.a. P_) iff the destination is mixed
1181 = hcat [ ppr_amode dest, equals,
1182 text "(P_)(", -- Here is the cast
1183 ppr_amode src, pp_paren_semi ]
1185 pprAssign kind other_dest src
1186 = hcat [ ppr_amode other_dest, equals,
1187 pprAmode src, semi ]
1191 %************************************************************************
1193 \subsection[a2r-CAddrModes]{Addressing modes}
1195 %************************************************************************
1197 @pprAmode@ is used to print r-values (which may need casts), whereas
1198 @ppr_amode@ is used for l-values {\em and} as a help function for
1202 pprAmode, ppr_amode :: CAddrMode -> SDoc
1205 For reasons discussed above under assignments, @CVal@ modes need
1206 to be treated carefully. First come special cases for floats and doubles,
1207 similar to those in @pprAssign@:
1209 (NB: @PK_FLT@ and @PK_DBL@ require the {\em address} of the value in
1213 pprAmode (CVal reg_rel FloatRep)
1214 = hcat [ text "PK_FLT((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1215 pprAmode (CVal reg_rel DoubleRep)
1216 = hcat [ text "PK_DBL((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1217 pprAmode (CVal reg_rel Int64Rep)
1218 = hcat [ text "PK_Int64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1219 pprAmode (CVal reg_rel Word64Rep)
1220 = hcat [ text "PK_Word64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1223 Next comes the case where there is some other cast need, and the
1228 | mixedTypeLocn amode
1229 = parens (hcat [ pprPrimKind (getAmodeRep amode), ptext SLIT(")("),
1231 | otherwise -- No cast needed
1235 When we have an indirection through a CIndex, we have to be careful to
1236 get the type casts right.
1240 CVal (CIndex kind1 base offset) kind2
1244 *(kind2 *)((kind1 *)base + offset)
1246 That is, the indexing is done in units of kind1, but the resulting
1250 ppr_amode (CVal reg_rel@(CIndex _ _ _) kind)
1251 = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1252 (pp_reg, Nothing) -> panic "ppr_amode: CIndex"
1253 (pp_reg, Just offset) ->
1254 hcat [ char '*', parens (pprPrimKind kind <> char '*'),
1255 parens (pp_reg <> char '+' <> offset) ]
1258 Now the rest of the cases for ``workhorse'' @ppr_amode@:
1261 ppr_amode (CVal reg_rel _)
1262 = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1263 (pp_reg, Nothing) -> (<>) (char '*') pp_reg
1264 (pp_reg, Just offset) -> hcat [ pp_reg, brackets offset ]
1266 ppr_amode (CAddr reg_rel)
1267 = case (pprRegRelative True{-sign wanted-} reg_rel) of
1268 (pp_reg, Nothing) -> pp_reg
1269 (pp_reg, Just offset) -> pp_reg <> offset
1271 ppr_amode (CReg magic_id) = pprMagicId magic_id
1273 ppr_amode (CTemp uniq kind) = char '_' <> pprUnique uniq <> char '_'
1275 ppr_amode (CLbl lbl kind) = pprCLabelAddr lbl
1277 ppr_amode (CCharLike ch)
1278 = hcat [ptext SLIT("CHARLIKE_CLOSURE"), char '(', pprAmode ch, rparen ]
1279 ppr_amode (CIntLike int)
1280 = hcat [ptext SLIT("INTLIKE_CLOSURE"), char '(', pprAmode int, rparen ]
1282 ppr_amode (CLit lit) = pprBasicLit lit
1284 ppr_amode (CJoinPoint _)
1285 = panic "ppr_amode: CJoinPoint"
1287 ppr_amode (CMacroExpr pk macro as)
1288 = parens (ptext (cExprMacroText macro) <>
1289 parens (hcat (punctuate comma (map pprAmode as))))
1293 cExprMacroText ENTRY_CODE = SLIT("ENTRY_CODE")
1294 cExprMacroText ARG_TAG = SLIT("ARG_TAG")
1295 cExprMacroText GET_TAG = SLIT("GET_TAG")
1296 cExprMacroText CCS_HDR = SLIT("CCS_HDR")
1297 cExprMacroText BYTE_ARR_CTS = SLIT("BYTE_ARR_CTS")
1298 cExprMacroText PTRS_ARR_CTS = SLIT("PTRS_ARR_CTS")
1299 cExprMacroText ForeignObj_CLOSURE_DATA = SLIT("ForeignObj_CLOSURE_DATA")
1301 cStmtMacroText UPD_CAF = SLIT("UPD_CAF")
1302 cStmtMacroText UPD_BH_UPDATABLE = SLIT("UPD_BH_UPDATABLE")
1303 cStmtMacroText UPD_BH_SINGLE_ENTRY = SLIT("UPD_BH_SINGLE_ENTRY")
1304 cStmtMacroText PUSH_UPD_FRAME = SLIT("PUSH_UPD_FRAME")
1305 cStmtMacroText SET_TAG = SLIT("SET_TAG")
1306 cStmtMacroText DATA_TO_TAGZH = SLIT("dataToTagzh")
1307 cStmtMacroText REGISTER_FOREIGN_EXPORT = SLIT("REGISTER_FOREIGN_EXPORT")
1308 cStmtMacroText REGISTER_IMPORT = SLIT("REGISTER_IMPORT")
1309 cStmtMacroText REGISTER_DIMPORT = SLIT("REGISTER_DIMPORT")
1310 cStmtMacroText GRAN_FETCH = SLIT("GRAN_FETCH")
1311 cStmtMacroText GRAN_RESCHEDULE = SLIT("GRAN_RESCHEDULE")
1312 cStmtMacroText GRAN_FETCH_AND_RESCHEDULE= SLIT("GRAN_FETCH_AND_RESCHEDULE")
1313 cStmtMacroText THREAD_CONTEXT_SWITCH = SLIT("THREAD_CONTEXT_SWITCH")
1314 cStmtMacroText GRAN_YIELD = SLIT("GRAN_YIELD")
1316 cCheckMacroText HP_CHK_NP = SLIT("HP_CHK_NP")
1317 cCheckMacroText STK_CHK_NP = SLIT("STK_CHK_NP")
1318 cCheckMacroText HP_STK_CHK_NP = SLIT("HP_STK_CHK_NP")
1319 cCheckMacroText HP_CHK_FUN = SLIT("HP_CHK_FUN")
1320 cCheckMacroText STK_CHK_FUN = SLIT("STK_CHK_FUN")
1321 cCheckMacroText HP_STK_CHK_FUN = SLIT("HP_STK_CHK_FUN")
1322 cCheckMacroText HP_CHK_NOREGS = SLIT("HP_CHK_NOREGS")
1323 cCheckMacroText HP_CHK_UNPT_R1 = SLIT("HP_CHK_UNPT_R1")
1324 cCheckMacroText HP_CHK_UNBX_R1 = SLIT("HP_CHK_UNBX_R1")
1325 cCheckMacroText HP_CHK_F1 = SLIT("HP_CHK_F1")
1326 cCheckMacroText HP_CHK_D1 = SLIT("HP_CHK_D1")
1327 cCheckMacroText HP_CHK_L1 = SLIT("HP_CHK_L1")
1328 cCheckMacroText HP_CHK_UNBX_TUPLE = SLIT("HP_CHK_UNBX_TUPLE")
1331 %************************************************************************
1333 \subsection[ppr-liveness-masks]{Liveness Masks}
1335 %************************************************************************
1338 bitmapAddrModes [] = [mkWordCLit 0]
1339 bitmapAddrModes xs = map mkWordCLit xs
1342 %************************************************************************
1344 \subsection[a2r-MagicIds]{Magic ids}
1346 %************************************************************************
1348 @pprRegRelative@ returns a pair of the @Doc@ for the register
1349 (some casting may be required), and a @Maybe Doc@ for the offset
1350 (zero offset gives a @Nothing@).
1353 addPlusSign :: Bool -> SDoc -> SDoc
1354 addPlusSign False p = p
1355 addPlusSign True p = (<>) (char '+') p
1357 pprSignedInt :: Bool -> Int -> Maybe SDoc -- Nothing => 0
1358 pprSignedInt sign_wanted n
1359 = if n == 0 then Nothing else
1360 if n > 0 then Just (addPlusSign sign_wanted (int n))
1363 pprRegRelative :: Bool -- True <=> Print leading plus sign (if +ve)
1365 -> (SDoc, Maybe SDoc)
1367 pprRegRelative sign_wanted (SpRel off)
1368 = (pprMagicId Sp, pprSignedInt sign_wanted (I# off))
1370 pprRegRelative sign_wanted r@(HpRel o)
1371 = let pp_Hp = pprMagicId Hp; off = I# o
1376 (pp_Hp, Just ((<>) (char '-') (int off)))
1378 pprRegRelative sign_wanted (NodeRel o)
1379 = let pp_Node = pprMagicId node; off = I# o
1384 (pp_Node, Just (addPlusSign sign_wanted (int off)))
1386 pprRegRelative sign_wanted (CIndex base offset kind)
1387 = ( hcat [text "((", pprPrimKind kind, text " *)(", ppr_amode base, text "))"]
1388 , Just (hcat [if sign_wanted then char '+' else empty,
1389 text "(I_)(", ppr_amode offset, ptext SLIT(")")])
1393 @pprMagicId@ just prints the register name. @VanillaReg@ registers are
1394 represented by a discriminated union (@StgUnion@), so we use the @PrimRep@
1395 to select the union tag.
1398 pprMagicId :: MagicId -> SDoc
1400 pprMagicId BaseReg = ptext SLIT("BaseReg")
1401 pprMagicId (VanillaReg pk n)
1402 = hcat [ pprVanillaReg n, char '.',
1404 pprMagicId (FloatReg n) = ptext SLIT("F") <> int (I# n)
1405 pprMagicId (DoubleReg n) = ptext SLIT("D") <> int (I# n)
1406 pprMagicId (LongReg _ n) = ptext SLIT("L") <> int (I# n)
1407 pprMagicId Sp = ptext SLIT("Sp")
1408 pprMagicId SpLim = ptext SLIT("SpLim")
1409 pprMagicId Hp = ptext SLIT("Hp")
1410 pprMagicId HpLim = ptext SLIT("HpLim")
1411 pprMagicId CurCostCentre = ptext SLIT("CCCS")
1412 pprMagicId VoidReg = ptext SLIT("VoidReg")
1414 pprVanillaReg :: Int# -> SDoc
1415 pprVanillaReg n = char 'R' <> int (I# n)
1417 pprUnionTag :: PrimRep -> SDoc
1419 pprUnionTag PtrRep = char 'p'
1420 pprUnionTag CodePtrRep = ptext SLIT("fp")
1421 pprUnionTag DataPtrRep = char 'd'
1422 pprUnionTag RetRep = char 'p'
1423 pprUnionTag CostCentreRep = panic "pprUnionTag:CostCentre?"
1425 pprUnionTag CharRep = char 'c'
1426 pprUnionTag Int8Rep = ptext SLIT("i8")
1427 pprUnionTag IntRep = char 'i'
1428 pprUnionTag WordRep = char 'w'
1429 pprUnionTag Int32Rep = char 'i'
1430 pprUnionTag Word32Rep = char 'w'
1431 pprUnionTag AddrRep = char 'a'
1432 pprUnionTag FloatRep = char 'f'
1433 pprUnionTag DoubleRep = panic "pprUnionTag:Double?"
1435 pprUnionTag StablePtrRep = char 'p'
1437 pprUnionTag _ = panic "pprUnionTag:Odd kind"
1441 Find and print local and external declarations for a list of
1442 Abstract~C statements.
1444 pprTempAndExternDecls :: AbstractC -> (SDoc{-temps-}, SDoc{-externs-})
1445 pprTempAndExternDecls AbsCNop = (empty, empty)
1447 pprTempAndExternDecls (AbsCStmts stmt1 stmt2)
1448 = initTE (ppr_decls_AbsC stmt1 `thenTE` \ (t_p1, e_p1) ->
1449 ppr_decls_AbsC stmt2 `thenTE` \ (t_p2, e_p2) ->
1450 case (catMaybes [t_p1, t_p2]) of { real_temps ->
1451 case (catMaybes [e_p1, e_p2]) of { real_exts ->
1452 returnTE (vcat real_temps, vcat real_exts) }}
1455 pprTempAndExternDecls other_stmt
1456 = initTE (ppr_decls_AbsC other_stmt `thenTE` \ (maybe_t, maybe_e) ->
1467 pprBasicLit :: Literal -> SDoc
1468 pprPrimKind :: PrimRep -> SDoc
1470 pprBasicLit lit = ppr lit
1471 pprPrimKind k = ppr k
1475 %************************************************************************
1477 \subsection[a2r-monad]{Monadery}
1479 %************************************************************************
1481 We need some monadery to keep track of temps and externs we have already
1482 printed. This info must be threaded right through the Abstract~C, so
1483 it's most convenient to hide it in this monad.
1485 WDP 95/02: Switched from \tr{([Unique], [CLabel])} to
1486 \tr{(UniqSet, CLabelSet)}. Allegedly for efficiency.
1489 type CLabelSet = FiniteMap CLabel (){-any type will do-}
1490 emptyCLabelSet = emptyFM
1491 x `elementOfCLabelSet` labs
1492 = case (lookupFM labs x) of { Just _ -> True; Nothing -> False }
1494 addToCLabelSet set x = addToFM set x ()
1496 type TEenv = (UniqSet Unique, CLabelSet)
1498 type TeM result = TEenv -> (TEenv, result)
1500 initTE :: TeM a -> a
1502 = case sa (emptyUniqSet, emptyCLabelSet) of { (_, result) ->
1505 {-# INLINE thenTE #-}
1506 {-# INLINE returnTE #-}
1508 thenTE :: TeM a -> (a -> TeM b) -> TeM b
1510 = case a u of { (u_1, result_of_a) ->
1513 mapTE :: (a -> TeM b) -> [a] -> TeM [b]
1514 mapTE f [] = returnTE []
1516 = f x `thenTE` \ r ->
1517 mapTE f xs `thenTE` \ rs ->
1520 returnTE :: a -> TeM a
1521 returnTE result env = (env, result)
1523 -- these next two check whether the thing is already
1524 -- recorded, and THEN THEY RECORD IT
1525 -- (subsequent calls will return False for the same uniq/label)
1527 tempSeenTE :: Unique -> TeM Bool
1528 tempSeenTE uniq env@(seen_uniqs, seen_labels)
1529 = if (uniq `elementOfUniqSet` seen_uniqs)
1531 else ((addOneToUniqSet seen_uniqs uniq,
1535 labelSeenTE :: CLabel -> TeM Bool
1536 labelSeenTE lbl env@(seen_uniqs, seen_labels)
1537 = if (lbl `elementOfCLabelSet` seen_labels)
1540 addToCLabelSet seen_labels lbl),
1545 pprTempDecl :: Unique -> PrimRep -> SDoc
1546 pprTempDecl uniq kind
1547 = hcat [ pprPrimKind kind, space, char '_', pprUnique uniq, ptext SLIT("_;") ]
1549 pprExternDecl :: Bool -> CLabel -> SDoc
1550 pprExternDecl in_srt clabel
1551 | not (needsCDecl clabel) = empty -- do not print anything for "known external" things
1553 hcat [ ppLocalnessMacro (not in_srt) clabel,
1554 lparen, dyn_wrapper (pprCLabel clabel), pp_paren_semi ]
1557 | in_srt && labelDynamic clabel = text "DLL_IMPORT_DATA_VAR" <> parens d
1563 ppr_decls_AbsC :: AbstractC -> TeM (Maybe SDoc{-temps-}, Maybe SDoc{-externs-})
1565 ppr_decls_AbsC AbsCNop = returnTE (Nothing, Nothing)
1567 ppr_decls_AbsC (AbsCStmts stmts_1 stmts_2)
1568 = ppr_decls_AbsC stmts_1 `thenTE` \ p1 ->
1569 ppr_decls_AbsC stmts_2 `thenTE` \ p2 ->
1570 returnTE (maybe_vcat [p1, p2])
1572 ppr_decls_AbsC (CSplitMarker) = returnTE (Nothing, Nothing)
1574 ppr_decls_AbsC (CAssign dest source)
1575 = ppr_decls_Amode dest `thenTE` \ p1 ->
1576 ppr_decls_Amode source `thenTE` \ p2 ->
1577 returnTE (maybe_vcat [p1, p2])
1579 ppr_decls_AbsC (CJump target) = ppr_decls_Amode target
1581 ppr_decls_AbsC (CFallThrough target) = ppr_decls_Amode target
1583 ppr_decls_AbsC (CReturn target _) = ppr_decls_Amode target
1585 ppr_decls_AbsC (CSwitch discrim alts deflt)
1586 = ppr_decls_Amode discrim `thenTE` \ pdisc ->
1587 mapTE ppr_alt_stuff alts `thenTE` \ palts ->
1588 ppr_decls_AbsC deflt `thenTE` \ pdeflt ->
1589 returnTE (maybe_vcat (pdisc:pdeflt:palts))
1591 ppr_alt_stuff (_, absC) = ppr_decls_AbsC absC
1593 ppr_decls_AbsC (CCodeBlock lbl absC)
1594 = ppr_decls_AbsC absC
1596 ppr_decls_AbsC (CInitHdr cl_info reg_rel cost_centre _)
1597 -- ToDo: strictly speaking, should chk "cost_centre" amode
1598 = labelSeenTE info_lbl `thenTE` \ label_seen ->
1603 Just (pprExternDecl False{-not in an SRT decl-} info_lbl))
1605 info_lbl = infoTableLabelFromCI cl_info
1607 ppr_decls_AbsC (CMachOpStmt res _ args _) = ppr_decls_Amodes (res : args)
1608 ppr_decls_AbsC (COpStmt results _ args _) = ppr_decls_Amodes (results ++ args)
1610 ppr_decls_AbsC (CSimultaneous abc) = ppr_decls_AbsC abc
1612 ppr_decls_AbsC (CSequential abcs)
1613 = mapTE ppr_decls_AbsC abcs `thenTE` \ t_and_e_s ->
1614 returnTE (maybe_vcat t_and_e_s)
1616 ppr_decls_AbsC (CCheck _ amodes code) =
1617 ppr_decls_Amodes amodes `thenTE` \p1 ->
1618 ppr_decls_AbsC code `thenTE` \p2 ->
1619 returnTE (maybe_vcat [p1,p2])
1621 ppr_decls_AbsC (CMacroStmt _ amodes) = ppr_decls_Amodes amodes
1623 ppr_decls_AbsC (CCallProfCtrMacro _ amodes) = ppr_decls_Amodes [] -- *****!!!
1624 -- you get some nasty re-decls of stdio.h if you compile
1625 -- the prelude while looking inside those amodes;
1626 -- no real reason to, anyway.
1627 ppr_decls_AbsC (CCallProfCCMacro _ amodes) = ppr_decls_Amodes amodes
1629 ppr_decls_AbsC (CStaticClosure _ closure_info cost_centre amodes)
1630 -- ToDo: strictly speaking, should chk "cost_centre" amode
1631 = ppr_decls_Amodes amodes
1633 ppr_decls_AbsC (CClosureInfoAndCode cl_info entry)
1634 = ppr_decls_Amodes [entry_lbl] `thenTE` \ p1 ->
1635 ppr_decls_AbsC entry `thenTE` \ p2 ->
1636 returnTE (maybe_vcat [p1, p2])
1638 entry_lbl = CLbl (entryLabelFromCI cl_info) CodePtrRep
1640 ppr_decls_AbsC (CSRT _ closure_lbls)
1641 = mapTE labelSeenTE closure_lbls `thenTE` \ seen ->
1643 if and seen then Nothing
1644 else Just (vcat [ pprExternDecl True{-in SRT decl-} l
1645 | (l,False) <- zip closure_lbls seen ]))
1647 ppr_decls_AbsC (CRetDirect _ code _ _) = ppr_decls_AbsC code
1648 ppr_decls_AbsC (CRetVector _ amodes _ _) = ppr_decls_Amodes amodes
1649 ppr_decls_AbsC (CModuleInitBlock _ _ code) = ppr_decls_AbsC code
1651 ppr_decls_AbsC (_) = returnTE (Nothing, Nothing)
1655 ppr_decls_Amode :: CAddrMode -> TeM (Maybe SDoc, Maybe SDoc)
1656 ppr_decls_Amode (CVal (CIndex base offset _) _) = ppr_decls_Amodes [base,offset]
1657 ppr_decls_Amode (CAddr (CIndex base offset _)) = ppr_decls_Amodes [base,offset]
1658 ppr_decls_Amode (CVal _ _) = returnTE (Nothing, Nothing)
1659 ppr_decls_Amode (CAddr _) = returnTE (Nothing, Nothing)
1660 ppr_decls_Amode (CReg _) = returnTE (Nothing, Nothing)
1661 ppr_decls_Amode (CLit _) = returnTE (Nothing, Nothing)
1663 -- CIntLike must be a literal -- no decls
1664 ppr_decls_Amode (CIntLike int) = returnTE (Nothing, Nothing)
1667 ppr_decls_Amode (CCharLike char) = returnTE (Nothing, Nothing)
1669 -- now, the only place where we actually print temps/externs...
1670 ppr_decls_Amode (CTemp uniq kind)
1672 VoidRep -> returnTE (Nothing, Nothing)
1674 tempSeenTE uniq `thenTE` \ temp_seen ->
1676 (if temp_seen then Nothing else Just (pprTempDecl uniq kind), Nothing)
1678 ppr_decls_Amode (CLbl lbl VoidRep)
1679 = returnTE (Nothing, Nothing)
1681 ppr_decls_Amode (CLbl lbl kind)
1682 = labelSeenTE lbl `thenTE` \ label_seen ->
1684 if label_seen then Nothing else Just (pprExternDecl False{-not in an SRT decl-} lbl))
1686 ppr_decls_Amode (CMacroExpr _ _ amodes)
1687 = ppr_decls_Amodes amodes
1689 ppr_decls_Amode other = returnTE (Nothing, Nothing)
1692 maybe_vcat :: [(Maybe SDoc, Maybe SDoc)] -> (Maybe SDoc, Maybe SDoc)
1694 = case (unzip ps) of { (ts, es) ->
1695 case (catMaybes ts) of { real_ts ->
1696 case (catMaybes es) of { real_es ->
1697 (if (null real_ts) then Nothing else Just (vcat real_ts),
1698 if (null real_es) then Nothing else Just (vcat real_es))
1703 ppr_decls_Amodes :: [CAddrMode] -> TeM (Maybe SDoc, Maybe SDoc)
1704 ppr_decls_Amodes amodes
1705 = mapTE ppr_decls_Amode amodes `thenTE` \ ps ->
1706 returnTE ( maybe_vcat ps )
1709 Print out a C Label where you want the *address* of the label, not the
1710 object it refers to. The distinction is important when the label may
1711 refer to a C structure (info tables and closures, for instance).
1713 When just generating a declaration for the label, use pprCLabel.
1716 pprCLabelAddr :: CLabel -> SDoc
1717 pprCLabelAddr clabel =
1718 case labelType clabel of
1719 InfoTblType -> addr_of_label
1720 RetInfoTblType -> addr_of_label
1721 ClosureType -> addr_of_label
1722 VecTblType -> addr_of_label
1723 DataType -> addr_of_label
1727 addr_of_label = ptext SLIT("(P_)&") <> pp_label
1728 pp_label = pprCLabel clabel
1731 -----------------------------------------------------------------------------
1732 Initialising static objects with floating-point numbers. We can't
1733 just emit the floating point number, because C will cast it to an int
1734 by rounding it. We want the actual bit-representation of the float.
1736 This is a hack to turn the floating point numbers into ints that we
1737 can safely initialise to static locations.
1740 big_doubles = (getPrimRepSize DoubleRep) /= 1
1742 #if __GLASGOW_HASKELL__ >= 504
1743 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
1744 newFloatArray = newArray_
1746 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
1747 newDoubleArray = newArray_
1749 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
1750 castFloatToIntArray = castSTUArray
1752 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
1753 castDoubleToIntArray = castSTUArray
1755 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
1756 writeFloatArray = writeArray
1758 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
1759 writeDoubleArray = writeArray
1761 readIntArray :: STUArray s Int Int -> Int -> ST s Int
1762 readIntArray = readArray
1766 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
1767 castFloatToIntArray = return
1769 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
1770 castDoubleToIntArray = return
1774 -- floats are always 1 word
1775 floatToWord :: CAddrMode -> CAddrMode
1776 floatToWord (CLit (MachFloat r))
1778 arr <- newFloatArray ((0::Int),0)
1779 writeFloatArray arr 0 (fromRational r)
1780 arr' <- castFloatToIntArray arr
1781 i <- readIntArray arr' 0
1782 return (CLit (MachInt (toInteger i)))
1785 doubleToWords :: CAddrMode -> [CAddrMode]
1786 doubleToWords (CLit (MachDouble r))
1787 | big_doubles -- doubles are 2 words
1789 arr <- newDoubleArray ((0::Int),1)
1790 writeDoubleArray arr 0 (fromRational r)
1791 arr' <- castDoubleToIntArray arr
1792 i1 <- readIntArray arr' 0
1793 i2 <- readIntArray arr' 1
1794 return [ CLit (MachInt (toInteger i1))
1795 , CLit (MachInt (toInteger i2))
1798 | otherwise -- doubles are 1 word
1800 arr <- newDoubleArray ((0::Int),0)
1801 writeDoubleArray arr 0 (fromRational r)
1802 arr' <- castDoubleToIntArray arr
1803 i <- readIntArray arr' 0
1804 return [ CLit (MachInt (toInteger i)) ]