[project @ 2001-10-25 02:13:10 by sof]
[ghc-hetmet.git] / ghc / compiler / ilxGen / IlxGen.lhs
1 %
2 \section{Generate COM+ extended assembler}
3
4 \begin{code}
5 module IlxGen( ilxGen ) where
6
7 #include "HsVersions.h"
8
9 import Char     ( ord, chr )
10 import StgSyn
11 import Id       ( idType, idName, isDeadBinder, idArity )
12 import Var      ( Var, Id, TyVar, isId, isTyVar, tyVarKind, tyVarName )
13 import VarEnv
14 import VarSet   ( isEmptyVarSet )
15 import TyCon    ( TyCon,  tyConPrimRep, isUnboxedTupleTyCon, tyConDataCons, 
16                   tyConTyVars, isDataTyCon, isAlgTyCon, tyConArity
17                 )
18 import Type     ( liftedTypeKind, openTypeKind, unliftedTypeKind,
19                   isUnLiftedType, isTyVarTy, mkTyVarTy, sourceTypeRep,
20                   splitForAllTys, splitFunTys, applyTy, applyTys, eqKind, tyVarsOfTypes
21                 )
22 import TypeRep  ( Type(..) )
23 import DataCon  ( isUnboxedTupleCon, dataConTyCon, dataConRepType, dataConRepArgTys, DataCon(..) )
24 import Literal  ( Literal(..) )
25 import PrelNames        -- Lots of keys
26 import PrimOp           ( PrimOp(..) )
27 import ForeignCall      ( CCallConv(..), ForeignCall(..), CCallSpec(..), CCallTarget(..), DNCallSpec(..) )
28 import TysWiredIn       ( mkTupleTy, tupleCon )
29 import PrimRep          ( PrimRep(..) )
30 import Name             ( nameModule, nameOccName, isGlobalName, isLocalName, NamedThing(getName) )
31 import Subst            ( substTyWith )
32
33 import Module           ( Module, PackageName, ModuleName, moduleName, 
34                           modulePackage, preludePackage,
35                           isHomeModule, isVanillaModule,
36                           pprModuleName, mkHomeModule, mkModuleName
37                         )
38
39 import UniqFM
40 import BasicTypes       ( Boxity(..) )
41 import CStrings         ( CLabelString, pprCLabelString )
42 import Outputable
43 import Char             ( ord )
44 import List             ( partition, elem, insertBy,any  )
45 import UniqSet
46 import PprType          ( pprType )     -- Only called in debug messages
47
48 import TysPrim  ( foreignObjPrimTyCon, weakPrimTyCon, byteArrayPrimTyCon, mutableByteArrayPrimTyCon )
49
50 -- opt_SimplDoEtaReduction is used to help with assembly naming conventions for different
51 -- versions of compiled Haskell code.  We add a ".O" to all assembly and module 
52 -- names when this is set (because that's clue that -O was set).  
53 -- One day this will be configured by the command line.
54 import CmdLineOpts      ( opt_InPackage, opt_SimplDoEtaReduction )
55
56 \end{code}
57
58
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{Main driver}
63 %*                                                                      *
64 %************************************************************************
65
66 \begin{code}
67 ilxGen :: Module -> [TyCon] -> [(StgBinding,[Id])] -> SDoc
68         -- The TyCons should include those arising from classes
69 ilxGen mod tycons binds_w_srts
70   =  vcat [ text ".module '" <> (ppr (moduleName mod)) <> hscOptionQual <> text "o'",
71             text ".assembly extern 'mscorlib' {}",
72             vcat (map (ilxImportPackage topenv) (uniqSetToList import_packages)),
73             vcat (map (ilxImportModule topenv) (uniqSetToList import_modules)),
74             vcat (map (ilxImportTyCon topenv) (uniqSetToList import_tycons)),
75             vcat (map (ilxImportCCall topenv) (map snd (ufmToList import_ccalls))),
76             vcat (map (ilxTyCon topenv) data_tycons),
77             vcat (map (ilxBindClosures topenv) binds),
78             ilxTopBind mod topenv toppairs
79          ]
80     where
81       binds = map fst binds_w_srts
82       toppairs = ilxPairs binds
83       topenv = extendIlxEnvWithTops (emptyIlxEnv False mod) mod toppairs
84         -- Generate info from class decls as well
85       (import_packages,import_modules,import_tycons,import_ccalls) = importsBinds topenv binds (importsPrelude emptyImpInfo)
86       data_tycons = filter isDataTyCon tycons
87 \end{code}
88
89 %************************************************************************
90 %*                                                                      *
91 \subsection{Find Imports}
92 %*                                                                      *
93 %************************************************************************
94
95 \begin{code}
96
97 importsBinds :: IlxEnv -> [StgBinding] -> ImportsInfo -> ImportsInfo
98 importsBinds env binds = foldR (importsBind env) binds
99
100 importsNone :: ImportsInfo -> ImportsInfo
101 importsNone sofar = sofar
102
103 importsBind :: IlxEnv -> StgBinding -> ImportsInfo -> ImportsInfo
104 importsBind env (StgNonRec _ b rhs) = importsRhs env rhs.importsVar env b
105 importsBind env (StgRec _ pairs) = foldR (\(b,rhs) -> importsRhs env rhs . importsVar env b) pairs
106
107 importsRhs :: IlxEnv -> StgRhs -> ImportsInfo -> ImportsInfo
108 importsRhs env (StgRhsCon _ con args) = importsDataCon env con . importsStgArgs env args
109 importsRhs env (StgRhsClosure _ _ _ _ args body) = importsExpr env body. importsVars env args
110
111 importsExpr :: IlxEnv -> StgExpr -> ImportsInfo -> ImportsInfo
112 importsExpr env (StgLit _) = importsNone
113 importsExpr env (StgApp f args) = importsVar env f.importsStgArgs env args
114 importsExpr env (StgConApp con args) = importsDataCon env con.importsStgArgs env args
115 importsExpr env (StgOpApp (StgFCallOp (CCall (CCallSpec (StaticTarget c) cc _)) _) args rty)
116   = addCCallInfo (c,cc, map stgArgType tm_args, rty) . importsStgArgs env args
117   where 
118     (ty_args,tm_args) = splitTyArgs1 args 
119
120 importsExpr env (StgOpApp _ args res_ty) = importsType env res_ty. importsStgArgs env args
121
122
123 importsExpr env (StgSCC _ expr) = importsExpr env expr
124 importsExpr env (StgCase scrut _ _ bndr _ alts)
125   = importsExpr env scrut. imports_alts alts. importsVar env bndr
126    where
127     imports_alts (StgAlgAlts _ alg_alts deflt)  -- The Maybe TyCon part is dealt with 
128                                                 -- by the case-binder's type
129       = foldR imports_alg_alt alg_alts .  imports_deflt deflt
130        where
131         imports_alg_alt (con, bndrs, _, rhs)
132           = importsExpr env rhs . importsDataCon env con. importsVars env bndrs
133
134     imports_alts (StgPrimAlts _ alg_alts deflt)
135       = foldR imports_prim_alt alg_alts . imports_deflt deflt
136        where
137         imports_prim_alt (_, rhs) = importsExpr env rhs
138     imports_deflt StgNoDefault = importsNone
139     imports_deflt (StgBindDefault rhs) = importsExpr env rhs
140
141
142 importsExpr env (StgLetNoEscape _ _ bind body) = importsExpr env (StgLet bind body)
143 importsExpr env (StgLet bind body)
144   = importsBind env bind .  importsExpr env body
145
146 importsApp env v args = importsVar env v.  importsStgArgs env args
147 importsStgArgs env args = foldR (importsStgArg env) args
148
149 importsStgArg :: IlxEnv -> StgArg -> ImportsInfo -> ImportsInfo
150 importsStgArg env (StgTypeArg ty) = importsType env ty
151 importsStgArg env (StgVarArg v) = importsVar env v
152 importsStgArg env _ = importsNone
153
154 importsVars env vs = foldR (importsVar env) vs
155 importsVar env v = importsName env (idName v). importsType env (idType v)
156
157 importsName env n
158    | isLocalName n = importsNone
159    | ilxEnvModule env == nameModule n = importsNone
160    | isHomeModule (nameModule n) =  addModuleImpInfo (moduleName (nameModule n))
161 -- See HACK below
162    | isVanillaModule (nameModule n)  && not inPrelude =  importsPrelude
163    | isVanillaModule (nameModule n)  && inPrelude =   addModuleImpInfo (moduleName (nameModule n))
164 -- End HACK
165    | otherwise = addPackageImpInfo (modulePackage (nameModule n))
166
167
168 importsPrelude | inPrelude = addModuleImpInfo (mkModuleName "PrelGHC")
169                | otherwise = addPackageImpInfo preludePackage
170
171
172 importsType :: IlxEnv -> Type -> ImportsInfo -> ImportsInfo
173 importsType env ty = importsType2 env (deepIlxRepType ty)
174
175 importsType2 :: IlxEnv -> Type -> ImportsInfo -> ImportsInfo
176 importsType2 env (AppTy f x) =  importsType2 env f . importsType2 env x
177 importsType2 env (TyVarTy _) = importsNone
178 importsType2 env (TyConApp tc args) =importsTyCon env tc . importsTypeArgs2 env args
179 importsType2 env (FunTy arg res) =  importsType env arg .  importsType2 env res
180 importsType2 env (ForAllTy tv body_ty) =  importsType2 env body_ty
181 importsType2 env (NoteTy _ ty) = importsType2 env ty
182 importsType2 _ _ = panic "IlxGen.lhs: importsType2 ty"
183 importsTypeArgs2 env tys = foldR (importsType2 env) tys
184
185 importsDataCon env dcon = importsTyCon env (dataConTyCon dcon)
186
187 importsTyCon env tc | (not (isDataTyCon tc) || 
188                    isLocalName (getName tc) || 
189                    ilxEnvModule env == nameModule (getName tc)) = importsNone
190 importsTyCon env tc | otherwise = importsName env (getName tc) . addTyConImpInfo tc .
191                                     foldR (importsTyConDataCon env) (tyConDataCons tc)
192
193
194 importsTyConDataCon :: IlxEnv -> DataCon -> ImportsInfo -> ImportsInfo
195 importsTyConDataCon env dcon = foldR (importsTyConDataConType env) (filter (not . isVoidIlxRepType) (dataConRepArgTys dcon))
196
197 importsTyConDataConType :: IlxEnv -> Type -> ImportsInfo -> ImportsInfo
198 importsTyConDataConType env ty = importsTyConDataConType2 env (deepIlxRepType ty)
199
200 importsTyConDataConType2 :: IlxEnv -> Type -> ImportsInfo -> ImportsInfo
201 importsTyConDataConType2 env (AppTy f x) =  importsTyConDataConType2 env f . importsTyConDataConType2 env x
202 importsTyConDataConType2 env (TyVarTy _) = importsNone
203 importsTyConDataConType2 env (TyConApp tc args) = importsTyConDataConTypeTyCon env tc . importsTyConDataConTypeArgs2 env args
204 importsTyConDataConType2 env (FunTy arg res) = importsTyConDataConType env arg .  importsTyConDataConType2 env res
205 importsTyConDataConType2 env (ForAllTy tv body_ty) = importsTyConDataConType2 env body_ty
206 importsTyConDataConType2 env (NoteTy _ ty) = importsTyConDataConType2 env ty
207 importsTyConDataConType2 _ _ = panic "IlxGen.lhs: importsTyConDataConType2 ty"
208 importsTyConDataConTypeArgs2 env tys = foldR (importsTyConDataConType2 env) tys
209
210 importsTyConDataConTypeTyCon env tc | (not (isDataTyCon tc) || 
211                    isLocalName (getName tc) || 
212                    ilxEnvModule env == nameModule (getName tc)) = importsNone
213 importsTyConDataConTypeTyCon env tc | otherwise = importsName env (getName tc)
214
215
216 type StaticCCallInfo = (CLabelString,CCallConv,[Type],Type)
217 type ImportsInfo = (UniqSet PackageName, UniqSet ModuleName, UniqSet TyCon, UniqFM StaticCCallInfo)
218    -- (Packages, Modules, Datatypes, Imported CCalls)
219
220 emptyImpInfo :: ImportsInfo
221 emptyImpInfo = (emptyUniqSet, emptyUniqSet, emptyUniqSet, emptyUFM)
222 addPackageImpInfo p (w,x,y,z) = (addOneToUniqSet w p, x, y,z)
223 addModuleImpInfo m (w,x,y,z) = (w, addOneToUniqSet x m, y,z)
224 addTyConImpInfo tc (w,x,y,z) = (w, x, addOneToUniqSet y tc,z)
225 addCCallInfo info@(nm,a,b,c) (w,x,y,z) = (w, x, y,addToUFM z nm info)
226
227 ilxImportTyCon :: IlxEnv -> TyCon -> SDoc
228 ilxImportTyCon env tycon | isDataTyCon tycon = ilxTyConDef True env tycon
229 ilxImportTyCon _ _ | otherwise =  empty
230
231 ilxImportPackage :: IlxEnv -> PackageName -> SDoc
232 ilxImportPackage _ p = text ".assembly extern" <+> singleQuotes (ppr p <> hscOptionQual) <+> text "{ }"
233
234 ilxImportModule :: IlxEnv -> ModuleName -> SDoc
235 ilxImportModule _ m = text ".module extern" <+> singleQuotes (ppr m <> hscOptionQual <> text "o")
236
237 -- Emit a P/Invoke declaration for the imported C function
238 -- TODO: emit the right DLL name
239 ilxImportCCall :: IlxEnv -> StaticCCallInfo -> SDoc
240 ilxImportCCall env (c,cc,args,ret) = 
241     text ".method static assembly pinvokeimpl" <+> 
242     parens (doubleQuotes (text "HSstd_cbits.dll") <+> text "cdecl") <+> retdoc <+> singleQuotes (pprCLabelString c) <+> 
243     pprCValArgTys ilxTypeL env (map deepIlxRepType (filter (not. isVoidIlxRepType) args)) <+> 
244     text "unmanaged preservesig { }"
245   where 
246     retdoc = 
247           if isVoidIlxRepType ret then text "void" 
248           else ilxTypeR env (deepIlxRepType ret)
249
250
251 \end{code}
252
253 %************************************************************************
254 %*                                                                      *
255 \subsection{Type declarations}
256 %*                                                                      *
257 %************************************************************************
258
259 \begin{code}
260
261
262 ilxTyCon :: IlxEnv -> TyCon -> SDoc
263 ilxTyCon env tycon =  ilxTyConDef False env tycon
264
265 -- filter to get only dataTyCons?
266 ilxTyConDef importing env tycon = 
267         vcat [empty $$ line,
268               text ".classunion" <+> (if importing then text "import" else empty) <+> tycon_ref <+> tyvars_text <+> super_text   <+> alts_text]
269    where
270      tycon_ref =  nameReference env (getName tycon)  <> (ppr tycon)
271      super_text = if importing then empty else text "extends thunk" <> angleBrackets (text "class" <+> tycon_ref)
272      tyvars = tyConTyVars tycon
273      (ilx_tvs, _) = categorizeTyVars tyvars
274      alts_env = extendIlxEnvWithFormalTyVars env ilx_tvs 
275      tyvars_text = pprTyVarBinders alts_env ilx_tvs 
276      alts = vcat (map (pprIlxDataCon alts_env) (tyConDataCons tycon))
277      alts_text = nest 2 (braces alts)
278
279 pprIlxDataCon env dcon =
280         text ".alternative" <+> pprId dcon <+> 
281         parens (pprSepWithCommas (ilxTypeL env) (map deepIlxRepType (filter (not. isVoidIlxRepType) (dataConRepArgTys dcon))))
282 \end{code}
283
284
285 %************************************************************************
286 %*                                                                      *
287 \subsection{Getting the .closures and literals out}                     *
288 %************************************************************************
289
290 \begin{code}
291
292 ilxBindClosures :: IlxEnv -> StgBinding -> SDoc
293 ilxBindClosures env (StgNonRec _ b rhs) = ilxRhsClosures env (b,rhs)
294 ilxBindClosures env (StgRec _ pairs)  
295   = vcat (map (ilxRhsClosures new_env) pairs)
296   where
297      new_env = extendIlxEnvWithBinds env pairs
298
299 ---------------
300 ilxRhsClosures _ (_, StgRhsCon _ _ _)
301   = empty
302
303 ilxRhsClosures env (bndr, StgRhsClosure _ _ fvs upd args rhs)
304   = vcat [ilxExprClosures next_env rhs,
305
306          empty $$ line,
307          kind_text <+> singleQuotes cloname <+>  free_vs_text,
308          nest 2 (braces (
309             nest 2 (vcat [empty,
310                           vcat [text ".apply" <+> closure_sig_text,
311                                 body_text
312                           ],
313                           empty
314                     ])
315                 ))
316     ]
317   where
318     kind_of_thing = case upd of
319                           Updatable -> ASSERT( null args ) ".thunk"
320                           otherwise -> ".closure"
321     kind_text = text kind_of_thing 
322                 
323     cloname = ilxEnvQualifyByModule env (ppr bndr)
324     next_env = ilxPlaceStgRhsClosure env bndr 
325     (free_vs_text,env_with_fvs) = pprFreeBinders next_env fvs
326
327
328     closure_sig_text =     
329       vcat [ text "()",
330              (case args of 
331                []        -> empty
332                otherwise -> args_text),
333              text "-->" <+>  rty_text]
334
335     (args_text,env_with_args) = pprArgBinders env_with_fvs args
336
337         -- Find the type returned, from the no. of args and the type of "bndr"
338     rty_text = 
339       case retType env_with_fvs (idIlxRepType bndr) args of
340        Just (env,ty) -> 
341           if isVoidIlxRepType ty  then  (text "void")
342           else ilxTypeR env ty 
343        Nothing -> trace "WARNING!  IlxGen.trace could not find return type - see generated ILX for context where this occurs." (text "// Could not find return type:" <+> ilxTypeR env_with_fvs (idIlxRepType bndr)<+> text ", non representation: " <+> ilxTypeR env_with_fvs (idType bndr))
344
345     -- strip off leading ForAll and Fun type constructions
346     -- up to the given number of arguments, extending the environment as
347     -- we go.  
348     retType env ty [] = Just (env, ty)
349     retType env (ForAllTy tv ty) (arg:args) = retType (extendIlxEnvWithTyArgs env [tv]) ty args
350     retType env (FunTy l r) (arg:args) = retType env r args
351     retType _ _ _  = Nothing
352
353         -- Code for the local variables
354     locals = ilxExprLocals env_with_args rhs
355
356     env_with_locals = extendIlxEnvWithLocals env_with_args locals
357
358         -- Code for the body of the main apply method
359     body_code = vcat [empty,
360                       pprIlxLocals env_with_args locals,
361                       ilxExpr (IlxEEnv env_with_locals (mkUniqSet (filter (not.isTyVar) args))) rhs Return,
362                       empty
363                 ]
364
365     body_text = nest 2 (braces (text ".maxstack 100" <+> nest 2 body_code))
366
367
368 pprIlxLocals env [] = empty
369 pprIlxLocals env vs 
370    = text ".locals" <+> parens (pprSepWithCommas (pprIlxLocal env) (filter nonVoidLocal vs))
371   where
372     nonVoidLocal (LocalId v,_) = not (isVoidIlxRepId v)
373     nonVoidLocal _ = True
374
375 pprIlxLocal env (LocalId v,_) = ilxTypeL env (idIlxRepType v) <+> pprId v
376 pprIlxLocal env (LocalSDoc (ty,doc,pin),_) = ilxTypeL env (deepIlxRepType ty) <+> (if pin then text "pinned" else empty) <+> doc
377
378
379 pprFreeBinders env fvs 
380     = (ilx_tvs_text <+> vs_text, env2)
381     where   
382        (free_ilx_tvs, _,free_vs) = categorizeVars fvs
383        real_free_vs = filter (not . isVoidIlxRepId) free_vs
384         -- ignore the higher order type parameters for the moment
385        env1 = extendIlxEnvWithFreeTyVars env free_ilx_tvs 
386        ilx_tvs_text = pprTyVarBinders env1 free_ilx_tvs
387        vs_text = parens (pprSepWithCommas ppr_id real_free_vs)
388        ppr_id v = ilxTypeL env1 (idIlxRepType v) <+> pprId v 
389        env2 = extendIlxEnvWithFreeVars env1 real_free_vs 
390
391 pprIdBinder env v = parens (ilxTypeL env (idIlxRepType v) <+> pprId v)
392
393         -- Declarations for the arguments of the main apply method
394 pprArgBinders env [] = (empty,env)
395 pprArgBinders env (arg:args)
396     = (arg_text <+> rest_text, res_env)
397    where 
398      (arg_text,env') = pprArgBinder env arg
399      (rest_text,res_env) = pprArgBinders env' args 
400
401 -- We could probably omit some void argument binders, but
402 -- don't...
403 pprArgBinder env arg 
404   | isVoidIlxRepId arg = (text "()", extendIlxEnvWithArgs env [arg])
405   | otherwise 
406       = if isTyVar arg then 
407          let env' = extendIlxEnvWithTyArgs env [arg] in 
408          (pprTyVarBinder env' arg, env')
409       else (pprIdBinder env arg,extendIlxEnvWithArgs env [arg])
410
411 --------------
412 -- Compute local variables used by generated method.
413 -- The names of some generated locals are recorded as SDocs.
414
415 data LocalSpec = LocalId Id | LocalSDoc (Type, SDoc, Bool)  -- flag is for pinning
416
417 ilxExprLocals :: IlxEnv -> StgExpr -> [(LocalSpec,Maybe (IlxEnv,StgRhs))]
418 ilxExprLocals env (StgLet bind body)              = ilxBindLocals env bind ++ ilxExprLocals env body
419 ilxExprLocals env (StgLetNoEscape _ _ bind body)  = ilxBindLocals env bind ++ ilxExprLocals env body  -- TO DO????
420 ilxExprLocals env (StgCase scrut _ _ bndr _ alts) 
421      = ilxExprLocals (ilxPlaceStgCaseScrut env) scrut ++ 
422        (if isDeadBinder bndr then [] else [(LocalId bndr,Nothing)]) ++ 
423        ilxAltsLocals env alts
424 ilxExprLocals env (StgOpApp (StgFCallOp fcall _) args _) 
425      = concat (ilxMapPlaceArgs 0 ilxCCallArgLocals env args)
426 ilxExprLocals _ _  = []
427
428 -- Generate locals to use for pinning arguments as we cross the boundary
429 -- to C.
430 ilxCCallArgLocals env (StgVarArg v) | pinCCallArg v = 
431    [(LocalSDoc (idType v, ilxEnvQualifyByExact env (ppr v) <> text "pin", True), Nothing)]
432 ilxCCallArgLocals _ _ | otherwise = []
433
434 ilxBindLocals env (StgNonRec _ b rhs) = [(LocalId b,Just (env, rhs))]
435 ilxBindLocals env (StgRec _ pairs)    = map (\(x,y) -> (LocalId x,Just (env, y))) pairs
436
437 ilxAltsLocals env (StgAlgAlts  _ alts deflt) = ilxDefltLocals env deflt ++ concat (ilxMapPlaceAlts ilxAlgAltLocals env alts)
438 ilxAltsLocals env (StgPrimAlts _ alts deflt) = ilxDefltLocals env deflt ++ concat (ilxMapPlaceAlts ilxPrimAltLocals env alts)
439
440 ilxAlgAltLocals env (_, bndrs, _, rhs) = map (\x -> (LocalId x,Nothing)) (filter (\v -> isId v && not (isDeadBinder v)) bndrs) ++ ilxExprLocals env rhs
441 ilxPrimAltLocals env (_, rhs)          = ilxExprLocals env rhs
442
443 ilxDefltLocals _ StgNoDefault   = []
444 ilxDefltLocals env (StgBindDefault rhs) = ilxExprLocals (ilxPlaceStgBindDefault env) rhs
445
446 --------------
447 ilxExprClosures :: IlxEnv -> StgExpr -> SDoc
448 ilxExprClosures env (StgApp _ args)
449   = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args)  -- get strings
450 ilxExprClosures env (StgConApp _ args)
451   = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args) -- get strings
452 ilxExprClosures env (StgOpApp _ args _)
453   = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args) -- get strings
454 ilxExprClosures env (StgLet bind body)
455   = ilxBindClosures env bind $$ ilxExprClosures (extendIlxEnvWithBinds env (ilxPairs1 bind)) body
456 ilxExprClosures env (StgLetNoEscape _ _ bind body)  -- TO DO????
457   = ilxBindClosures env bind $$ ilxExprClosures (extendIlxEnvWithBinds env (ilxPairs1 bind)) body
458 ilxExprClosures env (StgCase scrut _ _ _ _ alts)
459   = ilxExprClosures (ilxPlaceStgCaseScrut env) scrut $$ ilxAltsClosures env alts 
460 ilxExprClosures env (StgLit lit) 
461   = ilxGenLit env lit 
462 ilxExprClosures _ _ 
463   = empty
464
465 ilxAltsClosures env (StgAlgAlts _ alts deflt)
466   = vcat [ilxExprClosures (ilxPlaceAlt env i) rhs | (i,(_, _, _, rhs))  <- [1..] `zip` alts]
467     $$ 
468     ilxDefltClosures env deflt
469
470 ilxAltsClosures env (StgPrimAlts _ alts deflt)
471   = vcat [ilxExprClosures (ilxPlaceAlt env i) rhs | (i,(_, rhs)) <- [1..] `zip` alts]
472     $$ 
473     vcat [ ilxGenLit (ilxPlacePrimAltLit env i) lit | (i,(lit,_)) <- [1..] `zip` alts]
474     $$ 
475     ilxDefltClosures  env deflt
476
477 ilxDefltClosures env (StgBindDefault rhs) = ilxExprClosures (ilxPlaceStgBindDefault env) rhs
478 ilxDefltClosures _ StgNoDefault   = empty
479
480 ilxArgClosures env (StgLitArg lit) = ilxGenLit env lit 
481 ilxArgClosures _ _ = empty
482
483
484
485 ilxGenLit env (MachStr fs) 
486   = vcat [text ".field static assembly char "  <+> singleQuotes nm <+> text "at" <+> nm <> text "L",
487           text ".data" <+> nm <> text "L" <+> text "= char *("  <> pprFSInILStyle fs  <> text ")"
488          ]
489  where
490    nm = ilxEnvQualifyByExact env (text "string")
491
492 ilxGenLit  _ _ = empty
493
494 \end{code}
495
496
497 %************************************************************************
498 %*                                                                      *
499 \subsection{Generating code}
500 %*                                                                      *
501 %************************************************************************
502
503
504 \begin{code}
505
506 -- Environment when generating expressions
507 data IlxEEnv = IlxEEnv IlxEnv (UniqSet Id)
508
509 data Sequel = Return | Jump IlxLabel
510
511 ilxSequel Return     = text "ret"
512 ilxSequel (Jump lbl) = text "br" <+> pprIlxLabel lbl
513
514 isReturn Return = True
515 isReturn (Jump _) = False
516
517
518 ilxExpr :: IlxEEnv -> StgExpr 
519         -> Sequel       -- What to do at the end
520         -> SDoc
521
522 ilxExpr (IlxEEnv env _) (StgApp fun args) sequel
523   = ilxFunApp env fun args (isReturn sequel) $$ ilxSequel sequel
524
525 -- ilxExpr eenv (StgLit lit) sequel
526 ilxExpr (IlxEEnv env _) (StgLit lit) sequel
527   = pushLit env lit $$ ilxSequel sequel
528
529 -- ilxExpr eenv (StgConApp data_con args) sequel
530 ilxExpr (IlxEEnv env _) (StgConApp data_con args) sequel
531   = text " /* ilxExpr:StgConApp */ " <+>  ilxConApp env data_con args $$ ilxSequel sequel
532
533 -- ilxExpr eenv (StgPrimApp primop args _) sequel
534 ilxExpr (IlxEEnv env _) (StgOpApp (StgFCallOp fcall _) args ret_ty) sequel
535   = ilxFCall env fcall args ret_ty $$ ilxSequel sequel
536
537 ilxExpr (IlxEEnv env _) (StgOpApp (StgPrimOp primop) args ret_ty) sequel
538   = ilxPrimOpTable primop args env $$ ilxSequel sequel
539
540 --BEGIN TEMPORARY
541 -- The following are versions of a peephole optimizations for "let t = \[] t2[fvs] in t"
542 -- I think would be subsumed by a general treatmenet of let-no-rec bindings??
543 ilxExpr eenv@(IlxEEnv env _) (StgLet (StgNonRec _ bndr (StgRhsClosure _ _ _ _ [] rhs)) (StgApp fun [])) sequel 
544               | (bndr == fun && null (ilxExprLocals env rhs)) -- TO DO???
545   = ilxExpr eenv rhs sequel
546 ilxExpr eenv@(IlxEEnv env _) (StgLetNoEscape _ _ (StgNonRec _ bndr (StgRhsClosure _ _ _ _ [] rhs)) (StgApp fun [])) sequel 
547               | (bndr == fun && null (ilxExprLocals env rhs)) -- TO DO???
548   = ilxExpr eenv rhs sequel
549 --END TEMPORARY
550
551 ilxExpr eenv (StgLet bind body) sequel
552   = ilxBind eenv bind $$ ilxExpr eenv body sequel
553
554
555 ilxExpr eenv (StgLetNoEscape _ _ bind body) sequel -- TO DO???
556   = ilxBind eenv bind $$ ilxExpr eenv body sequel
557
558 -- StgCase: Special case 1 to avoid spurious branch.
559 ilxExpr eenv@(IlxEEnv env live) (StgCase (StgApp fun args) live_in_case _live_in_alts bndr _ alts) sequel
560   = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
561           ilxFunApp (ilxPlaceStgCaseScrut env) fun args False,
562           --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` _live_in_alts)),
563           --ilxAlts (IlxEEnv env _live_in_alts) bndr alts sequel
564           ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
565     ]
566
567 -- StgCase: Special case 2 to avoid spurious branch.
568 ilxExpr eenv@(IlxEEnv env live) (StgCase (StgOpApp (StgPrimOp primop) args ret_ty) live_in_case _live_in_alts bndr _ alts) sequel
569   = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
570           ilxPrimOpTable primop args (ilxPlaceStgCaseScrut env),
571           --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` _live_in_alts)),
572           --ilxAlts (IlxEEnv env _live_in_alts) bndr alts sequel
573           ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
574     ]
575
576 -- StgCase: Normal case.
577 ilxExpr eenv@(IlxEEnv env live) (StgCase scrut live_in_case _live_in_alts bndr _ alts) sequel
578   = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
579           ilxExpr (IlxEEnv (ilxPlaceStgCaseScrut env) live_in_case) scrut (Jump join_lbl),
580           ilxLabel join_lbl,
581           --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` _live_in_alts)),
582           --ilxAlts (IlxEEnv env _live_in_alts) bndr alts sequel
583           ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
584     ]
585   where
586     join_lbl = mkJoinLabel bndr
587
588 ilxExpr _ _ _ 
589   = panic "ilxExpr:  Patterns not matched:(IlxEEnv _ _) (StgSCC _ _) _ (IlxEEnv _ _) (StgLam _ _ _) _"
590
591
592 -- Wipe out locals and arguments that are no longer in use, to
593 -- prevent space leaks. If the VM is implemented 100% correctly then
594 -- this should probably not be needed, as the live variable analysis
595 -- in the JIT would tell the GC that these locals and arguments are
596 -- no longer live.  However I'm putting it in here so we can
597 -- check out if it helps.
598 --
599 -- Also, in any case this doesn't capture everything we need.  e.g.
600 -- when making a call:
601 --     case f x of ...
602 -- where x is not used in the alternatives, then the variable x
603 -- is no longer live from the point it is transferred to the call
604 -- onwards.  We should expunge "live_in_case - live_in_alts" right
605 -- before making the call, not after returning from the call....
606 --
607 -- Strictly speaking we also don't need to do this for primitive
608 -- values such as integers and addresses, i.e. things not
609 -- mapped down to GC'able objects.
610 ilxWipe env ids 
611    = vcat (map (ilxWipeOne env) (filter (not.isVoidIlxRepId) ids))
612
613 ilxWipeOne env id
614    = case lookupIlxVarEnv env id of
615           Just Local  -> text "ldloca " <+> pprId id <+> text "initobj.any" <+> (ilxTypeL env (idIlxRepType id))
616           Just Arg   -> text "deadarg " <+> pprId id <+> text "," <+> (ilxTypeL env (idIlxRepType id))
617           Just (CloVar _)  -> ilxComment (text "not yet wiping closure variable" <+> pprId id )
618           _ -> ilxComment (text "cannot wipe non-local/non-argument" <+> pprId id )
619   where 
620       
621
622 ----------------------
623
624 ilxAlts :: IlxEEnv -> Id -> StgCaseAlts -> Sequel -> SDoc
625 ilxAlts (IlxEEnv env live) bndr alts sequel
626         -- At the join label, the result is on top
627         -- of the stack
628   = vcat [store_in_bndr,
629           do_case_analysis alts
630     ]
631   where
632     scrut_rep_ty = deepIlxRepType (idType bndr)
633
634     store_in_bndr | isDeadBinder bndr = empty
635                   | isVoidIlxRepId bndr 
636                         = ilxComment (text "ignoring store of zero-rep value to be analyzed")
637                   | otherwise         = text "dup" $$ (text "stloc" <+> pprId bndr)
638
639     do_case_analysis (StgAlgAlts _ []    deflt)
640         = do_deflt deflt
641
642     do_case_analysis (StgAlgAlts _ args deflt) 
643         = do_alg_alts ([1..] `zip` args) deflt
644
645     do_case_analysis (StgPrimAlts _ alts deflt)
646         = do_prim_alts ([1..] `zip` alts) $$ do_deflt deflt
647
648     do_alg_alts [(i, alt@(data_con,bndrs,used_flags, rhs))] StgNoDefault | isUnboxedTupleCon data_con
649       -- Collapse the analysis of unboxed tuples where 
650       -- some or all elements are zero-sized
651       --
652       -- TO DO: add bndrs to set of live variables
653           = case bndrs' of
654                   [h] -> bind_collapse bndrs used_flags <+> do_rhs_no_pop alt_env rhs
655                   _ -> bind_components alt_env dcon' bndrs 0 used_flags <+> do_rhs alt_env rhs
656            where 
657             bndrs' = filter (not. isVoidIlxRepId) bndrs
658             -- Replacement unboxed tuple type constructor, used if any of the
659             -- arguments have zero-size and more than one remains.
660             dcon'  = tupleCon Unboxed (length bndrs')
661
662             alt_env = IlxEEnv (ilxPlaceAlt env i) live
663             --alt_env = IlxEEnv (ilxPlaceAlt env i) 
664
665             bind_collapse [] _ = panic "bind_collapse: unary element not found"
666             bind_collapse (h:t) (is_used:used_flags) 
667                 | isVoidIlxRepId h = ilxComment (text "zero-rep binding eliminated") <+> (bind_collapse t used_flags)
668                 | not is_used = ilxComment (text "not used") <+> text "pop"
669                 | otherwise = text "stloc" <+> pprId h
670
671
672     do_alg_alts [(i, alt@(data_con,bndrs,used_flags, rhs))] StgNoDefault 
673             = vcat [text "castdata" <+> sep [ilxTypeR env scrut_rep_ty <> comma,
674                                              ilxConRef env data_con],
675                 do_alg_alt (IlxEEnv (ilxPlaceAlt env i) live) alt
676               ]
677
678     do_alg_alts alts deflt
679         = vcat [text "datacase" <+> sep [ilxTypeR env scrut_rep_ty,text ",",
680                                          pprSepWithCommas pp_case labels_w_alts],
681                 do_deflt deflt,
682                 vcat (map do_labelled_alg_alt labels_w_alts)
683           ]
684         where
685           pp_case (i, (lbl, (data_con, _, _, _))) = parens (ilxConRef env data_con <> comma <> pprIlxLabel lbl)
686           labels_w_alts = [(i,(mkAltLabel bndr i, alt)) | (i, alt) <- alts]
687
688     do_prim_alts [] = empty
689     do_prim_alts ((i, (lit,alt)) : alts) 
690         = vcat [text "dup", pushLit (ilxPlacePrimAltLit env i) lit, text "bne.un" <+> pprIlxLabel lbl, 
691                 do_rhs (IlxEEnv (ilxPlaceAlt env i) live) alt, 
692                 ilxLabel lbl, do_prim_alts alts]
693         where
694           lbl = mkAltLabel bndr i
695
696     do_labelled_alg_alt (i,(lbl, alt)) 
697         = ilxLabel lbl $$ do_alg_alt (IlxEEnv (ilxPlaceAlt env i) live) alt
698
699     do_alg_alt alt_eenv (data_con, bndrs, used_flags, rhs) 
700       = vcat [bind_components alt_eenv data_con bndrs 0 used_flags,
701               do_rhs alt_eenv rhs
702              ]
703
704     bind_components alt_eenv data_con [] n _ = empty
705     bind_components alt_eenv data_con (h:t) n (is_used:used_flags) 
706        | isVoidIlxRepId h 
707              -- don't increase the count in this case
708              = ilxComment (text "zero-rep binding eliminated") 
709                <+> bind_components alt_eenv data_con t n used_flags
710        | otherwise 
711              = bind_component alt_eenv data_con h is_used n 
712                <+> bind_components alt_eenv data_con t (n + 1) used_flags
713
714     bind_component alt_eenv@(IlxEEnv alt_env _) data_con bndr is_used reduced_fld_no 
715         | not is_used 
716             = ilxComment (text "not used")
717         | isVoidIlxRepId bndr 
718             = ilxComment (text "ignoring bind of zero-rep variable")
719         | otherwise   = vcat [text "dup",
720                               ld_data alt_env data_con reduced_fld_no bndr,
721                               text "stloc" <+> pprId bndr]
722
723     do_deflt (StgBindDefault rhs) = do_rhs (IlxEEnv (ilxPlaceStgBindDefault env) live) rhs
724     do_deflt StgNoDefault         = empty
725
726     do_rhs alt_eenv rhs  
727         | isVoidIlxRepId bndr = do_rhs_no_pop alt_eenv rhs     -- void on the stack, nothing to pop
728         | otherwise = text "pop" $$ do_rhs_no_pop alt_eenv rhs  -- drop the value
729
730     do_rhs_no_pop alt_env rhs = ilxExpr alt_env rhs sequel
731
732     ld_data alt_env data_con reduced_fld_no bndr
733       | isUnboxedTupleCon data_con
734       = text "ldfld" <+> sep [text "!" <> integer reduced_fld_no,
735                               ilxTypeR alt_env scrut_rep_ty <> text "::fld" <> integer reduced_fld_no]
736       | otherwise 
737       = text "lddata" <+> sep [ilxTypeR alt_env scrut_rep_ty <> comma, 
738                                ilxConRef env data_con <> comma,
739                                integer reduced_fld_no]
740
741
742 -------------------------
743
744 ilxBestTermArity = 3
745 ilxBestTypeArity = 7
746
747
748 -- Constants of unlifted types are represented as
749 -- applications to no arguments.
750 ilxFunApp env fun [] _ | isUnLiftedType (idType fun)
751   = pushId env fun
752
753 ilxFunApp env fun args tail_call 
754   =     -- For example:
755         --      ldloc f         function of type forall a. a->a
756         --      ldloc x         arg of type Int
757         --      .tail callfunc <Int32> (!0) --> !0
758         --
759     vcat [pushId env fun,ilxFunAppAfterPush env fun args tail_call]
760
761 ilxFunAppAfterPush env fun args tail_call 
762   =     -- For example:
763         --      ldloc f         function of type forall a. a->a
764         --      ldloc x         arg of type Int
765         --      .tail callfunc <Int32> (!0) --> !0
766         --
767     vcat [ilxFunAppArgs env 0 (idIlxRepType fun) args tail_call known_clo]
768   where
769     known_clo :: KnownClosure
770     known_clo =
771       case lookupIlxBindEnv env fun of
772           Just (_, StgRhsClosure  _ _ _ Updatable _ _)   -> Nothing 
773           Just (place, StgRhsClosure  _ _ fvs _ args _)  -> Just (place,fun,args,fvs)
774           _ -> Nothing -- trace (show fun ++ " --> " ++ show (idArity fun))
775
776 type KnownClosure = Maybe (  IlxEnv     -- Of the binding site of the function
777                            , Id         -- The function
778                            , [Var]      -- Binders
779                            , [Var])     -- Free vars of the closure
780
781 -- Push as many arguments as ILX allows us to in one go, and call the function
782 -- Recurse until we're done.
783 -- The function is already on the stack
784 ilxFunAppArgs :: IlxEnv
785               -> Int            -- Number of args already pushed (zero is a special case;
786                                 --      otherwise used only for place generation)
787               -> Type           -- Type of the function
788               -> [StgArg]       -- The arguments
789               -> Bool           -- True <=> tail call please
790               -> KnownClosure   -- Information about the function we're calling
791               -> SDoc
792
793 ilxFunAppArgs env num_sofar funty args tail_call known_clo
794  =   vcat [vcat (ilxMapPlaceArgs num_sofar pushArgWithVoids env now_args),
795            call_instr <+> (if num_sofar == 0 then text "() /* first step in every Haskell app. is to a thunk */ " else empty)
796                      <+> now_args_text
797                      <+> text "-->" 
798                      <+> later_ty_text,
799            later
800           ]
801   where
802     now_args_text = 
803       case now_arg_tys of
804         [] -> empty
805         _ -> hsep (map (pprIlxArgInfo env_after_now_tyvs) now_arg_tys)
806
807     later_ty_text
808         | isVoidIlxRepType later_ty = text "void"
809         | otherwise = ilxTypeR env_after_now_tyvs later_ty
810
811     (now_args,now_arg_tys,env_after_now_tyvs,later_args,later_ty) = 
812         case args of
813           (StgTypeArg v:rest) -> get_type_args ilxBestTypeArity args env funty
814           _ -> get_term_args 0 ilxBestTermArity args env funty
815
816      -- Only apply up to maxArity real (non-type) arguments
817      -- at a time.  ILX should, in principle, allow us to apply
818      -- arbitrary numbers, but you will get more succinct 
819      -- (and perhaps more efficient) IL code
820      -- if you apply in clumps according to its maxArity setting.
821      -- This is because it has to unwind the stack and store it away
822      -- in local variables to do the partial applications.
823      --
824      -- Similarly, ILX only allows one type application at a time, at
825      -- least until we implement unwinding the stack for this case.
826      --
827      -- NB: In the future we may have to be more careful 
828      -- all the way through 
829      -- this file to bind type variables as we move through
830      -- type abstractions and "forall" types.  This would apply
831      -- especially if the type variables were ever bound by expressions
832      -- involving the type variables.  
833
834     -- This part strips off at most "max" term applications or one type application
835     get_type_args 0 args env funty = ([],[],env,args,funty)
836     get_type_args max args env (NoteTy _ ty) = 
837           trace "IlxGen Internal Error: non representation type passed to get_args" (get_type_args max args env ty)
838     get_type_args max ((arg@(StgTypeArg v)):rest) env (ForAllTy tv rem_funty) 
839         = if isIlxTyVar tv then 
840             let env2 = extendIlxEnvWithFormalTyVars env [tv] in 
841             let rest_ty = deepIlxRepType (substTyWith [tv] [v] rem_funty) in 
842             let (now,now_tys,env3,later,later_ty) = get_type_args (max - 1) rest env rest_ty in 
843             let arg_ty = mkTyVarTy tv in 
844             (arg:now,(arg,arg_ty):now_tys,env2, later, later_ty)
845           else 
846              get_type_args max rest env rem_funty  -- ? subst??
847     get_type_args _ (StgTypeArg _:_) _ _ = trace "IlxGen Internal Error: get_type_args could not get ForAllTy for corresponding arg" ([],[],env,[],funty)
848     get_type_args _ args env funty = ([],[],env,args,funty)
849
850     get_term_args n max args env (NoteTy _ ty)
851        -- Skip NoteTy types 
852        = trace "IlxGen Internal Error: non representation type passed to get_term_args" (get_term_args n max args env ty)
853     get_term_args n 0 args env funty
854        -- Stop if we've hit the maximum number of ILX arguments to apply n one hit.
855        = ([],[],env,args,funty)
856     get_term_args n max args env funty
857       | (case known_clo of
858            Just (_,_,needed,_) -> needed `lengthIs` n
859            Nothing -> False)
860        -- Stop if we have the optimal number for a direct call
861        = ([],[],env,args,funty)
862     get_term_args _ _ (args@(StgTypeArg _:_)) env funty 
863        -- Stop if we hit a type arg.
864        = ([],[],env,args,funty)
865     get_term_args n max (h:t) env (FunTy dom ran)
866        -- Take an argument.
867        = let (now,now_tys,env2,later,later_ty) = get_term_args (n+1) (max - 1) t env ran in 
868          (h:now, (h,dom):now_tys,env2,later,later_ty)
869     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)
870     get_term_args _ max args env funty = ([],[],env,args,funty)
871
872     -- Are there any remaining arguments?
873     done  = case later_args of
874           [] -> True
875           _ -> False
876
877     -- If so, generate the subsequent calls.
878     later = if done then text "// done"  
879             else ilxFunAppArgs env (num_sofar + length now_args) later_ty later_args tail_call Nothing
880
881     -- Work out whether to issue a direct call a known closure (callclo) or
882     -- an indirect call (callfunc).  Basically, see if the identifier has
883     -- been let-bound, and then check we are applying exactly the right 
884     -- number of arguments.  Also check that it's not a thunk (actually, this
885     -- is done up above).
886     -- 
887     -- The nasty "all" check makes sure that 
888     -- the set of type variables in scope at the callsite is a superset 
889     -- of the set of type variables needed for the direct call.  This is
890     -- is needed because not all of the type variables captured by a 
891     -- let-bound binding will get propogated down to the callsite, and 
892     -- the ILX system of polymorphism demands that the free type variables
893     -- get reapplied when we issue the direct "callclo".  The
894     -- type variables are in reality also "bound up" in the closure that is
895     -- passed as the first argument, so when we do an indirect call
896     -- to that closure we're fine, which is why we don't need them in 
897     -- the "callfunc" case.
898     basic_call_instr =
899       case known_clo of
900         Just (known_env,fun,needed,fvs) | (equalLength needed now_args) && 
901                                           all (\x -> elemIlxTyEnv x env) free_ilx_tvs -> 
902            vcat [text "callclo class",
903                  nameReference env (idName fun) <+> singleQuotes (ilxEnvQualifyByModule env (ppr fun)),
904                  pprTypeArgs ilxTypeR env (map mkTyVarTy free_ilx_tvs)]
905            <> text ","
906           where 
907            (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
908         otherwise -> text "callfunc"
909     call_instr =
910            if (tail_call && done) then text "tail." <+> basic_call_instr
911            else basic_call_instr
912
913
914 --------------------------
915 -- Print the arg info at the call site
916 -- For type args we are, at the moment, required to
917 -- give both the actual and the formal (bound).  The formal
918 -- bound is always System.Object at the moment (bounds are
919 -- not properly implemented in ILXASM in any case, and nor do
920 -- we plan on making use og them) For
921 -- non-type args the actuals are on the stack, and we just give the
922 -- formal type.
923 pprIlxArgInfo env (StgTypeArg  arg,ty) =  
924     angleBrackets (ilxTypeR env (deepIlxRepType arg) <+> ilxComment (text "actual for tyvar")) <+> text "<class [mscorlib] System.Object>" 
925 pprIlxArgInfo env (_,ty) =  
926     parens (ilxTypeL env ty)
927
928
929 ----------------------------
930 -- Code for a binding
931 ilxBind :: IlxEEnv -> StgBinding -> SDoc
932 ilxBind eenv@(IlxEEnv env _) bind = 
933     vcat [vcat (map (ilxRhs env rec) pairs), 
934           vcat (map (ilxFixupRec env rec) pairs)]
935        where 
936          rec = ilxRecIds1 bind
937          pairs = ilxPairs1 bind
938
939
940 ----------------------------
941 -- Allocate a closure or constructor.  Fix up recursive definitions.
942 ilxRhs :: IlxEnv -> [Id] -> (Id, StgRhs) -> SDoc
943
944 ilxRhs env rec (bndr, _) | isVoidIlxRepId bndr  
945   = empty
946
947 ilxRhs env rec (bndr, StgRhsCon _ con args)
948   = vcat [text " /* ilxRhs:StgRhsCon */ " <+> ilxConApp env con args,
949            text "stloc" <+> pprId bndr
950           ]
951
952 ilxRhs env rec (bndr, StgRhsClosure _ _ fvs upd args rhs)
953   =     -- Assume .closure v<any A>(int64,!A) { 
954         --              .apply <any B> (int32) (B) { ... }
955         --         }
956         -- Then
957         --    let v = \B (x:int32) (y:B). ... 
958         -- becomes:
959         --    newclo v<int32>(int64,!0)
960         --    stloc v
961     vcat [vcat (map pushFv free_vs),
962           (if null free_non_ilx_tvs then empty else (ilxComment (text "ignored some higher order type arguments in application - code will be non-verifiable"))),
963           text "newclo" <+> clotext,
964           text "stloc" <+> pprId bndr
965     ]
966   where
967     pushFv id = if elem id rec then text "ldnull" else pushId env id
968     (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
969     clotext = pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs)
970
971 ilxFixupRec env rec (bndr, _) | isVoidIlxRepId bndr = ilxComment (text "no recursive fixup for void-rep-id")
972
973 ilxFixupRec env rec (bndr, StgRhsCon _ con args)
974   = text "// no recursive fixup"
975
976 ilxFixupRec env rec (bndr, StgRhsClosure _ _ fvs upd args rhs)
977      = vcat [vcat (map fixFv rec)]
978   where
979     fixFv recid = if elem recid fvs then 
980                     vcat [pushId env bndr,
981                           pushId env recid,
982                           text "stclofld" <+> clotext <> text "," <+> pprId recid] 
983                 else text "//no fixup needed for" <+> pprId recid
984     (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
985     clotext = pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs)
986
987
988
989 ---------------------------------------------
990 -- Code for a top-level binding in a module
991 ilxPairs binds = concat (map ilxPairs1 binds)
992
993 ilxPairs1 (StgNonRec _ bndr rhs) = [(bndr,rhs)]
994 ilxPairs1 (StgRec _ pairs)       = pairs
995
996 ilxRecIds1 (StgNonRec _ bndr rhs) = []
997 ilxRecIds1 (StgRec _ pairs)       = map fst pairs
998
999 ---------------------------------------------
1000 -- Code for a top-level binding in a module
1001 -- TODO: fix up recursions amongst CAF's
1002 -- e.g. 
1003 --    x = S x
1004 -- for infinity...
1005 -- 
1006 -- For the moment I've put in a completely spurious "reverse"...
1007 --
1008 -- Consider: make fixing up of CAF's part of ILX?  i.e.
1009 -- put static, constant, allocated datastructures into ILX. 
1010
1011 stableSortBy :: (a -> a -> Ordering) -> [a] -> [a]
1012 stableSortBy f (h:t) = insertBy f h (stableSortBy f t)
1013 stableSortBy f [] = []
1014
1015 usedBy :: (Id,StgRhs) -> (Id,StgRhs) -> Ordering
1016 usedBy (m,_) (_,StgRhsCon _ data_con args) | any (isArg m) args = LT
1017 usedBy (m,_) (n,_) | m == n = EQ
1018 usedBy (m,_) (_,_) = GT
1019
1020 isArg m  (StgVarArg n) = (n == m)
1021 isArg m _ = False
1022
1023
1024 ilxTopBind :: Module -> IlxEnv -> [(Id,StgRhs)] -> SDoc
1025 --ilxTopBind mod env (StgNonRec _ bndr rhs) = 
1026 --ilxTopRhs env (bndr,rhs)
1027 ilxTopBind mod env pairs       = 
1028    vcat [text ".class" <+> pprId mod,
1029          nest 2 (braces (nest 2 (vcat [empty,cctor, flds, empty])))]
1030      where
1031        cctor = vcat [text ".method static rtspecialname specialname void .cctor()",
1032                      nest 2 (braces 
1033                       (nest 2 (vcat [text ".maxstack 100",
1034                                      text "ldstr \"LOG: initializing module" <+> pprId mod <+> text "\" call void ['mscorlib']System.Console::WriteLine(class [mscorlib]System.String)",
1035                                      vcat (map (ilxTopRhs mod env) (stableSortBy usedBy pairs)), 
1036                                      text "ldstr \"LOG: initialized module" <+> pprId mod <+> text "\" call void ['mscorlib']System.Console::WriteLine(class [mscorlib]System.String)",
1037                                      text "ret",
1038                                      empty])))]
1039        flds =   vcat (map (ilxTopRhsStorage mod env) pairs)
1040
1041 --ilxTopRhs mod env (bndr, _) | isVoidIlxRepId bndr 
1042 --  = empty
1043
1044 ilxTopRhs mod env (bndr, StgRhsClosure _ _ fvs upd args rhs)
1045   = vcat [vcat (map (pushId env) free_vs),
1046          (if null free_non_ilx_tvs then empty else (ilxComment (text "ignored some higher order type arguments in application - code will be non verifiable...."))),
1047           text "newclo" <+> pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs),
1048           text "stsfld"  <+> pprFieldRef env (mod,bndTy,bndr)
1049     ]
1050   where
1051     (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
1052     bndTy = idIlxRepType bndr
1053
1054 ilxTopRhs mod env (bndr, StgRhsCon _ data_con args)
1055   = vcat [ text " /* ilxTopRhs: StgRhsCon */ " <+> ilxConApp env data_con args, 
1056            text "stsfld" <+> pprFieldRef env (mod,bndTy,bndr)
1057     ]
1058   where
1059     bndTy = idIlxRepType bndr
1060
1061 pprFieldRef env (mod,ty,id) 
1062   =  ilxTypeL env ty <+> moduleReference env mod <+> pprId mod <> text "::" <> pprId id
1063
1064 ilxTopRhsStorage mod env (bndr, StgRhsClosure _ _ _ _ _ _) 
1065   =   text ".field public static " <+> ilxTypeL env bndTy <+> pprId bndr
1066   where
1067     bndTy = idIlxRepType bndr
1068 ilxTopRhsStorage mod env (bndr, StgRhsCon _ _ _) 
1069   =   text ".field public static " <+> ilxTypeL env bndTy <+> pprId bndr
1070   where
1071     bndTy = idIlxRepType bndr
1072
1073 --------------------------------------
1074 -- Push an argument
1075 pushArgWithVoids =  pushArg_aux True
1076 pushArg = pushArg_aux False
1077
1078 pushArg_aux voids env (StgTypeArg ty) = empty
1079 pushArg_aux voids env (StgVarArg var) = pushId_aux voids env var
1080 pushArg_aux voids env (StgLitArg lit) = pushLit env lit
1081
1082
1083 mapi f l = mapi_aux f l 0
1084
1085 mapi_aux f [] n = []
1086 mapi_aux f (h:t) n = f n h : mapi_aux f t (n+1)
1087
1088 --------------------------------------
1089 -- Push an Id
1090 pushId = pushId_aux False
1091
1092 pushId_aux :: Bool -> IlxEnv -> Id -> SDoc
1093 pushId_aux voids _ id | isVoidIlxRepId id =
1094    /* if voids then  text "ldunit" else */ ilxComment (text "pushId: void rep skipped")
1095 pushId_aux _ env var 
1096   = case lookupIlxVarEnv env var of
1097           Just Arg    -> text "ldarg"    <+> pprId var
1098           Just (CloVar n) -> text "ldenv" <+> int n
1099           Just Local  -> text "ldloc"    <+> pprId var
1100           Just (Top m)  -> 
1101              vcat [ilxComment (text "pushId (Top) " <+> pprId m), 
1102                    text "ldsfld" <+> ilxTypeL env (idIlxRepType var)
1103                       <+> moduleReference env m <+> pprId (moduleName m) <> text "::" <> pprId var]
1104
1105           Nothing ->  
1106              vcat [ilxComment (text "pushId (import) " <+> pprIlxTopVar env var), 
1107                    text "ldsfld" <+> ilxTypeL env (idIlxRepType var) 
1108                     <+> pprIlxTopVar env var]
1109
1110 --------------------------------------
1111 -- Push a literal
1112 pushLit env (MachChar c)   = text "ldc.i4" <+> int c
1113 pushLit env (MachStr s)    = text "ldsflda char "  <+> ilxEnvQualifyByExact env (text "string") -- pprFSInILStyle s 
1114 pushLit env (MachInt i)    = text "ldc.i4" <+> integer i
1115 pushLit env (MachInt64 i)  = text "ldc.i8" <+> integer i
1116 pushLit env (MachWord w)   = text "ldc.i4" <+> integer w <+> text "conv.u4"
1117 pushLit env (MachWord64 w) = text "ldc.i8" <+> integer w <+> text "conv.u8"
1118 pushLit env (MachFloat f)  = text "ldc.r4" <+> rational f
1119 pushLit env (MachDouble f) = text "ldc.r8" <+> rational f
1120 pushLit env (MachLitLit _ _) = trace "WARNING: Cannot compile MachLitLit to ILX in IlxGen.lhs" (text "// MachLitLit!!!  Not valid in ILX!!")
1121 pushLit env (MachAddr w) = text "ldc.i4" <+> integer w <+> text "conv.i"
1122 pushLit env (MachLabel l) = trace "WARNING: Cannot compile MachLabel to ILX in IlxGen.lhs" (text "// MachLabel!!!  Not valid in ILX!!")
1123
1124 pprIlxTopVar env v
1125   | isGlobalName n = (nameReference env n) <> pprId (nameModule n) <> text "::" <> singleQuotes (ppr (nameModule n) <> text "_" <> ppr (nameOccName n))
1126   | otherwise      = pprId (nameOccName n)
1127   where
1128     n = idName v
1129
1130 \end{code}
1131
1132
1133 %************************************************************************
1134 %*                                                                      *
1135 \subsection{Printing types}
1136 %*                                                                      *
1137 %************************************************************************
1138
1139
1140 \begin{code}
1141
1142 isVoidIlxRepType (NoteTy   _ ty) = isVoidIlxRepType ty
1143 isVoidIlxRepType (TyConApp tc _) | (tyConPrimRep tc == VoidRep) = True
1144 isVoidIlxRepType (TyConApp tc tys) 
1145   = isUnboxedTupleTyCon tc && null (filter (not. isVoidIlxRepType) tys)
1146 isVoidIlxRepType _ = False
1147
1148 isVoidIlxRepId id = isVoidIlxRepType (idType id)
1149
1150
1151
1152 -- Get rid of all NoteTy and NewTy artifacts
1153 deepIlxRepType :: Type -> Type
1154 deepIlxRepType (FunTy l r)
1155   = FunTy (deepIlxRepType l) (deepIlxRepType r)
1156
1157 deepIlxRepType ty@(TyConApp tc tys) 
1158   =        -- collapse UnboxedTupleTyCon down when it contains VoidRep types.
1159            -- e.g.      (# State#, Int#, Int# #)  ===>   (# Int#, Int# #)
1160             if isUnboxedTupleTyCon tc then 
1161                let tys' = map deepIlxRepType (filter (not. isVoidIlxRepType) tys) in 
1162                case tys' of
1163                   [h] -> h
1164                   _ -> mkTupleTy Unboxed (length tys') tys'
1165             else 
1166               TyConApp tc (map deepIlxRepType tys)
1167 deepIlxRepType (AppTy f x)     = AppTy (deepIlxRepType f) (deepIlxRepType x)
1168 deepIlxRepType (ForAllTy b ty) = ForAllTy b (deepIlxRepType ty)
1169 deepIlxRepType (NoteTy   _ ty) = deepIlxRepType ty
1170 deepIlxRepType (SourceTy p)    = deepIlxRepType (sourceTypeRep p)
1171 deepIlxRepType ty@(TyVarTy tv) = ty
1172
1173 idIlxRepType id = deepIlxRepType (idType id)
1174
1175 --------------------------
1176 -- Some primitive type constructors are not thunkable.
1177 -- Everything else needs to be marked thunkable.
1178 ilxTypeL :: IlxEnv -> Type -> SDoc
1179
1180 ilxTypeL env ty | isUnLiftedType ty ||  isVoidIlxRepType ty = ilxTypeR env ty
1181 ilxTypeL env ty = text "thunk" <> angleBrackets (ilxTypeR env ty)
1182
1183
1184 --------------------------
1185 -- Print non-thunkable version of type.
1186 --
1187
1188 ilxTypeR :: IlxEnv -> Type -> SDoc
1189 ilxTypeR env ty | isVoidIlxRepType ty = text "/* unit skipped */"
1190 ilxTypeR env ty@(AppTy f _) | isTyVarTy f    = ilxComment (text "type app:" <+> pprType ty) <+> (text "class [mscorlib]System.Object")
1191 ilxTypeR env ty@(AppTy f x)     = trace "ilxTypeR: should I be beta reducing types?!" (ilxComment (text "ilxTypeR: should I be beta reducing types?!") <+> ilxTypeR env (applyTy f x))
1192 ilxTypeR env (TyVarTy tv)       = ilxTyVar env tv
1193
1194 -- The following is a special rule for types constructed out of 
1195 -- higher kinds, e.g. Monad f or Functor f.  
1196 --
1197 -- The code below is not as general as it should be, but as I
1198 -- have no idea if this approach will even work, I'm going to
1199 -- just try it out on some simple cases arising from the prelude.
1200 ilxTypeR env ty@(TyConApp tc (h:t)) | isAlgTyCon tc && null (tyConTyVars tc)
1201    = ilxComment (text "what on earth? 2") <+> (ilxTypeR env (TyConApp tc t))
1202 ilxTypeR env ty@(TyConApp tc (h:t)) | isAlgTyCon tc && not (isIlxTyVar (hd (tyConTyVars tc)))
1203    = ilxTypeR env (TyConApp tc t)
1204 ilxTypeR env (TyConApp tc args) = ilxTyConApp env tc args
1205
1206   -- nb. the only legitimate place for VoidIlxRepTypes to occur in normalized IlxRepTypes 
1207   -- is on the left of an arrow
1208   --  We could probably eliminate all but a final occurrence of these.
1209 ilxTypeR env (FunTy arg res)| isVoidIlxRepType res 
1210     = pprIlxFunTy (ilxTypeL env arg) (text "void")
1211 ilxTypeR env (FunTy arg res)
1212     = pprIlxFunTy (ilxTypeL env arg) (ilxTypeR env res)
1213
1214 ilxTypeR env ty@(ForAllTy tv body_ty) | isIlxTyVar tv
1215   = parens (text "forall" <+> pprTyVarBinders env' [tv] <+> nest 2 (ilxTypeR env' body_ty))
1216     where
1217        env' = extendIlxEnvWithFormalTyVars env [tv]
1218
1219 ilxTypeR env ty@(ForAllTy tv body_ty) | otherwise
1220   = ilxComment (text "higher order type var " <+> pprId tv) <+>
1221     pprIlxFunTy (text "class [mscorlib]System.Object") (ilxTypeR env body_ty)
1222
1223 ilxTypeR env (NoteTy _ ty)       
1224    = trace "WARNING! non-representation type given to ilxTypeR: see generated ILX for context where this occurs"
1225      (vcat [text "/* WARNING! non-representation type given to ilxTypeR! */",
1226            ilxTypeR env ty ])
1227
1228 pprIlxFunTy dom ran = parens (hsep [text "func",parens dom,text "-->", ran])
1229
1230 ilxTyConApp env tc args =
1231    case lookupUFM tyPrimConTable (getUnique tc) of
1232         Just f  -> f args env
1233         Nothing -> 
1234             (if isUnboxedTupleTyCon tc then pprIlxUnBoxedTyConApp else pprIlxBoxedTyConApp)
1235               env ((nameReference env (getName tc)) <> (ppr tc)) args
1236
1237 pprIlxUnBoxedTyConApp env tcdoc args = text "value class" <+> tcdoc <> pprTypeArgs ilxTypeL env args
1238 pprIlxBoxedTyConApp env tcdoc args = text "class" <+> tcdoc <> pprTypeArgs ilxTypeR env args
1239
1240 -- Returns e.g: <Int32, Bool>
1241 pprTypeArgs f env tys = pprTypeArgs_aux f env (filter (not . isVoidIlxRepType) tys)
1242
1243 pprTypeArgs_aux f env []  = empty
1244 pprTypeArgs_aux f env tys = angleBrackets (pprSepWithCommas (f env) tys)
1245
1246
1247 pprTyVarBinders :: IlxEnv -> [TyVar] -> SDoc
1248 -- Returns e.g: <class [mscorlib]System.Object> <class [mscorlib]System.Object>
1249 -- plus a new environment with the type variables added.
1250 pprTyVarBinders env [] = empty
1251 pprTyVarBinders env tvs = angleBrackets (pprSepWithCommas (pprTyVarBinder_aux env) tvs)
1252
1253 pprTyVarBinder :: IlxEnv -> TyVar -> SDoc
1254 pprTyVarBinder env tv = 
1255     if isIlxTyVar tv then 
1256        angleBrackets (pprTyVarBinder_aux env tv)
1257     else
1258        ilxComment (text "higher order tyvar" <+> pprId tv <+> 
1259                          text ":" <+> ilxTypeR env (tyVarKind tv)) <+>
1260              ilxComment (text "omitted")
1261              -- parens (text "class [mscorlib]System.Object" <+> pprId tv)
1262
1263
1264 pprTyVarBinder_aux env tv = 
1265    ilxComment (text "tyvar" <+> pprId tv <+> text ":" <+> 
1266                         ilxTypeR env (tyVarKind tv)) <+>
1267              (text "class [mscorlib]System.Object")
1268
1269 -- Only a subset of Haskell types can be generalized using the type quantification
1270 -- of ILX
1271 isIlxForAllKind h = 
1272         ( h `eqKind` liftedTypeKind) ||
1273         ( h `eqKind` unliftedTypeKind) ||
1274         ( h `eqKind` openTypeKind)
1275
1276 isIlxTyVar v = isTyVar v && isIlxForAllKind (tyVarKind v)
1277
1278 categorizeVars fvs = (ilx_tvs, non_ilx_tvs, vs)
1279          where
1280            (tvs, vs) = partition isTyVar fvs
1281            (ilx_tvs, non_ilx_tvs) = categorizeTyVars tvs
1282
1283 categorizeTyVars tyvs = partition isIlxTyVar tyvs
1284
1285 pprValArgTys ppr_ty env tys = parens (pprSepWithCommas (ppr_ty env) tys)
1286
1287 pprId id = singleQuotes (ppr id)
1288
1289 \end{code}                      
1290
1291 %************************************************************************
1292 %*                                                                      *
1293 \subsection{IlxEnv}     
1294 %*                                                                      *
1295 %************************************************************************
1296
1297 \begin{code}
1298 type IlxTyEnv = [TyVar]
1299 emptyIlxTyEnv = []
1300
1301 -- Nb. There is currently no distinction between the kinds of type variables.
1302 -- We may need to add this to print out correct numbers, esp. for
1303 -- "forall" types
1304 extendIlxTyEnvWithFreeTyVars env tyvars = env ++ mkIlxTyEnv tyvars -- bound by .closure x<...> in a closure declared with type parameters
1305 extendIlxTyEnvWithFormalTyVars env tyvars = env ++ mkIlxTyEnv tyvars -- bound by "forall <...>" in a type
1306 extendIlxTyEnvWithTyArgs env tyvars = env ++ mkIlxTyEnv tyvars -- bound by "<...>" in a closure implementing a universal type
1307
1308 formalIlxTyEnv tyvars = mkIlxTyEnv tyvars
1309 mkIlxTyEnv tyvars = [ v | v <- tyvars, isIlxTyVar v ]
1310
1311 data HowBound = Top Module      -- Bound in a modules
1312               | Arg     -- Arguments to the enclosing closure
1313               | CloVar Int -- A free variable of the enclosing closure
1314                            -- The int is the index of the field in the 
1315                            -- environment
1316               | Local   -- Local let binding
1317
1318 -- The SDoc prints a unique name for the syntactic block we're currently processing,
1319 -- e.g. Foo_bar_baz when inside closure baz inside closure bar inside module Foo.
1320 data IlxEnv = IlxEnv (Module, IlxTyEnv, IdEnv HowBound,IdEnv (IlxEnv, StgRhs), Place,Bool)
1321 type Place = (SDoc,SDoc)
1322
1323 ilxTyVar  env tv
1324   = go 0 (ilxEnvTyEnv env)
1325   where
1326     go n []                 
1327       = pprTrace "ilxTyVar" (pprId tv <+> text "tv_env = { "
1328            <+> pprSepWithCommas
1329                  (\x -> pprId x <+> text ":" <+> ilxTypeR env (tyVarKind x)) 
1330                (ilxEnvTyEnv env) <+> text "}") 
1331         (char '!' <> pprId tv) 
1332     go n (x:xs)
1333       = {- pprTrace "go" (ppr (tyVarName tv) <+> ppr (tyVarName x)) -}
1334         (if tyVarName x== tyVarName tv then  char '!' <> int n <+> ilxComment (char '!' <> pprId tv) 
1335          else go (n+1) xs)
1336
1337 emptyIlxEnv :: Bool -> Module -> IlxEnv
1338 emptyIlxEnv trace mod = IlxEnv (mod, emptyIlxTyEnv, emptyVarEnv, emptyVarEnv, (ppr mod,empty),trace)
1339
1340 nextPlace place sdoc = place <> sdoc
1341 usePlace  place sdoc = place <> sdoc
1342
1343 ilxEnvModule (IlxEnv (m, _, _,  _, _,_)) = m
1344 ilxEnvSetPlace (IlxEnv (m, tv_env, id_env,  bind_env, (mod,exact),tr)) sdoc 
1345    = IlxEnv (m, tv_env, id_env,  bind_env, (mod, sdoc),tr)
1346 ilxEnvNextPlace (IlxEnv (m, tv_env, id_env,  bind_env, (mod,exact),tr)) sdoc 
1347    = IlxEnv (m, tv_env, id_env,  bind_env, (mod, nextPlace exact sdoc),tr)
1348 ilxEnvQualifyByModule (IlxEnv (_, _, _, _,(mod,_),_)) sdoc = usePlace mod sdoc
1349 ilxEnvQualifyByExact (IlxEnv (_, _, _, _,(mod,exact),_)) sdoc = usePlace mod sdoc <> usePlace exact sdoc
1350
1351 ilxPlaceStgBindDefault env = ilxEnvNextPlace env (text "D")
1352 ilxPlaceStgRhsClosure env bndr = ilxEnvSetPlace env (ppr bndr) -- binders are already unique
1353 ilxPlaceStgCaseScrut env = ilxEnvNextPlace env (text "S")
1354
1355 ilxPlaceAlt :: IlxEnv -> Int -> IlxEnv
1356 ilxPlaceAlt env i = ilxEnvNextPlace env (text "a" <> int i)
1357 ilxPlacePrimAltLit env i = ilxEnvNextPlace env (text "P" <> int i)
1358 ilxMapPlaceArgs start f env args = [ f (ilxEnvNextPlace env (text "A" <> int i)) a | (i,a) <- [start..] `zip` args ]
1359 ilxMapPlaceAlts f env alts = [ f (ilxPlaceAlt env i) alt | (i,alt) <- [1..] `zip` alts ]
1360
1361 extendIlxEnvWithFreeTyVars (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) tyvars 
1362   = IlxEnv (mod, extendIlxTyEnvWithFreeTyVars tv_env tyvars,id_env,  bind_env, place,tr)
1363
1364 extendIlxEnvWithFormalTyVars (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) tyvars 
1365   = IlxEnv (mod, extendIlxTyEnvWithFormalTyVars tv_env tyvars,id_env,  bind_env, place,tr)
1366
1367 extendIlxEnvWithTyArgs (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) tyvars 
1368   = IlxEnv (mod, extendIlxTyEnvWithTyArgs tv_env tyvars,id_env,  bind_env, place,tr)
1369
1370 extendIlxEnvWithArgs :: IlxEnv -> [Var] -> IlxEnv
1371 extendIlxEnvWithArgs (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) args
1372   = IlxEnv (mod, extendIlxTyEnvWithTyArgs tv_env [tv      | tv <- args, isIlxTyVar tv],
1373             extendVarEnvList id_env [(v,Arg) | v  <- args, not (isIlxTyVar v)], 
1374              bind_env, place,tr)
1375
1376 extendIlxEnvWithFreeVars (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) args
1377   = IlxEnv (mod, 
1378             extendIlxTyEnvWithFreeTyVars tv_env [tv | tv <- args, isIlxTyVar tv],
1379             extendVarEnvList id_env (clovs 0 args), 
1380             bind_env, 
1381             place,tr)
1382    where
1383      clovs _ [] = []
1384      clovs n (x:xs) = if not (isIlxTyVar x) then (x,CloVar n):clovs (n+1) xs else clovs n xs
1385
1386 extendIlxEnvWithBinds env@(IlxEnv (mod, tv_env, id_env, bind_env, place,tr)) bnds
1387   = IlxEnv (mod, tv_env, id_env, 
1388             extendVarEnvList bind_env [(v,(env,rhs)) | (v,rhs) <- bnds], 
1389             place,tr)
1390
1391 extendIlxEnvWithLocals (IlxEnv (m, tv_env, id_env, bind_env, p,tr)) locals
1392   = IlxEnv (m, tv_env, 
1393             extendVarEnvList id_env [(v,Local) | (LocalId v,_) <- locals],
1394             extendVarEnvList bind_env [(v,(env,rhs)) | (LocalId v,Just (env,rhs)) <- locals], 
1395             p,tr)
1396 extendIlxEnvWithTops env@(IlxEnv (m, tv_env, id_env, bind_env, place,tr)) mod binds
1397   = IlxEnv (m, tv_env, 
1398             extendVarEnvList id_env [(bndr,Top mod) | (bndr,rhs) <- binds], 
1399             extendVarEnvList bind_env [(bndr,(env, rhs)) | (bndr,rhs) <- binds], 
1400             place,tr)
1401
1402 formalIlxEnv (IlxEnv (m, tv_env, id_env, bind_env, place, tr)) tyvars 
1403   = IlxEnv (m, formalIlxTyEnv tyvars, id_env, bind_env, place, tr)
1404
1405 ilxEnvTyEnv :: IlxEnv -> IlxTyEnv
1406 ilxEnvTyEnv (IlxEnv (_, tv_env, _,_,_,_)) = tv_env 
1407 elemIlxTyEnv var env = elem var (ilxEnvTyEnv env )
1408 elemIlxVarEnv var (IlxEnv (_, _, id_env,_,_,_)) = elemVarEnv var id_env 
1409 lookupIlxVarEnv (IlxEnv (_, _, id_env,_,_,_)) var = lookupVarEnv id_env var
1410 lookupIlxBindEnv (IlxEnv (_, _, _, bind_env,_,_)) var = lookupVarEnv bind_env var
1411
1412 \end{code}
1413
1414
1415 \begin{code}
1416 type IlxLabel = SDoc
1417
1418 pprIlxLabel lbl = lbl
1419
1420 mkJoinLabel :: Id -> IlxLabel
1421 mkJoinLabel v = text "J_" <> ppr v
1422
1423 mkAltLabel  :: Id -> Int -> IlxLabel
1424 mkAltLabel v n = text "A" <> int n <> ppr v
1425
1426 ilxLabel :: IlxLabel -> SDoc
1427 ilxLabel lbl =  line $$ (pprIlxLabel lbl <> colon)
1428 \end{code}
1429
1430
1431 %************************************************************************
1432 %*                                                                      *
1433 \subsection{Local pretty helper functions}
1434 %*                                                                      *
1435 %************************************************************************
1436
1437 \begin{code}
1438 pprSepWithCommas :: (a -> SDoc) -> [a] -> SDoc
1439 pprSepWithCommas pp xs = sep (punctuate comma (map pp xs))
1440 ilxComment pp   = text "/*" <+> pp <+> text "*/"
1441 singleQuotes pp = char '\'' <> pp <> char '\''
1442
1443 line = text "// ----------------------------------"
1444
1445 hscOptionQual = text ".i_"
1446
1447 nameReference env n
1448   | isLocalName n = empty
1449   | ilxEnvModule env == nameModule n  = text ""
1450   | isHomeModule (nameModule n)   = moduleNameReference (moduleName (nameModule n))
1451 -- HACK: no Vanilla modules should be around, but they are!!  This
1452 -- gets things working for the scenario "standard library linked as one
1453 -- assembly with multiple modules + a one module program running on top of this"
1454 -- Same applies to all other mentions of Vailla modules in this file
1455   | isVanillaModule (nameModule n)  && not inPrelude =  preludePackageReference
1456   | isVanillaModule (nameModule n)  && inPrelude =   moduleNameReference (moduleName (nameModule n))
1457 -- end hack
1458   | otherwise = packageReference (modulePackage (nameModule n))
1459
1460 packageReference p = brackets (singleQuotes (ppr p  <> hscOptionQual))
1461 moduleNameReference m = brackets ((text ".module") <+> (singleQuotes (pprModuleName m <> hscOptionQual <> text "o")))
1462
1463 moduleReference env m
1464   | ilxEnvModule env   == m = text ""
1465   | isHomeModule m = moduleNameReference (moduleName m)
1466   -- See hack above
1467   | isVanillaModule m && not inPrelude =  preludePackageReference
1468   | isVanillaModule m && inPrelude =  moduleNameReference (moduleName m)
1469   -- end hack
1470   | otherwise  =  packageReference (modulePackage m)
1471
1472 preludePackageReference = packageReference preludePackage
1473 inPrelude = preludePackage == opt_InPackage
1474
1475 ------------------------------------------------
1476 -- This code is copied from absCSyn/CString.lhs,
1477 -- and modified to do the correct thing!  It's
1478 -- still a mess though.  Also, still have to do the
1479 -- right thing for embedded nulls.
1480
1481 pprFSInILStyle :: FAST_STRING -> SDoc
1482 pprFSInILStyle fs = doubleQuotes (text (stringToC (_UNPK_ fs)))
1483
1484 stringToC   :: String -> String
1485 -- Convert a string to the form required by C in a C literal string
1486 -- Tthe hassle is what to do w/ strings like "ESC 0"...
1487 stringToC ""  = ""
1488 stringToC [c] = charToC c
1489 stringToC (c:cs)
1490     -- if we have something "octifiable" in "c", we'd better "octify"
1491     -- the rest of the string, too.
1492   = if (c < ' ' || c > '~')
1493     then (charToC c) ++ (concat (map char_to_C cs))
1494     else (charToC c) ++ (stringToC cs)
1495   where
1496     char_to_C c | c == '\n' = "\\n"     -- use C escapes when we can
1497                 | c == '\a' = "\\a"
1498                 | c == '\b' = "\\b"     -- ToDo: chk some of these...
1499                 | c == '\r' = "\\r"
1500                 | c == '\t' = "\\t"
1501                 | c == '\f' = "\\f"
1502                 | c == '\v' = "\\v"
1503                 | otherwise = '\\' : (trigraph (ord c))
1504
1505 charToC :: Char -> String
1506 -- Convert a character to the form reqd in a C character literal
1507 charToC c = if (c >= ' ' && c <= '~')   -- non-portable...
1508             then case c of
1509                   '\'' -> "\\'"
1510                   '\\' -> "\\\\"
1511                   '"'  -> "\\\""
1512                   '\n' -> "\\n"
1513                   '\a' -> "\\a"
1514                   '\b' -> "\\b"
1515                   '\r' -> "\\r"
1516                   '\t' -> "\\t"
1517                   '\f' -> "\\f"
1518                   '\v' -> "\\v"
1519                   _    -> [c]
1520             else '\\' : (trigraph (ord c))
1521
1522 trigraph :: Int -> String
1523 trigraph n
1524   = [chr ((n `div` 100) `rem` 10 + ord '0'),
1525      chr ((n `div` 10) `rem` 10 + ord '0'),
1526      chr (n `rem` 10 + ord '0')]
1527
1528
1529 \end{code}
1530
1531 %************************************************************************
1532 %*                                                                      *
1533 \subsection{PrimOps and Constructors}
1534 %*                                                                      *
1535 %************************************************************************
1536
1537 \begin{code}
1538 ----------------------------
1539 -- Allocate a fresh constructor
1540
1541 ilxConApp env data_con args
1542   | isUnboxedTupleCon data_con
1543      = let tm_args' = filter (not. isVoidIlxRepType . stgArgType) tm_args in 
1544        case tm_args' of
1545         [h] -> 
1546           -- Collapse the construction of an unboxed tuple type where
1547           -- every element is zero-sized
1548             vcat (ilxMapPlaceArgs 0 pushArg env tm_args')
1549         _ -> 
1550           -- Minimize the construction of an unboxed tuple type, which
1551           -- may contain zero-sized elements.  Recompute all the 
1552           -- bits and pieces from the simpler case below for the new data
1553           -- type constructor....
1554            let data_con' = tupleCon Unboxed (length tm_args') in 
1555            let rep_ty_args' = filter (not . isVoidIlxRepType) rep_ty_args in 
1556
1557            let tycon' = dataConTyCon data_con' in
1558            let (formal_tyvars', formal_tau_ty') = splitForAllTys (dataConRepType data_con') in 
1559            let (formal_arg_tys', _)     = splitFunTys formal_tau_ty' in
1560            let formal_env'           = formalIlxEnv env formal_tyvars' in 
1561
1562            vcat [vcat (ilxMapPlaceArgs 0 pushArg env tm_args'),
1563                    sep [text "newobj void ",
1564                         ilxTyConApp env tycon' rep_ty_args',
1565                         text "::.ctor",
1566                         pprValArgTys ilxTypeR formal_env' (map deepIlxRepType formal_arg_tys')
1567                    ]
1568              ]
1569  | otherwise
1570     -- Now all other constructions
1571      =  --  Assume C :: forall a. a -> T a -> T a
1572         --      ldloc x         arg of type Int
1573         --      ldloc y         arg of type T Int
1574         --      newdata classunion T<Int32>, C(!0, T <!0>)
1575         --
1576         let tycon   = dataConTyCon data_con in 
1577         let (formal_tyvars, formal_tau_ty) = splitForAllTys (dataConRepType data_con) in
1578         let (formal_arg_tys, _)     = splitFunTys formal_tau_ty in 
1579
1580        vcat [vcat (ilxMapPlaceArgs 0 pushArg env tm_args),
1581           sep [ text "newdata",
1582                 nest 2 (ilxTyConApp env tycon rep_ty_args <> comma),
1583                 nest 2 (ilxConRef env data_con)
1584           ]
1585         ]
1586  where
1587    tycon   = dataConTyCon data_con 
1588    rep_ty_args = map deepIlxRepType ty_args
1589    (ty_args,tm_args) = if isAlgTyCon tycon then splitTyArgs (tyConTyVars tycon) args  else splitTyArgs1 args
1590
1591 -- Split some type arguments off, throwing away the higher kinded ones for the moment.
1592 -- Base the higher-kinded checks off a corresponding list of formals.
1593 splitTyArgs :: [Var]            -- Formals
1594             -> [StgArg]         -- Actuals
1595             -> ([Type], [StgArg])
1596 splitTyArgs (htv:ttv) (StgTypeArg h:t) 
1597    | isIlxTyVar htv = ((h:l), r) 
1598    | otherwise = trace "splitTyArgs: threw away higher kinded type arg" (l, r) 
1599    where (l,r) = splitTyArgs ttv t 
1600 splitTyArgs _ l = ([],l)
1601  
1602 -- Split some type arguments off, where none should be higher kinded
1603 splitTyArgs1 :: [StgArg] -> ([Type], [StgArg])
1604 splitTyArgs1 (StgTypeArg ty : args) = (ty:tys, args')
1605                                     where
1606                                       (tys, args') = splitTyArgs1 args
1607 splitTyArgs1 args                   = ([], args)
1608
1609 ilxConRef env data_con
1610     = pprId data_con <> pprValArgTys ilxTypeL env' (map deepIlxRepType (filter (not . isVoidIlxRepType) arg_tys))
1611   where
1612     (tyvars, tau_ty) = splitForAllTys (dataConRepType data_con)
1613     (arg_tys, _)     = splitFunTys tau_ty
1614     env'             = formalIlxEnv env tyvars
1615
1616
1617
1618
1619 \end{code}
1620
1621
1622 %************************************************************************
1623 %*                                                                      *
1624 \subsection{PrimOps and Prim Representations}                           *
1625 %************************************************************************
1626
1627 \begin{code}
1628
1629 ilxPrimApp env op              args ret_ty = ilxPrimOpTable op args env
1630
1631
1632 type IlxTyFrag = IlxEnv -> SDoc
1633 ilxType s env = text s
1634
1635 ilxLift ty env = text "thunk" <> angleBrackets (ty env)
1636
1637 ilxTypeSeq :: [IlxTyFrag] -> IlxTyFrag
1638 ilxTypeSeq ops env = hsep (map (\x -> x env) ops)
1639
1640 tyPrimConTable :: UniqFM ([Type] -> IlxTyFrag)
1641 tyPrimConTable = 
1642   listToUFM [(addrPrimTyConKey,         (\_ -> repAddr)),
1643 --           (fileStreamPrimTyConKey,   (\_ -> repFileStream)),
1644              (foreignObjPrimTyConKey,   (\_ -> repForeign)),
1645              (stablePtrPrimTyConKey,    (\[ty] -> repStablePtr {- (ilxTypeL2 ty) -})),
1646              (stableNamePrimTyConKey,   (\[ty] -> repStableName {- (ilxTypeL2 ty) -} )),
1647              (charPrimTyConKey,         (\_ -> repChar)),
1648              (wordPrimTyConKey,         (\_ -> repWord)),
1649              (byteArrayPrimTyConKey,    (\_ -> repByteArray)),
1650              (intPrimTyConKey,          (\_ -> repInt)),
1651              (int64PrimTyConKey,        (\_ -> repInt64)),
1652              (word64PrimTyConKey,       (\_ -> repWord64)),
1653              (floatPrimTyConKey,        (\_ -> repFloat)),
1654              (doublePrimTyConKey,       (\_ -> repDouble)),
1655               -- These can all also accept unlifted parameter types so we explicitly lift.
1656              (arrayPrimTyConKey,        (\[ty] -> repArray (ilxTypeL2 ty))),
1657              (mutableArrayPrimTyConKey,         (\[_, ty] -> repMutArray (ilxTypeL2 ty))),
1658              (weakPrimTyConKey,         (\[ty] -> repWeak (ilxTypeL2 ty))),
1659              (mVarPrimTyConKey,         (\[_, ty] -> repMVar (ilxTypeL2 ty))),
1660              (mutVarPrimTyConKey,       (\[ty1, ty2] -> repMutVar (ilxTypeL2 ty1) (ilxTypeL2 ty2))),
1661              (mutableByteArrayPrimTyConKey,     (\_ -> repByteArray)),
1662              (threadIdPrimTyConKey,     (\_ -> repThread)),
1663              (bcoPrimTyConKey,  (\_ -> repBCO))
1664              ]
1665
1666 ilxTypeL2 :: Type -> IlxTyFrag
1667 ilxTypeL2 ty env = ilxTypeL env ty
1668 ilxTypeR2 :: Type -> IlxTyFrag
1669 ilxTypeR2 ty env = ilxTypeR env ty
1670
1671 ilxMethTyVarA = ilxType "!!0"
1672 ilxMethTyVarB = ilxType "!!1"
1673 prelGHCReference :: IlxTyFrag
1674 prelGHCReference env =
1675    if ilxEnvModule env == mkHomeModule (mkModuleName "PrelGHC") then empty
1676    else if inPrelude then moduleNameReference (mkModuleName "PrelGHC")
1677    else preludePackageReference
1678
1679 prelBaseReference :: IlxTyFrag
1680 prelBaseReference env =
1681    if ilxEnvModule env == mkHomeModule (mkModuleName "PrelBase") then empty
1682    else if inPrelude then moduleNameReference (mkModuleName "PrelBase")
1683    else preludePackageReference
1684
1685 repThread = ilxType "class [mscorlib]System.Threading.Thread /* ThreadId# */ "
1686 repByteArray = ilxType "unsigned int8[] /* ByteArr# */ "
1687 --repFileStream = text "void * /* FileStream# */ "  -- text "class [mscorlib]System.IO.FileStream"
1688 repInt = ilxType "int32"
1689 repWord = ilxType "unsigned int32"
1690 repAddr =ilxType "/* Addr */ void *"
1691 repInt64 = ilxType "int64"
1692 repWord64 = ilxType "unsigned int64"
1693 repFloat = ilxType "float32"
1694 repDouble = ilxType "float64"
1695 repChar = ilxType "/* Char */ unsigned int8"
1696 repForeign = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_Foreignzh"]
1697 repInteger = ilxUnboxedPairRep repInt repByteArray
1698 repIntegerPair = ilxUnboxedQuadRep repInt repByteArray repInt repByteArray
1699 repArray ty = ilxTypeSeq [ty,ilxType "[]"]
1700 repMutArray ty = ilxTypeSeq [ty,ilxType "[]"]
1701 repMVar ty = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_MVarzh",ilxTyParams [ty]]
1702 repMutVar _ ty2 = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_MutVarzh",ilxTyParams [ty2]]
1703 repWeak ty1 = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_Weakzh",ilxTyParams [ty1]]
1704 repStablePtr {- ty1 -} = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_StablePtrzh" {- ,ilxTyParams [ty1] -} ]
1705 repStableName {- ty1 -}  = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_StableNamezh" {- ,ilxTyParams [ty1] -} ]
1706 classWeak = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_Weakzh"]
1707 repBCO = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_BCOzh"]
1708
1709 ilxTyPair l r = ilxTyParams [l,r]
1710 ilxTyTriple l m r = ilxTyParams [l,m,r]
1711 ilxTyQuad l m1 m2 r = ilxTyParams [l,m1,m2,r]
1712 ilxUnboxedEmptyRep = ilxTypeSeq [ilxType "value class",prelGHCReference,ilxType "PrelGHC_Z0H"]
1713 ilxUnboxedPairRep l r = ilxTypeSeq [ilxType "value class",prelGHCReference,ilxType "PrelGHC_Z1H",ilxTyPair l r]
1714 ilxUnboxedTripleRep l m r = ilxTypeSeq [ilxType "value class",prelGHCReference,ilxType "PrelGHC_Z2H",ilxTyTriple l m r]
1715 ilxUnboxedQuadRep l m1 m2 r = ilxTypeSeq [ilxType "value class",prelGHCReference,ilxType "PrelGHC_Z3H",ilxTyQuad l m1 m2 r]
1716
1717 ilxTyIO b = ilxTypeSeq [ilxType "(func ( /* unit skipped */ ) --> ", b, ilxType ")"]
1718
1719 ilxTyParams :: [IlxTyFrag] -> IlxTyFrag
1720 ilxTyParams [] env = empty
1721 ilxTyParams l env = angleBrackets (ilxTyParamsAux l env)
1722   where
1723    ilxTyParamsAux [] env = empty
1724    ilxTyParamsAux [h] env = h env
1725    ilxTyParamsAux (h:t) env = h env <> text "," <+> ilxTyParamsAux t env
1726    ilxTyParams [] env = empty
1727
1728
1729 type IlxOpFrag = IlxEnv -> SDoc
1730 ilxOp :: String -> IlxOpFrag
1731 ilxOp s env = text s
1732 ilxOpSeq :: [IlxOpFrag] -> IlxOpFrag
1733 ilxOpSeq ops env = hsep (map (\x -> x env) ops)
1734
1735 ilxParams :: [IlxOpFrag] -> IlxOpFrag
1736 ilxParams l env = parens (ilxParamsAux l env)
1737   where
1738    ilxParamsAux [] env = empty
1739    ilxParamsAux [h] env = h env
1740    ilxParamsAux (h:t) env = h env <> text "," <+> ilxParamsAux t env
1741
1742
1743 ilxMethodRef rty cls nm tyargs args = 
1744     ilxOpSeq [rty,cls,ilxOp "::",ilxOp nm,
1745               ilxTyParams tyargs,ilxParams args]
1746
1747 ilxCall m = ilxOpSeq [ilxOp "call", m]
1748
1749 ilxSupportClass = ilxOpSeq [prelGHCReference, ilxOp "'GHC.support'"]
1750 ilxSuppMeth rty nm tyargs args = ilxMethodRef rty ilxSupportClass nm tyargs args
1751
1752 ilxCallSuppMeth rty nm tyargs args  = ilxCall (ilxSuppMeth rty nm tyargs args)
1753
1754 ilxMkBool :: IlxOpFrag
1755 ilxMkBool =  ilxOpSeq [ilxOp "call class",prelBaseReference,
1756                        ilxOp "PrelBase_Bool",
1757                        prelGHCReference,ilxOp "GHC.support::mkBool(bool)"]
1758 ilxCgt = ilxOpSeq [ilxOp "cgt",ilxMkBool]
1759 ilxCge = ilxOpSeq [ilxOp "clt ldc.i4 0 ceq ",ilxMkBool]
1760 ilxClt = ilxOpSeq [ilxOp "clt ",ilxMkBool]
1761 ilxCle = ilxOpSeq [ilxOp "cgt ldc.i4 0 ceq ",ilxMkBool]
1762 ilxCeq = ilxOpSeq [ilxOp "ceq ",ilxMkBool]
1763 ilxCne = ilxOpSeq [ilxOp "ceq ldc.i4 0 ceq " ,ilxMkBool]
1764 ilxCgtUn = ilxOpSeq [ilxOp "cgt.un ",ilxMkBool]
1765 ilxCgeUn  = ilxOpSeq [ilxOp "clt.un ldc.i4 0 ceq ",ilxMkBool]
1766 ilxCltUn = ilxOpSeq [ilxOp "clt.un ",ilxMkBool]
1767 ilxCleUn = ilxOpSeq [ilxOp "cgt.un ldc.i4 0 ceq ",ilxMkBool]
1768
1769 ilxAddrOfForeignOp = ilxOpSeq [ilxOp "ldfld void *" , repForeign, ilxOp "::contents"]
1770 ilxAddrOfByteArrOp = ilxOp "ldc.i4 0 ldelema unsigned int8"
1771
1772 ilxPrimOpTable :: PrimOp -> [StgArg] -> IlxOpFrag
1773 ilxPrimOpTable op
1774   = case op of
1775         CharGtOp    -> simp_op ilxCgt
1776         CharGeOp    -> simp_op ilxCge
1777         CharEqOp    -> simp_op ilxCeq
1778         CharNeOp    -> simp_op ilxCne
1779         CharLtOp    -> simp_op ilxClt
1780         CharLeOp    -> simp_op ilxCle
1781
1782         OrdOp       -> simp_op (ilxOp "conv.i4") -- chars represented by UInt32 (u4)
1783         ChrOp       -> simp_op (ilxOp "conv.u4")
1784
1785         IntGtOp     -> simp_op ilxCgt
1786         IntGeOp     -> simp_op ilxCge
1787         IntEqOp     -> simp_op ilxCeq
1788         IntNeOp     -> simp_op ilxCne
1789         IntLtOp     -> simp_op ilxClt
1790         IntLeOp     -> simp_op ilxCle
1791
1792         Narrow8IntOp   -> simp_op  (ilxOp"conv.i1")
1793         Narrow16IntOp  -> simp_op (ilxOp "conv.i2")
1794         Narrow32IntOp  -> simp_op (ilxOp "conv.i4")
1795         Narrow8WordOp  -> simp_op (ilxOp "conv.u1")
1796         Narrow16WordOp -> simp_op (ilxOp "conv.u2")
1797         Narrow32WordOp -> simp_op (ilxOp "conv.u4")
1798
1799         WordGtOp     -> simp_op ilxCgtUn
1800         WordGeOp     -> simp_op ilxCgeUn
1801         WordEqOp     -> simp_op ilxCeq
1802         WordNeOp     -> simp_op ilxCne
1803         WordLtOp     -> simp_op ilxCltUn
1804         WordLeOp     -> simp_op ilxCleUn
1805
1806         AddrGtOp     -> simp_op ilxCgt
1807         AddrGeOp     -> simp_op ilxCge
1808         AddrEqOp     -> simp_op ilxCeq
1809         AddrNeOp     -> simp_op ilxCne
1810         AddrLtOp     -> simp_op ilxClt
1811         AddrLeOp     -> simp_op ilxCle
1812
1813         FloatGtOp     -> simp_op ilxCgt
1814         FloatGeOp     -> simp_op ilxCge
1815         FloatEqOp     -> simp_op ilxCeq
1816         FloatNeOp     -> simp_op ilxCne
1817         FloatLtOp     -> simp_op ilxClt
1818         FloatLeOp     -> simp_op ilxCle
1819
1820         DoubleGtOp     -> simp_op ilxCgt
1821         DoubleGeOp     -> simp_op ilxCge
1822         DoubleEqOp     -> simp_op ilxCeq
1823         DoubleNeOp     -> simp_op ilxCne
1824         DoubleLtOp     -> simp_op ilxClt
1825         DoubleLeOp     -> simp_op ilxCle
1826
1827     -- Int#-related ops:
1828         IntAddOp    -> simp_op (ilxOp "add")
1829         IntSubOp    -> simp_op (ilxOp "sub")
1830         IntMulOp    -> simp_op (ilxOp "mul")
1831         IntQuotOp   -> simp_op (ilxOp "div")
1832         IntNegOp    -> simp_op (ilxOp "neg")
1833         IntRemOp    -> simp_op (ilxOp "rem")
1834
1835     -- Addr# ops:
1836         AddrAddOp  -> simp_op (ilxOp "add")
1837         AddrSubOp  -> simp_op (ilxOp "sub")
1838         AddrRemOp  -> simp_op (ilxOp "rem")
1839         Int2AddrOp -> warn_op "int2Addr" (simp_op (ilxOp "/* PrimOp int2Addr */ "))
1840         Addr2IntOp -> warn_op "addr2Int" (simp_op (ilxOp "/* PrimOp addr2Int */ "))
1841
1842     -- Word#-related ops:
1843         WordAddOp    -> simp_op (ilxOp "add")
1844         WordSubOp    -> simp_op (ilxOp "sub")
1845         WordMulOp    -> simp_op (ilxOp "mul")
1846         WordQuotOp   -> simp_op (ilxOp "div")
1847         WordRemOp    -> simp_op (ilxOp "rem")
1848
1849         ISllOp      -> simp_op (ilxOp "shl")
1850         ISraOp      -> simp_op (ilxOp "shr")
1851         ISrlOp      -> simp_op (ilxOp "shr.un")
1852         IntAddCOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedPairRep repInt repInt) "IntAddCOp" [] [repInt, repInt])
1853         IntSubCOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedPairRep repInt repInt) "IntSubCOp" [] [repInt, repInt])
1854         IntMulCOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedPairRep repInt repInt) "IntMulCOp" [] [repInt, repInt])
1855         IntGcdOp    -> simp_op (ilxCallSuppMeth repInt "IntGcdOp" [] [repInt, repInt])
1856
1857
1858     -- Word#-related ops:
1859         AndOp       -> simp_op (ilxOp "and") 
1860         OrOp        -> simp_op (ilxOp "or") 
1861         NotOp       -> simp_op (ilxOp "not") 
1862         XorOp       -> simp_op (ilxOp "xor") 
1863         SllOp       -> simp_op (ilxOp "shl") 
1864         SrlOp       -> simp_op (ilxOp "shr") 
1865         Word2IntOp  -> simp_op (ilxOp "conv.i4")
1866         Int2WordOp  -> simp_op (ilxOp "conv.u4")
1867
1868     -- Float#-related ops:
1869         FloatAddOp   -> simp_op (ilxOp "add")
1870         FloatSubOp   -> simp_op (ilxOp "sub")
1871         FloatMulOp   -> simp_op (ilxOp "mul")
1872         FloatDivOp   -> simp_op (ilxOp "div")
1873         FloatNegOp   -> simp_op (ilxOp "neg")
1874         Float2IntOp  -> simp_op (ilxOp "conv.i4")
1875         Int2FloatOp  -> simp_op (ilxOp "conv.r4")
1876
1877         DoubleAddOp     -> simp_op (ilxOp "add")
1878         DoubleSubOp     -> simp_op (ilxOp "sub")
1879         DoubleMulOp     -> simp_op (ilxOp "mul")
1880         DoubleDivOp     -> simp_op (ilxOp "div")
1881         DoubleNegOp     -> simp_op (ilxOp "neg")
1882         Double2IntOp    -> simp_op (ilxOp "conv.i4")
1883         Int2DoubleOp    -> simp_op (ilxOp "conv.r4")
1884         Double2FloatOp  -> simp_op (ilxOp "conv.r4")
1885         Float2DoubleOp  -> simp_op (ilxOp "conv.r8")
1886         DoubleDecodeOp  -> simp_op (ilxCallSuppMeth (ilxUnboxedTripleRep repInt repInt repByteArray) "decodeDouble" [] [ilxType "float64"])
1887         FloatDecodeOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedTripleRep repInt repInt repByteArray) "decodeFloat" [] [ilxType "float32"])
1888
1889         FloatExpOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Exp(float64) conv.r4")
1890         FloatLogOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Log(float64) conv.r4")
1891         FloatSqrtOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Sqrt(float64) conv.r4")
1892         FloatSinOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Sin(float64) conv.r4")
1893         FloatCosOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Cos(float64) conv.r4")
1894         FloatTanOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Tan(float64) conv.r4")
1895         FloatAsinOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Asin(float64) conv.r4")
1896         FloatAcosOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Acos(float64) conv.r4")
1897         FloatAtanOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Atan(float64) conv.r4")
1898         FloatSinhOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Sinh(float64) conv.r4")
1899         FloatCoshOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Cosh(float64) conv.r4")
1900         FloatTanhOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Tanh(float64) conv.r4")
1901         FloatPowerOp -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Pow(float64, float64) conv.r4") -- ** op, make use of implicit cast to r8...
1902
1903         DoubleExpOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Exp(float64)")
1904         DoubleLogOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Log(float64)")
1905         DoubleSqrtOp  -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Sqrt(float64)")
1906           
1907         DoubleSinOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Sin(float64)")
1908         DoubleCosOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Cos(float64)")
1909         DoubleTanOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Tan(float64)")
1910           
1911         DoubleAsinOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Asin(float64)")
1912         DoubleAcosOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Acos(float64)")
1913         DoubleAtanOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Atan(float64)")
1914           
1915         DoubleSinhOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Sinh(float64)")
1916         DoubleCoshOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Cosh(float64)")
1917         DoubleTanhOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Tanh(float64)")
1918           
1919         DoublePowerOp  -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Pow(float64, float64)")
1920
1921     -- Integer (and related...) ops: bail out to support routines
1922         IntegerAndOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerAndOp" [] [repInt, repByteArray, repInt, repByteArray])
1923         IntegerOrOp        -> simp_op (ilxCallSuppMeth repInteger "IntegerOrOp" [] [repInt, repByteArray, repInt, repByteArray])
1924         IntegerXorOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerXorOp" [] [repInt, repByteArray, repInt, repByteArray])
1925         IntegerComplementOp -> simp_op (ilxCallSuppMeth repInteger "IntegerComplementOp" [] [repInt, repByteArray])
1926         IntegerAddOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerAddOp" [] [repInt, repByteArray, repInt, repByteArray])
1927         IntegerSubOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerSubOp" [] [repInt, repByteArray, repInt, repByteArray])
1928         IntegerMulOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerMulOp" [] [repInt, repByteArray, repInt, repByteArray])
1929         IntegerGcdOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerGcdOp" [] [repInt, repByteArray, repInt, repByteArray])
1930         IntegerQuotRemOp   -> simp_op (ilxCallSuppMeth repIntegerPair "IntegerQuotRemOp" [] [repInt, repByteArray, repInt, repByteArray])
1931         IntegerDivModOp    -> simp_op (ilxCallSuppMeth repIntegerPair "IntegerDivModOp" [] [repInt, repByteArray, repInt, repByteArray])
1932         IntegerIntGcdOp    -> simp_op (ilxCallSuppMeth repInt "IntegerIntGcdOp" [] [repInt, repByteArray, repInt])
1933         IntegerDivExactOp  -> simp_op (ilxCallSuppMeth repInteger "IntegerDivExactOp" [] [repInt, repByteArray, repInt, repByteArray])
1934         IntegerQuotOp      -> simp_op (ilxCallSuppMeth repInteger "IntegerQuotOp" [] [repInt, repByteArray, repInt, repByteArray])
1935         IntegerRemOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerRemOp" [] [repInt, repByteArray, repInt, repByteArray])
1936         IntegerCmpOp       -> simp_op (ilxCallSuppMeth repInt "IntegerCmpOp" [] [repInt, repByteArray, repInt, repByteArray])
1937         IntegerCmpIntOp    -> simp_op (ilxCallSuppMeth repInt "IntegerCmpIntOp" [] [repInt, repByteArray, repInt])
1938         Integer2IntOp      -> simp_op (ilxCallSuppMeth repInt "Integer2IntOp" [] [repInt, repByteArray])
1939         Integer2WordOp     -> simp_op (ilxCallSuppMeth repWord "Integer2WordOp" [] [repInt, repByteArray])
1940         Int2IntegerOp      -> simp_op (ilxCallSuppMeth repInteger "Int2IntegerOp" [] [repInt])
1941         Word2IntegerOp     -> simp_op (ilxCallSuppMeth repInteger "Word2IntegerOp" [] [repWord])
1942         IntegerToInt64Op   -> simp_op (ilxCallSuppMeth repInt64 "IntegerToInt64Op" [] [repInt,repByteArray])
1943         Int64ToIntegerOp   -> simp_op (ilxCallSuppMeth repInteger "Int64ToIntegerOp" [] [repInt64])
1944         IntegerToWord64Op  -> simp_op (ilxCallSuppMeth repWord64 "IntegerToWord64Op" [] [repInt,repByteArray])
1945         Word64ToIntegerOp  -> simp_op (ilxCallSuppMeth repInteger "Word64ToIntegerOp" [] [repWord64])
1946
1947
1948
1949         IndexByteArrayOp_Char      -> simp_op (ilxOp "ldelem.u1")
1950         IndexByteArrayOp_WideChar  -> simp_op (ilxOp "ldelem.u4")
1951         IndexByteArrayOp_Int       -> simp_op (ilxOp "ldelem.i4")
1952         IndexByteArrayOp_Word      -> simp_op (ilxOp "ldelem.u4")
1953         IndexByteArrayOp_Addr      -> simp_op (ilxOp "ldelem.u")
1954         IndexByteArrayOp_Float     -> simp_op (ilxOp "ldelem.r4")
1955         IndexByteArrayOp_Double    -> simp_op (ilxOp "ldelem.r8")
1956         IndexByteArrayOp_StablePtr -> simp_op (ilxOp "ldelem.ref")
1957         IndexByteArrayOp_Int8     -> simp_op (ilxOp "ldelem.i1")
1958         IndexByteArrayOp_Int16     -> simp_op (ilxOp "ldelem.i2")
1959         IndexByteArrayOp_Int32     -> simp_op (ilxOp "ldelem.i4")
1960         IndexByteArrayOp_Int64     -> simp_op (ilxOp "ldelem.i8")
1961         IndexByteArrayOp_Word8    -> simp_op (ilxOp "ldelem.u1")
1962         IndexByteArrayOp_Word16    -> simp_op (ilxOp "ldelem.u2")
1963         IndexByteArrayOp_Word32    -> simp_op (ilxOp "ldelem.u4")
1964         IndexByteArrayOp_Word64    -> simp_op (ilxOp "ldelem.u8")
1965
1966             {- should be monadic??? -}
1967         ReadByteArrayOp_Char      -> simp_op (ilxOp "ldelem.u1")
1968         ReadByteArrayOp_WideChar  -> simp_op (ilxOp "ldelem.u4")
1969         ReadByteArrayOp_Int       -> simp_op (ilxOp "ldelem.i4")
1970         ReadByteArrayOp_Word      -> simp_op (ilxOp "ldelem.u4")
1971         ReadByteArrayOp_Addr      -> simp_op (ilxOp "ldelem.u")
1972         ReadByteArrayOp_Float     -> simp_op (ilxOp "ldelem.r4")
1973         ReadByteArrayOp_Double    -> simp_op (ilxOp "ldelem.r8")
1974         ReadByteArrayOp_StablePtr -> simp_op (ilxOp "ldelem.ref")
1975         ReadByteArrayOp_Int8     -> simp_op (ilxOp "ldelem.i1")
1976         ReadByteArrayOp_Int16     -> simp_op (ilxOp "ldelem.i2")
1977         ReadByteArrayOp_Int32     -> simp_op (ilxOp "ldelem.i4")
1978         ReadByteArrayOp_Int64     -> simp_op (ilxOp "ldelem.i8")
1979         ReadByteArrayOp_Word8    -> simp_op (ilxOp "ldelem.u1")
1980         ReadByteArrayOp_Word16    -> simp_op (ilxOp "ldelem.u2")
1981         ReadByteArrayOp_Word32    -> simp_op (ilxOp "ldelem.u4")
1982         ReadByteArrayOp_Word64    -> simp_op (ilxOp "ldelem.u8")
1983                  {-   MutByteArr# s -> Int# -> State# s -> (# State# s, Char# #) -}
1984                  {- ByteArr# -> Int# -> Char# -}
1985
1986
1987         WriteByteArrayOp_Char      -> simp_op (ilxOp "stelem.u1")
1988         WriteByteArrayOp_WideChar   -> simp_op (ilxOp "stelem.u4")
1989         WriteByteArrayOp_Int       -> simp_op (ilxOp "stelem.i4")
1990         WriteByteArrayOp_Word      -> simp_op (ilxOp "stelem.u4")
1991         WriteByteArrayOp_Addr      -> simp_op (ilxOp "stelem.u")
1992         WriteByteArrayOp_Float     -> simp_op (ilxOp "stelem.r4")
1993         WriteByteArrayOp_Double    -> simp_op (ilxOp "stelem.r8")
1994         WriteByteArrayOp_StablePtr -> simp_op (ilxOp "stelem.ref")
1995         WriteByteArrayOp_Int8     -> simp_op (ilxOp "stelem.i1")
1996         WriteByteArrayOp_Int16     -> simp_op (ilxOp "stelem.i2")
1997         WriteByteArrayOp_Int32     -> simp_op (ilxOp "stelem.i4")
1998         WriteByteArrayOp_Int64     -> simp_op (ilxOp "stelem.i8")
1999         WriteByteArrayOp_Word8    -> simp_op (ilxOp "stelem.u1")
2000         WriteByteArrayOp_Word16    -> simp_op (ilxOp "stelem.u2")
2001         WriteByteArrayOp_Word32    -> simp_op (ilxOp "stelem.u4")
2002         WriteByteArrayOp_Word64    -> simp_op (ilxOp "stelem.i8 /* nb. no stelem.u8 */")
2003                  {- MutByteArr# s -> Int# -> Char# -> State# s -> State# s -}
2004
2005         IndexOffAddrOp_Char    -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
2006         IndexOffAddrOp_WideChar    -> simp_op (ilxOp "sizeof int32 mul add ldind.u4")
2007         IndexOffAddrOp_Int     -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
2008         IndexOffAddrOp_Word    -> simp_op (ilxOp "sizeof int32 mul add ldind.u4")
2009         IndexOffAddrOp_Addr    -> simp_op (ilxOp "sizeof native unsigned int mul add ldind.i")
2010         IndexOffAddrOp_StablePtr   -> simp_op (ilxOp "sizeof native unsigned int mul add ldind.ref")
2011         IndexOffAddrOp_Float   -> simp_op (ilxOp "sizeof float32 mul add ldind.r4")
2012         IndexOffAddrOp_Double  -> simp_op (ilxOp "sizeof float64 mul add ldind.r8")
2013         IndexOffAddrOp_Int8   -> simp_op (ilxOp "sizeof int8 mul add ldind.i1")
2014         IndexOffAddrOp_Int16   -> simp_op (ilxOp "sizeof int16 mul add ldind.i2")
2015         IndexOffAddrOp_Int32   -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
2016         IndexOffAddrOp_Int64   -> simp_op (ilxOp "sizeof int64 mul add ldind.i8")
2017         IndexOffAddrOp_Word8  -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
2018         IndexOffAddrOp_Word16 -> simp_op (ilxOp "sizeof unsigned int16 mul add ldind.u2")
2019         IndexOffAddrOp_Word32  -> simp_op (ilxOp "sizeof unsigned int32 mul add ldind.u4")
2020         IndexOffAddrOp_Word64  -> simp_op (ilxOp "sizeof int64 mul add ldind.u8")
2021
2022         -- ForeignObj: load the address inside the object first
2023         -- TODO: is this remotely right?
2024         EqForeignObj                 -> warn_op "eqForeignObj" (simp_op (ilxOp "pop /* PrimOp eqForeignObj */ "))
2025         IndexOffForeignObjOp_Char    -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int8 mul add ldind.u1"])
2026         IndexOffForeignObjOp_WideChar    -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int32 mul add ldind.u4"])
2027         IndexOffForeignObjOp_Int     -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int32 mul add ldind.i4"])
2028         IndexOffForeignObjOp_Word    -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int32 mul add ldind.u4"])
2029         IndexOffForeignObjOp_Addr    ->  arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof native unsigned int mul add ldind.i  "])
2030         IndexOffForeignObjOp_StablePtr    ->  ty1_arg2_op (\ty fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof native unsigned int mul add ldind.ref  "])
2031         IndexOffForeignObjOp_Float   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof float32 mul add ldind.r4"])
2032         IndexOffForeignObjOp_Double  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof float64 mul add ldind.r8"])
2033         IndexOffForeignObjOp_Int8   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int8 mul add ldind.i1"])
2034         IndexOffForeignObjOp_Int16   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int16 mul add ldind.i2"])
2035         IndexOffForeignObjOp_Int32   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int32 mul add ldind.i4"])
2036         IndexOffForeignObjOp_Int64   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int64 mul add ldind.i8"])
2037         IndexOffForeignObjOp_Word8  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int8 mul add ldind.u1"])
2038         IndexOffForeignObjOp_Word16  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int16 mul add ldind.u2"])
2039         IndexOffForeignObjOp_Word32  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int32 mul add ldind.u4"])
2040         IndexOffForeignObjOp_Word64  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int64 mul add ldind.u8"])
2041
2042         ReadOffAddrOp_Char   -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
2043         ReadOffAddrOp_WideChar -> simp_op (ilxOp "sizeof int32 mul add ldind.u4")
2044         ReadOffAddrOp_Int    -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
2045         ReadOffAddrOp_Word   -> simp_op (ilxOp "sizeof unsigned int32 mul add ldind.u4")
2046         ReadOffAddrOp_Addr   -> simp_op (ilxOp "sizeof native unsigned int mul add ldind.i")
2047         ReadOffAddrOp_Float  -> simp_op (ilxOp "sizeof float32 mul add ldind.r4")
2048         ReadOffAddrOp_Double -> simp_op (ilxOp "sizeof float64 mul add ldind.r8")
2049         ReadOffAddrOp_StablePtr  -> simp_op (ilxOp "sizeof native unsigned int mul add ldind.ref")
2050         ReadOffAddrOp_Int8  -> simp_op (ilxOp "sizeof int8 mul add ldind.i1")
2051         ReadOffAddrOp_Int16  -> simp_op (ilxOp "sizeof int16 mul add ldind.i2")
2052         ReadOffAddrOp_Int32  -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
2053         ReadOffAddrOp_Int64  -> simp_op (ilxOp "sizeof int64 mul add ldind.i8")
2054         ReadOffAddrOp_Word8 -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
2055         ReadOffAddrOp_Word16 -> simp_op (ilxOp "sizeof unsigned int16 mul add ldind.u2")
2056         ReadOffAddrOp_Word32 -> simp_op (ilxOp "sizeof unsigned int32 mul add ldind.u4")
2057         ReadOffAddrOp_Word64 -> simp_op (ilxOp "sizeof unsigned int64 mul add ldind.u8")
2058                   {-    Addr# -> Int# -> Char# -> State# s -> State# s -} 
2059
2060         WriteOffAddrOp_Char   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "add", v, ilxOp "stind.u1"])
2061         WriteOffAddrOp_WideChar   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof int32 mul add", v, ilxOp "stind.u4"])
2062         WriteOffAddrOp_Int    -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof int32 mul add", v, ilxOp "stind.i4"])
2063         WriteOffAddrOp_Word   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof int32 mul add", v, ilxOp "stind.u4"])
2064         WriteOffAddrOp_Addr   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof native unsigned int mul add", v, ilxOp "stind.i"])
2065         WriteOffAddrOp_ForeignObj   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof native unsigned int mul add", v, ilxOp "stind.ref"])
2066         WriteOffAddrOp_Float  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof float32 mul add", v,ilxOp "stind.r4"])
2067         WriteOffAddrOp_StablePtr   -> ty2_arg4_op (\ty1 sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof native unsigned int mul add", v, ilxOp "stind.ref"])
2068         WriteOffAddrOp_Double -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof float64 mul add",v,ilxOp "stind.r8"])
2069         WriteOffAddrOp_Int8  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int8 mul add",v,ilxOp "stind.i1"])
2070         WriteOffAddrOp_Int16  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int16 mul add",v,ilxOp "stind.i2"])
2071         WriteOffAddrOp_Int32  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int32 mul add",v,ilxOp "stind.i4"])
2072         WriteOffAddrOp_Int64  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int64 mul add",v,ilxOp "stind.i8"])
2073         WriteOffAddrOp_Word8 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int8 mul add",v,ilxOp "stind.u1"])
2074         WriteOffAddrOp_Word16 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int16 mul add",v,ilxOp "stind.u2"])
2075         WriteOffAddrOp_Word32 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int32 mul add",v,ilxOp "stind.u4"])
2076         WriteOffAddrOp_Word64 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int64 mul add",v,ilxOp "stind.u8"])
2077                   {-    Addr# -> Int# -> Char# -> State# s -> State# s -} 
2078
2079             {- should be monadic??? -}
2080         NewPinnedByteArrayOp_Char -> warn_op "newPinnedByteArray" (simp_op (ilxOp "newarr [mscorlib]System.Byte "))
2081         NewByteArrayOp_Char      -> simp_op (ilxOp "newarr [mscorlib]System.Byte")
2082 --      NewByteArrayOp_Int       -> simp_op (ilxOp "newarr [mscorlib]System.Int32")
2083 --      NewByteArrayOp_Word      -> simp_op (ilxOp "newarr [mscorlib]System.UInt32")
2084 --      NewByteArrayOp_Addr      -> simp_op (ilxOp "newarr [mscorlib]System.UInt64")
2085 --      NewByteArrayOp_Float     -> simp_op (ilxOp "newarr [mscorlib]System.Single")
2086 --      NewByteArrayOp_Double    -> simp_op (ilxOp "newarr [mscorlib]System.Double")
2087 --      NewByteArrayOp_StablePtr -> simp_op (ilxOp "newarr [mscorlib]System.UInt32")
2088 --      NewByteArrayOp_Int64     -> simp_op (ilxOp "newarr [mscorlib]System.Int64")  TODO: there is no unique for this one -}
2089 --      NewByteArrayOp_Word64    -> simp_op (ilxOp "newarr  [mscorlib]System.UInt64") -}
2090                   {- Int# -> State# s -> (# State# s, MutByteArr# s #) -}
2091         ByteArrayContents_Char   -> warn_op "byteArrayContents" (simp_op ilxAddrOfByteArrOp)
2092
2093         UnsafeFreezeByteArrayOp ->   ty1_op (\ty1  -> ilxOp "nop ")
2094                   {- MutByteArr# s -> State# s -> (# State# s, ByteArr# #) -}
2095         SizeofByteArrayOp  -> simp_op (ilxOp "ldlen")
2096                   {- ByteArr# -> Int# -}
2097
2098         SameMutableByteArrayOp -> ty1_op (\ty1  -> ilxCeq)
2099                  {- MutByteArr# s -> MutByteArr# s -> Bool -}
2100         SizeofMutableByteArrayOp -> ty1_op (\ty1  -> ilxOp "ldlen")
2101                  {- MutByteArr# s -> Int# -}
2102
2103         SameMutVarOp -> ty2_op (\ty1 ty2 -> ilxCeq)
2104                  {- MutVar# s a -> MutVar# s a -> Bool -}
2105         NewMutVarOp -> ty2_op (\ty1 ty2 -> ilxOpSeq [ilxOp "newobj void" , repMutVar ty1 ty2 , ilxOp "::.ctor(!0)"])
2106                  {- a -> State# s -> (# State# s, MutVar# s a #) -}
2107         ReadMutVarOp -> ty2_op (\ty1 ty2 ->  ilxOpSeq [ilxOp "ldfld !0" , repMutVar ty1 ty2 , ilxOp "::contents"])
2108                  {-  MutVar# s a -> State# s -> (# State# s, a #) -}
2109         WriteMutVarOp -> ty2_op (\ty1 ty2 -> ilxOpSeq [ilxOp "stfld !0" , repMutVar ty1 ty2 , ilxOp "::contents"])
2110                  {- MutVar# s a -> a -> State# s -> State# s -}
2111
2112         NewArrayOp -> ty2_op (\ty1 ty2 -> ilxCallSuppMeth (ilxType "!!0[]") "newArray" [ty1] [repInt,ilxMethTyVarA])
2113                  {- Int# -> a -> State# s -> (# State# s, MutArr# s a #) -}
2114         IndexArrayOp -> ty1_op (\ty1 -> ilxOp "ldelem.ref")
2115                  {- Array# a -> Int# -> (# a #) -}
2116         WriteArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "stelem.ref")
2117                  {- MutArr# s a -> Int# -> a -> State# s -> State# s -}
2118         ReadArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "ldelem.ref")
2119                  {- MutArr# s a -> Int# -> State# s -> (# State# s, a #) -}
2120         UnsafeFreezeArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "nop")
2121                  {-   MutArr# s a -> State# s -> (# State# s, Array# a #) -}
2122         UnsafeThawArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "nop")
2123                  {-  Array# a -> State# s -> (# State# s, MutArr# s a #) -}
2124
2125         SameMutableArrayOp -> ty2_op (\ty1 ty2 -> ilxCeq)
2126                  {- MutArr# s a -> MutArr# s a -> Bool -}
2127
2128
2129         RaiseOp -> ty2_op (\ty1 ty2 -> ilxOp "throw")
2130         CatchOp -> ty2_op (\ty1 ty2 -> 
2131                 ilxCallSuppMeth ilxMethTyVarA "'catch'" [ty1,ty2] [ilxLift (ilxTyIO (ilxType "!!0")), 
2132                                                               ilxOp "thunk<(func (!!1) --> (func ( /* unit skipped */ ) --> !!0))>"])
2133                             {-        (State# RealWorld -> (# State# RealWorld, a #) )
2134                                    -> (b -> State# RealWorld -> (# State# RealWorld, a #) ) 
2135                                    -> State# RealWorld
2136                                    -> (# State# RealWorld, a #) 
2137                              -} 
2138
2139         BlockAsyncExceptionsOp -> ty1_op (\ty1 -> 
2140                 ilxCallSuppMeth ilxMethTyVarA "blockAsyncExceptions" [ty1] [ilxLift (ilxTyIO (ilxType "!!0"))])
2141
2142                 {-     (State# RealWorld -> (# State# RealWorld, a #))
2143                     -> (State# RealWorld -> (# State# RealWorld, a #))
2144                 -}
2145
2146         UnblockAsyncExceptionsOp -> ty1_op (\ty1 -> 
2147                 ilxCallSuppMeth ilxMethTyVarA "unblockAsyncExceptions" [ty1] [ilxLift (ilxTyIO (ilxType "!!0"))])
2148
2149                 {-
2150                     State# RealWorld -> (# State# RealWorld, a #))
2151                     -> (State# RealWorld -> (# State# RealWorld, a #))
2152                 -}
2153  
2154         NewMVarOp -> ty2_op (\sty ty -> 
2155                 ilxOpSeq [ilxOp "newobj void " , repMVar ty , ilxOp "::.ctor()"])
2156                  {- State# s -> (# State# s, MVar# s a #) -}
2157
2158         TakeMVarOp -> ty2_op (\sty ty -> 
2159                 ilxCallSuppMeth ilxMethTyVarA "takeMVar" [ty] [repMVar ilxMethTyVarA])
2160                   {-  MVar# s a -> State# s -> (# State# s, a #) -}
2161
2162         -- These aren't yet right
2163         TryTakeMVarOp -> ty2_op (\sty ty -> 
2164                 ilxCallSuppMeth (ilxUnboxedPairRep repInt ilxMethTyVarA) "tryTakeMVar" [ty] [repMVar ilxMethTyVarA])
2165                   {-  MVar# s a -> State# s -> (# State# s, a #) -}
2166
2167         TryPutMVarOp -> ty2_op (\sty ty -> 
2168                 ilxCallSuppMeth repInt "tryPutMVar" [ty] [repMVar ilxMethTyVarA,ilxMethTyVarA])
2169                   {-  MVar# s a -> State# s -> (# State# s, a #) -}
2170
2171         PutMVarOp -> ty2_op (\sty ty -> 
2172                 ilxCallSuppMeth (ilxOp "void") "putMVar" [ty] [repMVar ilxMethTyVarA, ilxMethTyVarA])
2173                    {- MVar# s a -> a -> State# s -> State# s -}
2174
2175         SameMVarOp -> ty2_op (\sty ty -> ilxCeq)
2176                    {- MVar# s a -> MVar# s a -> Bool -}
2177
2178 --      TakeMaybeMVarOp -> ty2_op (\sty ty -> 
2179 --              (ilxCallSuppMeth (ilxUnboxedPairRep repInt ilxMethTyVarA) "tryTakeMVar" [ty] [repMVar ilxMethTyVarA]))
2180 --              {- MVar# s a -> State# s -> (# State# s, Int#, a #) -}
2181
2182         IsEmptyMVarOp -> ty2_op (\sty ty -> 
2183                 ilxCallSuppMeth repInt "isEmptyMVar" [ty] [repMVar ilxMethTyVarA])
2184                {- MVar# s a -> State# s -> (# State# s, Int# #) -}
2185
2186         TouchOp -> warn_op "touch" (ty1_op (\ty1 -> ilxOp "pop /* PrimOp touch */ "))
2187
2188                {- a -> Int# -}
2189         DataToTagOp -> ty1_op (\ty1 -> 
2190                 ilxCallSuppMeth repInt "dataToTag" [ty1] [ilxMethTyVarA])
2191                {- a -> Int# -}
2192
2193         TagToEnumOp -> ty1_op (\ty1 -> 
2194                 ilxCallSuppMeth ilxMethTyVarA "tagToEnum" [ty1] [repInt])
2195                {- Int# -> a -}
2196
2197         MakeStablePtrOp -> ty1_op (\ty1 -> ilxOpSeq [ilxOp "box", ty1, ilxOp "newobj void", repStablePtr {- ty1 -}, ilxOp "::.ctor(class [mscorlib]System.Object)"])
2198                  {-   a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #) -}
2199         MakeStableNameOp -> ty1_op (\ty1 -> ilxOpSeq [ilxOp "pop newobj void", repStableName {- ty1 -}, ilxOp "::.ctor()"])
2200                         -- primOpInfo MakeStableNameOp = mkGenPrimOp SLIT("makeStableName#")  [alphaTyVar] [alphaTy, mkStatePrimTy realWorldTy] ((mkTupleTy Unboxed 2 [mkStatePrimTy realWorldTy, mkStableNamePrimTy alphaTy]))
2201
2202         EqStableNameOp -> ty1_op (\ty1 -> ilxOp "ceq")
2203                -- [alphaTyVar] [mkStableNamePrimTy alphaTy, mkStableNamePrimTy alphaTy] (intPrimTy)
2204         StableNameToIntOp -> warn_op "StableNameToIntOp" (ty1_op (\ty1 -> ilxOp "pop ldc.i4 0"))
2205                -- [alphaTyVar] [mkStableNamePrimTy alphaTy] (intPrimTy)
2206
2207         DeRefStablePtrOp -> ty1_op (\ty1 -> ilxOpSeq [ilxOp "ldfld class [mscorlib]System.Object", repStablePtr {- ty1 -}, ilxOp "::contents"])
2208                  {-  StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #) -}
2209
2210         EqStablePtrOp -> ty1_op (\ty1 -> ilxOp "ceq")
2211                  {-  StablePtr# a -> StablePtr# a -> Int# -}
2212
2213             -- The 3rd argument to MkWeakOp is always a IO Monad action, i.e. passed as () --> ()
2214         MkWeakOp -> ty3_op (\ty1 ty2 ty3 ->  ilxCall (ilxMethodRef (repWeak ilxMethTyVarB) classWeak "bake" [ilxLift ty1,ilxLift ty2] [ilxMethTyVarA, ilxMethTyVarB, ilxLift (ilxTyIO ilxUnboxedEmptyRep)]))
2215                  {- o -> b -> c -> State# RealWorld -> (# State# RealWorld, Weak# b #) -}
2216
2217         DeRefWeakOp -> ty1_op (\ty1 ->  ilxCall (ilxMethodRef (ilxUnboxedPairRep repInt ilxMethTyVarA) classWeak "deref" [ty1] [repWeak ilxMethTyVarA]))
2218         FinalizeWeakOp -> ty1_op (\ty1 ->  ilxCall (ilxMethodRef (ilxUnboxedPairRep repInt (ilxTyIO ilxUnboxedEmptyRep)) classWeak "finalizer" [ty1] [repWeak ilxMethTyVarA]))
2219                    {-    Weak# a -> State# RealWorld -> (# State# RealWorld, Int#, 
2220         State# RealWorld -> (# State# RealWorld, Unit #)) #) -}
2221
2222         MkForeignObjOp -> simp_op (ilxOpSeq [ilxOp "newobj void", repForeign, ilxOp "::.ctor(void *)"])
2223         WriteForeignObjOp -> ty1_op (\sty -> ilxOpSeq [ilxOp "stfld void *", repForeign, ilxOp "::contents"])
2224         ForeignObjToAddrOp -> simp_op ilxAddrOfForeignOp
2225         YieldOp -> simp_op (ilxOpSeq [ilxOp "call class [mscorlib]System.Threading.Thread class [mscorlib]System.Threading.Thread::get_CurrentThread() 
2226                                 call instance void class [mscorlib]System.Threading.Thread::Suspend()"])
2227         MyThreadIdOp -> simp_op (ilxOpSeq [ilxOp "call default  class [mscorlib]System.Threading.Thread class [mscorlib]System.Threading.Thread::get_CurrentThread() "])
2228         KillThreadOp -> ty1_op (\ty -> ilxOpSeq [ilxOp "box", ty, ilxOp "call instance void class [mscorlib]System.Threading.Thread::Abort(class [mscorlib]System.Object) "])
2229               {-   ThreadId# -> a -> State# RealWorld -> State# RealWorld -}
2230
2231         ForkOp -> warn_op "ForkOp" (simp_op (ilxOp "/* ForkOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2232         ParOp ->  warn_op "ParOp" (simp_op (ilxOp "/* ParOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2233         DelayOp -> simp_op (ilxOp "call void class [mscorlib]System.Threading.Thread::Sleep(int32) ")
2234                  {-    Int# -> State# s -> State# s -}
2235
2236         WaitReadOp  -> warn_op "WaitReadOp" (simp_op (ilxOp "/* WaitReadOp skipped... */ pop"))
2237         WaitWriteOp -> warn_op "WaitWriteOp" (simp_op (ilxOp " /* WaitWriteOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2238         ParAtForNowOp -> warn_op "ParAtForNowOp" (simp_op (ilxOp " /* ParAtForNowOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2239         ParAtRelOp -> warn_op "ParAtRelOp" (simp_op (ilxOp " /* ParAtRelOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2240         ParAtAbsOp -> warn_op "ParAtAbsOp" (simp_op (ilxOp " /* ParAtAbsOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2241         ParAtOp -> warn_op "ParAtOp" (simp_op (ilxOp " /* ParAtOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2242         ParLocalOp -> warn_op "ParLocalOp" (simp_op (ilxOp " /* ParLocalOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2243         ParGlobalOp -> warn_op "ParGlobalOp" (simp_op (ilxOp " /* ParGlobalOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2244         SeqOp -> warn_op "SeqOp" (simp_op (ilxOp " newobj void [mscorlib]System.Object::.ctor() throw "))
2245         AddrToHValueOp -> warn_op "AddrToHValueOp" (simp_op (ilxOp "newobj void [mscorlib]System.Object::.ctor() throw"))
2246         ReallyUnsafePtrEqualityOp -> simp_op (ilxOp "ceq")
2247
2248         MkApUpd0_Op ->  warn_op "MkApUpd0_Op" (simp_op (ilxOp " newobj void [mscorlib]System.Object::.ctor() throw"))
2249         NewBCOOp ->  warn_op "NewBCOOp" (simp_op (ilxOp " newobj void [mscorlib]System.Object::.ctor() throw"))
2250                   -- ("newBCO#")  [alphaTyVar, deltaTyVar] [byteArrayPrimTy, byteArrayPrimTy, mkArrayPrimTy alphaTy, byteArrayPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed 2 [mkStatePrimTy deltaTy, bcoPrimTy]))
2251         _        -> pprPanic "Unimplemented primop" (ppr op)
2252
2253
2254 ty1_op :: (IlxTyFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2255 ty1_op  op ((StgTypeArg ty1):rest)  = 
2256       ilxOpSeq [getArgsStartingAt 1 rest, 
2257                 op (ilxTypeR2 (deepIlxRepType ty1))]
2258
2259 ty2_op :: (IlxTyFrag -> IlxTyFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2260 ty2_op  op ((StgTypeArg ty1):(StgTypeArg ty2):rest)  = 
2261       ilxOpSeq [getArgsStartingAt 2 rest, 
2262                 op (ilxTypeR2 (deepIlxRepType ty1)) 
2263                    (ilxTypeR2 (deepIlxRepType ty2))]
2264
2265 ty3_op :: (IlxTyFrag -> IlxTyFrag -> IlxTyFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2266 ty3_op  op ((StgTypeArg ty1):(StgTypeArg ty2):(StgTypeArg ty3):rest) = 
2267       ilxOpSeq [getArgsStartingAt 3 rest, 
2268                 op (ilxTypeR2 (deepIlxRepType ty1)) 
2269                    (ilxTypeR2 (deepIlxRepType ty2))
2270                    (ilxTypeR2 (deepIlxRepType ty3))]
2271
2272 arg2_op :: (IlxTyFrag -> IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2273 arg2_op  op [a1, a2] = 
2274        op (getAsArg 1 a1)
2275           (getAsArg 2 a2)
2276
2277 ty1_arg2_op :: (IlxTyFrag -> IlxOpFrag ->  IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2278 ty1_arg2_op  op [(StgTypeArg ty1), a1, a2] = 
2279        op (ilxTypeR2 (deepIlxRepType ty1)) 
2280           (getAsArg 1 a1)
2281           (getAsArg 2 a2)
2282
2283 ty1_arg4_op :: (IlxTyFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2284 ty1_arg4_op  op [(StgTypeArg ty1), a1, a2, a3, a4] = 
2285        op (ilxTypeR2 (deepIlxRepType ty1)) 
2286           (getAsArg 1 a1)
2287           (getAsArg 2 a2)
2288           (getAsArg 3 a3)
2289           (getAsArg 4 a4)
2290
2291 ty2_arg4_op :: (IlxTyFrag -> IlxTyFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2292 ty2_arg4_op  op [(StgTypeArg ty1), (StgTypeArg ty2),a1, a2, a3, a4] = 
2293        op (ilxTypeR2 (deepIlxRepType ty1)) 
2294           (ilxTypeR2 (deepIlxRepType ty2)) 
2295           (getAsArg 2 a1)
2296           (getAsArg 3 a2)
2297           (getAsArg 4 a3)
2298           (getAsArg 5 a4)
2299
2300 hd (h:t) = h
2301
2302 getAsArg n a env = hd (ilxMapPlaceArgs n pushArg env [a])
2303 getArgsStartingAt n a env = vcat (ilxMapPlaceArgs n pushArg env a)
2304
2305 simp_op :: IlxOpFrag -> [StgArg] -> IlxOpFrag
2306 simp_op  op args env    = vcat (ilxMapPlaceArgs 0 pushArg env args) $$ op env
2307 warn_op  warning f args = trace ("WARNING! IlxGen cannot translate primop " ++ warning) (f args)
2308 \end{code}
2309
2310 %************************************************************************
2311 %*                                                                      *
2312 \subsection{C Calls}
2313 %*                                                                      *
2314 %************************************************************************
2315
2316 \begin{code}
2317 -- Call the P/Invoke stub wrapper generated in the import section.
2318 -- We eliminate voids in and around an IL C Call.  
2319 -- We also do some type-directed translation for pinning Haskell-managed blobs
2320 -- of data as we throw them across the boundary.
2321 ilxFCall env (CCall (CCallSpec (StaticTarget c) cconv gc)) args ret_ty
2322  = ilxComment ((text "C call") <+> pprCLabelString c) <+> 
2323         vcat [vcat (ilxMapPlaceArgs 0 pushCArg env args),
2324               text "call" <+> retdoc <+> pprCLabelString c <+> tyarg_doc
2325                     <+> pprCValArgTys ilxTypeL env (map deepIlxRepType (filter (not. isVoidIlxRepType) (map stgArgType tm_args))) ]
2326   where 
2327     retdoc | isVoidIlxRepType ret_ty = text "void"
2328            | otherwise               = ilxTypeR env (deepIlxRepType ret_ty)
2329     (ty_args,tm_args) = splitTyArgs1 args
2330     tyarg_doc | not (isEmptyVarSet (tyVarsOfTypes ty_args)) = text "/* type variable found */"
2331               | otherwise = pprTypeArgs ilxTypeR env ty_args
2332
2333 ilxFCall env (DNCall (DNCallSpec call_instr)) args ret_ty
2334   = ilxComment (text "IL call") <+> 
2335     vcat [vcat (ilxMapPlaceArgs 0 pushEvalArg env tm_args), 
2336           ptext call_instr
2337                 -- In due course we'll need to pass the type arguments
2338                 -- and to do that we'll need to have more than just a string
2339                 -- for call_instr
2340     ]
2341   where
2342     (ty_args,tm_args) = splitTyArgs1 args 
2343
2344 -- Push and argument and force its evaluation if necessary.
2345 pushEvalArg _ (StgTypeArg _) = empty
2346 pushEvalArg env (StgVarArg arg) = ilxFunApp env arg [] False
2347 pushEvalArg env (StgLitArg lit) = pushLit env lit
2348
2349
2350 hasTyCon (TyConApp tc _) tc2 = tc == tc2
2351 hasTyCon _  _ = False
2352
2353 isByteArrayCArgTy ty = hasTyCon ty byteArrayPrimTyCon || hasTyCon ty mutableByteArrayPrimTyCon
2354 isByteArrayCArg v = isByteArrayCArgTy (deepIlxRepType (idType v))
2355
2356 isForeignObjCArgTy ty = hasTyCon ty foreignObjPrimTyCon
2357 isForeignObjCArg v = isForeignObjCArgTy (deepIlxRepType (idType v))
2358
2359 pinCCallArg v = isByteArrayCArg v || isForeignObjCArg v  
2360
2361 pinCArg  env arg v = pushArg env arg <+> text "dup stloc" <+> singleQuotes (ilxEnvQualifyByExact env (ppr v) <> text "pin") 
2362 pushCArg  env arg@(StgVarArg v) | isByteArrayCArg v = pinCArg env arg v <+> ilxAddrOfByteArrOp env
2363 pushCArg env arg@(StgVarArg v) | isForeignObjCArg v = pinCArg env arg v <+> ilxAddrOfForeignOp env
2364 pushCArg env arg | otherwise = pushArg env arg
2365
2366 pprCValArgTys f env tys = parens (pprSepWithCommas (pprCValArgTy f env) tys)
2367 pprCValArgTy f env ty | isByteArrayCArgTy ty = text "void *" <+> ilxComment (text "interior pointer into ByteArr#")
2368 pprCValArgTy f env ty | isForeignObjCArgTy ty = text "void *" <+> ilxComment (text "foreign object")
2369 pprCValArgTy f env ty | otherwise = f env ty
2370
2371
2372 foldR            :: (a -> b -> b) -> [a] -> b -> b
2373 -- foldR _ [] z     =  z
2374 -- foldR f (x:xs) z =  f x (foldR f xs z) 
2375 {-# INLINE foldR #-}
2376 foldR k xs z = go xs
2377              where
2378                go []     = z
2379                go (y:ys) = y `k` go ys
2380
2381 \end{code}
2382