2 \section{Generate COM+ extended assembler}
5 module IlxGen( ilxGen ) where
7 #include "HsVersions.h"
9 import Char ( ord, chr )
11 import Id ( idType, idName, isDeadBinder, idArityInfo )
12 import IdInfo ( arityLowerBound )
13 import Var ( Var, Id, TyVar, isId, isTyVar, tyVarKind, tyVarName )
15 import TyCon ( TyCon, tyConPrimRep, isUnboxedTupleTyCon, tyConDataCons,
16 newTyConRep, tyConTyVars, isDataTyCon, isAlgTyCon, tyConArity
18 import Class ( Class )
19 import Type ( liftedTypeKind, openTypeKind, unliftedTypeKind,
20 isUnLiftedType, isTyVarTy, mkTyVarTy, predRepTy,
21 splitForAllTys, splitFunTys, applyTy, applyTys
23 import TypeRep ( Type(..) )
24 import DataCon ( isUnboxedTupleCon, dataConTyCon, dataConRepType, dataConRepArgTys )
25 import Literal ( Literal(..) )
26 import PrelNames -- Lots of keys
27 import PrimOp ( PrimOp(..), CCallTarget(..),CCall(..) )
28 import TysWiredIn ( mkTupleTy, tupleCon )
29 import PrimRep ( PrimRep(..) )
30 import Name ( nameModule, nameOccName, isGlobalName, isLocalName, isDllName, NamedThing(getName) )
31 import Subst ( substTy, mkTyVarSubst )
33 import Module ( Module, PackageName, ModuleName, moduleName,
34 modulePackage, preludePackage,
35 isPrelModule, isHomeModule, isVanillaModule,
36 pprModuleName, mkHomeModule, mkModuleName
40 import BasicTypes ( Boxity(..) )
41 import CStrings ( pprCLabelString )
44 import List ( partition, elem, insertBy,any )
47 import TysPrim ( byteArrayPrimTyCon, mutableByteArrayPrimTyCon )
49 -- opt_SimplDoEtaReduction is used to help with assembly naming conventions for different
50 -- versions of compiled Haskell code. We add a ".O" to all assembly and module
51 -- names when this is set (because that's clue that -O was set).
52 -- One day this will be configured by the command line.
53 import CmdLineOpts ( opt_Static, opt_InPackage, opt_SimplDoEtaReduction )
59 %************************************************************************
61 \subsection{Main driver}
63 %************************************************************************
66 ilxGen :: Module -> [TyCon] -> [(StgBinding,[Id])] -> SDoc
67 -- The TyCons should include those arising from classes
68 ilxGen mod tycons binds_w_srts
69 = vcat [vcat (map (ilxImportPackage topenv) (uniqSetToList import_packages)),
70 vcat (map (ilxImportModule topenv) (uniqSetToList import_modules)),
71 vcat (map (ilxImportTyCon topenv) (uniqSetToList import_tycons)),
72 vcat (map (ilxTyCon topenv) data_tycons),
73 vcat (map (ilxBindClosures topenv) binds),
74 ilxTopBind mod topenv toppairs
77 binds = map fst binds_w_srts
78 (import_packages,import_modules,import_tycons) = importsBinds binds (importsPrelude emptyImpInfo)
79 toppairs = ilxPairs binds
80 topenv = extendIlxEnvWithTops (emptyIlxEnv False mod) mod toppairs
81 -- Generate info from class decls as well
82 data_tycons = filter isDataTyCon tycons
85 %************************************************************************
87 \subsection{Find Imports}
89 %************************************************************************
93 importsBinds :: [StgBinding] -> ImportsInfo-> ImportsInfo
94 importsBinds binds = foldR importsBind binds
96 importsNone :: ImportsInfo -> ImportsInfo
97 importsNone sofar = sofar
99 importsBind :: StgBinding -> ImportsInfo -> ImportsInfo
100 importsBind (StgNonRec _ b rhs) = importsRhs rhs.importsVar b
101 importsBind (StgRec _ pairs) = foldR (\(b,rhs) -> importsRhs rhs . importsVar b) pairs
103 importsRhs (StgRhsCon _ con args) = importsDataCon con . importsStgArgs args
104 importsRhs (StgRhsClosure _ _ _ upd args body) = importsExpr body. importsVars args
106 importsExpr :: StgExpr -> ImportsInfo -> ImportsInfo
107 importsExpr (StgLit l) = importsNone
108 importsExpr (StgApp f args) = importsVar f.importsStgArgs args
109 importsExpr (StgConApp con args) = importsDataCon con.importsStgArgs args
110 importsExpr (StgPrimApp op args res_ty) = importsType res_ty. importsStgArgs args
111 importsExpr (StgSCC cc expr) = importsExpr expr
112 importsExpr (StgCase scrut _ _ bndr srt alts)
113 = importsExpr scrut. imports_alts alts. importsVar bndr
115 imports_alts (StgAlgAlts _ alts deflt) -- The Maybe TyCon part is dealt with
116 -- by the case-binder's type
117 = foldR imports_alg_alt alts . imports_deflt deflt
119 imports_alg_alt (con, bndrs, _, rhs)
120 = importsExpr rhs . importsDataCon con. importsVars bndrs
122 imports_alts (StgPrimAlts _ alts deflt)
123 = foldR imports_prim_alt alts . imports_deflt deflt
125 imports_prim_alt (lit, rhs) = importsExpr rhs
126 imports_deflt StgNoDefault = importsNone
127 imports_deflt (StgBindDefault rhs) = importsExpr rhs
130 importsExpr (StgLetNoEscape _ _ bind body) = importsExpr (StgLet bind body)
131 importsExpr (StgLet bind body)
132 = importsBind bind . importsExpr body
134 importsApp v args = importsVar v. importsStgArgs args
135 importsStgArgs args = foldR importsStgArg args
137 importsStgArg :: StgArg -> ImportsInfo -> ImportsInfo
138 importsStgArg (StgTypeArg ty) = importsType ty
139 importsStgArg (StgVarArg v) = importsVar v
140 importsStgArg _ = importsNone
142 importsVars vs = foldR importsVar vs
143 importsVar v = importsName (idName v). importsType (idType v)
146 | isLocalName n = importsNone
147 | thisModule == nameModule n = importsNone
148 | isHomeModule (nameModule n) = addModuleImpInfo (moduleName (nameModule n))
149 | isVanillaModule (nameModule n) = addPackageImpInfo preludePackage
150 | otherwise = addPackageImpInfo (modulePackage (nameModule n))
154 | thisModule == m = importsNone
155 | isHomeModule m = trace "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" (addModuleImpInfo (moduleName m))
156 | isVanillaModule m = addPackageImpInfo preludePackage
157 | otherwise = addPackageImpInfo (modulePackage m)
159 importsType :: Type -> ImportsInfo -> ImportsInfo
160 importsType ty = importsType2 (deepIlxRepType ty)
162 importsType2 :: Type -> ImportsInfo -> ImportsInfo
163 importsType2 (AppTy f x) = importsType2 f . importsType2 x
164 importsType2 (TyVarTy _) = importsNone
165 importsType2 (TyConApp tc args) =importsTyCon tc . importsTypeArgs2 args
166 importsType2 (FunTy arg res) = importsType arg . importsType2 res
167 importsType2 (ForAllTy tv body_ty) = importsType2 body_ty
168 importsType2 (NoteTy _ ty) = importsType2 ty
169 importsTypeArgs2 tys = foldR importsType2 tys
171 importsDataCon dcon = importsTyCon (dataConTyCon dcon)
173 importsMaybeTyCon Nothing = importsNone
174 importsMaybeTyCon (Just tc) = importsName (getName tc)
176 importsTyCon tc | (not (isDataTyCon tc) ||
177 isLocalName (getName tc) ||
178 thisModule == nameModule (getName tc)) = importsNone
179 importsTyCon tc | otherwise = importsName (getName tc) . addTyConImpInfo tc
181 importsPrelude | preludePackage == opt_InPackage = addModuleImpInfo (mkModuleName "PrelGHC")
182 | otherwise = addPackageImpInfo preludePackage
184 type ImportsInfo = (UniqSet PackageName, UniqSet ModuleName, UniqSet TyCon)
185 -- (Packages, Modules, Datatypes)
187 emptyImpInfo :: ImportsInfo
188 emptyImpInfo = (emptyUniqSet, emptyUniqSet, emptyUniqSet)
189 addPackageImpInfo p (w,x,y) = (addOneToUniqSet w p, x, y)
190 addModuleImpInfo m (w,x,y) = (w, addOneToUniqSet x m, y)
191 addTyConImpInfo tc (w,x,y) = (w, x, addOneToUniqSet y tc)
193 ilxImportTyCon :: IlxEnv -> TyCon -> SDoc
194 ilxImportTyCon env tycon | isDataTyCon tycon = pprIlxTyConDef True env tycon
195 ilxImportTyCon env tycon | otherwise = empty
197 ilxImportPackage :: IlxEnv -> PackageName -> SDoc
198 ilxImportPackage env p = text ".assembly extern ilx" <+> singleQuotes (ppr p <> hscOptionQual) <+> text "{ }"
200 ilxImportModule :: IlxEnv -> ModuleName -> SDoc
201 ilxImportModule env m = text ".module extern ilx" <+> singleQuotes (ppr m <> hscOptionQual)
206 %************************************************************************
208 \subsection{Type declarations}
210 %************************************************************************
215 ilxTyCon :: IlxEnv -> TyCon -> SDoc
216 ilxTyCon env tycon = pprIlxTyConDef False env tycon
218 -- filter to get only dataTyCons?
219 pprIlxTyConDef importing env tycon =
221 text ".classunion" <+> (if importing then text "extern" else empty) <+> text "thunk"
222 <+> ((nameReference env (getName tycon)) <> (ppr tycon)) <+> tyvars_text <+> alts_text]
224 tyvars = tyConTyVars tycon
225 (ilx_tvs, non_ilx_tvs) = categorizeTyVars tyvars
226 alts_env = extendIlxEnvWithFormalTyVars env ilx_tvs
227 tyvars_text = pprTyVarBinders alts_env ilx_tvs
228 alts = vcat (map (pprIlxDataCon alts_env) (tyConDataCons tycon))
229 alts_text = nest 2 (braces alts)
231 pprIlxDataCon env dcon =
232 text ".alternative" <+> pprId dcon <+>
233 parens (pprSepWithCommas (pprIlxTypeL env) (map deepIlxRepType (filter (not. isVoidIlxRepType) (dataConRepArgTys dcon))))
237 %************************************************************************
239 \subsection{Getting the .closures and literals out} *
240 %************************************************************************
244 ilxBindClosures :: IlxEnv -> StgBinding -> SDoc
245 ilxBindClosures env (StgNonRec _ b rhs) = ilxRhsClosures env (b,rhs)
246 ilxBindClosures env (StgRec _ pairs)
247 = vcat (map (ilxRhsClosures new_env) pairs)
249 new_env = extendIlxEnvWithBinds env pairs
252 ilxRhsClosures env (bndr, StgRhsCon _ _ _)
255 ilxRhsClosures env (bndr, StgRhsClosure _ _ fvs upd args rhs)
256 = vcat [ilxExprClosures next_env rhs,
259 kind_text <+> squotes cloname <+> free_vs_text,
262 vcat [text ".apply" <+> closure_sig_text,
270 kind_of_thing = case upd of
271 Updatable -> ASSERT( null args ) ".thunk"
273 kind_text = text kind_of_thing
275 cloname = ilxEnvQualifyByModule env (ppr bndr)
276 next_env = ilxPlaceStgRhsClosure env bndr
277 (free_vs_text,env_with_fvs) = pprFreeBinders next_env fvs
285 text "-->" <+> rty_text]
287 (args_text,env_with_args) = pprArgBinders env_with_fvs args
289 -- Find the type returned, from the no. of args and the type of "bndr"
291 case retType env_with_fvs (idIlxRepType bndr) args of
292 Just (env,ty) -> pprIlxTypeR env ty
293 Nothing -> trace "WARNING! IlxGen.trace could not find return type - see generated ILX for context where this occurs." (text "// Could not find return type:" <+> pprIlxTypeR env_with_fvs (idIlxRepType bndr)<+> text ", non representation: " <+> pprIlxTypeR env_with_fvs (idType bndr))
295 -- strip off leading ForAll and Fun type constructions
296 -- up to the given number of arguments, extending the environment as
298 retType env ty [] = Just (env, ty)
299 retType env (ForAllTy tv ty) (arg:args) = retType (extendIlxEnvWithTyArgs env [tv]) ty args
300 retType env (FunTy l r) (arg:args) = retType env r args
301 retType _ _ _ = Nothing
303 -- Code for the local variables
304 locals = ilxExprLocals env_with_args rhs
306 env_with_locals = extendIlxEnvWithLocals env_with_args locals
308 -- Code for the body of the main apply method
309 body_code = vcat [empty,
310 pprIlxLocals env_with_args locals,
311 ilxExpr (IlxEEnv env_with_locals (mkUniqSet (filter (not.isTyVar) args))) rhs Return,
315 body_text = nest 2 (braces (text ".maxstack 100" <+> nest 2 body_code))
318 pprIlxLocals env [] = empty
320 = text ".locals" <+> parens (pprSepWithCommas (pprIlxLocal env) (filter nonVoidLocal vs))
322 nonVoidLocal (LocalId v,_) = not (isVoidIlxRepId v)
323 nonVoidLocal _ = True
325 pprIlxLocal env (LocalId v,_) = pprIlxTypeL env (idIlxRepType v) <+> pprId v
326 pprIlxLocal env (LocalSDoc (ty,doc,pin),_) = pprIlxTypeL env (deepIlxRepType ty) <+> (if pin then text "pinned" else empty) <+> doc
329 pprFreeBinders env fvs
330 = (ilx_tvs_text <+> vs_text, env2)
332 (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
333 real_free_vs = filter (not . isVoidIlxRepId) free_vs
334 -- ignore the higher order type parameters for the moment
335 env1 = extendIlxEnvWithFreeTyVars env free_ilx_tvs
336 ilx_tvs_text = pprTyVarBinders env1 free_ilx_tvs
337 vs_text = parens (pprSepWithCommas ppr_id real_free_vs)
338 ppr_id v = pprIlxTypeL env1 (idIlxRepType v) <+> pprId v
339 env2 = extendIlxEnvWithFreeVars env1 real_free_vs
341 pprIdBinder env v = parens (pprIlxTypeL env (idIlxRepType v) <+> pprId v)
343 -- Declarations for the arguments of the main apply method
344 pprArgBinders env [] = (empty,env)
345 pprArgBinders env (arg:args)
346 = (arg_text <+> rest_text, res_env)
348 (arg_text,env') = pprArgBinder env arg
349 (rest_text,res_env) = pprArgBinders env' args
351 -- We could probably omit some void argument binders, but
354 | isVoidIlxRepId arg = (text "(unit)", extendIlxEnvWithArgs env [arg])
356 = if isTyVar arg then
357 let env' = extendIlxEnvWithTyArgs env [arg] in
358 (pprTyVarBinder env' arg, env')
359 else (pprIdBinder env arg,extendIlxEnvWithArgs env [arg])
362 -- Compute local variables used by generated method.
363 -- The names of some generated locals are recorded as SDocs.
365 data LocalSpec = LocalId Id | LocalSDoc (Type, SDoc, Bool) -- flag is for pinning
367 ilxExprLocals :: IlxEnv -> StgExpr -> [(LocalSpec,Maybe (IlxEnv,StgRhs))]
368 ilxExprLocals env (StgLet bind body) = ilxBindLocals env bind ++ ilxExprLocals env body
369 ilxExprLocals env (StgLetNoEscape _ _ bind body) = ilxBindLocals env bind ++ ilxExprLocals env body -- TO DO????
370 ilxExprLocals env (StgCase scrut _ _ bndr _ alts)
371 = ilxExprLocals (ilxPlaceStgCaseScrut env) scrut ++
372 (if isDeadBinder bndr then [] else [(LocalId bndr,Nothing)]) ++
373 ilxAltsLocals env alts
374 ilxExprLocals env (StgPrimApp (CCallOp (CCall (StaticTarget c) casm gc cconv)) args ret_ty)
375 = concat (ilxMapPlaceArgs 0 ilxCCallArgLocals env args)
376 ilxExprLocals _ _ = []
378 -- Generate locals to use for pinning arguments as we cross the boundary
380 ilxCCallArgLocals env arg@(StgVarArg v) | pinCCallArg v =
381 [(LocalSDoc (idType v, ilxEnvQualifyByExact env (ppr v) <> text "pin", True), Nothing)]
382 ilxCCallArgLocals _ _ | otherwise = []
384 ilxBindLocals env (StgNonRec _ b rhs) = [(LocalId b,Just (env, rhs))]
385 ilxBindLocals env (StgRec _ pairs) = map (\(x,y) -> (LocalId x,Just (env, y))) pairs
387 ilxAltsLocals env (StgAlgAlts _ alts deflt) = ilxDefltLocals env deflt ++ concat (ilxMapPlaceAlts ilxAlgAltLocals env alts)
388 ilxAltsLocals env (StgPrimAlts _ alts deflt) = ilxDefltLocals env deflt ++ concat (ilxMapPlaceAlts ilxPrimAltLocals env alts)
390 ilxAlgAltLocals env (con, bndrs, _, rhs) = map (\x -> (LocalId x,Nothing)) (filter (\v -> isId v && not (isDeadBinder v)) bndrs) ++ ilxExprLocals env rhs
391 ilxPrimAltLocals env (lit, rhs) = ilxExprLocals env rhs
393 ilxDefltLocals env StgNoDefault = []
394 ilxDefltLocals env (StgBindDefault rhs) = ilxExprLocals (ilxPlaceStgBindDefault env) rhs
397 ilxExprClosures :: IlxEnv -> StgExpr -> SDoc
398 ilxExprClosures env (StgApp _ args)
399 = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args) -- get strings
400 ilxExprClosures env (StgConApp _ args)
401 = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args) -- get strings
402 ilxExprClosures env (StgPrimApp _ args _)
403 = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args) -- get strings
404 ilxExprClosures env (StgLet bind body)
405 = ilxBindClosures env bind $$ ilxExprClosures (extendIlxEnvWithBinds env (ilxPairs1 bind)) body
406 ilxExprClosures env (StgLetNoEscape _ _ bind body) -- TO DO????
407 = ilxBindClosures env bind $$ ilxExprClosures (extendIlxEnvWithBinds env (ilxPairs1 bind)) body
408 ilxExprClosures env (StgCase scrut _ _ _ _ alts)
409 = ilxExprClosures (ilxPlaceStgCaseScrut env) scrut $$ ilxAltsClosures env alts
410 ilxExprClosures env (StgLit lit)
412 ilxExprClosures env other
415 ilxAltsClosures env (StgAlgAlts _ alts deflt)
416 = vcat [ilxExprClosures (ilxPlaceAlt env i) rhs | (i,(_, _, _, rhs)) <- [1..] `zip` alts]
418 ilxDefltClosures env deflt
420 ilxAltsClosures env (StgPrimAlts _ alts deflt)
421 = vcat [ilxExprClosures (ilxPlaceAlt env i) rhs | (i,(_, rhs)) <- [1..] `zip` alts]
423 vcat [ ilxGenLit (ilxPlacePrimAltLit env i) lit | (i,(lit,_)) <- [1..] `zip` alts]
425 ilxDefltClosures env deflt
427 ilxDefltClosures env (StgBindDefault rhs) = ilxExprClosures (ilxPlaceStgBindDefault env) rhs
428 ilxDefltClosures env StgNoDefault = empty
430 ilxArgClosures env (StgLitArg lit) = ilxGenLit env lit
431 ilxArgClosures _ _ = empty
435 ilxGenLit env (MachStr fs)
436 = vcat [text ".field static assembly char " <+> squotes nm <+> text "at" <+> nm <> text "L",
437 text ".data" <+> nm <> text "L" <+> text "= char *(" <> pprFSInILStyle fs <> text ")"
440 nm = ilxEnvQualifyByExact env (text "string")
442 ilxGenLit _ _ = empty
447 %************************************************************************
449 \subsection{Generating code}
451 %************************************************************************
456 -- Environment when generating expressions
457 data IlxEEnv = IlxEEnv IlxEnv (UniqSet Id)
459 data Sequel = Return | Jump IlxLabel
461 ilxSequel Return = text "ret"
462 ilxSequel (Jump lbl) = text "br" <+> pprIlxLabel lbl
464 isReturn Return = True
465 isReturn (Jump _) = False
468 ilxExpr :: IlxEEnv -> StgExpr
469 -> Sequel -- What to do at the end
472 ilxExpr eenv@(IlxEEnv env _) (StgApp fun args) sequel
473 = ilxFunApp env fun args (isReturn sequel) $$ ilxSequel sequel
475 -- ilxExpr eenv (StgLit lit) sequel
476 ilxExpr eenv@(IlxEEnv env _) (StgLit lit) sequel
477 = pushLit env lit $$ ilxSequel sequel
479 -- ilxExpr eenv (StgConApp data_con args) sequel
480 ilxExpr eenv@(IlxEEnv env _) (StgConApp data_con args) sequel
481 = text " /* ilxExpr:StgConApp */ " <+> ilxConApp env data_con args $$ ilxSequel sequel
483 -- ilxExpr eenv (StgPrimApp primop args _) sequel
484 ilxExpr eenv@(IlxEEnv env _) (StgPrimApp primop args ret_ty) sequel
485 = ilxPrimApp env primop args ret_ty $$ ilxSequel sequel
488 -- The following are versions of a peephole optimizations for "let t = \[] t2[fvs] in t"
489 -- I think would be subsumed by a general treatmenet of let-no-rec bindings??
490 ilxExpr eenv@(IlxEEnv env _) (StgLet (StgNonRec _ bndr (StgRhsClosure _ _ fvs upd [] rhs)) (StgApp fun [])) sequel
491 | (bndr == fun && null (ilxExprLocals env rhs)) -- TO DO???
492 = ilxExpr eenv rhs sequel
493 ilxExpr eenv@(IlxEEnv env _) (StgLetNoEscape _ _ (StgNonRec _ bndr (StgRhsClosure _ _ fvs upd [] rhs)) (StgApp fun [])) sequel
494 | (bndr == fun && null (ilxExprLocals env rhs)) -- TO DO???
495 = ilxExpr eenv rhs sequel
498 ilxExpr eenv (StgLet bind body) sequel
499 = ilxBind eenv bind $$ ilxExpr eenv body sequel
502 ilxExpr eenv (StgLetNoEscape _ _ bind body) sequel -- TO DO???
503 = ilxBind eenv bind $$ ilxExpr eenv body sequel
505 -- StgCase: Special case 1 to avoid spurious branch.
506 ilxExpr eenv@(IlxEEnv env live) (StgCase (StgApp fun args) live_in_case live_in_alts bndr _ alts) sequel
507 = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
508 ilxFunApp (ilxPlaceStgCaseScrut env) fun args False,
509 --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` live_in_alts)),
510 --ilxAlts (IlxEEnv env live_in_alts) bndr alts sequel
511 ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
514 -- StgCase: Special case 2 to avoid spurious branch.
515 ilxExpr eenv@(IlxEEnv env live) (StgCase (StgPrimApp primop args ret_ty) live_in_case live_in_alts bndr _ alts) sequel
516 = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
517 ilxPrimApp (ilxPlaceStgCaseScrut env) primop args ret_ty,
518 --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` live_in_alts)),
519 --ilxAlts (IlxEEnv env live_in_alts) bndr alts sequel
520 ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
523 -- StgCase: Normal case.
524 ilxExpr eenv@(IlxEEnv env live) (StgCase scrut live_in_case live_in_alts bndr _ alts) sequel
525 = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
526 ilxExpr (IlxEEnv (ilxPlaceStgCaseScrut env) live_in_case) scrut (Jump join_lbl),
528 --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` live_in_alts)),
529 --ilxAlts (IlxEEnv env live_in_alts) bndr alts sequel
530 ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
533 join_lbl = mkJoinLabel bndr
535 -- Wipe out locals and arguments that are no longer in use, to
536 -- prevent space leaks. If the VM is implemented 100% correctly then
537 -- this should probably not be needed, as the live variable analysis
538 -- in the JIT would tell the GC that these locals and arguments are
539 -- no longer live. However I'm putting it in here so we can
540 -- check out if it helps.
542 -- Also, in any case this doesn't capture everything we need. e.g.
543 -- when making a call:
545 -- where x is not used in the alternatives, then the variable x
546 -- is no longer live from the point it is transferred to the call
547 -- onwards. We should expunge "live_in_case - live_in_alts" right
548 -- before making the call, not after returning from the call....
550 -- Strictly speaking we also don't need to do this for primitive
551 -- values such as integers and addresses, i.e. things not
552 -- mapped down to GC'able objects.
554 = vcat (map (ilxWipeOne env) (filter (not.isVoidIlxRepId) ids))
557 = case lookupIlxVarEnv env id of
558 Just Local -> text "ldloca " <+> pprId id <+> text "initobj" <+> (pprIlxTypeL env (idIlxRepType id))
559 Just Arg -> text "deadarg " <+> pprId id <+> text "," <+> (pprIlxTypeL env (idIlxRepType id))
560 Just (CloVar _) -> ilxComment (text "not yet wiping closure variable" <+> pprId id )
561 _ -> ilxComment (text "cannot wipe non-local/non-argument" <+> pprId id )
565 ----------------------
567 ilxAlts :: IlxEEnv -> Id -> StgCaseAlts -> Sequel -> SDoc
568 ilxAlts eenv@(IlxEEnv env live) bndr alts sequel
569 -- At the join label, the result is on top
571 = vcat [store_in_bndr,
572 do_case_analysis alts
575 scrut_rep_ty = deepIlxRepType (idType bndr)
577 store_in_bndr | isDeadBinder bndr = empty
578 | isVoidIlxRepId bndr
579 = ilxComment (text "ignoring store of zero-rep value to be analyzed")
580 | otherwise = text "dup" $$ (text "stloc" <+> pprId bndr)
582 do_case_analysis (StgAlgAlts _ [] deflt)
585 do_case_analysis (StgAlgAlts _ args deflt)
586 = do_alg_alts ([1..] `zip` args) deflt
588 do_case_analysis (StgPrimAlts _ alts deflt)
589 = do_prim_alts ([1..] `zip` alts) $$ do_deflt deflt
591 do_alg_alts [(i, alt@(data_con,bndrs,used_flags, rhs))] StgNoDefault | isUnboxedTupleCon data_con
592 -- Collapse the analysis of unboxed tuples where
593 -- some or all elements are zero-sized
595 -- TO DO: add bndrs to set of live variables
597 [h] -> bind_collapse bndrs used_flags <+> do_rhs_no_pop alt_env rhs
598 _ -> bind_components alt_env dcon' bndrs 0 used_flags <+> do_rhs alt_env rhs
600 bndrs' = filter (not. isVoidIlxRepId) bndrs
601 -- Replacement unboxed tuple type constructor, used if any of the
602 -- arguments have zero-size and more than one remains.
603 dcon' = tupleCon Unboxed (length bndrs')
605 alt_env = IlxEEnv (ilxPlaceAlt env i) live
606 --alt_env = IlxEEnv (ilxPlaceAlt env i)
608 bind_collapse [] _ = panic "bind_collapse: unary element not found"
609 bind_collapse (h:t) (is_used:used_flags)
610 | isVoidIlxRepId h = ilxComment (text "zero-rep binding eliminated") <+> (bind_collapse t used_flags)
611 | not is_used = ilxComment (text "not used") <+> text "pop"
612 | otherwise = text "stloc" <+> pprId h
615 do_alg_alts [(i, alt@(data_con,bndrs,used_flags, rhs))] StgNoDefault
616 = vcat [text "castdata" <+> sep [pprIlxTypeR env scrut_rep_ty <> comma,
617 ilxConRef env data_con],
618 do_alg_alt (IlxEEnv (ilxPlaceAlt env i) live) alt
621 do_alg_alts alts deflt
622 = vcat [text "datacase" <+> sep [pprIlxTypeR env scrut_rep_ty,text ",",
623 pprSepWithCommas pp_case labels_w_alts],
625 vcat (map do_labelled_alg_alt labels_w_alts)
628 pp_case (i, (lbl, (data_con, _, _, _))) = parens (ilxConRef env data_con <> comma <> pprIlxLabel lbl)
629 labels_w_alts = [(i,(mkAltLabel bndr i, alt)) | (i, alt) <- alts]
631 do_prim_alts [] = empty
632 do_prim_alts ((i, (lit,alt)) : alts)
633 = vcat [text "dup", pushLit (ilxPlacePrimAltLit env i) lit, text "bne.un" <+> pprIlxLabel lbl,
634 do_rhs (IlxEEnv (ilxPlaceAlt env i) live) alt,
635 ilxLabel lbl, do_prim_alts alts]
637 lbl = mkAltLabel bndr i
639 do_labelled_alg_alt (i,(lbl, alt))
640 = ilxLabel lbl $$ do_alg_alt (IlxEEnv (ilxPlaceAlt env i) live) alt
642 do_alg_alt alt_eenv (data_con, bndrs, used_flags, rhs)
643 = vcat [bind_components alt_eenv data_con bndrs 0 used_flags,
647 bind_components alt_eenv data_con [] n _ = empty
648 bind_components alt_eenv data_con (h:t) n (is_used:used_flags)
650 -- don't increase the count in this case
651 = ilxComment (text "zero-rep binding eliminated")
652 <+> bind_components alt_eenv data_con t n used_flags
654 = bind_component alt_eenv data_con h is_used n
655 <+> bind_components alt_eenv data_con t (n + 1) used_flags
657 bind_component alt_eenv@(IlxEEnv alt_env _) data_con bndr is_used reduced_fld_no
659 = ilxComment (text "not used")
660 | isVoidIlxRepId bndr
661 = ilxComment (text "ignoring bind of zero-rep variable")
662 | otherwise = vcat [text "dup",
663 ld_data alt_env data_con reduced_fld_no bndr,
664 text "stloc" <+> pprId bndr]
666 do_deflt (StgBindDefault rhs) = do_rhs (IlxEEnv (ilxPlaceStgBindDefault env) live) rhs
667 do_deflt StgNoDefault = empty
670 | isVoidIlxRepId bndr = do_rhs_no_pop alt_eenv rhs -- void on the stack, nothing to pop
671 | otherwise = text "pop" $$ do_rhs_no_pop alt_eenv rhs -- drop the value
673 do_rhs_no_pop alt_env rhs = ilxExpr alt_env rhs sequel
675 ld_data alt_env data_con reduced_fld_no bndr
676 | isUnboxedTupleCon data_con
677 = text "ldfld" <+> sep [text "!" <> integer reduced_fld_no,
678 pprIlxTypeR alt_env scrut_rep_ty <> text "::fld" <> integer reduced_fld_no]
680 = text "lddata" <+> sep [pprIlxTypeR alt_env scrut_rep_ty <> comma,
681 ilxConRef env data_con <> comma,
682 integer reduced_fld_no]
685 -------------------------
691 -- Constants of unlifted types are represented as
692 -- applications to no arguments.
693 ilxFunApp env fun [] _ | isUnLiftedType (idType fun)
696 ilxFunApp env fun args tail_call
698 -- ldloc f function of type forall a. a->a
699 -- ldloc x arg of type Int
700 -- .tail callfunc <Int32> (!0) --> !0
702 vcat [pushId env fun,ilxFunAppArgs env 0 (idIlxRepType fun) args tail_call known_clo]
705 case lookupIlxBindEnv env fun of
706 Just (place, StgRhsClosure _ _ _ Updatable _ _) -> Nothing
707 Just (place, StgRhsClosure _ _ fvs _ args _) -> Just (place,fun,args,fvs)
708 _ -> trace (show fun ++ " --> " ++ show (arityLowerBound (idArityInfo fun))) Nothing
710 -- Push as many arguments as ILX allows us to in one go.
711 -- Recurse until we're done.
712 ilxFunAppArgs env num_sofar funty args tail_call known_clo
713 = vcat [vcat (ilxMapPlaceArgs num_sofar pushArgWithVoids env now_args),
714 call_instr <+> text "()" <+> now_args_text
716 <+> (pprIlxTypeR env_after_now_tyvs later_ty),
723 _ -> hsep (map (pprIlxArgInfo env_after_now_tyvs) now_arg_tys)
725 (now_args,now_arg_tys,env_after_now_tyvs,later_args,later_ty) =
727 (StgTypeArg v:rest) -> get_type_args ilxBestTypeArity args env funty
728 _ -> get_term_args ilxBestTermArity args env funty
730 -- Only apply up to maxArity real (non-type) arguments
731 -- at a time. ILX should, in principle, allow us to apply
732 -- arbitrary numbers, but you will get more succinct
733 -- (and perhaps more efficient) IL code
734 -- if you apply in clumps according to its maxArity setting.
735 -- This is because it has to unwind the stack and store it away
736 -- in local variables to do the partial applications.
738 -- Similarly, ILX only allows one type application at a time, at
739 -- least until we implement unwinding the stack for this case.
741 -- NB: In the future we may have to be more careful
742 -- all the way through
743 -- this file to bind type variables as we move through
744 -- type abstractions and "forall" types. This would apply
745 -- especially if the type variables were ever bound by expressions
746 -- involving the type variables.
748 -- This part strips off at most "max" term applications or one type application
749 get_type_args 0 args env funty = ([],[],env,args,funty)
750 get_type_args max args env (NoteTy _ ty) =
751 trace "IlxGen Internal Error: non representation type passed to get_args" (get_type_args max args env ty)
752 get_type_args max ((arg@(StgTypeArg v)):rest) env (ForAllTy tv rem_funty)
753 = if isIlxTyVar tv then
754 let env2 = extendIlxEnvWithFormalTyVars env [tv] in
755 let rest_ty = deepIlxRepType (substTy (mkTyVarSubst [tv] [v]) rem_funty) in
756 let (now,now_tys,env3,later,later_ty) = get_type_args (max - 1) rest env rest_ty in
757 let arg_ty = mkTyVarTy tv in
758 (arg:now,(arg,arg_ty):now_tys,env2, later, later_ty)
760 get_type_args max rest env rem_funty -- ? subst??
761 get_type_args _ (StgTypeArg _:_) _ _ = trace "IlxGen Internal Error: get_type_args could not get ForAllTy for corresponding arg" ([],[],env,[],funty)
762 get_type_args _ args env funty = ([],[],env,args,funty)
764 -- We could probably skip some void-rep arguments. Instead we
765 -- emit "ldvoid" for these and let ILXASM optimize them away.
766 -- get_term_args max (h@(StgVarArg v):t) env (FunTy dom ran) | isVoidIlxRepId v
767 -- = get_term_args max t env ran
768 get_term_args max args env (NoteTy _ ty) =
770 trace "IlxGen Internal Error: non representation type passed to get_term_args" (get_term_args max args env ty)
771 get_term_args 0 args env funty = ([],[],env,args,funty)
773 get_term_args _ (args@(StgTypeArg _:_)) env funty = ([],[],env,args,funty)
774 get_term_args max (h:t) env (FunTy dom ran) =
775 let (now,now_tys,env2,later,later_ty) = get_term_args (max - 1) t env ran in
776 (h:now, (h,dom):now_tys,env2,later,later_ty)
777 get_term_args max (h:t) env funty = trace "IlxGen Internal Error: get_term_args could not get FunTy or ForAllTy for corresponding arg" ([],[],env,[],funty)
778 get_term_args max args env funty = ([],[],env,args,funty)
780 -- Are there any remaining arguments?
781 done = case later_args of
785 -- If so, generate the subsequent calls.
786 later = if done then text "// done"
787 else ilxFunAppArgs env (num_sofar + length now_args) later_ty later_args tail_call Nothing
789 -- Work out whether to issue a direct call a known closure (callclo) or
790 -- an indirect call (callfunc). Basically, see if the identifier has
791 -- been let-bound, and then check we are applying exactly the right
792 -- number of arguments. Also check that it's not a thunk (actually, this
793 -- is done up above).
795 -- The nasty "all" check makes sure that
796 -- the set of type variables in scope at the callsite is a superset
797 -- of the set of type variables needed for the direct call. This is
798 -- is needed because not all of the type variables captured by a
799 -- let-bound binding will get propogated down to the callsite, and
800 -- the ILX system of polymorphism demands that the free type variables
801 -- get reapplied when we issue the direct "callclo". The
802 -- type variables are in reality also "bound up" in the closure that is
803 -- passed as the first argument, so when we do an indirect call
804 -- to that closure we're fine, which is why we don't need them in
805 -- the "callfunc" case.
808 Just (known_env,fun,needed,fvs) | (length needed == length args) &&
809 all (\x -> elemIlxTyVarEnv x env) free_ilx_tvs ->
810 vcat [text "callclo class",
811 nameReference env (idName fun) <+> squotes (ilxEnvQualifyByModule env (ppr fun)),
812 pprTypeArgs pprIlxTypeR env (map mkTyVarTy free_ilx_tvs)]
815 (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
816 otherwise -> text "callfunc"
818 if (tail_call && done) then text "tail." <+> basic_call_instr
819 else basic_call_instr
822 --------------------------
823 -- Print the arg info at the call site
824 -- For type args we are, at the moment, required to
825 -- give both the actual and the formal (bound). The formal
826 -- bound is always System.Object at the moment (bounds are
827 -- not properly implemented in ILXASM in any case, and nor do
828 -- we plan on making use og them) For
829 -- non-type args the actuals are on the stack, and we just give the
831 pprIlxArgInfo env (StgTypeArg arg,ty) =
832 angleBrackets (pprIlxTypeR env (deepIlxRepType arg) <+> ilxComment (text "actual for tyvar")) <+> text "<class [mscorlib] System.Object>"
833 pprIlxArgInfo env (_,ty) =
834 parens (pprIlxTypeL env ty)
837 ----------------------------
838 -- Code for a binding
839 ilxBind :: IlxEEnv -> StgBinding -> SDoc
840 ilxBind eenv@(IlxEEnv env _) bind =
841 vcat [vcat (map (ilxRhs env rec) pairs),
842 vcat (map (ilxFixupRec env rec) pairs)]
844 rec = ilxRecIds1 bind
845 pairs = ilxPairs1 bind
848 ----------------------------
849 -- Allocate a closure or constructor. Fix up recursive definitions.
850 ilxRhs :: IlxEnv -> [Id] -> (Id, StgRhs) -> SDoc
852 ilxRhs env rec (bndr, _) | isVoidIlxRepId bndr
855 ilxRhs env rec (bndr, StgRhsCon _ con args)
856 = vcat [text " /* ilxRhs:StgRhsCon */ " <+> ilxConApp env con args,
857 text "stloc" <+> pprId bndr
860 ilxRhs env rec (bndr, StgRhsClosure _ _ fvs upd args rhs)
861 = -- Assume .closure v<any A>(int64,!A) {
862 -- .apply <any B> (int32) (B) { ... }
865 -- let v = \B (x:int32) (y:B). ...
867 -- newclo v<int32>(int64,!0)
869 vcat [vcat (map pushFv free_vs),
870 (if null free_non_ilx_tvs then empty else (ilxComment (text "ignored some higher order type arguments in application - code will be non-verifiable"))),
871 text "newclo" <+> clotext,
872 text "stloc" <+> pprId bndr
875 pushFv id = if elem id rec then text "ldnull" else pushId env id
876 (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
877 clotext = pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs)
879 ilxFixupRec env rec (bndr, _) | isVoidIlxRepId bndr = ilxComment (text "no recursive fixup for void-rep-id")
881 ilxFixupRec env rec (bndr, StgRhsCon _ con args)
882 = text "// no recursive fixup"
884 ilxFixupRec env rec (bndr, StgRhsClosure _ _ fvs upd args rhs)
885 = vcat [vcat (map fixFv rec)]
887 fixFv recid = if elem recid fvs then
888 vcat [pushId env bndr,
890 text "stclofld" <+> clotext <> text "," <+> pprId recid]
891 else text "//no fixup needed for" <+> pprId recid
892 (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
893 clotext = pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs)
897 ---------------------------------------------
898 -- Code for a top-level binding in a module
899 ilxPairs binds = concat (map ilxPairs1 binds)
901 ilxPairs1 (StgNonRec _ bndr rhs) = [(bndr,rhs)]
902 ilxPairs1 (StgRec _ pairs) = pairs
904 ilxRecIds1 (StgNonRec _ bndr rhs) = []
905 ilxRecIds1 (StgRec _ pairs) = map fst pairs
907 ---------------------------------------------
908 -- Code for a top-level binding in a module
909 -- TODO: fix up recursions amongst CAF's
914 -- For the moment I've put in a completely spurious "reverse"...
916 -- Consider: make fixing up of CAF's part of ILX? i.e.
917 -- put static, constant, allocated datastructures into ILX.
919 stableSortBy :: (a -> a -> Ordering) -> [a] -> [a]
920 stableSortBy f (h:t) = insertBy f h (stableSortBy f t)
921 stableSortBy f [] = []
923 usedBy :: (Id,StgRhs) -> (Id,StgRhs) -> Ordering
924 usedBy (m,_) (_,StgRhsCon _ data_con args) | any (isArg m) args = LT
925 usedBy (m,_) (n,_) | m == n = EQ
926 usedBy (m,_) (_,_) = GT
928 isArg m (StgVarArg n) = (n == m)
932 ilxTopBind :: Module -> IlxEnv -> [(Id,StgRhs)] -> SDoc
933 --ilxTopBind mod env (StgNonRec _ bndr rhs) =
934 --ilxTopRhs env (bndr,rhs)
935 ilxTopBind mod env pairs =
936 vcat [text ".class" <+> pprId mod,
937 nest 2 (braces (nest 2 (vcat [empty,cctor, flds, empty])))]
939 cctor = vcat [text ".method static rtspecialname specialname void .cctor()",
941 (nest 2 (vcat [text ".maxstack 100",
942 text "ldstr \"LOG: initializing module" <+> pprId mod <+> text "\" call void ['mscorlib']System.Console::WriteLine(class [mscorlib]System.String)",
943 vcat (map (ilxTopRhs mod env) (stableSortBy usedBy pairs)),
944 text "ldstr \"LOG: initialized module" <+> pprId mod <+> text "\" call void ['mscorlib']System.Console::WriteLine(class [mscorlib]System.String)",
947 flds = vcat (map (ilxTopRhsStorage mod env) pairs)
949 --ilxTopRhs mod env (bndr, _) | isVoidIlxRepId bndr
952 ilxTopRhs mod env (bndr, StgRhsClosure _ _ fvs upd args rhs)
953 = vcat [vcat (map (pushId env) free_vs),
954 (if null free_non_ilx_tvs then empty else (ilxComment (text "ignored some higher order type arguments in application - code will be non verifiable...."))),
955 text "newclo" <+> pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs),
956 text "stsfld" <+> pprFieldRef env (mod,bndTy,bndr)
959 (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
960 bndTy = idIlxRepType bndr
962 ilxTopRhs mod env (bndr, StgRhsCon _ data_con args)
963 = vcat [ text " /* ilxTopRhs: StgRhsCon */ " <+> ilxConApp env data_con args,
964 text "stsfld" <+> pprFieldRef env (mod,bndTy,bndr)
967 bndTy = idIlxRepType bndr
969 pprFieldRef env (mod,ty,id)
970 = pprIlxTypeL env ty <+> moduleReference env mod <+> pprId mod <> text "::" <> pprId id
972 ilxTopRhsStorage mod env (bndr, StgRhsClosure _ _ _ _ _ _)
973 = text ".field public static " <+> pprIlxTypeL env bndTy <+> pprId bndr
975 bndTy = idIlxRepType bndr
976 ilxTopRhsStorage mod env (bndr, StgRhsCon _ _ _)
977 = text ".field public static " <+> pprIlxTypeL env bndTy <+> pprId bndr
979 bndTy = idIlxRepType bndr
981 --------------------------------------
983 pushArgWithVoids = pushArg_aux True
984 pushArg = pushArg_aux False
986 pushArg_aux voids env (StgTypeArg ty) = empty
987 pushArg_aux voids env (StgVarArg var) = pushId_aux voids env var
988 pushArg_aux voids env (StgLitArg lit) = pushLit env lit
991 mapi f l = mapi_aux f l 0
994 mapi_aux f (h:t) n = f n h : mapi_aux f t (n+1)
996 --------------------------------------
998 pushId = pushId_aux False
1000 pushId_aux :: Bool -> IlxEnv -> Id -> SDoc
1001 pushId_aux voids _ id | isVoidIlxRepId id =
1002 if voids then text "ldunit" else ilxComment (text "pushId: void rep skipped")
1003 pushId_aux _ env var
1004 = case lookupIlxVarEnv env var of
1005 Just Arg -> text "ldarg" <+> pprId var
1006 Just (CloVar n) -> text "ldenv" <+> int n
1007 Just Local -> text "ldloc" <+> pprId var
1009 vcat [ilxComment (text "pushId (Top) " <+> pprId m),
1010 text "ldsfld" <+> pprIlxTypeL env (idIlxRepType var)
1011 <+> moduleReference env m <+> pprId (moduleName m) <> text "::" <> pprId var]
1014 vcat [ilxComment (text "pushId (import) " <+> pprIlxTopVar env var),
1015 text "ldsfld" <+> pprIlxTypeL env (idIlxRepType var)
1016 <+> pprIlxTopVar env var]
1018 --------------------------------------
1020 pushLit env (MachChar c) = text "ldc.i4" <+> int c
1021 pushLit env (MachStr s) = text "ldsflda char " <+> ilxEnvQualifyByExact env (text "string") -- pprFSInILStyle s
1022 pushLit env (MachInt i) = text "ldc.i4" <+> integer i
1023 pushLit env (MachInt64 i) = text "ldc.i8" <+> integer i
1024 pushLit env (MachWord w) = text "ldc.i4" <+> integer w <+> text "conv.u4"
1025 pushLit env (MachWord64 w) = text "ldc.i8" <+> integer w <+> text "conv.u8"
1026 pushLit env (MachFloat f) = text "ldc.r4" <+> rational f
1027 pushLit env (MachDouble f) = text "ldc.r8" <+> rational f
1028 pushLit env (MachLitLit _ _) = trace "WARNING: Cannot compile MachLitLit to ILX in IlxGen.lhs" (text "// MachLitLit!!! Not valid in ILX!!")
1029 pushLit env (MachAddr w) = text "ldc.i4 conv.i " <+> integer w
1033 | isGlobalName n = (nameReference env n) <> pprId (nameModule n) <> text "::" <> squotes (ppr (nameModule n) <> text "_" <> ppr (nameOccName n))
1034 | otherwise = pprId (nameOccName n)
1041 %************************************************************************
1043 \subsection{Printing types}
1045 %************************************************************************
1050 isVoidIlxRepType (NoteTy _ ty) = isVoidIlxRepType ty
1051 isVoidIlxRepType (TyConApp tc _) | (tyConPrimRep tc == VoidRep) = True
1052 isVoidIlxRepType (TyConApp tc tys)
1053 = case newTyConRep tc of
1054 Just rep_ty -> isVoidIlxRepType (applyTys rep_ty tys)
1056 isUnboxedTupleTyCon tc &&
1057 null (filter (not. isVoidIlxRepType) tys)
1058 isVoidIlxRepType _ = False
1060 isVoidIlxRepId id = isVoidIlxRepType (idType id)
1064 -- Get rid of all NoteTy and NewTy artifacts
1065 deepIlxRepType :: Type -> Type
1066 deepIlxRepType (FunTy l r)
1067 = FunTy (deepIlxRepType l) (deepIlxRepType r)
1069 deepIlxRepType (TyConApp tc tys)
1070 = case newTyConRep tc of
1071 Just rep_ty -> ASSERT( length tys == tyConArity tc )
1072 -- The assert should hold because deepIlxRepType should
1073 -- only be applied to *types* (of kind *)
1074 deepIlxRepType (applyTys rep_ty tys)
1076 -- collapse UnboxedTupleTyCon down when it contains VoidRep types.
1077 if isUnboxedTupleTyCon tc then
1078 let tys' = map deepIlxRepType (filter (not. isVoidIlxRepType) tys) in
1081 _ -> mkTupleTy Unboxed (length tys') tys'
1083 TyConApp tc (map deepIlxRepType tys)
1084 deepIlxRepType (AppTy f x) = AppTy (deepIlxRepType f) (deepIlxRepType x)
1085 deepIlxRepType (ForAllTy b ty) = ForAllTy b (deepIlxRepType ty)
1086 deepIlxRepType (NoteTy _ ty) = deepIlxRepType ty
1087 deepIlxRepType (PredTy p) = deepIlxRepType (predRepTy p)
1088 deepIlxRepType ty@(TyVarTy tv) = ty
1090 idIlxRepType id = deepIlxRepType (idType id)
1092 --------------------------
1093 -- Some primitive type constructors are not thunkable.
1094 -- Everything else needs to be marked thunkable.
1095 pprIlxTypeL :: IlxEnv -> Type -> SDoc
1097 pprIlxTypeL env ty | isUnLiftedType ty || isVoidIlxRepType ty = pprIlxTypeR env ty
1098 pprIlxTypeL env ty = text "thunk" <> angleBrackets (pprIlxTypeR env ty)
1100 --------------------------
1101 -- Print non-thunkable version of type.
1104 pprIlxTypeR :: IlxEnv -> Type -> SDoc
1105 pprIlxTypeR env ty | isVoidIlxRepType ty = text "unit"
1106 pprIlxTypeR env ty@(AppTy f _) | isTyVarTy f = ilxComment (text "type app:" <+> pprId ty) <+> (text "class [mscorlib]System.Object")
1107 pprIlxTypeR env ty@(AppTy f x) = trace "pprIlxTypeR: should I be beta reducing types?!" (ilxComment (text "pprIlxTypeR: should I be beta reducing types...") <+> pprIlxTypeR env (applyTy f x))
1108 pprIlxTypeR env (TyVarTy tv) = pprIlxTyVar env tv
1110 -- The following is a special rule for types constructed out of
1111 -- higher kinds, e.g. Monad f or Functor f.
1113 -- The code below is not as general as it should be, but as I
1114 -- have no idea if this approach will even work, I'm going to
1115 -- just try it out on some simple cases arising from the prelude.
1116 pprIlxTypeR env ty@(TyConApp tc (h:t)) | isAlgTyCon tc && null (tyConTyVars tc)
1117 = ilxComment (text "what the fuck? 2") <+> (pprIlxTypeR env (TyConApp tc t))
1118 pprIlxTypeR env ty@(TyConApp tc (h:t)) | isAlgTyCon tc && not (isIlxTyVar (hd (tyConTyVars tc)))
1119 = pprIlxTypeR env (TyConApp tc t)
1120 pprIlxTypeR env (TyConApp tc args) = pprIlxTyConApp env tc args
1122 -- nb. the only legitimate place for VoidIlxRepTypes to occur in normalized IlxRepTypes
1123 -- is on the left of an arrow
1124 -- We could probably eliminate all but a final occurrence of these.
1125 pprIlxTypeR env (FunTy arg res)
1126 = pprIlxFunTy (pprIlxTypeL env arg) (pprIlxTypeR env res)
1128 pprIlxTypeR env ty@(ForAllTy tv body_ty) | isIlxTyVar tv
1129 = parens (text "forall" <+> pprTyVarBinders env' [tv] <+> nest 2 (pprIlxTypeR env' body_ty))
1131 env' = extendIlxEnvWithFormalTyVars env [tv]
1133 pprIlxTypeR env ty@(ForAllTy tv body_ty) | otherwise
1134 = ilxComment (text "higher order type var " <+> pprId tv) <+>
1135 pprIlxFunTy (text "class [mscorlib]System.Object") (pprIlxTypeR env body_ty)
1137 pprIlxTypeR env (NoteTy _ ty)
1138 = trace "WARNING! non-representation type given to pprIlxTypeR: see generated ILX for context where this occurs"
1139 (vcat [text "/* WARNING! non-representation type given to pprIlxTypeR! */",
1140 pprIlxTypeR env ty ])
1142 pprIlxFunTy dom ran = parens (hsep [text "func",parens dom,text "-->", ran])
1144 pprIlxTyConApp env tc args =
1145 case lookupUFM tyPrimConTable (getUnique tc) of
1146 Just f -> f env args
1148 (if isUnboxedTupleTyCon tc then pprIlxUnBoxedTyConApp else pprIlxBoxedTyConApp)
1149 env ((nameReference env (getName tc)) <> (ppr tc)) args
1151 pprIlxUnBoxedTyConApp env tcdoc args = text "value class" <+> tcdoc <> pprTypeArgs pprIlxTypeL env args
1152 pprIlxBoxedTyConApp env tcdoc args = text "class" <+> tcdoc <> pprTypeArgs pprIlxTypeR env args
1154 -- Returns e.g: <Int32, Bool>
1155 pprTypeArgs f env tys = pprTypeArgs_aux f env (filter (not . isVoidIlxRepType) tys)
1157 pprTypeArgs_aux f env [] = empty
1158 pprTypeArgs_aux f env tys = angleBrackets (pprSepWithCommas (f env) tys)
1161 pprTyVarBinders :: IlxEnv -> [TyVar] -> SDoc
1162 -- Returns e.g: <class [mscorlib]System.Object> <class [mscorlib]System.Object>
1163 -- plus a new environment with the type variables added.
1164 pprTyVarBinders env [] = empty
1165 pprTyVarBinders env tvs = angleBrackets (pprSepWithCommas (pprTyVarBinder_aux env) tvs)
1167 pprTyVarBinder :: IlxEnv -> TyVar -> SDoc
1168 pprTyVarBinder env tv =
1169 if isIlxTyVar tv then
1170 angleBrackets (pprTyVarBinder_aux env tv)
1172 ilxComment (text "higher order tyvar" <+> pprId tv <+>
1173 text ":" <+> pprIlxTypeR env (tyVarKind tv)) <+>
1174 ilxComment (text "omitted")
1175 -- parens (text "class [mscorlib]System.Object" <+> pprId tv)
1178 pprTyVarBinder_aux env tv =
1179 ilxComment (text "tyvar" <+> pprId tv <+> text ":" <+>
1180 pprIlxTypeR env (tyVarKind tv)) <+>
1181 (text "class [mscorlib]System.Object")
1183 -- Only a subset of Haskell types can be generalized using the type quantification
1186 ( h == liftedTypeKind) ||
1187 ( h == unliftedTypeKind) ||
1188 ( h == openTypeKind)
1190 isIlxTyVar v = isTyVar v && isIlxForAllKind (tyVarKind v)
1192 categorizeVars fvs = (ilx_tvs, non_ilx_tvs, vs)
1194 (tvs, vs) = partition isTyVar fvs
1195 (ilx_tvs, non_ilx_tvs) = categorizeTyVars tvs
1197 categorizeTyVars tyvs = partition isIlxTyVar tyvs
1199 pprValArgTys ppr_ty env tys = parens (pprSepWithCommas (ppr_ty env) tys)
1201 pprId id = squotes (ppr id)
1202 squotes s = text "'" <> s <> text "'"
1206 %************************************************************************
1210 %************************************************************************
1213 type IlxTyEnv = [TyVar]
1216 -- Nb. There is currently no distinction between the kinds of type variables.
1217 -- We may need to add this to print out correct numbers, esp. for
1219 extendIlxTyEnvWithFreeTyVars env tyvars = env ++ mkIlxTyEnv tyvars -- bound by .closure x<...> in a closure declared with type parameters
1220 extendIlxTyEnvWithFormalTyVars env tyvars = env ++ mkIlxTyEnv tyvars -- bound by "forall <...>" in a type
1221 extendIlxTyEnvWithTyArgs env tyvars = env ++ mkIlxTyEnv tyvars -- bound by "<...>" in a closure implementing a universal type
1223 formalIlxTyEnv tyvars = mkIlxTyEnv tyvars
1224 mkIlxTyEnv tyvars = [ v | v <- tyvars, isIlxTyVar v ]
1226 pprIlxTyVarInIlxTyEnv :: IlxTyEnv -> TyVar -> SDoc
1227 pprIlxTyVarInIlxTyEnv tv_env tv
1231 = pprTrace "pprIlxTyVar" (pprId tv <+> text "tv_env = { "
1232 <+> pprSepWithCommas (\x -> pprId x <+> text ":"
1233 <+> pprIlxTypeR (IlxEnv (thisModule, tv_env, emptyVarEnv, emptyVarEnv, (empty,empty),False)) (tyVarKind x)) tv_env <+> text "}")
1234 (char '!' <> pprId tv)
1236 = {- pprTrace "go" (ppr (tyVarName tv) <+> ppr (tyVarName x)) -}
1237 (if tyVarName x== tyVarName tv then char '!' <> int n <+> ilxComment (char '!' <> pprId tv)
1241 data HowBound = Top Module -- Bound in a modules
1242 | Arg -- Arguments to the enclosing closure
1243 | CloVar Int -- A free variable of the enclosing closure
1244 -- The int is the index of the field in the
1246 | Local -- Local let binding
1248 -- The SDoc prints a unique name for the syntactic block we're currently processing,
1249 -- e.g. Foo_bar_baz when inside closure baz inside closure bar inside module Foo.
1250 data IlxEnv = IlxEnv (Module, IlxTyEnv, IdEnv HowBound,IdEnv (IlxEnv, StgRhs), Place,Bool)
1251 type Place = (SDoc,SDoc)
1252 thisModule = mkHomeModule (mkModuleName "")
1254 pprIlxTyVar (IlxEnv (_, tv_env, _, _,_,_)) tv = pprIlxTyVarInIlxTyEnv tv_env tv
1256 emptyIlxEnv :: Bool -> Module -> IlxEnv
1257 emptyIlxEnv trace mod = IlxEnv (mod, emptyIlxTyEnv, emptyVarEnv, emptyVarEnv, (ppr mod,empty),trace)
1259 nextPlace place sdoc = place <> sdoc
1260 usePlace place sdoc = place <> sdoc
1262 ilxEnvSetPlace (IlxEnv (m, tv_env, id_env, bind_env, (mod,exact),tr)) sdoc
1263 = IlxEnv (m, tv_env, id_env, bind_env, (mod, sdoc),tr)
1264 ilxEnvNextPlace (IlxEnv (m, tv_env, id_env, bind_env, (mod,exact),tr)) sdoc
1265 = IlxEnv (m, tv_env, id_env, bind_env, (mod, nextPlace exact sdoc),tr)
1266 ilxEnvQualifyByModule (IlxEnv (_, _, _, _,(mod,_),_)) sdoc = usePlace mod sdoc
1267 ilxEnvQualifyByExact (IlxEnv (_, _, _, _,(mod,exact),_)) sdoc = usePlace mod sdoc <> usePlace exact sdoc
1269 ilxPlaceStgBindDefault env = ilxEnvNextPlace env (text "D")
1270 ilxPlaceStgRhsClosure env bndr = ilxEnvSetPlace env (ppr bndr) -- binders are already unique
1271 ilxPlaceStgCaseScrut env = ilxEnvNextPlace env (text "S")
1273 ilxPlaceAlt :: IlxEnv -> Int -> IlxEnv
1274 ilxPlaceAlt env i = ilxEnvNextPlace env (text "a" <> int i)
1275 ilxPlacePrimAltLit env i = ilxEnvNextPlace env (text "P" <> int i)
1276 ilxMapPlaceArgs start f env args = [ f (ilxEnvNextPlace env (text "A" <> int i)) a | (i,a) <- [start..] `zip` args ]
1277 ilxMapPlaceAlts f env alts = [ f (ilxPlaceAlt env i) alt | (i,alt) <- [1..] `zip` alts ]
1279 extendIlxEnvWithFreeTyVars (IlxEnv (mod, tv_env, id_env, bind_env, place,tr)) tyvars
1280 = IlxEnv (mod, extendIlxTyEnvWithFreeTyVars tv_env tyvars,id_env, bind_env, place,tr)
1282 extendIlxEnvWithFormalTyVars (IlxEnv (mod, tv_env, id_env, bind_env, place,tr)) tyvars
1283 = IlxEnv (mod, extendIlxTyEnvWithFormalTyVars tv_env tyvars,id_env, bind_env, place,tr)
1285 extendIlxEnvWithTyArgs (IlxEnv (mod, tv_env, id_env, bind_env, place,tr)) tyvars
1286 = IlxEnv (mod, extendIlxTyEnvWithTyArgs tv_env tyvars,id_env, bind_env, place,tr)
1288 extendIlxEnvWithArgs :: IlxEnv -> [Var] -> IlxEnv
1289 extendIlxEnvWithArgs (IlxEnv (mod, tv_env, id_env, bind_env, place,tr)) args
1290 = IlxEnv (mod, extendIlxTyEnvWithTyArgs tv_env [tv | tv <- args, isIlxTyVar tv],
1291 extendVarEnvList id_env [(v,Arg) | v <- args, not (isIlxTyVar v)],
1294 extendIlxEnvWithFreeVars (IlxEnv (mod, tv_env, id_env, bind_env, place,tr)) args
1296 extendIlxTyEnvWithFreeTyVars tv_env [tv | tv <- args, isIlxTyVar tv],
1297 extendVarEnvList id_env (clovs 0 args),
1302 clovs n (x:xs) = if not (isIlxTyVar x) then (x,CloVar n):clovs (n+1) xs else clovs n xs
1304 extendIlxEnvWithBinds env@(IlxEnv (mod, tv_env, id_env, bind_env, place,tr)) bnds
1305 = IlxEnv (mod, tv_env, id_env,
1306 extendVarEnvList bind_env [(v,(env,rhs)) | (v,rhs) <- bnds],
1309 extendIlxEnvWithLocals (IlxEnv (m, tv_env, id_env, bind_env, p,tr)) locals
1310 = IlxEnv (m, tv_env,
1311 extendVarEnvList id_env [(v,Local) | (LocalId v,_) <- locals],
1312 extendVarEnvList bind_env [(v,(env,rhs)) | (LocalId v,Just (env,rhs)) <- locals],
1314 extendIlxEnvWithTops env@(IlxEnv (m, tv_env, id_env, bind_env, place,tr)) mod binds
1315 = IlxEnv (m, tv_env,
1316 extendVarEnvList id_env [(bndr,Top mod) | (bndr,rhs) <- binds],
1317 extendVarEnvList bind_env [(bndr,(env, rhs)) | (bndr,rhs) <- binds],
1320 formalIlxEnv (IlxEnv (m, tv_env, id_env, bind_env, place, tr)) tyvars
1321 = IlxEnv (m, formalIlxTyEnv tyvars, id_env, bind_env, place, tr)
1323 elemIlxTyVarEnv var env@(IlxEnv (_, tv_env, _,_,_,_)) = elem var tv_env
1324 elemIlxVarEnv var env@(IlxEnv (_, _, id_env,_,_,_)) = elemVarEnv var id_env
1325 lookupIlxVarEnv env@(IlxEnv (_, _, id_env,_,_,_)) var = lookupVarEnv id_env var
1326 lookupIlxBindEnv env@(IlxEnv (_, _, _, bind_env,_,_)) var = lookupVarEnv bind_env var
1332 type IlxLabel = SDoc
1334 pprIlxLabel lbl = lbl
1336 mkJoinLabel :: Id -> IlxLabel
1337 mkJoinLabel v = text "J_" <> ppr v
1339 mkAltLabel :: Id -> Int -> IlxLabel
1340 mkAltLabel v n = text "A" <> int n <> ppr v
1342 ilxLabel :: IlxLabel -> SDoc
1343 ilxLabel lbl = line $$ (pprIlxLabel lbl <> colon)
1347 %************************************************************************
1349 \subsection{Local pretty helper functions}
1351 %************************************************************************
1354 pprSepWithCommas :: (a -> SDoc) -> [a] -> SDoc
1355 pprSepWithCommas pp xs = sep (punctuate comma (map pp xs))
1356 ilxComment pp = text "/*" <+> pp <+> text "*/"
1357 singleQuotes pp = char '\'' <> pp <> char '\''
1359 line = text "// ----------------------------------"
1361 hscOptionQual = if opt_SimplDoEtaReduction then text ".O" else text ".Onot"
1363 nameReference (IlxEnv (thisMod, _, _, _, _, _)) n
1364 | isLocalName n = empty
1365 | thisMod == nameModule n = text ""
1366 | isHomeModule (nameModule n) = moduleNameReference (moduleName (nameModule n))
1367 | isVanillaModule (nameModule n) = packageReference preludePackage
1368 | otherwise = packageReference (modulePackage (nameModule n))
1370 packageReference p = brackets ((text "ilx") <+> singleQuotes (ppr p <> hscOptionQual))
1371 moduleNameReference m = brackets ((text ".module") <+> (text "ilx") <+> singleQuotes (pprModuleName m <> hscOptionQual))
1373 moduleReference (IlxEnv (thisMod, _, _, _, _, _)) m
1374 | thisMod == m = text ""
1375 | isHomeModule m = moduleNameReference (moduleName m)
1376 | isVanillaModule m = packageReference preludePackage
1377 | otherwise = packageReference (modulePackage m)
1379 ------------------------------------------------
1380 -- This code is copied from absCSyn/CString.lhs,
1381 -- and modified to do the correct thing! It's
1382 -- still a mess though. Also, still have to do the
1383 -- right thing for embedded nulls.
1385 pprFSInILStyle :: FAST_STRING -> SDoc
1386 pprFSInILStyle fs = doubleQuotes (text (stringToC (_UNPK_ fs)))
1388 stringToC :: String -> String
1389 -- Convert a string to the form required by C in a C literal string
1390 -- Tthe hassle is what to do w/ strings like "ESC 0"...
1392 stringToC [c] = charToC c
1394 -- if we have something "octifiable" in "c", we'd better "octify"
1395 -- the rest of the string, too.
1396 = if (c < ' ' || c > '~')
1397 then (charToC c) ++ (concat (map char_to_C cs))
1398 else (charToC c) ++ (stringToC cs)
1400 char_to_C c | c == '\n' = "\\n" -- use C escapes when we can
1402 | c == '\b' = "\\b" -- ToDo: chk some of these...
1407 | otherwise = '\\' : (trigraph (ord c))
1409 charToC :: Char -> String
1410 -- Convert a character to the form reqd in a C character literal
1411 charToC c = if (c >= ' ' && c <= '~') -- non-portable...
1424 else '\\' : (trigraph (ord c))
1426 trigraph :: Int -> String
1428 = [chr ((n `div` 100) `rem` 10 + ord '0'),
1429 chr ((n `div` 10) `rem` 10 + ord '0'),
1430 chr (n `rem` 10 + ord '0')]
1435 %************************************************************************
1437 \subsection{PrimOps and Constructors}
1439 %************************************************************************
1442 ----------------------------
1443 -- Allocate a fresh constructor
1445 ilxConApp env data_con args
1446 | isUnboxedTupleCon data_con
1447 = let tm_args' = filter (not. isVoidIlxRepType . stgArgType) tm_args in
1450 -- Collapse the construction of an unboxed tuple type where
1451 -- every element is zero-sized
1452 vcat (ilxMapPlaceArgs 0 pushArg env tm_args')
1454 -- Minimize the construction of an unboxed tuple type, which
1455 -- may contain zero-sized elements. Recompute all the
1456 -- bits and pieces from the simpler case below for the new data
1457 -- type constructor....
1458 let data_con' = tupleCon Unboxed (length tm_args') in
1459 let rep_ty_args' = filter (not . isVoidIlxRepType) rep_ty_args in
1461 let tycon' = dataConTyCon data_con' in
1462 let (formal_tyvars', formal_tau_ty') = splitForAllTys (dataConRepType data_con') in
1463 let (formal_arg_tys', _) = splitFunTys formal_tau_ty' in
1464 let formal_env' = formalIlxEnv env formal_tyvars' in
1466 vcat [vcat (ilxMapPlaceArgs 0 pushArg env tm_args'),
1467 sep [text "newobj void ",
1468 pprIlxTyConApp env tycon' rep_ty_args',
1470 pprValArgTys pprIlxTypeR formal_env' (map deepIlxRepType formal_arg_tys')
1474 -- Now all other constructions
1475 = -- Assume C :: forall a. a -> T a -> T a
1476 -- ldloc x arg of type Int
1477 -- ldloc y arg of type T Int
1478 -- newdata classunion T<Int32>, C(!0, T <!0>)
1480 let tycon = dataConTyCon data_con in
1481 let (formal_tyvars, formal_tau_ty) = splitForAllTys (dataConRepType data_con) in
1482 let (formal_arg_tys, _) = splitFunTys formal_tau_ty in
1484 vcat [vcat (ilxMapPlaceArgs 0 pushArg env tm_args),
1485 sep [ text "newdata",
1486 nest 2 (pprIlxTyConApp env tycon rep_ty_args <> comma),
1487 nest 2 (ilxConRef env data_con)
1491 tycon = dataConTyCon data_con
1492 rep_ty_args = map deepIlxRepType ty_args
1493 (ty_args,tm_args) = if isAlgTyCon tycon then splitTyArgs (tyConTyVars tycon) args else splitTyArgs1 args
1495 -- split some type arguments off, throwing away the higher kinded ones for the moment
1496 -- base the higher-kinded checks off a corresponding list of formals
1497 splitTyArgs (htv:ttv) (StgTypeArg h:t)
1498 | isIlxTyVar htv = ((h:l), r)
1499 | otherwise = trace "splitTyArgs: threw away higher kinded type arg" (l, r)
1500 where (l,r) = splitTyArgs ttv t
1501 splitTyArgs _ l = ([],l)
1503 -- split some type arguments off, where none should be higher kinded
1504 splitTyArgs1 (StgTypeArg h:t)
1506 where (l,r) = splitTyArgs1 t
1507 splitTyArgs1 l = ([],l)
1510 ilxConRef env data_con
1511 = pprId data_con <> pprValArgTys pprIlxTypeL env' (map deepIlxRepType (filter (not . isVoidIlxRepType) arg_tys))
1513 (tyvars, tau_ty) = splitForAllTys (dataConRepType data_con)
1514 (arg_tys, _) = splitFunTys tau_ty
1515 env' = formalIlxEnv env tyvars
1518 tyPrimConTable :: UniqFM (IlxEnv -> [Type] -> SDoc)
1519 tyPrimConTable = listToUFM [(addrPrimTyConKey, (\_ _ -> repAddr)),
1520 -- (fileStreamPrimTyConKey, (\_ _ -> repFileStream)),
1521 (foreignObjPrimTyConKey, (\_ _ -> text "/* ForeignObj */ void *")),
1522 -- (stablePtrPrimTyConKey, (\_ _ -> text "/* StablePtr */ void *")),
1523 (charPrimTyConKey, (\_ _ -> repChar)),
1524 (wordPrimTyConKey, (\_ _ -> repWord)),
1525 (byteArrayPrimTyConKey, (\_ _ -> repByteArray)),
1526 (intPrimTyConKey, (\_ _ -> repInt)),
1527 (int64PrimTyConKey, (\_ _ -> repInt64)),
1528 (word64PrimTyConKey, (\_ _ -> repWord64)),
1529 (floatPrimTyConKey, (\_ _ -> text "float32")),
1530 (arrayPrimTyConKey, (\env [ty] -> pprIlxTypeL env ty <> text "[]")),
1531 (mutableArrayPrimTyConKey, (\env [_, ty] -> pprIlxTypeL env ty <> text "[]")),
1532 (mVarPrimTyConKey, (\env [_, ty] -> repMVar (pprIlxTypeL env ty))),
1533 (mutVarPrimTyConKey, (\env [ty1, ty2] -> repMutVar (pprIlxTypeL env ty1) (pprIlxTypeL env ty2))),
1534 (mutableByteArrayPrimTyConKey, (\_ _ -> repByteArray)),
1535 (threadIdPrimTyConKey, (\_ _ -> text "class [mscorlib]System.Threading.Thread /* ThreadId# */ ")),
1536 (doublePrimTyConKey, (\_ _ -> text "float64"))
1543 %************************************************************************
1545 \subsection{PrimOps}
1547 %************************************************************************
1554 if preludePackage == opt_InPackage then
1555 brackets (text ".module ilx PrelGHC" <> hscOptionQual)
1556 else brackets (text "ilx" <+> text (_UNPK_ preludePackage) <> hscOptionQual)
1560 if preludePackage == opt_InPackage then
1561 brackets (text ".module ilx PrelBase" <> hscOptionQual)
1562 else brackets (text "ilx" <+> text (_UNPK_ preludePackage) <> hscOptionQual)
1565 ilxPrimApp env (CCallOp ccall) args ret_ty = ilxCCall env ccall args ret_ty
1566 ilxPrimApp env op args ret_ty = ilxPrimOpTable op env args
1568 ilxMkBool = text "call class" <+> prelBaseReference <+>
1569 text "PrelBase_Bool" <+>
1570 prelGHCReference <+> text "GHC.support::mkBool(bool)"
1571 ilxCgt = text "cgt " <+> ilxMkBool
1572 ilxCge = text "clt ldc.i4 0 ceq " <+> ilxMkBool
1573 ilxClt = text "clt " <+> ilxMkBool
1574 ilxCle = text "cgt ldc.i4 0 ceq " <+> ilxMkBool
1575 ilxCeq = text "ceq " <+> ilxMkBool
1576 ilxCne = text "ceq ldc.i4 0 ceq " <+> ilxMkBool
1577 ilxCgtUn = text "cgt.un " <+> ilxMkBool
1578 ilxCgeUn = text "clt.un ldc.i4 0 ceq " <+> ilxMkBool
1579 ilxCltUn = text "clt.un " <+> ilxMkBool
1580 ilxCleUn = text "cgt.un ldc.i4 0 ceq " <+> ilxMkBool
1581 ldDummyInteger = text " ldc.i4 0 ldnull newobj void" <+> ilxUnboxedPairRep repInt repByteArray <+> text "::.ctor(!0,!1)"
1582 ldDummyInteger2 = text " ldc.i4 0 ldnull ldc.i4 0 ldnull newobj void" <+> ilxUnboxedQuadRep repInt repByteArray repInt repByteArray <+> text "::.ctor(!0,!1,!2,!3)"
1584 repByteArray = text "unsigned int8[] /* ByteArr# */ "
1585 repFileStream = text "void * /* FileStream# */ " -- text "class [mscorlib]System.IO.FileStream"
1586 repInt = text "int32"
1587 repWord = text "unsigned int32"
1588 repAddr = text "/* Addr */ void *"
1589 repInt64 = text "int64"
1590 repWord64 = text "unsigned int64"
1591 repChar = text "/* Char */ unsigned int8"
1592 repInteger = ilxUnboxedPairRep repInt repByteArray
1593 repIntegerPair = ilxUnboxedQuadRep repInt repByteArray repInt repByteArray
1594 repMVar ty = text "class " <+> prelGHCReference <+> text "PrelGHC_MVarzh" <+> ilxTyParams [ty]
1595 repMutVar _ ty2 = text "class " <+> prelGHCReference <+> text "PrelGHC_MutVarzh" <+> ilxTyParams [ty2]
1596 repWeak ty1 = text "class " <+> prelGHCReference <+> text "PrelGHC_Weakzh" <+> ilxTyParams [ty1]
1598 ilxParamsAux [] = empty
1599 ilxParamsAux [h] = h
1600 ilxParamsAux (h:t) = h <> text "," <+> ilxParamsAux t
1601 ilxParams [] = empty
1602 ilxParams l = parens (ilxParamsAux l)
1604 ilxTyParamsAux [] = empty
1605 ilxTyParamsAux [h] = h
1606 ilxTyParamsAux (h:t) = h <> text "," <+> ilxTyParamsAux t
1607 ilxTyParams [] = empty
1608 ilxTyParams l = angleBrackets (ilxTyParamsAux l)
1610 ilxMethA = text "!!0"
1612 ilxTyPair l r = ilxTyParams [l,r]
1613 ilxTyTriple l m r = ilxTyParams [l,m,r]
1614 ilxTyQuad l m1 m2 r = ilxTyParams [l,m1,m2,r]
1615 ilxUnboxedPairRep l r = text "value class" <+> prelGHCReference <+> text "PrelGHC_ZLzhzx2czhZR" <+> ilxTyPair l r
1616 ilxUnboxedTripleRep l m r = text "value class" <+> prelGHCReference <+> text "PrelGHC_ZLzhzx2czx2czhZR" <+> ilxTyTriple l m r
1617 ilxUnboxedQuadRep l m1 m2 r = text "value class" <+> prelGHCReference <+> text "PrelGHC_ZLzhzx2czx2czx2czhZR" <+> ilxTyQuad l m1 m2 r
1619 ilxMethodRef rty cls nm tyargs args = rty <+> cls <+> text "::" <> squotes (text nm) <> ilxTyParams tyargs <> ilxParams args
1621 ilxSupportClass = prelGHCReference <+> text "GHC.support"
1622 ilxSuppMeth rty nm tyargs args = ilxMethodRef rty ilxSupportClass nm tyargs args
1624 ilxPrimOpTable :: PrimOp -> IlxEnv -> [StgArg] -> SDoc
1627 CharGtOp -> simp_op ilxCgt
1628 CharGeOp -> simp_op ilxCge
1629 CharEqOp -> simp_op ilxCeq
1630 CharNeOp -> simp_op ilxCne
1631 CharLtOp -> simp_op ilxClt
1632 CharLeOp -> simp_op ilxCle
1634 OrdOp -> simp_op (text "conv.i4") -- chars represented by UInt32 (u4)
1635 ChrOp -> simp_op (text "conv.u4")
1637 IntGtOp -> simp_op ilxCgt
1638 IntGeOp -> simp_op ilxCge
1639 IntEqOp -> simp_op ilxCeq
1640 IntNeOp -> simp_op ilxCne
1641 IntLtOp -> simp_op ilxClt
1642 IntLeOp -> simp_op ilxCle
1644 WordGtOp -> simp_op ilxCgtUn -- words represented by UInt32 (u4)
1645 WordGeOp -> simp_op ilxCgeUn
1646 WordEqOp -> simp_op ilxCeq
1647 WordNeOp -> simp_op ilxCne
1648 WordLtOp -> simp_op ilxCltUn
1649 WordLeOp -> simp_op ilxCleUn
1651 AddrGtOp -> simp_op ilxCgt
1652 AddrGeOp -> simp_op ilxCge
1653 AddrEqOp -> simp_op ilxCeq
1654 AddrNeOp -> simp_op ilxCne
1655 AddrLtOp -> simp_op ilxClt
1656 AddrLeOp -> simp_op ilxCle
1658 FloatGtOp -> simp_op ilxCgt
1659 FloatGeOp -> simp_op ilxCge
1660 FloatEqOp -> simp_op ilxCeq
1661 FloatNeOp -> simp_op ilxCne
1662 FloatLtOp -> simp_op ilxClt
1663 FloatLeOp -> simp_op ilxCle
1665 DoubleGtOp -> simp_op ilxCgt
1666 DoubleGeOp -> simp_op ilxCge
1667 DoubleEqOp -> simp_op ilxCeq
1668 DoubleNeOp -> simp_op ilxCne
1669 DoubleLtOp -> simp_op ilxClt
1670 DoubleLeOp -> simp_op ilxCle
1672 -- Int#-related ops:
1673 IntAddOp -> simp_op (text "add")
1674 IntSubOp -> simp_op (text "sub")
1675 IntMulOp -> simp_op (text "mul")
1676 IntQuotOp -> simp_op (text "div")
1677 IntNegOp -> simp_op (text "neg")
1678 IntRemOp -> simp_op (text "rem")
1680 Addr2IntOp -> simp_op (text "conv.i4") -- Addresses are very dodgy for ILX. They are used for both C-strings and
1681 Int2AddrOp -> simp_op (text "conv.i") -- the FFI. This needs more work.
1682 ISllOp -> simp_op (text "shl")
1683 ISraOp -> simp_op (text "shr")
1684 ISrlOp -> simp_op (text "shr.un")
1685 IntAddCOp -> simp_op (text "call" <+> ilxSuppMeth (ilxUnboxedPairRep repInt repInt) "IntAddCOp" [] [repInt, repInt])
1686 IntSubCOp -> simp_op (text "call" <+> ilxSuppMeth (ilxUnboxedPairRep repInt repInt) "IntSubCOp" [] [repInt, repInt])
1687 IntMulCOp -> simp_op (text "call" <+> ilxSuppMeth (ilxUnboxedPairRep repInt repInt) "IntMulCOp" [] [repInt, repInt])
1688 IntGcdOp -> simp_op (text "call" <+> ilxSuppMeth repInt "IntMulCOp" [] [repInt, repInt])
1691 -- Word#-related ops:
1692 AndOp -> simp_op (text "and")
1693 OrOp -> simp_op (text "or")
1694 NotOp -> simp_op (text "not")
1695 XorOp -> simp_op (text "xor")
1696 SllOp -> simp_op (text "shl")
1697 SrlOp -> simp_op (text "shr")
1698 Word2IntOp -> simp_op (text "conv.i4")
1699 Int2WordOp -> simp_op (text "conv.u4")
1701 -- Float#-related ops:
1702 FloatAddOp -> simp_op (text "add")
1703 FloatSubOp -> simp_op (text "sub")
1704 FloatMulOp -> simp_op (text "mul")
1705 FloatDivOp -> simp_op (text "div")
1706 FloatNegOp -> simp_op (text "neg")
1707 Float2IntOp -> simp_op (text "conv.i4")
1708 Int2FloatOp -> simp_op (text "conv.r4")
1710 DoubleAddOp -> simp_op (text "add")
1711 DoubleSubOp -> simp_op (text "sub")
1712 DoubleMulOp -> simp_op (text "mul")
1713 DoubleDivOp -> simp_op (text "div")
1714 DoubleNegOp -> simp_op (text "neg")
1715 Double2IntOp -> simp_op (text "conv.i4")
1716 Int2DoubleOp -> simp_op (text "conv.r4")
1717 Double2FloatOp -> simp_op (text "conv.r4")
1718 Float2DoubleOp -> simp_op (text "conv.r8")
1719 DoubleDecodeOp -> simp_op (text "call" <+> ilxSuppMeth (ilxUnboxedTripleRep repInt repInt repByteArray) "decodeDouble" [] [text "float64"])
1720 FloatDecodeOp -> simp_op (text "call" <+> ilxSuppMeth (ilxUnboxedTripleRep repInt repInt repByteArray) "decodeFloat" [] [text "float32"])
1722 FloatExpOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Exp(float64) conv.r4")
1723 FloatLogOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Log(float64) conv.r4")
1724 FloatSqrtOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Sqrt(float64) conv.r4")
1725 FloatSinOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Sin(float64) conv.r4")
1726 FloatCosOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Cos(float64) conv.r4")
1727 FloatTanOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Tan(float64) conv.r4")
1728 FloatAsinOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Asin(float64) conv.r4")
1729 FloatAcosOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Acos(float64) conv.r4")
1730 FloatAtanOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Atan(float64) conv.r4")
1731 FloatSinhOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Sinh(float64) conv.r4")
1732 FloatCoshOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Cosh(float64) conv.r4")
1733 FloatTanhOp -> simp_op (text "conv.r8 call float64 [mscorlib]System.Math::Tanh(float64) conv.r4")
1734 FloatPowerOp -> simp_op (text "call float64 [mscorlib]System.Math::Pow(float64, float64) conv.r4") -- ** op, make use of implicit cast to r8...
1736 DoubleExpOp -> simp_op (text "call float64 [mscorlib]System.Math::Exp(float64)")
1737 DoubleLogOp -> simp_op (text "call float64 [mscorlib]System.Math::Log(float64)")
1738 DoubleSqrtOp -> simp_op (text "call float64 [mscorlib]System.Math::Sqrt(float64)")
1740 DoubleSinOp -> simp_op (text "call float64 [mscorlib]System.Math::Sin(float64)")
1741 DoubleCosOp -> simp_op (text "call float64 [mscorlib]System.Math::Cos(float64)")
1742 DoubleTanOp -> simp_op (text "call float64 [mscorlib]System.Math::Tan(float64)")
1744 DoubleAsinOp -> simp_op (text "call float64 [mscorlib]System.Math::Asin(float64)")
1745 DoubleAcosOp -> simp_op (text "call float64 [mscorlib]System.Math::Acos(float64)")
1746 DoubleAtanOp -> simp_op (text "call float64 [mscorlib]System.Math::Atan(float64)")
1748 DoubleSinhOp -> simp_op (text "call float64 [mscorlib]System.Math::Sinh(float64)")
1749 DoubleCoshOp -> simp_op (text "call float64 [mscorlib]System.Math::Cosh(float64)")
1750 DoubleTanhOp -> simp_op (text "call float64 [mscorlib]System.Math::Tanh(float64)")
1752 DoublePowerOp -> simp_op (text "call float64 [mscorlib]System.Math::Pow(float64, float64)")
1754 -- Integer (and related...) ops: bail out to support routines
1755 -- IntegerNegOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "IntegerNegOp" [] [repInt, repByteArray])
1756 -- Addr2IntegerOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "Addr2IntegerOp" [] [repAddr])
1757 IntegerAddOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "IntegerAddOp" [] [repInt, repByteArray, repInt, repByteArray])
1758 IntegerSubOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "IntegerSubOp" [] [repInt, repByteArray, repInt, repByteArray])
1759 IntegerMulOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "IntegerMulOp" [] [repInt, repByteArray, repInt, repByteArray])
1760 IntegerGcdOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "IntegerGcdOp" [] [repInt, repByteArray, repInt, repByteArray])
1761 IntegerQuotRemOp -> simp_op (text "call" <+> ilxSuppMeth repIntegerPair "IntegerQuotRemOp" [] [repInt, repByteArray, repInt, repByteArray])
1762 IntegerDivModOp -> simp_op (text "call" <+> ilxSuppMeth repIntegerPair "IntegerDivModOp" [] [repInt, repByteArray, repInt, repByteArray])
1763 IntegerIntGcdOp -> simp_op (text "call" <+> ilxSuppMeth repInt "IntegerIntGcdOp" [] [repInt, repByteArray, repInt])
1764 IntegerDivExactOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "IntegerDivExactOp" [] [repInt, repByteArray, repInt, repByteArray])
1765 IntegerQuotOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "IntegerQuotOp" [] [repInt, repByteArray, repInt, repByteArray])
1766 IntegerRemOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "IntegerRemOp" [] [repInt, repByteArray, repInt, repByteArray])
1767 IntegerCmpOp -> simp_op (text "call" <+> ilxSuppMeth repInt "IntegerCmpOp" [] [repInt, repByteArray, repInt, repByteArray])
1768 IntegerCmpIntOp -> simp_op (text "call" <+> ilxSuppMeth repInt "IntegerCmpIntOp" [] [repInt, repByteArray, repInt])
1769 Integer2IntOp -> simp_op (text "call" <+> ilxSuppMeth repInt "Integer2IntOp" [] [repInt, repByteArray])
1770 Integer2WordOp -> simp_op (text "call" <+> ilxSuppMeth repWord "Integer2WordOp" [] [repInt, repByteArray])
1771 Int2IntegerOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "Int2IntegerOp" [] [repInt])
1772 Word2IntegerOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "Word2IntegerOp" [] [repWord])
1773 IntegerToInt64Op -> simp_op (text "call" <+> ilxSuppMeth repAddr "IntegerToInt64Op" [] [repInt,repByteArray])
1774 Int64ToIntegerOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "Int64ToIntegerOp" [] [repInt64])
1775 IntegerToWord64Op -> simp_op (text "call" <+> ilxSuppMeth repWord64 "IntegerToWord64Op" [] [repInt,repByteArray])
1776 Word64ToIntegerOp -> simp_op (text "call" <+> ilxSuppMeth repInteger "Word64ToIntegerOp" [] [repWord64])
1778 IndexOffForeignObjOp_Char -> simp_op (text "add ldind.u1")
1779 IndexOffForeignObjOp_Int -> simp_op (text "ldc.i4 4 mul add ldind.i4")
1780 IndexOffForeignObjOp_Word -> simp_op (text "ldc.i4 4 mul add ldind.u4")
1781 IndexOffForeignObjOp_Addr -> warn_op "IndexOffForeignObjOp Addr: assuing 32 bit architecture" (simp_op (text "ldc.i4 4 mul add ldind.i "))
1782 IndexOffForeignObjOp_Float -> simp_op (text "ldc.i4 4 mul add ldind.r4")
1783 IndexOffForeignObjOp_Double -> simp_op (text "ldc.i4 8 mul add ldind.r8")
1784 IndexOffForeignObjOp_Int64 -> simp_op (text "ldc.i4 8 mul add ldind.i8")
1785 IndexOffForeignObjOp_Word64 -> simp_op (text "ldc.i4 8 mul add ldind.u8")
1787 IndexOffAddrOp_Char -> simp_op (text "add ldind.u1")
1788 IndexOffAddrOp_Int -> simp_op (text "ldc.i4 4 mul add ldind.i4")
1789 IndexOffAddrOp_Word -> simp_op (text "ldc.i4 4 mul add ldind.u4")
1790 IndexOffAddrOp_Addr -> warn_op "IndexOffAddrOp Addr: assuing 32 bit architecture" (simp_op (text "ldc.i4 4 mul add ldind.i"))
1791 IndexOffAddrOp_Float -> simp_op (text "ldc.i4 4 mul add ldind.r4")
1792 IndexOffAddrOp_Double -> simp_op (text "ldc.i4 8 mul add ldind.r8")
1793 IndexOffAddrOp_Int64 -> simp_op (text "ldc.i4 8 mul add ldind.i8")
1794 IndexOffAddrOp_Word64 -> simp_op (text "ldc.i4 8 mul add ldind.u8")
1797 WriteOffAddrOp_Char -> ty1_arg4_op (\sty addr n v s -> addr <+> n <+> text "add" <+> v <+> text "stind.u1")
1798 WriteOffAddrOp_Int -> ty1_arg4_op (\sty addr n v s -> addr <+> n <+> text "ldc.i4 4 mul add" <+> v <+> text "stind.i4")
1799 WriteOffAddrOp_Word -> ty1_arg4_op (\sty addr n v s -> addr <+> n <+> text "ldc.i4 4 mul add" <+> v <+> text "stind.u4")
1800 WriteOffAddrOp_Addr -> ty1_arg4_op (\sty addr n v s -> addr <+> n <+> text "ldc.i4 4 mul add" <+> v <+> text "stind.i")
1801 WriteOffAddrOp_Float -> ty1_arg4_op (\sty addr n v s -> addr <+> n <+> text "ldc.i4 4 mul add" <+> v <+> text "stind.r4")
1802 WriteOffAddrOp_Double -> ty1_arg4_op (\sty addr n v s -> addr <+> n <+> text "ldc.i4 8 mul add" <+> v <+> text "stind.r8")
1803 WriteOffAddrOp_Int64 -> ty1_arg4_op (\sty addr n v s -> addr <+> n <+> text "ldc.i4 8 mul add" <+> v <+> text "stind.i8")
1804 WriteOffAddrOp_Word64 -> ty1_arg4_op (\sty addr n v s -> addr <+> n <+> text "ldc.i4 8 mul add" <+> v <+> text "stind.u8")
1805 {- Addr# -> Int# -> Char# -> State# s -> State# s -}
1807 ReadOffAddrOp_Char -> simp_op (text "add ldind.u1")
1808 ReadOffAddrOp_Int -> simp_op (text "ldc.i4 4 mul add ldind.i4")
1809 ReadOffAddrOp_Word -> simp_op (text "ldc.i4 4 mul add ldind.u4")
1810 ReadOffAddrOp_Addr -> simp_op (text "ldc.i4 4 mul add ldind.i")
1811 ReadOffAddrOp_Float -> simp_op (text "ldc.i4 4 mul add ldind.r4")
1812 ReadOffAddrOp_Double -> simp_op (text "ldc.i4 8 mul add ldind.r8")
1813 ReadOffAddrOp_Int64 -> simp_op (text "ldc.i4 8 mul add ldind.i8")
1814 ReadOffAddrOp_Word64 -> simp_op (text "ldc.i4 8 mul add ldind.u8")
1815 {- Addr# -> Int# -> Char# -> State# s -> State# s -}
1817 IndexByteArrayOp_Char -> simp_op (text "ldelem.u1")
1818 IndexByteArrayOp_Int -> simp_op (text "ldelem.i4")
1819 IndexByteArrayOp_Word -> simp_op (text "ldelem.u4")
1820 IndexByteArrayOp_Addr -> simp_op (text "ldelem.u")
1821 IndexByteArrayOp_Float -> simp_op (text "ldelem.r4")
1822 IndexByteArrayOp_Double -> simp_op (text "ldelem.r8")
1823 IndexByteArrayOp_StablePtr -> simp_op (text "ldelem.i4")
1824 IndexByteArrayOp_Int64 -> simp_op (text "ldelem.i8")
1825 IndexByteArrayOp_Word64 -> simp_op (text "ldelem.u8")
1827 {- ByteArr# -> Int# -> Char# -}
1829 WriteByteArrayOp_Char -> simp_op (text "stelem.u1")
1830 WriteByteArrayOp_Int -> simp_op (text "stelem.i4")
1831 WriteByteArrayOp_Word -> simp_op (text "stelem.u4")
1832 WriteByteArrayOp_Addr -> simp_op (text "stelem.u")
1833 WriteByteArrayOp_Float -> simp_op (text "stelem.r4")
1834 WriteByteArrayOp_Double -> simp_op (text "stelem.r8")
1835 WriteByteArrayOp_StablePtr -> simp_op (text "stelem.i4")
1836 WriteByteArrayOp_Int64 -> simp_op (text "stelem.i8")
1837 WriteByteArrayOp_Word64 -> simp_op (text "stelem.u8")
1839 {- MutByteArr# s -> Int# -> Char# -> State# s -> State# s -}
1841 {- should be monadic??? -}
1842 ReadByteArrayOp_Char -> simp_op (text "ldelem.u1")
1843 ReadByteArrayOp_Int -> simp_op (text "ldelem.i4")
1844 ReadByteArrayOp_Word -> simp_op (text "ldelem.u4")
1845 ReadByteArrayOp_Addr -> simp_op (text "ldelem.u")
1846 ReadByteArrayOp_Float -> simp_op (text "ldelem.r4")
1847 ReadByteArrayOp_Double -> simp_op (text "ldelem.r8")
1848 ReadByteArrayOp_StablePtr -> simp_op (text "ldelem.i4")
1849 ReadByteArrayOp_Int64 -> simp_op (text "ldelem.i8")
1850 ReadByteArrayOp_Word64 -> simp_op (text "ldelem.u8")
1851 {- MutByteArr# s -> Int# -> State# s -> (# State# s, Char# #) -}
1853 {- should be monadic??? -}
1854 NewByteArrayOp_Char -> simp_op (text "newarr [mscorlib]System.Byte")
1855 -- NewByteArrayOp_Int -> simp_op (text "newarr [mscorlib]System.Int32")
1856 -- NewByteArrayOp_Word -> simp_op (text "newarr [mscorlib]System.UInt32")
1857 -- NewByteArrayOp_Addr -> simp_op (text "newarr [mscorlib]System.UInt64")
1858 -- NewByteArrayOp_Float -> simp_op (text "newarr [mscorlib]System.Single")
1859 -- NewByteArrayOp_Double -> simp_op (text "newarr [mscorlib]System.Double")
1860 -- NewByteArrayOp_StablePtr -> simp_op (text "newarr [mscorlib]System.UInt32")
1861 -- NewByteArrayOp_Int64 -> simp_op (text "newarr [mscorlib]System.Int64") TODO: there is no unique for this one -}
1862 -- NewByteArrayOp_Word64 -> simp_op (text "newarr [mscorlib]System.UInt64") -}
1863 {- Int# -> State# s -> (# State# s, MutByteArr# s #) -}
1865 UnsafeFreezeByteArrayOp -> ty1_op (\ty1 -> text "nop ")
1866 {- MutByteArr# s -> State# s -> (# State# s, ByteArr# #) -}
1867 SizeofByteArrayOp -> simp_op (text "ldlen")
1868 {- ByteArr# -> Int# -}
1870 SameMutableByteArrayOp -> ty1_op (\ty1 -> text "ceq " <+> ilxMkBool)
1871 {- MutByteArr# s -> MutByteArr# s -> Bool -}
1872 SizeofMutableByteArrayOp -> ty1_op (\ty1 -> text "ldlen")
1873 {- MutByteArr# s -> Int# -}
1875 SameMutVarOp -> ty2_op (\ty1 ty2 -> text "ceq " <+> ilxMkBool)
1876 {- MutVar# s a -> MutVar# s a -> Bool -}
1877 NewMutVarOp -> ty2_op (\ty1 ty2 -> text "newobj void" <+> repMutVar ty1 ty2 <+> text "::.ctor(!0)")
1878 {- a -> State# s -> (# State# s, MutVar# s a #) -}
1879 ReadMutVarOp -> ty2_op (\ty1 ty2 -> text "ldfld !0" <+> repMutVar ty1 ty2 <+> text "::contents")
1880 {- MutVar# s a -> State# s -> (# State# s, a #) -}
1881 WriteMutVarOp -> ty2_op (\ty1 ty2 -> text "stfld !0" <+> repMutVar ty1 ty2 <+> text "::contents")
1882 {- MutVar# s a -> a -> State# s -> State# s -}
1884 NewArrayOp -> ty2_op (\ty1 ty2 -> text "call !!0[] " <+> ilxSupportClass <+> text "::newArray<" <> ty1 <> text ">(" <> repInt <> text ", !!0)")
1885 {- Int# -> a -> State# s -> (# State# s, MutArr# s a #) -}
1886 IndexArrayOp -> ty1_op (\ty1 -> text "ldelem.ref")
1887 {- Array# a -> Int# -> (# a #) -}
1888 WriteArrayOp -> ty2_op (\ty1 ty2 -> text "stelem.ref")
1889 {- MutArr# s a -> Int# -> a -> State# s -> State# s -}
1890 ReadArrayOp -> ty2_op (\ty1 ty2 -> text "ldelem.ref")
1891 {- MutArr# s a -> Int# -> State# s -> (# State# s, a #) -}
1892 UnsafeFreezeArrayOp -> ty2_op (\ty1 ty2 -> text "nop")
1893 {- MutArr# s a -> State# s -> (# State# s, Array# a #) -}
1894 UnsafeThawArrayOp -> ty2_op (\ty1 ty2 -> text "nop")
1895 {- Array# a -> State# s -> (# State# s, MutArr# s a #) -}
1897 SameMutableArrayOp -> ty2_op (\ty1 ty2 -> text "ceq " <+> ilxMkBool)
1898 {- MutArr# s a -> MutArr# s a -> Bool -}
1901 RaiseOp -> ty2_op (\ty1 ty2 -> text "throw")
1902 CatchOp -> ty2_op (\ty1 ty2 ->
1903 text "call" <+> ilxSuppMeth ilxMethA "catch" [ty1,ty2] [text "(func (unit) --> !!0)", text "(func (!!1) --> (func (unit) --> !!0))"])
1904 {- (State# RealWorld -> (# State# RealWorld, a #) )
1905 -> (b -> State# RealWorld -> (# State# RealWorld, a #) )
1907 -> (# State# RealWorld, a #)
1910 BlockAsyncExceptionsOp -> ty1_op (\ty1 ->
1911 text "call" <+> ilxSuppMeth ilxMethA "blockAsyncExceptions" [ty1] [text "(func (unit) --> !!0)"])
1913 {- (State# RealWorld -> (# State# RealWorld, a #))
1914 -> (State# RealWorld -> (# State# RealWorld, a #))
1917 UnblockAsyncExceptionsOp -> ty1_op (\ty1 ->
1918 text "call" <+> ilxSuppMeth ilxMethA "unblockAsyncExceptions" [ty1] [text "(func (unit) --> !!0)"])
1921 State# RealWorld -> (# State# RealWorld, a #))
1922 -> (State# RealWorld -> (# State# RealWorld, a #))
1925 NewMVarOp -> ty2_op (\sty ty ->
1926 text "newobj void " <+> repMVar ty <+> text "::.ctor()")
1927 {- State# s -> (# State# s, MVar# s a #) -}
1929 TakeMVarOp -> ty2_op (\sty ty ->
1930 text "call" <+> ilxSuppMeth ilxMethA "takeMVar" [ty] [repMVar ilxMethA])
1931 {- MVar# s a -> State# s -> (# State# s, a #) -}
1933 -- These aren't yet right
1934 TryTakeMVarOp -> ty2_op (\sty ty ->
1935 text "call" <+> ilxSuppMeth ilxMethA "tryTakeMVar" [ty] [repMVar ilxMethA])
1936 {- MVar# s a -> State# s -> (# State# s, a #) -}
1938 TryPutMVarOp -> ty2_op (\sty ty ->
1939 text "call" <+> ilxSuppMeth ilxMethA "tryPutMVar" [ty] [repMVar ilxMethA])
1940 {- MVar# s a -> State# s -> (# State# s, a #) -}
1942 PutMVarOp -> ty2_op (\sty ty ->
1943 text "call" <+> ilxSuppMeth (text "void") "putMVar" [ty] [repMVar ilxMethA, ilxMethA])
1944 {- MVar# s a -> a -> State# s -> State# s -}
1946 SameMVarOp -> ty2_op (\sty ty -> text "ceq " <+> ilxMkBool)
1947 {- MVar# s a -> MVar# s a -> Bool -}
1949 -- TakeMaybeMVarOp -> ty2_op (\sty ty ->
1950 -- text "call" <+> ilxSuppMeth (ilxUnboxedPairRep repInt ilxMethA) "tryTakeMVar" [ty] [repMVar ilxMethA])
1951 -- {- MVar# s a -> State# s -> (# State# s, Int#, a #) -}
1953 IsEmptyMVarOp -> ty2_op (\sty ty ->
1954 text "call" <+> ilxSuppMeth repInt "isEmptyMVar" [ty] [repMVar ilxMethA])
1955 {- MVar# s a -> State# s -> (# State# s, Int# #) -}
1957 DataToTagOp -> ty1_op (\ty1 ->
1958 text "call" <+> ilxSuppMeth repInt "dataToTag" [ty1] [ilxMethA])
1961 TagToEnumOp -> ty1_op (\ty1 ->
1962 text "call" <+> ilxSuppMeth ilxMethA "tagToEnum" [ty1] [repInt])
1965 MakeStablePtrOp -> ty1_op (\ty1 -> text "newobj void class " <+> prelGHCReference <+> text "PrelGHC_StablePtrzh<" <> ty1 <> text ">::.ctor(!0)")
1966 {- a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #) -}
1968 DeRefStablePtrOp -> ty1_op (\ty1 -> text "ldfld !0 class " <+> prelGHCReference <+> text "PrelGHC_StablePtrzh<" <> ty1 <> text ">::contents")
1969 {- StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #) -}
1971 EqStablePtrOp -> ty1_op (\ty1 -> text "ceq " <+> ilxMkBool)
1972 {- StablePtr# a -> StablePtr# a -> Int# -}
1974 MkWeakOp -> ty3_op (\ty1 ty2 ty3 -> text "call" <+> ilxMethodRef (repWeak (text "!!1")) (text "class " <+> prelGHCReference <+> text "PrelGHC_Weakzh") "bake" [ty1,ty2,ty3] [text "!!0", text "!!1", text "!!2"])
1975 {- o -> b -> c -> State# RealWorld -> (# State# RealWorld, Weak# b #) -}
1977 DeRefWeakOp -> ty1_op (\ty1 -> text "call" <+> ilxMethodRef (ilxUnboxedPairRep repInt (text "!0")) (repWeak ty1) "deref" [] [])
1978 FinalizeWeakOp -> ty1_op (\ty1 -> text "call" <+> ilxMethodRef (ilxUnboxedPairRep repInt (text "(func (unit) --> class '()')")) (repWeak ty1) "finalizer" [] [])
1979 {- Weak# a -> State# RealWorld -> (# State# RealWorld, Int#,
1980 State# RealWorld -> (# State# RealWorld, Unit #)) #) -}
1982 MkForeignObjOp -> simp_op (text "nop /* newobj void class " <+> prelGHCReference <+> text "PrelGHC_ForeignObjzh::.ctor(void *) */")
1983 WriteForeignObjOp -> simp_op (text "pop /* stfld void * class " <+> prelGHCReference <+> text "PrelGHC_ForeignObjzh::contents */ ")
1984 -- (ForeignObjToAddrOp -> simp_op (text "ldfld void * class " <+> prelGHCReference <+> text "PrelGHC_ForeignObjzh::contents"))
1985 YieldOp -> simp_op (text "call class [mscorlib]System.Threading.Thread class [mscorlib]System.Threading.Thread::get_CurrentThread()
1986 call void class [mscorlib]System.Threading.Thread::Suspend()")
1987 MyThreadIdOp -> simp_op (text "call default class [mscorlib]System.Threading.Thread class [mscorlib]System.Threading.Thread::get_CurrentThread() ")
1988 KillThreadOp -> simp_op (text "call instance void class [mscorlib]System.Threading.Thread::Abort(class [mscorlib]System.Object) ")
1989 {- ThreadId# -> a -> State# RealWorld -> State# RealWorld -}
1991 ForkOp -> ty1_op (\ty -> text "call default class [mscorlib]System.Threading.Thread " <+> ilxSupportClass <+> text "::fork<" <> ty <> text ">(thunk<!0>)")
1993 ParOp -> warn_op "ParOp" (simp_op (text "/* ParOp skipped... */ pop ldc.i4 0"))
1995 DelayOp -> simp_op (text "call void class [mscorlib]System.Threading.Thread::Sleep(int32) ")
1996 {- Int# -> State# s -> State# s -}
1998 WaitReadOp -> warn_op "WaitReadOp" (simp_op (text "/* WaitReadOp skipped... */ pop"))
1999 WaitWriteOp -> warn_op "WaitWriteOp" (simp_op (text " /* WaitWriteOp skipped... */ pop"))
2002 other -> \env args -> ilxComment (simp_op (text "Unknown primop!:" <+> pprId op) env args)
2006 ty1_op op env ((StgTypeArg ty1):rest) =
2007 vcat (ilxMapPlaceArgs 1 pushArg env rest) $$ op (pprIlxTypeR env (deepIlxRepType ty1))
2008 --ty1_after1_op op env (h:(StgTypeArg ty1):rest) =
2009 -- vcat (ilxMapPlaceArgs 0 pushArg env [h]) $$ vcat (ilxMapPlaceArgs 2 pushArg env rest) $$ op (pprIlxTypeR env (deepIlxRepType ty1))
2010 ty2_op op env ((StgTypeArg ty1):(StgTypeArg ty2):rest) =
2011 vcat (ilxMapPlaceArgs 2 pushArg env rest) $$ op (pprIlxTypeR env (deepIlxRepType ty1)) (pprIlxTypeR env (deepIlxRepType ty2))
2013 ty3_op op env ((StgTypeArg ty1):(StgTypeArg ty2):(StgTypeArg ty3):rest) =
2014 vcat (ilxMapPlaceArgs 2 pushArg env rest) $$
2015 op (pprIlxTypeR env (deepIlxRepType ty1))
2016 (pprIlxTypeR env (deepIlxRepType ty2))
2017 (pprIlxTypeR env (deepIlxRepType ty3))
2019 ty1_arg4_op op env [(StgTypeArg ty1), a1, a2, a3, a4] =
2020 op (pprIlxTypeR env (deepIlxRepType ty1))
2021 (hd2 (ilxMapPlaceArgs 1 pushArg env [a1]) )
2022 (hd2 (ilxMapPlaceArgs 2 pushArg env [a2]) )
2023 (hd2 (ilxMapPlaceArgs 3 pushArg env [a3]) )
2024 (hd2 (ilxMapPlaceArgs 4 pushArg env [a4]) )
2029 simp_op op env args = vcat (ilxMapPlaceArgs 0 pushArg env args) $$ op
2030 warn_op warning f args = trace ("WARNING! IlxGen cannot translate primop " ++ warning) (f args)
2033 %************************************************************************
2035 \subsection{C Calls}
2037 %************************************************************************
2041 -- We eliminate voids in and around an IL C Call. We don't yet emit PInvoke stubs.
2042 -- We also do some type-directed translation for pinning Haskell-managed blobs
2043 -- of data as we throw them across the boundary.
2044 ilxCCall env (CCall (StaticTarget c) casm gc cconv) args ret_ty =
2045 ilxComment (text "C call <+> pprCLabelString c") <+>
2046 vcat [vcat (ilxMapPlaceArgs 0 pushCArg env args),
2047 text "call" <+> retdoc <+> text "class " <+> prelGHCReference <+> text "PrelGHC::" <+> pprCLabelString c <+> pprTypeArgs pprIlxTypeR env ty_args
2048 <+> pprCValArgTys pprIlxTypeL env (map deepIlxRepType (filter (not. isVoidIlxRepType) (map stgArgType tm_args))) ]
2051 if isVoidIlxRepType ret_ty then text "void"
2052 else pprIlxTypeR env (deepIlxRepType ret_ty)
2053 (ty_args,tm_args) = splitTyArgs1 args
2056 hasTyCon (TyConApp tc _) tc2 = tc == tc2
2057 hasTyCon _ _ = False
2059 isByteArrayCArgTy ty = hasTyCon ty byteArrayPrimTyCon || hasTyCon ty mutableByteArrayPrimTyCon
2060 isByteArrayCArg v = isByteArrayCArgTy (deepIlxRepType (idType v))
2061 pinCCallArg v = isByteArrayCArg v
2063 ilxAddrOfPinnedByteArr = text "ldc.i4 0 ldelema unsigned int8"
2065 pushCArg env arg@(StgVarArg v) | isByteArrayCArg v = pushArg env arg <+> text "dup stloc" <+> squotes (ilxEnvQualifyByExact env (ppr v) <> text "pin") <+> ilxAddrOfPinnedByteArr
2066 pushCArg env arg | otherwise = pushArg env arg
2068 pprCValArgTys f env tys = parens (pprSepWithCommas (pprCValArgTy f env) tys)
2069 pprCValArgTy f env ty | isByteArrayCArgTy ty = text "void *" <+> ilxComment (text "interior pointer into ByteArr#")
2070 pprCValArgTy f env ty | otherwise = f env ty
2073 foldR :: (a -> b -> b) -> [a] -> b -> b
2075 -- foldR f (x:xs) z = f x (foldR f xs z)
2076 {-# INLINE foldR #-}
2077 foldR k xs z = go xs
2080 go (y:ys) = y `k` go ys