Home My Page Projects Code Snippets Project Openings diderot
Summary Activity Tracker Tasks SCM

SCM Repository

[diderot] Annotation of /branches/vis15/src/compiler/simplify/simplify.sml
ViewVC logotype

Annotation of /branches/vis15/src/compiler/simplify/simplify.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 4426 - (view) (download)

1 : jhr 3437 (* simplify.sml
2 :     *
3 :     * This code is part of the Diderot Project (http://diderot-language.cs.uchicago.edu)
4 :     *
5 :     * COPYRIGHT (c) 2015 The University of Chicago
6 :     * All rights reserved.
7 :     *
8 : jhr 3468 * Simplify the AST representation. This phase involves the following transformations:
9 :     *
10 : jhr 4317 * - types are simplified by removing meta variables (which will have been resolved)
11 : jhr 3468 *
12 : jhr 4317 * - expressions are simplified to involve a single operation on variables
13 : jhr 3468 *
14 : jhr 4317 * - global reductions are converted to MapReduce statements
15 : jhr 3468 *
16 : jhr 4317 * - other comprehensions and reductions are converted to foreach loops
17 : jhr 3468 *
18 : jhr 4317 * - unreachable code is pruned
19 : jhr 3468 *
20 : jhr 4317 * - negation of literal integers and reals are constant folded
21 : jhr 3437 *)
22 :    
23 :     structure Simplify : sig
24 :    
25 : jhr 4371 val transform : Error.err_stream * AST.program * GlobalEnv.t -> Simple.program
26 : jhr 3437
27 :     end = struct
28 :    
29 :     structure TU = TypeUtil
30 :     structure S = Simple
31 : jhr 3445 structure STy = SimpleTypes
32 :     structure Ty = Types
33 : jhr 3437 structure VMap = Var.Map
34 : jhr 4193 structure II = ImageInfo
35 : jhr 4359 structure BV = BasisVars
36 : jhr 3437
37 : jhr 4371 (* context for simplification *)
38 :     type context = {errStrm : Error.err_stream, gEnv : GlobalEnv.t}
39 :    
40 :     fun error ({errStrm, gEnv}, msg) = Error.error (errStrm, msg)
41 :     fun warning ({errStrm, gEnv}, msg) = Error.warning (errStrm, msg)
42 :    
43 : jhr 3445 (* convert a Types.ty to a SimpleTypes.ty *)
44 :     fun cvtTy ty = (case ty
45 :     of Ty.T_Var(Ty.TV{bind, ...}) => (case !bind
46 :     of NONE => raise Fail "unresolved type variable"
47 :     | SOME ty => cvtTy ty
48 :     (* end case *))
49 :     | Ty.T_Bool => STy.T_Bool
50 :     | Ty.T_Int => STy.T_Int
51 :     | Ty.T_String => STy.T_String
52 :     | Ty.T_Sequence(ty, NONE) => STy.T_Sequence(cvtTy ty, NONE)
53 : jhr 3452 | Ty.T_Sequence(ty, SOME dim) => STy.T_Sequence(cvtTy ty, SOME(TU.monoDim dim))
54 : jhr 4317 | Ty.T_Strand id => STy.T_Strand id
55 : jhr 4207 | Ty.T_Kernel _ => STy.T_Kernel
56 : jhr 3445 | Ty.T_Tensor shape => STy.T_Tensor(TU.monoShape shape)
57 : jhr 4193 | Ty.T_Image{dim, shape} =>
58 : jhr 4317 STy.T_Image(II.mkInfo(TU.monoDim dim, TU.monoShape shape))
59 : jhr 3445 | Ty.T_Field{diff, dim, shape} => STy.T_Field{
60 :     diff = TU.monoDiff diff,
61 :     dim = TU.monoDim dim,
62 :     shape = TU.monoShape shape
63 :     }
64 : jhr 4163 | Ty.T_Fun(tys1, ty2) => raise Fail "unexpected T_Fun in Simplify"
65 : jhr 4317 | Ty.T_Error => raise Fail "unexpected T_Error in Simplify"
66 : jhr 3445 (* end case *))
67 : jhr 3437
68 : jhr 3811 fun apiTypeOf x = let
69 : jhr 4317 fun cvtTy STy.T_Bool = APITypes.BoolTy
70 :     | cvtTy STy.T_Int = APITypes.IntTy
71 :     | cvtTy STy.T_String = APITypes.StringTy
72 :     | cvtTy (STy.T_Sequence(ty, len)) = APITypes.SeqTy(cvtTy ty, len)
73 :     | cvtTy (STy.T_Tensor shape) = APITypes.TensorTy shape
74 :     | cvtTy (STy.T_Image info) =
75 :     APITypes.ImageTy(II.dim info, II.voxelShape info)
76 :     | cvtTy ty = raise Fail "bogus API type"
77 :     in
78 :     cvtTy (SimpleVar.typeOf x)
79 :     end
80 : jhr 3811
81 : jhr 4117 fun newTemp (ty as STy.T_Image _) = SimpleVar.new ("img", SimpleVar.LocalVar, ty)
82 :     | newTemp ty = SimpleVar.new ("_t", SimpleVar.LocalVar, ty)
83 : jhr 3437
84 : jhr 4163 (* a property to map AST function variables to SimpleAST functions *)
85 :     local
86 :     fun cvt x = let
87 : jhr 4317 val Ty.T_Fun(paramTys, resTy) = Var.monoTypeOf x
88 :     in
89 :     SimpleFunc.new (Var.nameOf x, cvtTy resTy, List.map cvtTy paramTys)
90 :     end
91 : jhr 4163 in
92 :     val {getFn = cvtFunc, ...} = Var.newProp cvt
93 :     end
94 :    
95 : jhr 3456 (* a property to map AST variables to SimpleAST variables *)
96 :     local
97 :     fun cvt x = SimpleVar.new (Var.nameOf x, Var.kindOf x, cvtTy(Var.monoTypeOf x))
98 : jhr 4193 val {getFn, setFn, ...} = Var.newProp cvt
99 : jhr 3456 in
100 : jhr 4193 val cvtVar = getFn
101 :     fun newVarWithType (x, ty) = let
102 : jhr 4317 val x' = SimpleVar.new (Var.nameOf x, Var.kindOf x, ty)
103 :     in
104 :     setFn (x, x');
105 :     x'
106 :     end
107 : jhr 3456 end
108 : jhr 3452
109 : jhr 3456 fun cvtVars xs = List.map cvtVar xs
110 : jhr 3452
111 : jhr 3437 (* make a block out of a list of statements that are in reverse order *)
112 : jhr 3501 fun mkBlock stms = S.Block{props = PropList.newHolder(), code = List.rev stms}
113 : jhr 3437
114 : jhr 4393 (* make a variable definition *)
115 :     fun mkDef (x, e) = S.S_Var(x, SOME e)
116 :    
117 : jhr 4394 fun mkRDiv (res, a, b) = mkDef (res, S.E_Prim(BV.div_rr, [], [a, b], STy.realTy))
118 :     fun mkToReal (res, a) =
119 :     mkDef (res, S.E_Coerce{srcTy = STy.T_Int, dstTy = STy.realTy, x = a})
120 :     fun mkLength (res, elemTy, xs) =
121 :     mkDef (res, S.E_Prim(BV.fn_length, [STy.TY elemTy], [xs], STy.T_Int))
122 :    
123 : jhr 3437 (* simplify a statement into a single statement (i.e., a block if it expands
124 :     * into more than one new statement).
125 :     *)
126 : jhr 4371 fun simplifyBlock (cxt, stm) = mkBlock (simplifyStmt (cxt, stm, []))
127 : jhr 3437
128 : jhr 4193 (* convert the lhs variable of a var decl or assignment; if the rhs is a LoadImage,
129 :     * then we use the info from the proxy image to determine the type of the lhs
130 :     * variable.
131 :     *)
132 :     and cvtLHS (lhs, S.E_LoadImage(_, _, info)) = newVarWithType(lhs, STy.T_Image info)
133 :     | cvtLHS (lhs, _) = cvtVar lhs
134 :    
135 : jhr 3437 (* simplify the statement stm where stms is a reverse-order list of preceeding simplified
136 :     * statements. This function returns a reverse-order list of simplified statements.
137 :     * Note that error reporting is done in the typechecker, but it does not prune unreachable
138 :     * code.
139 :     *)
140 : jhr 4371 and simplifyStmt (cxt, stm, stms) : S.stmt list = (case stm
141 : jhr 3437 of AST.S_Block body => let
142 : jhr 3456 fun simplify ([], stms) = stms
143 : jhr 4371 | simplify (stm::r, stms) = simplify (r, simplifyStmt (cxt, stm, stms))
144 : jhr 3437 in
145 : jhr 3456 simplify (body, stms)
146 : jhr 3437 end
147 : jhr 3452 | AST.S_Decl(x, NONE) => let
148 : jhr 3456 val x' = cvtVar x
149 : jhr 3452 in
150 : jhr 3465 S.S_Var(x', NONE) :: stms
151 : jhr 3452 end
152 :     | AST.S_Decl(x, SOME e) => let
153 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, stms)
154 : jhr 4193 val x' = cvtLHS (x, e')
155 : jhr 3437 in
156 : jhr 3465 S.S_Var(x', SOME e') :: stms
157 : jhr 3437 end
158 : jhr 4310 (* FIXME: we should also define a "boolean negate" operation on AST expressions so that we can
159 : jhr 4254 * handle both cases!
160 :     *)
161 :     | AST.S_IfThenElse(AST.E_Orelse(e1, e2), s1 as AST.S_Block[], s2) =>
162 : jhr 4371 simplifyStmt (cxt, AST.S_IfThenElse(e1, s1, AST.S_IfThenElse(e2, s1, s2)), stms)
163 : jhr 4254 | AST.S_IfThenElse(AST.E_Andalso(e1, e2), s1, s2 as AST.S_Block[]) =>
164 : jhr 4371 simplifyStmt (cxt, AST.S_IfThenElse(e1, AST.S_IfThenElse(e2, s1, s2), s2), stms)
165 : jhr 3437 | AST.S_IfThenElse(e, s1, s2) => let
166 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
167 :     val s1 = simplifyBlock (cxt, s1)
168 :     val s2 = simplifyBlock (cxt, s2)
169 : jhr 3437 in
170 : jhr 3456 S.S_IfThenElse(x, s1, s2) :: stms
171 : jhr 3437 end
172 : jhr 4317 | AST.S_Foreach((x, e), body) => let
173 : jhr 4371 val (stms, xs') = simplifyExpToVar (cxt, e, stms)
174 :     val body' = simplifyBlock (cxt, body)
175 : jhr 4317 in
176 :     S.S_Foreach(cvtVar x, xs', body') :: stms
177 :     end
178 : jhr 3452 | AST.S_Assign((x, _), e) => let
179 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, stms)
180 : jhr 4193 val x' = cvtLHS (x, e')
181 : jhr 3437 in
182 : jhr 4193 S.S_Assign(x', e') :: stms
183 : jhr 3437 end
184 :     | AST.S_New(name, args) => let
185 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, args, stms)
186 : jhr 3437 in
187 : jhr 3456 S.S_New(name, xs) :: stms
188 : jhr 3437 end
189 : jhr 3456 | AST.S_Continue => S.S_Continue :: stms
190 :     | AST.S_Die => S.S_Die :: stms
191 :     | AST.S_Stabilize => S.S_Stabilize :: stms
192 : jhr 3437 | AST.S_Return e => let
193 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
194 : jhr 3437 in
195 : jhr 3456 S.S_Return x :: stms
196 : jhr 3437 end
197 :     | AST.S_Print args => let
198 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, args, stms)
199 : jhr 3437 in
200 : jhr 3456 S.S_Print xs :: stms
201 : jhr 3437 end
202 :     (* end case *))
203 :    
204 : jhr 4371 and simplifyExp (cxt, exp, stms) = let
205 : jhr 4317 fun doBorderCtl (f, args) = let
206 : jhr 4359 val (ctl, arg) = if Var.same(BV.image_border, f)
207 : jhr 4317 then (BorderCtl.Default(hd args), hd(tl args))
208 : jhr 4359 else if Var.same(BV.image_clamp, f)
209 : jhr 4317 then (BorderCtl.Clamp, hd args)
210 : jhr 4359 else if Var.same(BV.image_mirror, f)
211 : jhr 4317 then (BorderCtl.Mirror, hd args)
212 : jhr 4359 else if Var.same(BV.image_wrap, f)
213 : jhr 4317 then (BorderCtl.Wrap, hd args)
214 :     else raise Fail "impossible"
215 :     in
216 :     S.E_BorderCtl(ctl, arg)
217 :     end
218 :     fun doPrimApply (f, tyArgs, args, ty) = let
219 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, args, stms)
220 : jhr 4378 fun cvtTyArg (Types.TYPE tv) = S.TY(cvtTy(TU.resolve tv))
221 :     | cvtTyArg (Types.DIFF dv) = S.DIFF(TU.monoDiff(TU.resolveDiff dv))
222 :     | cvtTyArg (Types.SHAPE sv) = S.SHAPE(TU.monoShape(TU.resolveShape sv))
223 :     | cvtTyArg (Types.DIM dv) = S.DIM(TU.monoDim(TU.resolveDim dv))
224 : jhr 4317 in
225 :     if Basis.isBorderCtl f
226 :     then (stms, doBorderCtl (f, xs))
227 : jhr 4368 else if Var.same(f, BV.fn_sphere_im)
228 : jhr 4371 then let
229 : jhr 4378 (* get the strand type for the query *)
230 :     val tyArgs as [S.TY(STy.T_Strand strand)] = List.map cvtTyArg tyArgs
231 :     (* get the strand environment for the strand *)
232 :     val SOME sEnv = GlobalEnv.findStrand(#gEnv cxt, strand)
233 :     fun result (query, pos) =
234 :     (stms, S.E_Prim(query, tyArgs, cvtVar pos::xs, cvtTy ty))
235 :     in
236 :     (* extract the position variable and spatial dimension *)
237 :     case (StrandEnv.findPosVar sEnv, StrandEnv.getSpaceDim sEnv)
238 :     of (SOME pos, SOME 1) => result (BV.fn_sphere1_r, pos)
239 :     | (SOME pos, SOME 2) => result (BV.fn_sphere2_t, pos)
240 :     | (SOME pos, SOME 3) => result (BV.fn_sphere3_t, pos)
241 :     | _ => raise Fail "impossible"
242 :     (* end case *)
243 :     end
244 : jhr 4317 else (case Var.kindOf f
245 :     of Var.BasisVar => let
246 :     val tyArgs = List.map cvtTyArg tyArgs
247 :     in
248 :     (stms, S.E_Prim(f, tyArgs, xs, cvtTy ty))
249 :     end
250 :     | _ => raise Fail "bogus prim application"
251 :     (* end case *))
252 :     end
253 :     in
254 :     case exp
255 :     of AST.E_Var(x, _) => (case Var.kindOf x
256 :     of Var.BasisVar => let
257 :     val ty = cvtTy(Var.monoTypeOf x)
258 :     val x' = newTemp ty
259 :     val stm = S.S_Var(x', SOME(S.E_Prim(x, [], [], ty)))
260 :     in
261 :     (stm::stms, S.E_Var x')
262 :     end
263 :     | _ => (stms, S.E_Var(cvtVar x))
264 :     (* end case *))
265 :     | AST.E_Lit lit => (stms, S.E_Lit lit)
266 :     | AST.E_Kernel h => (stms, S.E_Kernel h)
267 :     | AST.E_Select(e, (fld, _)) => let
268 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
269 : jhr 4317 in
270 :     (stms, S.E_Select(x, cvtVar fld))
271 :     end
272 :     | AST.E_Prim(rator, tyArgs, args as [e], ty) => (case e
273 : jhr 4359 of AST.E_Lit(Literal.Int n) => if Var.same(BV.neg_i, rator)
274 : jhr 4317 then (stms, S.E_Lit(Literal.Int(~n))) (* constant-fold negation of integer literals *)
275 :     else doPrimApply (rator, tyArgs, args, ty)
276 :     | AST.E_Lit(Literal.Real f) =>
277 : jhr 4359 if Var.same(BV.neg_t, rator)
278 : jhr 4317 then (stms, S.E_Lit(Literal.Real(RealLit.negate f))) (* constant-fold negation of real literals *)
279 :     else doPrimApply (rator, tyArgs, args, ty)
280 : jhr 4364 (* QUESTION: is there common code in handling a reduction over a sequence of strands vs. over a strand set? *)
281 : jhr 4317 | AST.E_Comprehension(e', (x, e''), seqTy) => if Basis.isReductionOp rator
282 :     then let
283 : jhr 4371 val (stms, xs) = simplifyExpToVar (cxt, e'', stms)
284 : jhr 4393 val (bodyStms, bodyResult) = simplifyExpToVar (cxt, e', [])
285 : jhr 4317 val seqTy' as STy.T_Sequence(elemTy, NONE) = cvtTy seqTy
286 : jhr 4393 fun mkReductionLoop (redOp, bodyStms, bodyResult, stms) = let
287 :     val {rator, init, mvs} = Util.reductionInfo redOp
288 :     val acc = SimpleVar.new ("accum", Var.LocalVar, cvtTy ty)
289 :     val initStm = S.S_Var(acc, SOME(S.E_Lit init))
290 :     val updateStm = S.S_Assign(acc,
291 :     S.E_Prim(rator, mvs, [acc, bodyResult], seqTy'))
292 :     val foreachStm = S.S_Foreach(cvtVar x, xs,
293 :     mkBlock(updateStm :: bodyStms))
294 :     in
295 :     (foreachStm :: initStm :: stms, S.E_Var acc)
296 :     end
297 :     in
298 :     case Util.identifyReduction rator
299 :     of Util.MEAN => let
300 :     val (stms, S.E_Var resultV) = mkReductionLoop (
301 :     Reductions.SUM, bodyStms, bodyResult, stms)
302 :     val num = SimpleVar.new ("num", Var.LocalVar, STy.T_Int)
303 :     val rNum = SimpleVar.new ("rNum", Var.LocalVar, STy.realTy)
304 :     val mean = SimpleVar.new ("mean", Var.LocalVar, STy.realTy)
305 :     val stms =
306 : jhr 4394 mkRDiv (mean, resultV, rNum) ::
307 :     mkToReal (rNum, num) ::
308 :     mkLength (num, elemTy, xs) ::
309 : jhr 4393 stms
310 :     in
311 :     (stms, S.E_Var mean)
312 :     end
313 :     | Util.VARIANCE => raise Fail "FIXME: VARIANCE"
314 :     | Util.RED red => mkReductionLoop (red, bodyStms, bodyResult, stms)
315 :     (* end case *)
316 :     end
317 : jhr 4317 else doPrimApply (rator, tyArgs, args, ty)
318 :     | AST.E_ParallelMap(e', x, xs, _) =>
319 :     if Basis.isReductionOp rator
320 :     then let
321 : jhr 4394 val (result, stms) = simplifyReduction (cxt, rator, e', x, xs, ty, stms)
322 : jhr 4317 in
323 : jhr 4394 (stms, S.E_Var result)
324 : jhr 4317 end
325 :     else raise Fail "unsupported operation on parallel map"
326 :     | _ => doPrimApply (rator, tyArgs, args, ty)
327 :     (* end case *))
328 :     | AST.E_Prim(f, tyArgs, args, ty) => doPrimApply (f, tyArgs, args, ty)
329 :     | AST.E_Apply((f, _), args, ty) => let
330 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, args, stms)
331 : jhr 4317 in
332 :     case Var.kindOf f
333 :     of Var.FunVar => (stms, S.E_Apply(SimpleFunc.use(cvtFunc f), xs))
334 :     | _ => raise Fail "bogus application"
335 :     (* end case *)
336 :     end
337 :     | AST.E_Comprehension(e, (x, e'), seqTy) => let
338 :     (* convert a comprehension to a foreach loop over the sequence defined by e' *)
339 : jhr 4371 val (stms, xs) = simplifyExpToVar (cxt, e', stms)
340 :     val (bodyStms, bodyResult) = simplifyExpToVar (cxt, e, [])
341 : jhr 4317 val seqTy' as STy.T_Sequence(elemTy, NONE) = cvtTy seqTy
342 :     val acc = SimpleVar.new ("accum", Var.LocalVar, seqTy')
343 :     val initStm = S.S_Var(acc, SOME(S.E_Seq([], seqTy')))
344 :     val updateStm = S.S_Assign(acc,
345 : jhr 4359 S.E_Prim(BV.at_dT, [S.TY elemTy], [acc, bodyResult], seqTy'))
346 : jhr 4317 val foreachStm = S.S_Foreach(cvtVar x, xs, mkBlock(updateStm :: bodyStms))
347 :     in
348 :     (foreachStm :: initStm :: stms, S.E_Var acc)
349 :     end
350 :     | AST.E_ParallelMap(e, x, xs, ty) => raise Fail "FIXME: ParallelMap"
351 :     | AST.E_Tensor(es, ty) => let
352 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, es, stms)
353 : jhr 4317 in
354 :     (stms, S.E_Tensor(xs, cvtTy ty))
355 :     end
356 :     | AST.E_Seq(es, ty) => let
357 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, es, stms)
358 : jhr 4317 in
359 :     (stms, S.E_Seq(xs, cvtTy ty))
360 :     end
361 :     | AST.E_Slice(e, indices, ty) => let (* tensor slicing *)
362 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
363 : jhr 4317 fun f NONE = NONE
364 :     | f (SOME(AST.E_Lit(Literal.Int i))) = SOME(Int.fromLarge i)
365 :     | f _ = raise Fail "expected integer literal in slice"
366 :     val indices = List.map f indices
367 :     in
368 :     (stms, S.E_Slice(x, indices, cvtTy ty))
369 :     end
370 :     | AST.E_Cond(e1, e2, e3, ty) => let
371 :     (* a conditional expression gets turned into an if-then-else statememt *)
372 :     val result = newTemp(cvtTy ty)
373 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e1, S.S_Var(result, NONE) :: stms)
374 : jhr 4317 fun simplifyBranch e = let
375 : jhr 4371 val (stms, e) = simplifyExp (cxt, e, [])
376 : jhr 4317 in
377 :     mkBlock (S.S_Assign(result, e)::stms)
378 :     end
379 :     val s1 = simplifyBranch e2
380 :     val s2 = simplifyBranch e3
381 :     in
382 :     (S.S_IfThenElse(x, s1, s2) :: stms, S.E_Var result)
383 :     end
384 :     | AST.E_Orelse(e1, e2) => simplifyExp (
385 : jhr 4371 cxt,
386 : jhr 4317 AST.E_Cond(e1, AST.E_Lit(Literal.Bool true), e2, Ty.T_Bool),
387 :     stms)
388 :     | AST.E_Andalso(e1, e2) => simplifyExp (
389 : jhr 4371 cxt,
390 : jhr 4317 AST.E_Cond(e1, e2, AST.E_Lit(Literal.Bool false), Ty.T_Bool),
391 :     stms)
392 :     | AST.E_LoadNrrd(_, nrrd, ty) => (case cvtTy ty
393 :     of ty as STy.T_Sequence(_, NONE) => (stms, S.E_LoadSeq(ty, nrrd))
394 :     | ty as STy.T_Image info => let
395 :     val dim = II.dim info
396 :     val shape = II.voxelShape info
397 :     in
398 : jhr 4371 case NrrdInfo.getInfo (#errStrm cxt, nrrd)
399 : jhr 4317 of SOME nrrdInfo => (case II.fromNrrd(nrrdInfo, dim, shape)
400 :     of NONE => (
401 : jhr 4371 error (cxt, [
402 : jhr 4317 "nrrd file \"", nrrd, "\" does not have expected type"
403 :     ]);
404 :     (stms, S.E_LoadImage(ty, nrrd, II.mkInfo(dim, shape))))
405 :     | SOME imgInfo =>
406 :     (stms, S.E_LoadImage(STy.T_Image imgInfo, nrrd, imgInfo))
407 :     (* end case *))
408 :     | NONE => (
409 : jhr 4371 warning (cxt, [
410 : jhr 4317 "nrrd file \"", nrrd, "\" does not exist"
411 :     ]);
412 :     (stms, S.E_LoadImage(ty, nrrd, II.mkInfo(dim, shape))))
413 :     (* end case *)
414 :     end
415 :     | _ => raise Fail "bogus type for E_LoadNrrd"
416 :     (* end case *))
417 :     | AST.E_Coerce{dstTy, e=AST.E_Lit(Literal.Int n), ...} => (case cvtTy dstTy
418 :     of SimpleTypes.T_Tensor[] => (stms, S.E_Lit(Literal.Real(RealLit.fromInt n)))
419 :     | _ => raise Fail "impossible: bad coercion"
420 :     (* end case *))
421 :     | AST.E_Coerce{srcTy, dstTy, e} => let
422 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
423 : jhr 4317 val dstTy = cvtTy dstTy
424 :     val result = newTemp dstTy
425 :     val rhs = S.E_Coerce{srcTy = cvtTy srcTy, dstTy = dstTy, x = x}
426 :     in
427 :     (S.S_Var(result, SOME rhs)::stms, S.E_Var result)
428 :     end
429 :     (* end case *)
430 :     end
431 : jhr 3437
432 : jhr 4371 and simplifyExpToVar (cxt, exp, stms) = let
433 :     val (stms, e) = simplifyExp (cxt, exp, stms)
434 : jhr 3437 in
435 :     case e
436 :     of S.E_Var x => (stms, x)
437 :     | _ => let
438 :     val x = newTemp (S.typeOf e)
439 :     in
440 : jhr 3465 (S.S_Var(x, SOME e)::stms, x)
441 : jhr 3437 end
442 :     (* end case *)
443 :     end
444 :    
445 : jhr 4371 and simplifyExpsToVars (cxt, exps, stms) = let
446 : jhr 3437 fun f ([], xs, stms) = (stms, List.rev xs)
447 :     | f (e::es, xs, stms) = let
448 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
449 : jhr 3437 in
450 :     f (es, x::xs, stms)
451 :     end
452 :     in
453 :     f (exps, [], stms)
454 :     end
455 :    
456 : jhr 4359 (* simplify a parallel map-reduce *)
457 : jhr 4394 and simplifyReduction (cxt, rator, e, x, xs, resTy, stms) = let
458 : jhr 4378 val result = SimpleVar.new ("res", Var.LocalVar, cvtTy resTy)
459 : jhr 4368 val x' = cvtVar x
460 : jhr 4371 val (bodyStms, bodyResult) = simplifyExpToVar (cxt, e, [])
461 : jhr 4378 (* convert the domain from a variable to a StrandSets.t value *)
462 :     val domain = if Var.same(BV.set_active, xs) then StrandSets.ACTIVE
463 :     else if Var.same(BV.set_all, xs) then StrandSets.ALL
464 :     else if Var.same(BV.set_stable, xs) then StrandSets.STABLE
465 :     else raise Fail "impossible: not a strand set"
466 : jhr 4368 val (func, args) = Util.makeFunction(
467 :     Var.nameOf rator, mkBlock(S.S_Return bodyResult :: bodyStms),
468 :     SimpleVar.typeOf bodyResult)
469 : jhr 4359
470 : jhr 4394 in
471 :     case Util.identifyReduction rator
472 :     of Util.MEAN => let
473 :     val mapReduceStm = S.S_MapReduce[
474 :     S.MapReduce{
475 :     result = result, reduction = Reductions.SUM, mapf = func,
476 :     args = args, source = x', domain = domain
477 :     }]
478 :     val num = SimpleVar.new ("num", Var.LocalVar, STy.T_Int)
479 :     val rNum = SimpleVar.new ("rNum", Var.LocalVar, STy.realTy)
480 :     val mean = SimpleVar.new ("mean", Var.LocalVar, STy.realTy)
481 :     val numStrandsOp = (case domain
482 :     of StrandSets.ACTIVE => BV.numActive
483 :     | StrandSets.ALL => BV.numStrands
484 :     | StrandSets.STABLE => BV.numStable
485 :     (* end case *))
486 :     val stms =
487 :     mkRDiv (mean, result, rNum) ::
488 :     mkToReal (rNum, num) ::
489 :     mkDef (num, S.E_Prim(numStrandsOp, [], [], STy.T_Int)) ::
490 :     mapReduceStm ::
491 :     stms
492 :     in
493 :     (mean, stms)
494 :     end
495 :     | Util.VARIANCE => raise Fail "FIXME: variance reduction"
496 :     | Util.RED rator' => let
497 :     val mapReduceStm = S.S_MapReduce[
498 :     S.MapReduce{
499 :     result = result, reduction = rator', mapf = func, args = args,
500 :     source = x', domain = domain
501 :     }]
502 :     in
503 :     (result, mapReduceStm :: stms)
504 :     end
505 :     (* end case *)
506 :     end
507 :    
508 : jhr 4113 (* simplify a block and then prune unreachable and dead code *)
509 : jhr 4371 fun simplifyAndPruneBlock cxt blk =
510 :     DeadCode.eliminate (simplifyBlock (cxt, blk))
511 : jhr 4113
512 : jhr 4371 fun simplifyStrand (cxt, strand) = let
513 : jhr 4368 val AST.Strand{
514 :     name, params, spatialDim, state, stateInit, initM, updateM, stabilizeM
515 :     } = strand
516 : jhr 3456 val params' = cvtVars params
517 :     fun simplifyState ([], xs, stms) = (List.rev xs, mkBlock stms)
518 :     | simplifyState ((x, optE) :: r, xs, stms) = let
519 :     val x' = cvtVar x
520 : jhr 4317 in
521 :     case optE
522 :     of NONE => simplifyState (r, x'::xs, stms)
523 :     | SOME e => let
524 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, stms)
525 : jhr 4317 in
526 :     simplifyState (r, x'::xs, S.S_Assign(x', e') :: stms)
527 :     end
528 :     (* end case *)
529 :     end
530 : jhr 3456 val (xs, stm) = simplifyState (state, [], [])
531 : jhr 3437 in
532 : jhr 3452 S.Strand{
533 :     name = name,
534 :     params = params',
535 : jhr 4368 spatialDim = spatialDim,
536 : jhr 3456 state = xs,
537 : jhr 4317 stateInit = stm,
538 : jhr 4371 initM = Option.map (simplifyAndPruneBlock cxt) initM,
539 :     updateM = simplifyAndPruneBlock cxt updateM,
540 :     stabilizeM = Option.map (simplifyAndPruneBlock cxt) stabilizeM
541 : jhr 3452 }
542 : jhr 3437 end
543 :    
544 : jhr 4371 fun transform (errStrm, prog, gEnv) = let
545 : jhr 4317 val AST.Program{
546 :     props, const_dcls, input_dcls, globals, globInit, strand, create, init, update
547 :     } = prog
548 : jhr 4378 val cxt = {errStrm = errStrm, gEnv = gEnv}
549 : jhr 4317 val consts' = ref[]
550 :     val constInit = ref[]
551 :     val inputs' = ref[]
552 :     val globals' = ref[]
553 :     val globalInit = ref[]
554 :     val funcs = ref[]
555 :     fun simplifyConstDcl (x, SOME e) = let
556 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, [])
557 : jhr 4317 val x' = cvtVar x
558 :     in
559 :     consts' := x' :: !consts';
560 :     constInit := S.S_Assign(x', e') :: (stms @ !constInit)
561 :     end
562 :     fun simplifyInputDcl ((x, NONE), desc) = let
563 :     val x' = cvtVar x
564 :     val init = (case SimpleVar.typeOf x'
565 :     of STy.T_Image info => S.Image info
566 :     | _ => S.NoDefault
567 :     (* end case *))
568 :     val inp = S.INP{
569 :     var = x',
570 :     name = Var.nameOf x,
571 :     ty = apiTypeOf x',
572 :     desc = desc,
573 :     init = init
574 :     }
575 :     in
576 :     inputs' := inp :: !inputs'
577 :     end
578 :     | simplifyInputDcl ((x, SOME(AST.E_LoadNrrd(tvs, nrrd, ty))), desc) = let
579 :     val (x', init) = (case Var.monoTypeOf x
580 :     of Ty.T_Sequence(_, NONE) => (cvtVar x, S.LoadSeq nrrd)
581 :     | Ty.T_Image{dim, shape} => let
582 :     val dim = TU.monoDim dim
583 :     val shape = TU.monoShape shape
584 :     in
585 : jhr 4371 case NrrdInfo.getInfo (#errStrm cxt, nrrd)
586 : jhr 4317 of SOME nrrdInfo => (case II.fromNrrd(nrrdInfo, dim, shape)
587 :     of NONE => (
588 : jhr 4371 error (cxt, [
589 : jhr 4426 "proxy input file \"", nrrd,
590 : jhr 4317 "\" does not have expected type"
591 :     ]);
592 :     (cvtVar x, S.Image(II.mkInfo(dim, shape))))
593 :     | SOME info =>
594 :     (newVarWithType(x, STy.T_Image info), S.Proxy(nrrd, info))
595 :     (* end case *))
596 :     | NONE => (
597 : jhr 4371 warning (cxt, [
598 : jhr 4426 "proxy input file \"", nrrd, "\" does not exist"
599 : jhr 4317 ]);
600 :     (cvtVar x, S.Image(II.mkInfo(dim, shape))))
601 :     (* end case *)
602 :     end
603 :     | _ => raise Fail "impossible"
604 :     (* end case *))
605 :     val inp = S.INP{
606 :     var = x',
607 :     name = Var.nameOf x,
608 :     ty = apiTypeOf x',
609 :     desc = desc,
610 :     init = init
611 :     }
612 :     in
613 :     inputs' := inp :: !inputs'
614 :     end
615 :     | simplifyInputDcl ((x, SOME e), desc) = let
616 :     val x' = cvtVar x
617 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, [])
618 : jhr 4317 val inp = S.INP{
619 :     var = x',
620 :     name = Var.nameOf x,
621 :     ty = apiTypeOf x',
622 :     desc = desc,
623 :     init = S.ConstExpr
624 :     }
625 :     in
626 :     inputs' := inp :: !inputs';
627 :     constInit := S.S_Assign(x', e') :: (stms @ !constInit)
628 :     end
629 :     fun simplifyGlobalDcl (AST.D_Var(x, NONE)) = globals' := cvtVar x :: !globals'
630 :     | simplifyGlobalDcl (AST.D_Var(x, SOME e)) = let
631 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, [])
632 : jhr 4317 val x' = cvtLHS (x, e')
633 :     in
634 :     globals' := x' :: !globals';
635 :     globalInit := S.S_Assign(x', e') :: (stms @ !globalInit)
636 :     end
637 :     | simplifyGlobalDcl (AST.D_Func(f, params, body)) = let
638 :     val f' = cvtFunc f
639 :     val params' = cvtVars params
640 : jhr 4371 val body' = simplifyAndPruneBlock cxt body
641 : jhr 4317 in
642 :     funcs := S.Func{f=f', params=params', body=body'} :: !funcs
643 :     end
644 :     val () = (
645 :     List.app simplifyConstDcl const_dcls;
646 :     List.app simplifyInputDcl input_dcls;
647 :     List.app simplifyGlobalDcl globals)
648 :     (* make the global-initialization block *)
649 :     val globInit = (case globInit
650 : jhr 4371 of SOME stm => mkBlock (simplifyStmt (cxt, stm, !globalInit))
651 : jhr 4317 | NONE => mkBlock (!globalInit)
652 :     (* end case *))
653 :     (* if the globInit block is non-empty, record the fact in the property list *)
654 :     val props = (case globInit
655 :     of S.Block{code=[], ...} => props
656 :     | _ => Properties.GlobalInit :: props
657 :     (* end case *))
658 : jhr 3452 in
659 :     S.Program{
660 :     props = props,
661 : jhr 4317 consts = List.rev(!consts'),
662 : jhr 3452 inputs = List.rev(!inputs'),
663 : jhr 4317 constInit = mkBlock (!constInit),
664 : jhr 3452 globals = List.rev(!globals'),
665 : jhr 3995 globInit = globInit,
666 : jhr 3452 funcs = List.rev(!funcs),
667 : jhr 4371 strand = simplifyStrand (cxt, strand),
668 :     create = Create.map (simplifyAndPruneBlock cxt) create,
669 :     init = Option.map (simplifyAndPruneBlock cxt) init,
670 :     update = Option.map (simplifyAndPruneBlock cxt) update
671 : jhr 3452 }
672 :     end
673 :    
674 : jhr 3437 end

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0