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

SCM Repository

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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3837 - (view) (download)

1 : jhr 3471 (* translate.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 3476 * Translate Simple-AST code into the HighIR representation. This translation is based on the
9 : jhr 3471 * algorithm described in
10 :     *
11 :     * Single-pass generation of static single assignment form for structured languages
12 :     * ACM TOPLAS, Nov. 1994
13 :     * by Brandis and MossenBock.
14 :     *)
15 :    
16 :     structure Translate : sig
17 :    
18 : jhr 3476 val translate : Simple.program -> HighIR.program
19 : jhr 3471
20 :     end = struct
21 :    
22 :     structure S = Simple
23 :     structure Ty = SimpleTypes
24 : jhr 3485 structure SV = SimpleVar
25 :     structure VMap = SV.Map
26 :     structure VSet = SV.Set
27 : jhr 3476 structure IR = HighIR
28 : jhr 3471 structure Op = HighOps
29 : jhr 3476 structure DstTy = HighTypes
30 :     structure Census = HighCensus
31 : jhr 3493 structure Inp = Inputs
32 : jhr 3471
33 :     val cvtTy = TranslateTy.tr
34 :    
35 :     (* maps from SimpleAST variables to the current corresponding SSA variable *)
36 : jhr 3476 type env = IR.var VMap.map
37 : jhr 3471
38 :     (* +DEBUG *)
39 :     fun prEnv (prefix, env) = let
40 :     val wid = ref 0
41 :     fun pr s = (print s; wid := !wid + size s)
42 :     fun nl () = if (!wid > 0) then (print "\n"; wid := 0) else ()
43 :     fun prElem (src, dst) = let
44 :     val s = String.concat [
45 : jhr 3485 " ", SV.uniqueNameOf src, "->", IR.Var.toString dst
46 : jhr 3471 ]
47 :     in
48 :     pr s;
49 :     if (!wid >= 100) then (nl(); pr " ") else ()
50 :     end
51 :     in
52 :     pr prefix; pr " ENV: {"; nl(); pr " ";
53 :     VMap.appi prElem env;
54 :     nl(); pr "}"; nl()
55 :     end
56 :     (* -DEBUG *)
57 :    
58 :     fun lookup env x = (case VMap.find (env, x)
59 :     of SOME x' => x'
60 :     | NONE => raise Fail(concat[
61 : jhr 3508 "no binding for ", SV.uniqueNameOf x, "::",
62 :     SV.kindToString(SV.kindOf x), " in environment"
63 : jhr 3471 ])
64 :     (* end case *))
65 :    
66 :     (* create a new instance of a variable *)
67 : jhr 3485 fun newVar x = IR.Var.new (SV.nameOf x, cvtTy(SV.typeOf x))
68 : jhr 3471
69 : jhr 3506 (* is a Simple AST variable mapped to an IR.global_var? *)
70 :     fun isGlobalVar x = (case SV.kindOf x
71 :     of SV.ConstVar => true
72 :     | SV.InputVar => true
73 :     | SV.GlobalVar => true
74 :     | _ => false
75 :     (* end case *))
76 :    
77 :     (* convert a global and cache the result in a property *)
78 :     local
79 :     fun new x = let
80 : jhr 3837 val (kind, apiTy) = (case SV.kindOf x
81 :     of SV.ConstVar => (IR.ConstVar, NONE)
82 :     | SV.InputVar => (IR.InputVar, SOME(TranslateTy.toAPITy (SV.typeOf x)))
83 :     | SV.GlobalVar => (IR.GlobalVar, NONE)
84 : jhr 3506 | k => raise Fail(concat[
85 :     "global variable ", SV.uniqueNameOf x,
86 :     " has kind ", SV.kindToString k
87 :     ])
88 :     (* end case *))
89 :     in
90 : jhr 3538 IR.GlobalVar.new(
91 : jhr 3837 kind, AnalyzeSimple.updatedGlobal x, SV.nameOf x, cvtTy(SV.typeOf x), apiTy)
92 : jhr 3506 end
93 :     in
94 :     val {getFn = cvtGlobalVar, ...} = SV.newProp new
95 :     end
96 :    
97 : jhr 3471 (* generate fresh SSA variables and add them to the environment *)
98 :     fun freshVars (env, xs) = let
99 :     fun cvtVar (x, (env, xs)) = let
100 :     val x' = newVar x
101 :     in
102 :     (VMap.insert(env, x, x'), x'::xs)
103 :     end
104 :     val (env, xs) = List.foldl cvtVar (env, []) xs
105 :     in
106 :     (env, List.rev xs)
107 :     end
108 :    
109 :     (* a pending-join node tracks the phi nodes needed to join the assignments
110 :     * that flow into the join node.
111 :     *)
112 :     datatype join = JOIN of {
113 :     env : env, (* the environment that was current at the conditional *)
114 :     (* associated with this node. *)
115 :     arity : int ref, (* actual number of predecessors *)
116 : jhr 3476 nd : IR.node, (* the CFG node for this pending join *)
117 :     phiMap : (IR.var * IR.var list) VMap.map ref,
118 : jhr 3471 (* a mapping from Simple AST variables that are assigned *)
119 :     (* to their phi nodes. *)
120 :     predKill : bool array (* killed predecessor edges (because of DIE or STABILIZE *)
121 :     }
122 :    
123 :     (* a stack of pending joins. The first component specifies the path index of the current
124 :     * path to the join.
125 :     *)
126 :     type pending_joins = (int * join) list
127 :    
128 : jhr 3504 (* create a new pending-join node for a conditional *)
129 : jhr 3471 fun newJoin (env, arity) = JOIN{
130 : jhr 3476 env = env, arity = ref arity, nd = IR.Node.mkJOIN [], phiMap = ref VMap.empty,
131 : jhr 3471 predKill = Array.array(arity, false)
132 :     }
133 :    
134 : jhr 3504 (* create a new pending-join node for a loop *)
135 : jhr 3502 fun newForeach (env, x, xs, phiVars) = let
136 : jhr 3509 fun doVar (y, (env', phiMap)) = (case VMap.find(env, y)
137 :     of SOME y' => let
138 :     val y'' = newVar y
139 : jhr 3502 in
140 : jhr 3509 (VMap.insert(env', y, y''), VMap.insert(phiMap, y, (y', [y'', y''])))
141 : jhr 3502 end
142 : jhr 3509 | NONE => raise Fail(concat["variable ", SV.uniqueNameOf y, " is not bound"])
143 : jhr 3502 (* end case *))
144 :     val (env', phiMap) = List.foldl doVar (env, VMap.empty) phiVars
145 :     in
146 :     JOIN{
147 :     env = env',
148 :     arity = ref 2,
149 :     nd = IR.Node.mkFOREACH(x, xs),
150 :     phiMap = ref phiMap,
151 : jhr 3504 predKill = Array.array(2, false)
152 : jhr 3502 }
153 :     end
154 : jhr 3500
155 : jhr 3471 (* record that a path to the top join in the stack has been killed because f DIE or STABILIZE *)
156 :     fun killPath ((i, JOIN{arity, predKill, ...}) :: _) = (
157 :     arity := !arity - 1;
158 :     Array.update (predKill, i, true))
159 :     | killPath _ = ()
160 :    
161 : jhr 3476 (* record an assignment to the IR variable dstVar (corresponding to the Simple AST variable
162 : jhr 3471 * srcVar) in the current pending-join node. The predIndex specifies which path into the
163 :     * JOIN node this assignment occurs on.
164 :     *)
165 :     fun recordAssign ([], _, _) = ()
166 :     | recordAssign ((predIndex, JOIN{env, phiMap, predKill, nd, ...})::_, srcVar, dstVar) = let
167 :     val arity = Array.length predKill (* the original arity before any killPath calls *)
168 :     val m = !phiMap
169 :     in
170 :     case VMap.find (env, srcVar)
171 :     of NONE => () (* local temporary *)
172 :     | SOME dstVar' => (case VMap.find (m, srcVar)
173 :     of NONE => let
174 :     val lhs = newVar srcVar
175 :     val rhs = List.tabulate (arity, fn i => if (i = predIndex) then dstVar else dstVar')
176 :     in
177 :     (*
178 : jhr 3485 print(concat["recordAssign: ", SV.uniqueNameOf srcVar, " --> ", IR.Var.toString lhs,
179 : jhr 3476 " @ ", IR.Node.toString nd, "\n"]);
180 : jhr 3471 *)
181 :     phiMap := VMap.insert (m, srcVar, (lhs, rhs))
182 :     end
183 :     | SOME(lhs, rhs) => let
184 :     fun update (i, l as x::r) = if (i = predIndex)
185 :     then dstVar::r
186 :     else x::update(i+1, r)
187 :     | update _ = raise Fail "invalid predecessor index"
188 :     in
189 :     phiMap := VMap.insert (m, srcVar, (lhs, update(0, rhs)))
190 :     end
191 :     (* end case *))
192 :     (* end case *)
193 :     end
194 :    
195 :     (* complete a pending join operation by filling in the phi nodes from the phi map and
196 :     * updating the environment.
197 :     *)
198 :     fun commitJoin (joinStk, JOIN{env, arity, nd, phiMap, predKill}) = let
199 : jhr 3509 val (preds, phis, mask) = (case IR.Node.kind nd
200 :     of IR.JOIN{preds, phis, mask, ...} => (!preds, phis, mask)
201 :     | IR.FOREACH{pred, bodyExit, phis, mask, ...} => ([!pred, !bodyExit], phis, mask)
202 :     | _ => raise Fail "invalid JOIN node"
203 :     (* end case *))
204 : jhr 3471 (* update the predKill array based on reachability *)
205 :     val _ = let
206 :     fun update (_, []) = ()
207 :     | update (i, nd::nds) = (
208 : jhr 3476 if IR.Node.isReachable nd then ()
209 : jhr 3471 else if Array.sub(predKill, i) then ()
210 :     else (arity := !arity-1; Array.update(predKill, i, true));
211 :     update (i+1, nds))
212 :     in
213 : jhr 3509 update (0, preds)
214 : jhr 3471 end
215 :     (* compute the predecessor mask *)
216 :     val mask' = Array.foldr (op ::) [] predKill
217 :     in
218 :     mask := mask';
219 :     case !arity
220 :     of 0 => env (* all incoming edges are fake *)
221 :     | 1 => let
222 :     (* there is only one path to the join, so we do not need phi nodes, but
223 :     * we still need to propogate assignments to the next join on the stack.
224 :     *)
225 :     val ix = let (* find pred index of this join *)
226 :     fun find i = if Array.sub(predKill, i) then find(i+1) else i
227 :     in
228 :     find 0
229 :     end
230 :     fun doVar (srcVar, (_, xs), env) = let
231 :     val dstVar = List.nth(xs, ix)
232 :     in
233 :     (*
234 : jhr 3485 print(concat["doVar (", SV.uniqueNameOf srcVar, ", ", IR.phiToString phi, ", _) @ ", IR.Node.toString nd, "\n"]);
235 : jhr 3471 *)
236 :     recordAssign (joinStk, srcVar, dstVar);
237 :     VMap.insert (env, srcVar, dstVar)
238 :     end
239 :     val env = VMap.foldli doVar env (!phiMap)
240 :     in
241 :     env
242 :     end
243 :     | nPreds => if (nPreds < Array.length predKill)
244 :     then let
245 :     (* filter out variables that correspond to fake preds from the RHS of a phi *)
246 :     fun filterPhiRHS xs = let
247 :     fun f ([], _, xs') = List.rev xs'
248 :     | f (x::xs, i, xs') = if Array.sub(predKill, i)
249 :     then f (xs, i+1, NONE :: xs')
250 :     else f (xs, i+1, (SOME x) :: xs')
251 :     in
252 :     f (xs, 0, [])
253 :     end
254 :     fun doVar (srcVar, phi as (dstVar, srcVars), (env, phis)) = (
255 :     (*
256 : jhr 3485 print(concat["doVar (", SV.uniqueNameOf srcVar, ", ", IR.phiToString phi, ", _) @ ", IR.Node.toString nd, "\n"]);
257 : jhr 3471 *)
258 :     recordAssign (joinStk, srcVar, dstVar);
259 :     (VMap.insert (env, srcVar, dstVar), (dstVar, filterPhiRHS srcVars) ::phis))
260 :     val (env, phis') = VMap.foldli doVar (env, []) (!phiMap)
261 :     in
262 :     phis := phis';
263 :     env
264 :     end
265 :     else let
266 :     fun doVar (srcVar, phi as (dstVar, xs), (env, phis)) = let
267 :     val xs = List.map SOME xs
268 :     in
269 :     (*
270 : jhr 3485 print(concat["doVar (", SV.uniqueNameOf srcVar, ", ", IR.phiToString phi, ", _) @ ", IR.Node.toString nd, "\n"]);
271 : jhr 3471 *)
272 :     recordAssign (joinStk, srcVar, dstVar);
273 : jhr 3476 IR.Var.setBinding (dstVar, IR.VB_PHI xs);
274 : jhr 3471 (VMap.insert (env, srcVar, dstVar), (dstVar, xs)::phis)
275 :     end
276 :     val (env, phis') = VMap.foldli doVar (env, []) (!phiMap)
277 :     in
278 :     phis := phis';
279 :     env
280 :     end
281 :     (* end case *)
282 :     end
283 :    
284 :     (* expression translation *)
285 :     fun cvtExp (env : env, lhs, exp) = (case exp
286 : jhr 3476 of S.E_Var x => [IR.ASSGN(lhs, IR.VAR(lookup env x))]
287 :     | S.E_Lit lit => [IR.ASSGN(lhs, IR.LIT lit)]
288 : jhr 3485 | S.E_Select(x, fld) => raise Fail "FIXME"
289 : jhr 3471 | S.E_Apply _ => raise Fail "unexpected E_Apply"
290 :     | S.E_Prim(f, tyArgs, args, ty) => let
291 :     val args' = List.map (lookup env) args
292 :     in
293 :     TranslateBasis.translate (lhs, f, tyArgs, args')
294 :     end
295 : jhr 3485 | S.E_Tensor(args, _) => [IR.ASSGN(lhs, IR.CONS(List.map (lookup env) args, IR.Var.ty lhs))]
296 : jhr 3476 | S.E_Seq(args, _) => [IR.ASSGN(lhs, IR.SEQ(List.map (lookup env) args, IR.Var.ty lhs))]
297 : jhr 3719 (* FIXME: use Ein operators to implement tensor (and field!) indexing and slicing *)
298 : jhr 3471 | S.E_Slice(x, indices, ty) => let
299 :     val x = lookup env x
300 : jhr 3797 (* check the indices to the slice. There are two special cases: if all of the indices
301 :     * are NONE, then the result is just the original tensor; and if all of the indices
302 :     * are SOME ix, then the result is scalar so we use TensorIndex.
303 :     *)
304 :     fun chkIndices ([], _, true, idxs) = IR.OP(Op.TensorIndex(IR.Var.ty x, rev idxs), [x])
305 :     | chkIndices ([], true, _, _) = IR.VAR x (* all axes *)
306 :     | chkIndices (NONE :: r, true, _, _) = chkIndices (r, true, false, [])
307 :     | chkIndices (SOME ix :: r, _, true, idxs) = chkIndices (r, false, true, ix::idxs)
308 :     | chkIndices _ = IR.OP(Op.TensorSlice(IR.Var.ty x, indices), [x])
309 : jhr 3471 in
310 : jhr 3797 [IR.ASSGN(lhs, chkIndices (indices, true, true, []))]
311 : jhr 3471 end
312 :     | S.E_Coerce{srcTy, dstTy, x} => (case (srcTy, dstTy)
313 :     of (Ty.T_Int, Ty.T_Tensor _) =>
314 : jhr 3476 [IR.ASSGN(lhs, IR.OP(Op.IntToReal, [lookup env x]))]
315 : jhr 3485 | (Ty.T_Sequence(ty, SOME n), Ty.T_Sequence(_, NONE)) =>
316 : jhr 3476 [IR.ASSGN(lhs, IR.OP(Op.MkDynamic(cvtTy ty, n), [lookup env x]))]
317 : jhr 3471 | (Ty.T_Field _, Ty.T_Field _) =>
318 :     (* change in continuity is a no-op *)
319 : jhr 3476 [IR.ASSGN(lhs, IR.VAR(lookup env x))]
320 : jhr 3471 | _ => raise Fail(concat[
321 :     "unsupported type coercion: ", Ty.toString srcTy,
322 :     " ==> ", Ty.toString dstTy
323 :     ])
324 :     (* end case *))
325 : jhr 3476 | S.E_LoadSeq(ty, nrrd) => [IR.ASSGN(lhs, IR.OP(Op.LoadSeq(cvtTy ty, nrrd), []))]
326 :     | S.E_LoadImage(_, nrrd, info) => [IR.ASSGN(lhs, IR.OP(Op.LoadImage(DstTy.ImageTy info, nrrd), []))]
327 : jhr 3471 (* end case *))
328 :    
329 :     (* add nodes to save the strand state, followed by an exit node *)
330 :     fun saveStrandState (env, (srcState, dstState), exit) = let
331 :     val stateOut = List.map (lookup env) srcState
332 : jhr 3476 fun save (x, x', cfg) = IR.CFG.appendNode (cfg, IR.Node.mkSAVE(x, x'))
333 : jhr 3471 in
334 : jhr 3476 IR.CFG.appendNode (
335 :     ListPair.foldlEq save IR.CFG.empty (dstState, stateOut),
336 : jhr 3471 exit)
337 :     end
338 :     (*DEBUG*)handle ex => raise ex
339 :    
340 : jhr 3501 fun cvtBlock (state, env : env, joinStk, blk as S.Block{code, ...}) = let
341 :     val _ = AnalyzeSimple.analyze blk
342 : jhr 3471 fun cvt (env : env, cfg, []) = (cfg, env)
343 :     | cvt (env, cfg, stm::stms) = (case stm
344 : jhr 3485 of S.S_Var(x, NONE) => let
345 : jhr 3471 val x' = newVar x
346 :     in
347 :     cvt (VMap.insert (env, x, x'), cfg, stms)
348 :     end
349 : jhr 3485 | S.S_Var(x, SOME e) => let
350 :     val x' = newVar x
351 :     val assigns = cvtExp (env, x', e)
352 :     in
353 :     recordAssign (joinStk, x, x');
354 :     cvt (
355 :     VMap.insert(env, x, x'),
356 :     IR.CFG.concat(cfg, IR.CFG.mkBlock assigns),
357 :     stms)
358 :     end
359 : jhr 3471 | S.S_Assign(lhs, rhs) => let
360 : jhr 3506 val lhs' = newVar lhs
361 :     val assigns = cvtExp (env, lhs', rhs)
362 :     in
363 :     (* check for assignment to global (i.e., constant, input, or other global) *)
364 : jhr 3550 (* FIXME: for the global initialization block, we should batch up the saving of globals until
365 :     * the end so that we can properly set the bindings (i.e., so that we avoid conflicts between
366 :     * branches of an if statement).
367 :     *)
368 : jhr 3506 if isGlobalVar lhs
369 :     then cvt (
370 :     VMap.insert(env, lhs, lhs'),
371 : jhr 3618 IR.CFG.concat(
372 :     cfg,
373 :     IR.CFG.mkBlock(assigns @ [IR.GASSGN(cvtGlobalVar lhs, lhs')])),
374 : jhr 3506 stms)
375 :     else (
376 :     recordAssign (joinStk, lhs, lhs');
377 :     cvt (
378 :     VMap.insert(env, lhs, lhs'),
379 :     IR.CFG.concat(cfg, IR.CFG.mkBlock assigns),
380 :     stms))
381 :     end
382 : jhr 3471 | S.S_IfThenElse(x, b0, b1) => let
383 :     val x' = lookup env x
384 :     val join as JOIN{nd=joinNd, ...} = newJoin (env, 2)
385 :     val (cfg0, _) = cvtBlock (state, env, (0, join)::joinStk, b0)
386 :     val (cfg1, _) = cvtBlock (state, env, (1, join)::joinStk, b1)
387 : jhr 3476 val cond = IR.Node.mkCOND x'
388 :     fun addEdgeToJoin nd = (case IR.Node.kind nd
389 :     of IR.EXIT{succ, ...} => (
390 : jhr 3471 succ := SOME joinNd;
391 : jhr 3476 IR.Node.setPred (joinNd, nd)) (* will be converted to fake later *)
392 :     | _ => IR.Node.addEdge(nd, joinNd)
393 : jhr 3471 (* end case *))
394 :     (* package the CFG the represents the conditional (cond, two blocks, and join) *)
395 :     (* QUESTION: under what conditions do we insert an UNREACHABLE exit node? Is it when there
396 :     * are no real predecessors to the join and the join stack is empty?
397 :     *)
398 :     val condCFG = (
399 : jhr 3476 if IR.CFG.isEmpty cfg0
400 : jhr 3471 then (
401 : jhr 3476 IR.Node.setTrueBranch (cond, joinNd);
402 :     IR.Node.setPred (joinNd, cond))
403 : jhr 3471 else (
404 : jhr 3476 IR.Node.setTrueBranch (cond, IR.CFG.entry cfg0);
405 :     IR.Node.setPred (IR.CFG.entry cfg0, cond);
406 :     addEdgeToJoin (IR.CFG.exit cfg0));
407 :     if IR.CFG.isEmpty cfg1
408 : jhr 3471 then (
409 : jhr 3476 IR.Node.setFalseBranch (cond, joinNd);
410 :     IR.Node.setPred (joinNd, cond))
411 : jhr 3471 else (
412 : jhr 3476 IR.Node.setFalseBranch (cond, IR.CFG.entry cfg1);
413 :     IR.Node.setPred (IR.CFG.entry cfg1, cond);
414 :     addEdgeToJoin (IR.CFG.exit cfg1));
415 :     IR.CFG{entry = cond, exit = joinNd})
416 : jhr 3471 val env = commitJoin (joinStk, join)
417 :     in
418 : jhr 3476 cvt (env, IR.CFG.concat (cfg, condCFG), stms)
419 : jhr 3471 end
420 : jhr 3500 | S.S_Foreach(x, xs, b) => let
421 :     val x' = newVar x
422 :     val xs' = lookup env xs
423 : jhr 3502 (* For any local variable y that is both live on exit of the block b and
424 :     * assigned to in b, we will need a phi node for y.
425 : jhr 3501 *)
426 : jhr 3505 val phiVars = VSet.listItems(
427 :     VSet.intersection(AnalyzeSimple.assignedVars b, AnalyzeSimple.liveOut b))
428 : jhr 3502 val join as JOIN{env, nd=foreachNd, ...} = newForeach (env, x', xs', phiVars)
429 : jhr 3509 val (body, _) = cvtBlock (state, VMap.insert(env, x, x'), (1, join)::joinStk, b)
430 : jhr 3754 val body = IR.CFG.appendNode (body, IR.Node.mkNEXT())
431 : jhr 3502 val env = commitJoin (joinStk, join)
432 : jhr 3500 in
433 : jhr 3501 (* link in CFG edges *)
434 : jhr 3502 IR.Node.setBodyEntry (foreachNd, IR.CFG.entry body); (* loop header to body *)
435 :     IR.Node.setPred (IR.CFG.entry body, foreachNd); (* back edge *)
436 : jhr 3837 IR.Node.setSucc (IR.CFG.exit body, foreachNd);
437 : jhr 3502 IR.Node.setBodyExit (foreachNd, IR.CFG.exit body);
438 :     (* process the rest of the block *)
439 :     cvt (env, IR.CFG.concat (cfg, IR.CFG{entry=foreachNd, exit=foreachNd}), stms)
440 : jhr 3500 end
441 : jhr 3471 | S.S_New(strandId, args) => let
442 : jhr 3476 val nd = IR.Node.mkNEW{
443 : jhr 3471 strand = strandId,
444 :     args = List.map (lookup env) args
445 :     }
446 :     in
447 : jhr 3476 cvt (env, IR.CFG.appendNode (cfg, nd), stms)
448 : jhr 3471 end
449 :     | S.S_Continue => (
450 :     killPath joinStk;
451 : jhr 3476 (IR.CFG.concat (cfg, saveStrandState (env, state, IR.Node.mkACTIVE())), env))
452 : jhr 3471 | S.S_Die => (
453 :     killPath joinStk;
454 : jhr 3476 (IR.CFG.appendNode (cfg, IR.Node.mkDIE ()), env))
455 : jhr 3471 | S.S_Stabilize => (
456 :     killPath joinStk;
457 : jhr 3476 (IR.CFG.concat (cfg, saveStrandState (env, state, IR.Node.mkSTABILIZE())), env))
458 : jhr 3471 | S.S_Return _ => raise Fail "unexpected return"
459 :     | S.S_Print args => let
460 :     val args = List.map (lookup env) args
461 : jhr 3476 val nd = IR.Node.mkMASSIGN([], Op.Print(List.map IR.Var.ty args), args)
462 : jhr 3471 in
463 : jhr 3476 cvt (env, IR.CFG.appendNode (cfg, nd), stms)
464 : jhr 3471 end
465 : jhr 3505 | S.S_MapReduce{results, reductions, body, args, source} => raise Fail "FIXME"
466 : jhr 3471 (* end case *))
467 :     in
468 : jhr 3505 cvt (env, IR.CFG.empty, code)
469 : jhr 3471 end
470 :     (*DEBUG*)handle ex => raise ex
471 :    
472 : jhr 3506 (* a function for generating a block of assignments to load globals *)
473 :     fun loadGlobs (globs : SV.t list) env = let
474 :     fun load (env, [], stms) = (IR.CFG.mkBlock(List.rev stms), env)
475 :     | load (env, x::globs, stms) = let
476 :     val x' = newVar x
477 :     val stm = IR.ASSGN(x', IR.GLOBAL(cvtGlobalVar x))
478 :     val env = VMap.insert (env, x, x')
479 :     in
480 :     load (env, globs, stm::stms)
481 :     end
482 :     in
483 :     load (env, globs, [])
484 :     end
485 :    
486 : jhr 3505 fun cvtMethod (loadGlobals, env, isStabilize, state, svars, blk) = let
487 : jhr 3471 (* load the globals into fresh variables *)
488 :     val (loadGlobsCFG, env) = loadGlobals env
489 :     (* load the state into fresh variables *)
490 :     val (env, loadCFG) = let
491 :     (* allocate shadow variables for the state variables *)
492 :     val (env, stateIn) = freshVars (env, state)
493 : jhr 3476 fun load (x, x') = IR.ASSGN(x, IR.STATE x')
494 :     val cfg = IR.CFG.mkBlock (ListPair.map load (stateIn, svars))
495 : jhr 3471 in
496 : jhr 3476 (env, IR.CFG.concat(loadGlobsCFG, cfg))
497 : jhr 3471 end
498 :     (* convert the body of the method *)
499 :     val (cfg, env) = cvtBlock ((state, svars), env, [], blk)
500 :     (* add the entry/exit nodes *)
501 : jhr 3476 val entry = IR.Node.mkENTRY ()
502 :     val loadCFG = IR.CFG.prependNode (entry, loadCFG)
503 : jhr 3505 val exit = if isStabilize
504 :     then IR.Node.mkRETURN()
505 :     else IR.Node.mkACTIVE()
506 : jhr 3476 val body = IR.CFG.concat (loadCFG, cfg)
507 : jhr 3471 (*DEBUG**val _ = prEnv (StrandUtil.nameToString name, env);*)
508 :     (* FIXME: the following code doesn't work properly *)
509 : jhr 3476 val body = if IR.Node.hasSucc(IR.CFG.exit body)
510 :     then IR.CFG.concat (body, saveStrandState (env, (state, svars), exit))
511 :     else IR.CFG{entry = IR.CFG.entry body, exit = exit}
512 : jhr 3471 in
513 : jhr 3505 body
514 : jhr 3471 end
515 : jhr 3505 (*DEBUG*)handle ex => (print "error in cvtMethod\n"; raise ex)
516 : jhr 3471
517 : jhr 3506 (* convert global code *)
518 :     fun cvtGlobalBlock loadGlobals block = let
519 :     (* load the globals into fresh variables *)
520 :     val (loadCFG, env) = loadGlobals VMap.empty
521 :     (* convert the code *)
522 :     val (cfg, _) = cvtBlock (([], []), env, [], block)
523 : jhr 3509 val cfg = IR.CFG.concat (loadCFG, cfg)
524 :     val cfg = IR.CFG.prependNode (IR.Node.mkENTRY(), cfg)
525 : jhr 3837 val cfg = IR.CFG.appendNode (cfg, IR.Node.mkRETURN())
526 : jhr 3505 in
527 : jhr 3509 cfg
528 : jhr 3505 end
529 : jhr 3471
530 : jhr 3505 (* convert the initial strand creation code *)
531 : jhr 3506 fun cvtCreate (loadGlobals, S.Create{dim, code}) = IR.Create{
532 :     dim = dim,
533 :     code = cvtGlobalBlock loadGlobals code
534 :     }
535 : jhr 3505 (*DEBUG*)handle ex => raise ex
536 :    
537 : jhr 3485 fun translate prog = let
538 :     val S.Program{
539 :     props, consts, inputs, constInit, globals, funcs, init, strand, create, update
540 :     } = prog
541 : jhr 3506 val consts' = List.map cvtGlobalVar consts
542 :     val inputs' = List.map (Inputs.map cvtGlobalVar) inputs
543 :     val inputs = List.map Inputs.varOf inputs
544 : jhr 3525 val constInit = let
545 :     val (cfg, _) = cvtBlock (([], []), VMap.empty, [], constInit)
546 :     val cfg = IR.CFG.prependNode (IR.Node.mkENTRY(), cfg)
547 : jhr 3837 val cfg = IR.CFG.appendNode (cfg, IR.Node.mkRETURN())
548 : jhr 3525 in
549 :     cfg
550 :     end
551 : jhr 3506 val globals' = List.map cvtGlobalVar globals
552 : jhr 3471 (* create the global initialization code *)
553 :     val globalInit = let
554 :     (* we start by loading the input globals, since they may be needed to compute the
555 :     * other globals
556 :     *)
557 : jhr 3506 val (loadBlk, env) = loadGlobs (consts @ inputs) VMap.empty
558 : jhr 3505 val (globBlk, env) = cvtBlock (([], []), env, [], init)
559 : jhr 3506 val cfg = IR.CFG.prependNode (IR.Node.mkENTRY(), loadBlk)
560 : jhr 3476 val cfg = IR.CFG.concat(cfg, globBlk)
561 : jhr 3837 val cfg = IR.CFG.appendNode (cfg, IR.Node.mkRETURN())
562 : jhr 3471 in
563 :     cfg
564 :     end
565 : jhr 3506 val loadGlobals = loadGlobs (consts @ inputs @ globals)
566 : jhr 3505 fun cvtStrand (S.Strand{name, params, state, stateInit, initM, updateM, stabilizeM}) = let
567 : jhr 3471 (* extend the global environment with the strand's parameters *)
568 :     val (env, params) = let
569 :     fun cvtParam (x, (env, xs)) = let
570 :     val x' = newVar x
571 :     in
572 :     (VMap.insert(env, x, x'), x'::xs)
573 :     end
574 :     val (env, params) = List.foldl cvtParam (VMap.empty, []) params
575 :     in
576 :     (env, List.rev params)
577 :     end
578 :     (* create the state variables *)
579 :     val svars = let
580 : jhr 3476 fun newSVar x = IR.StateVar.new (
581 : jhr 3837 SV.nameOf x,
582 :     cvtTy(SV.typeOf x),
583 :     if (SV.kindOf x = SV.StrandOutputVar)
584 :     then SOME(TranslateTy.toAPITy (SV.typeOf x))
585 :     else NONE)
586 : jhr 3471 in
587 :     List.map newSVar state
588 :     end
589 :     (* convert the state initialization code *)
590 :     val (stateInit, env) = let
591 :     (* load globals into local variables *)
592 :     val (loadGlobsCFG, env) = loadGlobals env
593 :     val (cfg, env) = cvtBlock (([], []), env, [], stateInit)
594 : jhr 3476 val cfg = IR.CFG.concat(loadGlobsCFG, cfg)
595 :     val cfg = IR.CFG.prependNode (IR.Node.mkENTRY(), cfg)
596 :     val cfg = IR.CFG.concat (cfg,
597 : jhr 3505 saveStrandState (env, (state, svars), IR.Node.mkRETURN()))
598 : jhr 3471 in
599 :     (cfg, env)
600 :     end
601 : jhr 3505 fun cvtMeth isStabilize blk =
602 :     cvtMethod (loadGlobals, env, isStabilize, state, svars, blk)
603 : jhr 3471 in
604 : jhr 3476 IR.Strand{
605 : jhr 3471 name = name,
606 :     params = params,
607 :     state = svars,
608 :     stateInit = stateInit,
609 : jhr 3505 initM = Option.map (cvtMeth false) initM,
610 :     updateM = cvtMeth false updateM,
611 :     stabilizeM = Option.map (cvtMeth true) stabilizeM
612 : jhr 3471 }
613 :     end
614 : jhr 3506 val create = cvtCreate (loadGlobals, create)
615 : jhr 3538 val _ = AnalyzeSimple.analyzeGlobalUpdate update
616 : jhr 3476 val prog = IR.Program{
617 : jhr 3471 props = props,
618 : jhr 3506 consts = consts',
619 :     inputs = inputs',
620 :     globals = globals',
621 :     constInit = constInit,
622 : jhr 3471 globalInit = globalInit,
623 : jhr 3505 strand = cvtStrand strand,
624 :     create = create,
625 : jhr 3506 update = Option.map (cvtGlobalBlock loadGlobals) update
626 : jhr 3505 }
627 : jhr 3471 in
628 :     Census.init prog;
629 :     prog
630 :     end
631 :    
632 :     end

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