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 resultVar = "_ccall_result"
850 hasAssemArg = isStatic || kind == DNConstructor
854 | isStatic -> "DN_invokeStatic"
855 | otherwise -> "DN_invokeMethod"
865 DNConstructor -> "DN_createObject"
867 (methArrDecl, methArrInit, methArrName, methArrLen)
868 | null argTys = (empty, empty, text "NULL", text "0")
870 ( text "DotnetArg __meth_args[" <> int (length argTys) <> text "];"
871 , vcat (zipWith3 (\ idx arg argTy ->
872 text "__meth_args[" <> int idx <> text "].arg." <> text (toDotnetArgField argTy) <> equals <> ppr_amode arg <> semi $$
873 text "__meth_args[" <> int idx <> text "].arg_type=" <> text (toDotnetTy argTy) <> semi)
878 , int (length non_void_args)
883 vcat local_arg_decls,
886 , text "_ccall_result1 =" <+> text invokeOp <> parens (
887 hcat (punctuate comma $
892 doubleQuotes (text assem)):)
895 [ doubleQuotes $ text nm
898 , text (toDotnetTy resTy)
899 , text "(void*)&" <> text resultVar
906 (pp_saves, pp_restores) = ppr_vol_regs vol_regs
908 makeCall target safety theCall =
909 vcat [ pp_save_context, theCall, pp_restore_context ]
911 (pp_save_context, pp_restore_context)
912 | playSafe safety = ( text "{ I_" <+> ppr_uniq_token <>
913 text "; SUSPEND_THREAD" <> parens thread_macro_args <> semi
914 , text "RESUME_THREAD" <> parens thread_macro_args <> text ";}"
916 | otherwise = ( pp_basic_saves $$ pp_saves,
917 pp_basic_restores $$ pp_restores)
919 thread_macro_args = ppr_uniq_token <> comma <+>
920 text "rts" <> ppr (playThreadSafe safety)
921 ppr_uniq_token = text "tok_" <> ppr uniq
926 in ASSERT2 ( all non_void nvas, ppr call <+> hsep (map pprAmode args) )
928 -- the last argument will be the "I/O world" token (a VoidRep)
929 -- all others should be non-void
932 let nvrs = grab_non_void_amodes results
933 in ASSERT (forDotnet || listLengthCmp nvrs 1 /= GT) nvrs
934 -- there will usually be two results: a (void) state which we
935 -- should ignore and a (possibly void) result.
937 (local_arg_decls, pp_non_void_args)
938 = unzip [ ppr_casm_arg a i | (a,i) <- non_void_args `zip` [1..] ]
940 (declare_local_vars, local_vars, assign_results)
941 = ppr_casm_results non_void_results forDotnet
950 StaticTarget fn -> mk_ccall_str (pprCLabelString fn) ccall_args
951 DynamicTarget -> mk_ccall_str dyn_fun (tail ccall_args)
953 ccall_args = zipWith (\ _ i -> char '%' <> int i) non_void_args [0..]
954 dyn_fun = parens (parens (ptext SLIT("_ccall_fun_ty") <> ppr uniq) <> text "%0")
957 -- Remainder only used for ccall
958 mk_ccall_str fun_name ccall_fun_args = showSDoc
960 if null non_void_results
963 lparen, fun_name, lparen,
964 hcat (punctuate comma ccall_fun_args),
968 toDotnetTy :: DNType -> String
971 DNByte -> "Dotnet_Byte"
972 DNBool -> "Dotnet_Bool"
973 DNChar -> "Dotnet_Char"
974 DNDouble -> "Dotnet_Double"
975 DNFloat -> "Dotnet_Float"
976 DNInt -> "Dotnet_Int"
977 DNInt8 -> "Dotnet_Int8"
978 DNInt16 -> "Dotnet_Int16"
979 DNInt32 -> "Dotnet_Int32"
980 DNInt64 -> "Dotnet_Int64"
981 DNWord8 -> "Dotnet_Word8"
982 DNWord16 -> "Dotnet_Word16"
983 DNWord32 -> "Dotnet_Word32"
984 DNWord64 -> "Dotnet_Word64"
985 DNPtr -> "Dotnet_Ptr"
986 DNUnit -> "Dotnet_Unit"
987 DNObject -> "Dotnet_Object"
988 DNString -> "Dotnet_String"
990 toDotnetArgField :: DNType -> String
996 DNDouble -> "arg_double"
997 DNFloat -> "arg_float"
1000 DNInt16 -> "arg_int16"
1001 DNInt32 -> "arg_int32"
1002 DNInt64 -> "arg_int64"
1003 DNWord8 -> "arg_word8"
1004 DNWord16 -> "arg_word16"
1005 DNWord32 -> "arg_word32"
1006 DNWord64 -> "arg_word64"
1008 DNUnit -> "arg_ptr" -- can't happen
1009 DNObject -> "arg_obj"
1010 DNString -> "arg_str"
1012 ppr_casm_arg :: CAddrMode -> Int -> (SDoc, SDoc)
1013 -- (a) decl and assignment, (b) local var to be used later
1015 ppr_casm_arg amode a_num
1017 a_kind = getAmodeRep amode
1018 pp_amode = pprAmode amode
1019 pp_kind = pprPrimKind a_kind
1021 local_var = (<>) (ptext SLIT("_ccall_arg")) (int a_num)
1024 = hcat [ pp_kind, space, local_var, equals, pp_amode, semi ]
1026 (declare_local_var, local_var)
1029 For l-values, the critical questions are:
1031 1) Are there any results at all?
1033 We only allow zero or one results.
1037 :: [CAddrMode] -- list of results (length <= 1)
1038 -> Bool -- True => multiple results OK.
1040 ( SDoc, -- declaration of any local vars
1041 [SDoc], -- list of result vars (same length as results)
1042 SDoc ) -- assignment (if any) of results in local var to registers
1044 ppr_casm_results [] _
1045 = (empty, [], empty) -- no results
1047 ppr_casm_results (r:rs) multiResultsOK
1048 | not multiResultsOK && not (null rs) = panic "ppr_casm_results: ccall/casm with many results"
1050 = foldr (\ (a,b,c) (as,bs,cs) -> (a $$ as, b ++ bs, c $$ cs))
1052 (zipWith pprRes (r:rs) ("" : map show [(1::Int)..]))
1054 pprRes r suf = (declare_local_var, [local_var], assign_result)
1056 result_reg = ppr_amode r
1057 r_kind = getAmodeRep r
1059 local_var = ptext SLIT("_ccall_result") <> text suf
1061 (result_type, assign_result)
1062 = (pprPrimKind r_kind,
1063 hcat [ result_reg, equals, local_var, semi ])
1065 declare_local_var = hcat [ result_type, space, local_var, semi ]
1070 Note the sneaky way _the_ result is represented by a list so that we
1071 can complain if it's used twice.
1073 ToDo: Any chance of giving line numbers when process-casm fails?
1074 Or maybe we should do a check _much earlier_ in compiler. ADR
1077 process_casm :: [SDoc] -- results (length <= 1)
1078 -> [SDoc] -- arguments
1079 -> String -- format string (with embedded %'s)
1080 -> SDoc -- code being generated
1082 process_casm results args string = process results args string
1084 process [] _ "" = empty
1085 process (_:_) _ "" = error ("process_casm: non-void result not assigned while processing _casm_ \"" ++
1087 "\"\n(Try changing result type to IO ()\n")
1089 process ress args ('%':cs)
1092 error ("process_casm: lonely % while processing _casm_ \"" ++ string ++ "\".\n")
1095 char '%' <> process ress args css
1099 [] -> error ("process_casm: no result to match %r while processing _casm_ \"" ++ string ++ "\".\nTry deleting %r or changing result type from PrimIO ()\n")
1100 [r] -> r <> (process [] args css)
1101 _ -> panic ("process_casm: casm with many results while processing _casm_ \"" ++ string ++ "\".\n")
1105 read_int :: ReadS Int
1108 case (read_int other) of
1110 if num >= 0 && args `lengthExceeds` num
1111 then parens (args !! num) <> process ress args css
1112 else error ("process_casm: no such arg #:"++(show num)++" while processing \"" ++ string ++ "\".\n")
1113 _ -> error ("process_casm: not %<num> while processing _casm_ \"" ++ string ++ "\".\n")
1115 process ress args (other_c:cs)
1116 = char other_c <> process ress args cs
1119 %************************************************************************
1121 \subsection[a2r-assignments]{Assignments}
1123 %************************************************************************
1125 Printing assignments is a little tricky because of type coercion.
1127 First of all, the kind of the thing being assigned can be gotten from
1128 the destination addressing mode. (It should be the same as the kind
1129 of the source addressing mode.) If the kind of the assignment is of
1130 @VoidRep@, then don't generate any code at all.
1133 pprAssign :: PrimRep -> CAddrMode -> CAddrMode -> SDoc
1135 pprAssign VoidRep dest src = empty
1138 Special treatment for floats and doubles, to avoid unwanted conversions.
1141 pprAssign FloatRep dest@(CVal reg_rel _) src
1142 = hcat [ ptext SLIT("ASSIGN_FLT((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1144 pprAssign DoubleRep dest@(CVal reg_rel _) src
1145 = hcat [ ptext SLIT("ASSIGN_DBL((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1147 pprAssign Int64Rep dest@(CVal reg_rel _) src
1148 = hcat [ ptext SLIT("ASSIGN_Int64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1149 pprAssign Word64Rep dest@(CVal reg_rel _) src
1150 = hcat [ ptext SLIT("ASSIGN_Word64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1153 Lastly, the question is: will the C compiler think the types of the
1154 two sides of the assignment match?
1156 We assume that the types will match if neither side is a
1157 @CVal@ addressing mode for any register which can point into
1160 Why? Because the heap and stack are used to store miscellaneous
1161 things, whereas the temporaries, registers, etc., are only used for
1162 things of fixed type.
1165 pprAssign kind (CReg (VanillaReg _ dest)) (CReg (VanillaReg _ src))
1166 = hcat [ pprVanillaReg dest, equals,
1167 pprVanillaReg src, semi ]
1169 pprAssign kind dest src
1170 | mixedTypeLocn dest
1171 -- Add in a cast to StgWord (a.k.a. W_) iff the destination is mixed
1172 = hcat [ ppr_amode dest, equals,
1173 text "(W_)(", -- Here is the cast
1174 ppr_amode src, pp_paren_semi ]
1176 pprAssign kind dest src
1177 | mixedPtrLocn dest && getAmodeRep src /= PtrRep
1178 -- Add in a cast to StgPtr (a.k.a. P_) iff the destination is mixed
1179 = hcat [ ppr_amode dest, equals,
1180 text "(P_)(", -- Here is the cast
1181 ppr_amode src, pp_paren_semi ]
1183 pprAssign kind other_dest src
1184 = hcat [ ppr_amode other_dest, equals,
1185 pprAmode src, semi ]
1189 %************************************************************************
1191 \subsection[a2r-CAddrModes]{Addressing modes}
1193 %************************************************************************
1195 @pprAmode@ is used to print r-values (which may need casts), whereas
1196 @ppr_amode@ is used for l-values {\em and} as a help function for
1200 pprAmode, ppr_amode :: CAddrMode -> SDoc
1203 For reasons discussed above under assignments, @CVal@ modes need
1204 to be treated carefully. First come special cases for floats and doubles,
1205 similar to those in @pprAssign@:
1207 (NB: @PK_FLT@ and @PK_DBL@ require the {\em address} of the value in
1211 pprAmode (CVal reg_rel FloatRep)
1212 = hcat [ text "PK_FLT((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1213 pprAmode (CVal reg_rel DoubleRep)
1214 = hcat [ text "PK_DBL((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1215 pprAmode (CVal reg_rel Int64Rep)
1216 = hcat [ text "PK_Int64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1217 pprAmode (CVal reg_rel Word64Rep)
1218 = hcat [ text "PK_Word64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1221 Next comes the case where there is some other cast need, and the
1226 | mixedTypeLocn amode
1227 = parens (hcat [ pprPrimKind (getAmodeRep amode), ptext SLIT(")("),
1229 | otherwise -- No cast needed
1233 When we have an indirection through a CIndex, we have to be careful to
1234 get the type casts right.
1238 CVal (CIndex kind1 base offset) kind2
1242 *(kind2 *)((kind1 *)base + offset)
1244 That is, the indexing is done in units of kind1, but the resulting
1248 ppr_amode (CVal reg_rel@(CIndex _ _ _) kind)
1249 = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1250 (pp_reg, Nothing) -> panic "ppr_amode: CIndex"
1251 (pp_reg, Just offset) ->
1252 hcat [ char '*', parens (pprPrimKind kind <> char '*'),
1253 parens (pp_reg <> char '+' <> offset) ]
1256 Now the rest of the cases for ``workhorse'' @ppr_amode@:
1259 ppr_amode (CVal reg_rel _)
1260 = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1261 (pp_reg, Nothing) -> (<>) (char '*') pp_reg
1262 (pp_reg, Just offset) -> hcat [ pp_reg, brackets offset ]
1264 ppr_amode (CAddr reg_rel)
1265 = case (pprRegRelative True{-sign wanted-} reg_rel) of
1266 (pp_reg, Nothing) -> pp_reg
1267 (pp_reg, Just offset) -> pp_reg <> offset
1269 ppr_amode (CReg magic_id) = pprMagicId magic_id
1271 ppr_amode (CTemp uniq kind) = char '_' <> pprUnique uniq <> char '_'
1273 ppr_amode (CLbl lbl kind) = pprCLabelAddr lbl
1275 ppr_amode (CCharLike ch)
1276 = hcat [ptext SLIT("CHARLIKE_CLOSURE"), char '(', pprAmode ch, rparen ]
1277 ppr_amode (CIntLike int)
1278 = hcat [ptext SLIT("INTLIKE_CLOSURE"), char '(', pprAmode int, rparen ]
1280 ppr_amode (CLit lit) = pprBasicLit lit
1282 ppr_amode (CJoinPoint _)
1283 = panic "ppr_amode: CJoinPoint"
1285 ppr_amode (CMacroExpr pk macro as)
1286 = parens (ptext (cExprMacroText macro) <>
1287 parens (hcat (punctuate comma (map pprAmode as))))
1291 cExprMacroText ENTRY_CODE = SLIT("ENTRY_CODE")
1292 cExprMacroText ARG_TAG = SLIT("ARG_TAG")
1293 cExprMacroText GET_TAG = SLIT("GET_TAG")
1294 cExprMacroText CCS_HDR = SLIT("CCS_HDR")
1295 cExprMacroText BYTE_ARR_CTS = SLIT("BYTE_ARR_CTS")
1296 cExprMacroText PTRS_ARR_CTS = SLIT("PTRS_ARR_CTS")
1297 cExprMacroText ForeignObj_CLOSURE_DATA = SLIT("ForeignObj_CLOSURE_DATA")
1299 cStmtMacroText UPD_CAF = SLIT("UPD_CAF")
1300 cStmtMacroText UPD_BH_UPDATABLE = SLIT("UPD_BH_UPDATABLE")
1301 cStmtMacroText UPD_BH_SINGLE_ENTRY = SLIT("UPD_BH_SINGLE_ENTRY")
1302 cStmtMacroText PUSH_UPD_FRAME = SLIT("PUSH_UPD_FRAME")
1303 cStmtMacroText SET_TAG = SLIT("SET_TAG")
1304 cStmtMacroText DATA_TO_TAGZH = SLIT("dataToTagzh")
1305 cStmtMacroText REGISTER_FOREIGN_EXPORT = SLIT("REGISTER_FOREIGN_EXPORT")
1306 cStmtMacroText REGISTER_IMPORT = SLIT("REGISTER_IMPORT")
1307 cStmtMacroText REGISTER_DIMPORT = SLIT("REGISTER_DIMPORT")
1308 cStmtMacroText GRAN_FETCH = SLIT("GRAN_FETCH")
1309 cStmtMacroText GRAN_RESCHEDULE = SLIT("GRAN_RESCHEDULE")
1310 cStmtMacroText GRAN_FETCH_AND_RESCHEDULE= SLIT("GRAN_FETCH_AND_RESCHEDULE")
1311 cStmtMacroText THREAD_CONTEXT_SWITCH = SLIT("THREAD_CONTEXT_SWITCH")
1312 cStmtMacroText GRAN_YIELD = SLIT("GRAN_YIELD")
1314 cCheckMacroText HP_CHK_NP = SLIT("HP_CHK_NP")
1315 cCheckMacroText STK_CHK_NP = SLIT("STK_CHK_NP")
1316 cCheckMacroText HP_STK_CHK_NP = SLIT("HP_STK_CHK_NP")
1317 cCheckMacroText HP_CHK_FUN = SLIT("HP_CHK_FUN")
1318 cCheckMacroText STK_CHK_FUN = SLIT("STK_CHK_FUN")
1319 cCheckMacroText HP_STK_CHK_FUN = SLIT("HP_STK_CHK_FUN")
1320 cCheckMacroText HP_CHK_NOREGS = SLIT("HP_CHK_NOREGS")
1321 cCheckMacroText HP_CHK_UNPT_R1 = SLIT("HP_CHK_UNPT_R1")
1322 cCheckMacroText HP_CHK_UNBX_R1 = SLIT("HP_CHK_UNBX_R1")
1323 cCheckMacroText HP_CHK_F1 = SLIT("HP_CHK_F1")
1324 cCheckMacroText HP_CHK_D1 = SLIT("HP_CHK_D1")
1325 cCheckMacroText HP_CHK_L1 = SLIT("HP_CHK_L1")
1326 cCheckMacroText HP_CHK_UNBX_TUPLE = SLIT("HP_CHK_UNBX_TUPLE")
1329 %************************************************************************
1331 \subsection[ppr-liveness-masks]{Liveness Masks}
1333 %************************************************************************
1336 bitmapAddrModes [] = [mkWordCLit 0]
1337 bitmapAddrModes xs = map mkWordCLit xs
1340 %************************************************************************
1342 \subsection[a2r-MagicIds]{Magic ids}
1344 %************************************************************************
1346 @pprRegRelative@ returns a pair of the @Doc@ for the register
1347 (some casting may be required), and a @Maybe Doc@ for the offset
1348 (zero offset gives a @Nothing@).
1351 addPlusSign :: Bool -> SDoc -> SDoc
1352 addPlusSign False p = p
1353 addPlusSign True p = (<>) (char '+') p
1355 pprSignedInt :: Bool -> Int -> Maybe SDoc -- Nothing => 0
1356 pprSignedInt sign_wanted n
1357 = if n == 0 then Nothing else
1358 if n > 0 then Just (addPlusSign sign_wanted (int n))
1361 pprRegRelative :: Bool -- True <=> Print leading plus sign (if +ve)
1363 -> (SDoc, Maybe SDoc)
1365 pprRegRelative sign_wanted (SpRel off)
1366 = (pprMagicId Sp, pprSignedInt sign_wanted (I# off))
1368 pprRegRelative sign_wanted r@(HpRel o)
1369 = let pp_Hp = pprMagicId Hp; off = I# o
1374 (pp_Hp, Just ((<>) (char '-') (int off)))
1376 pprRegRelative sign_wanted (NodeRel o)
1377 = let pp_Node = pprMagicId node; off = I# o
1382 (pp_Node, Just (addPlusSign sign_wanted (int off)))
1384 pprRegRelative sign_wanted (CIndex base offset kind)
1385 = ( hcat [text "((", pprPrimKind kind, text " *)(", ppr_amode base, text "))"]
1386 , Just (hcat [if sign_wanted then char '+' else empty,
1387 text "(I_)(", ppr_amode offset, ptext SLIT(")")])
1391 @pprMagicId@ just prints the register name. @VanillaReg@ registers are
1392 represented by a discriminated union (@StgUnion@), so we use the @PrimRep@
1393 to select the union tag.
1396 pprMagicId :: MagicId -> SDoc
1398 pprMagicId BaseReg = ptext SLIT("BaseReg")
1399 pprMagicId (VanillaReg pk n)
1400 = hcat [ pprVanillaReg n, char '.',
1402 pprMagicId (FloatReg n) = ptext SLIT("F") <> int (I# n)
1403 pprMagicId (DoubleReg n) = ptext SLIT("D") <> int (I# n)
1404 pprMagicId (LongReg _ n) = ptext SLIT("L") <> int (I# n)
1405 pprMagicId Sp = ptext SLIT("Sp")
1406 pprMagicId SpLim = ptext SLIT("SpLim")
1407 pprMagicId Hp = ptext SLIT("Hp")
1408 pprMagicId HpLim = ptext SLIT("HpLim")
1409 pprMagicId CurCostCentre = ptext SLIT("CCCS")
1410 pprMagicId VoidReg = ptext SLIT("VoidReg")
1412 pprVanillaReg :: Int# -> SDoc
1413 pprVanillaReg n = char 'R' <> int (I# n)
1415 pprUnionTag :: PrimRep -> SDoc
1417 pprUnionTag PtrRep = char 'p'
1418 pprUnionTag CodePtrRep = ptext SLIT("fp")
1419 pprUnionTag DataPtrRep = char 'd'
1420 pprUnionTag RetRep = char 'p'
1421 pprUnionTag CostCentreRep = panic "pprUnionTag:CostCentre?"
1423 pprUnionTag CharRep = char 'c'
1424 pprUnionTag Int8Rep = ptext SLIT("i8")
1425 pprUnionTag IntRep = char 'i'
1426 pprUnionTag WordRep = char 'w'
1427 pprUnionTag Int32Rep = char 'i'
1428 pprUnionTag Word32Rep = char 'w'
1429 pprUnionTag AddrRep = char 'a'
1430 pprUnionTag FloatRep = char 'f'
1431 pprUnionTag DoubleRep = panic "pprUnionTag:Double?"
1433 pprUnionTag StablePtrRep = char 'p'
1435 pprUnionTag _ = panic "pprUnionTag:Odd kind"
1439 Find and print local and external declarations for a list of
1440 Abstract~C statements.
1442 pprTempAndExternDecls :: AbstractC -> (SDoc{-temps-}, SDoc{-externs-})
1443 pprTempAndExternDecls AbsCNop = (empty, empty)
1445 pprTempAndExternDecls (AbsCStmts stmt1 stmt2)
1446 = initTE (ppr_decls_AbsC stmt1 `thenTE` \ (t_p1, e_p1) ->
1447 ppr_decls_AbsC stmt2 `thenTE` \ (t_p2, e_p2) ->
1448 case (catMaybes [t_p1, t_p2]) of { real_temps ->
1449 case (catMaybes [e_p1, e_p2]) of { real_exts ->
1450 returnTE (vcat real_temps, vcat real_exts) }}
1453 pprTempAndExternDecls other_stmt
1454 = initTE (ppr_decls_AbsC other_stmt `thenTE` \ (maybe_t, maybe_e) ->
1465 pprBasicLit :: Literal -> SDoc
1466 pprPrimKind :: PrimRep -> SDoc
1468 pprBasicLit lit = ppr lit
1469 pprPrimKind k = ppr k
1473 %************************************************************************
1475 \subsection[a2r-monad]{Monadery}
1477 %************************************************************************
1479 We need some monadery to keep track of temps and externs we have already
1480 printed. This info must be threaded right through the Abstract~C, so
1481 it's most convenient to hide it in this monad.
1483 WDP 95/02: Switched from \tr{([Unique], [CLabel])} to
1484 \tr{(UniqSet, CLabelSet)}. Allegedly for efficiency.
1487 type CLabelSet = FiniteMap CLabel (){-any type will do-}
1488 emptyCLabelSet = emptyFM
1489 x `elementOfCLabelSet` labs
1490 = case (lookupFM labs x) of { Just _ -> True; Nothing -> False }
1492 addToCLabelSet set x = addToFM set x ()
1494 type TEenv = (UniqSet Unique, CLabelSet)
1496 type TeM result = TEenv -> (TEenv, result)
1498 initTE :: TeM a -> a
1500 = case sa (emptyUniqSet, emptyCLabelSet) of { (_, result) ->
1503 {-# INLINE thenTE #-}
1504 {-# INLINE returnTE #-}
1506 thenTE :: TeM a -> (a -> TeM b) -> TeM b
1508 = case a u of { (u_1, result_of_a) ->
1511 mapTE :: (a -> TeM b) -> [a] -> TeM [b]
1512 mapTE f [] = returnTE []
1514 = f x `thenTE` \ r ->
1515 mapTE f xs `thenTE` \ rs ->
1518 returnTE :: a -> TeM a
1519 returnTE result env = (env, result)
1521 -- these next two check whether the thing is already
1522 -- recorded, and THEN THEY RECORD IT
1523 -- (subsequent calls will return False for the same uniq/label)
1525 tempSeenTE :: Unique -> TeM Bool
1526 tempSeenTE uniq env@(seen_uniqs, seen_labels)
1527 = if (uniq `elementOfUniqSet` seen_uniqs)
1529 else ((addOneToUniqSet seen_uniqs uniq,
1533 labelSeenTE :: CLabel -> TeM Bool
1534 labelSeenTE lbl env@(seen_uniqs, seen_labels)
1535 = if (lbl `elementOfCLabelSet` seen_labels)
1538 addToCLabelSet seen_labels lbl),
1543 pprTempDecl :: Unique -> PrimRep -> SDoc
1544 pprTempDecl uniq kind
1545 = hcat [ pprPrimKind kind, space, char '_', pprUnique uniq, ptext SLIT("_;") ]
1547 pprExternDecl :: Bool -> CLabel -> SDoc
1548 pprExternDecl in_srt clabel
1549 | not (needsCDecl clabel) = empty -- do not print anything for "known external" things
1551 hcat [ ppLocalnessMacro (not in_srt) clabel,
1552 lparen, dyn_wrapper (pprCLabel clabel), pp_paren_semi ]
1555 | in_srt && labelDynamic clabel = text "DLL_IMPORT_DATA_VAR" <> parens d
1561 ppr_decls_AbsC :: AbstractC -> TeM (Maybe SDoc{-temps-}, Maybe SDoc{-externs-})
1563 ppr_decls_AbsC AbsCNop = returnTE (Nothing, Nothing)
1565 ppr_decls_AbsC (AbsCStmts stmts_1 stmts_2)
1566 = ppr_decls_AbsC stmts_1 `thenTE` \ p1 ->
1567 ppr_decls_AbsC stmts_2 `thenTE` \ p2 ->
1568 returnTE (maybe_vcat [p1, p2])
1570 ppr_decls_AbsC (CSplitMarker) = returnTE (Nothing, Nothing)
1572 ppr_decls_AbsC (CAssign dest source)
1573 = ppr_decls_Amode dest `thenTE` \ p1 ->
1574 ppr_decls_Amode source `thenTE` \ p2 ->
1575 returnTE (maybe_vcat [p1, p2])
1577 ppr_decls_AbsC (CJump target) = ppr_decls_Amode target
1579 ppr_decls_AbsC (CFallThrough target) = ppr_decls_Amode target
1581 ppr_decls_AbsC (CReturn target _) = ppr_decls_Amode target
1583 ppr_decls_AbsC (CSwitch discrim alts deflt)
1584 = ppr_decls_Amode discrim `thenTE` \ pdisc ->
1585 mapTE ppr_alt_stuff alts `thenTE` \ palts ->
1586 ppr_decls_AbsC deflt `thenTE` \ pdeflt ->
1587 returnTE (maybe_vcat (pdisc:pdeflt:palts))
1589 ppr_alt_stuff (_, absC) = ppr_decls_AbsC absC
1591 ppr_decls_AbsC (CCodeBlock lbl absC)
1592 = ppr_decls_AbsC absC
1594 ppr_decls_AbsC (CInitHdr cl_info reg_rel cost_centre _)
1595 -- ToDo: strictly speaking, should chk "cost_centre" amode
1596 = labelSeenTE info_lbl `thenTE` \ label_seen ->
1601 Just (pprExternDecl False{-not in an SRT decl-} info_lbl))
1603 info_lbl = infoTableLabelFromCI cl_info
1605 ppr_decls_AbsC (CMachOpStmt res _ args _) = ppr_decls_Amodes (res : args)
1606 ppr_decls_AbsC (COpStmt results _ args _) = ppr_decls_Amodes (results ++ args)
1608 ppr_decls_AbsC (CSimultaneous abc) = ppr_decls_AbsC abc
1610 ppr_decls_AbsC (CSequential abcs)
1611 = mapTE ppr_decls_AbsC abcs `thenTE` \ t_and_e_s ->
1612 returnTE (maybe_vcat t_and_e_s)
1614 ppr_decls_AbsC (CCheck _ amodes code) =
1615 ppr_decls_Amodes amodes `thenTE` \p1 ->
1616 ppr_decls_AbsC code `thenTE` \p2 ->
1617 returnTE (maybe_vcat [p1,p2])
1619 ppr_decls_AbsC (CMacroStmt _ amodes) = ppr_decls_Amodes amodes
1621 ppr_decls_AbsC (CCallProfCtrMacro _ amodes) = ppr_decls_Amodes [] -- *****!!!
1622 -- you get some nasty re-decls of stdio.h if you compile
1623 -- the prelude while looking inside those amodes;
1624 -- no real reason to, anyway.
1625 ppr_decls_AbsC (CCallProfCCMacro _ amodes) = ppr_decls_Amodes amodes
1627 ppr_decls_AbsC (CStaticClosure _ closure_info cost_centre amodes)
1628 -- ToDo: strictly speaking, should chk "cost_centre" amode
1629 = ppr_decls_Amodes amodes
1631 ppr_decls_AbsC (CClosureInfoAndCode cl_info entry)
1632 = ppr_decls_Amodes [entry_lbl] `thenTE` \ p1 ->
1633 ppr_decls_AbsC entry `thenTE` \ p2 ->
1634 returnTE (maybe_vcat [p1, p2])
1636 entry_lbl = CLbl (entryLabelFromCI cl_info) CodePtrRep
1638 ppr_decls_AbsC (CSRT _ closure_lbls)
1639 = mapTE labelSeenTE closure_lbls `thenTE` \ seen ->
1641 if and seen then Nothing
1642 else Just (vcat [ pprExternDecl True{-in SRT decl-} l
1643 | (l,False) <- zip closure_lbls seen ]))
1645 ppr_decls_AbsC (CRetDirect _ code _ _) = ppr_decls_AbsC code
1646 ppr_decls_AbsC (CRetVector _ amodes _ _) = ppr_decls_Amodes amodes
1647 ppr_decls_AbsC (CModuleInitBlock _ _ code) = ppr_decls_AbsC code
1649 ppr_decls_AbsC (_) = returnTE (Nothing, Nothing)
1653 ppr_decls_Amode :: CAddrMode -> TeM (Maybe SDoc, Maybe SDoc)
1654 ppr_decls_Amode (CVal (CIndex base offset _) _) = ppr_decls_Amodes [base,offset]
1655 ppr_decls_Amode (CAddr (CIndex base offset _)) = ppr_decls_Amodes [base,offset]
1656 ppr_decls_Amode (CVal _ _) = returnTE (Nothing, Nothing)
1657 ppr_decls_Amode (CAddr _) = returnTE (Nothing, Nothing)
1658 ppr_decls_Amode (CReg _) = returnTE (Nothing, Nothing)
1659 ppr_decls_Amode (CLit _) = returnTE (Nothing, Nothing)
1661 -- CIntLike must be a literal -- no decls
1662 ppr_decls_Amode (CIntLike int) = returnTE (Nothing, Nothing)
1665 ppr_decls_Amode (CCharLike char) = returnTE (Nothing, Nothing)
1667 -- now, the only place where we actually print temps/externs...
1668 ppr_decls_Amode (CTemp uniq kind)
1670 VoidRep -> returnTE (Nothing, Nothing)
1672 tempSeenTE uniq `thenTE` \ temp_seen ->
1674 (if temp_seen then Nothing else Just (pprTempDecl uniq kind), Nothing)
1676 ppr_decls_Amode (CLbl lbl VoidRep)
1677 = returnTE (Nothing, Nothing)
1679 ppr_decls_Amode (CLbl lbl kind)
1680 = labelSeenTE lbl `thenTE` \ label_seen ->
1682 if label_seen then Nothing else Just (pprExternDecl False{-not in an SRT decl-} lbl))
1684 ppr_decls_Amode (CMacroExpr _ _ amodes)
1685 = ppr_decls_Amodes amodes
1687 ppr_decls_Amode other = returnTE (Nothing, Nothing)
1690 maybe_vcat :: [(Maybe SDoc, Maybe SDoc)] -> (Maybe SDoc, Maybe SDoc)
1692 = case (unzip ps) of { (ts, es) ->
1693 case (catMaybes ts) of { real_ts ->
1694 case (catMaybes es) of { real_es ->
1695 (if (null real_ts) then Nothing else Just (vcat real_ts),
1696 if (null real_es) then Nothing else Just (vcat real_es))
1701 ppr_decls_Amodes :: [CAddrMode] -> TeM (Maybe SDoc, Maybe SDoc)
1702 ppr_decls_Amodes amodes
1703 = mapTE ppr_decls_Amode amodes `thenTE` \ ps ->
1704 returnTE ( maybe_vcat ps )
1707 Print out a C Label where you want the *address* of the label, not the
1708 object it refers to. The distinction is important when the label may
1709 refer to a C structure (info tables and closures, for instance).
1711 When just generating a declaration for the label, use pprCLabel.
1714 pprCLabelAddr :: CLabel -> SDoc
1715 pprCLabelAddr clabel =
1716 case labelType clabel of
1717 InfoTblType -> addr_of_label
1718 RetInfoTblType -> addr_of_label
1719 ClosureType -> addr_of_label
1720 VecTblType -> addr_of_label
1721 DataType -> addr_of_label
1725 addr_of_label = ptext SLIT("(P_)&") <> pp_label
1726 pp_label = pprCLabel clabel
1729 -----------------------------------------------------------------------------
1730 Initialising static objects with floating-point numbers. We can't
1731 just emit the floating point number, because C will cast it to an int
1732 by rounding it. We want the actual bit-representation of the float.
1734 This is a hack to turn the floating point numbers into ints that we
1735 can safely initialise to static locations.
1738 big_doubles = (getPrimRepSize DoubleRep) /= 1
1740 #if __GLASGOW_HASKELL__ >= 504
1741 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
1742 newFloatArray = newArray_
1744 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
1745 newDoubleArray = newArray_
1747 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
1748 castFloatToIntArray = castSTUArray
1750 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
1751 castDoubleToIntArray = castSTUArray
1753 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
1754 writeFloatArray = writeArray
1756 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
1757 writeDoubleArray = writeArray
1759 readIntArray :: STUArray s Int Int -> Int -> ST s Int
1760 readIntArray = readArray
1764 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
1765 castFloatToIntArray = return
1767 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
1768 castDoubleToIntArray = return
1772 -- floats are always 1 word
1773 floatToWord :: CAddrMode -> CAddrMode
1774 floatToWord (CLit (MachFloat r))
1776 arr <- newFloatArray ((0::Int),0)
1777 writeFloatArray arr 0 (fromRational r)
1778 arr' <- castFloatToIntArray arr
1779 i <- readIntArray arr' 0
1780 return (CLit (MachInt (toInteger i)))
1783 doubleToWords :: CAddrMode -> [CAddrMode]
1784 doubleToWords (CLit (MachDouble r))
1785 | big_doubles -- doubles are 2 words
1787 arr <- newDoubleArray ((0::Int),1)
1788 writeDoubleArray arr 0 (fromRational r)
1789 arr' <- castDoubleToIntArray arr
1790 i1 <- readIntArray arr' 0
1791 i2 <- readIntArray arr' 1
1792 return [ CLit (MachInt (toInteger i1))
1793 , CLit (MachInt (toInteger i2))
1796 | otherwise -- doubles are 1 word
1798 arr <- newDoubleArray ((0::Int),0)
1799 writeDoubleArray arr 0 (fromRational r)
1800 arr' <- castDoubleToIntArray arr
1801 i <- readIntArray arr' 0
1802 return [ CLit (MachInt (toInteger i)) ]