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

SCM Repository

[diderot] Annotation of /branches/vis15/src/compiler/cfg-ir/ssa-fn.sml
ViewVC logotype

Annotation of /branches/vis15/src/compiler/cfg-ir/ssa-fn.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3754 - (view) (download)

1 : jhr 3470 (* ssa-fn.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 3475 * The SSAFn functor is used to generate the High, Med, and Low IRs in the Diderot
9 :     * compiler. These IRs have the same program and control-flow structure, but differ
10 : jhr 3470 * in their types and operators.
11 :     *)
12 :    
13 :     functor SSAFn (
14 :    
15 : jhr 3508 val irName : string
16 : jhr 3470
17 :     structure Ty : SSA_TYPES
18 :     structure Op : OPERATORS where type ty = Ty.ty
19 :    
20 :     ) : SSA = struct
21 :    
22 :     structure Ty = Ty
23 :     structure Op = Op
24 :    
25 : jhr 3508 val irName = irName
26 : jhr 3470
27 :     (***** CFG *****)
28 :    
29 : jhr 3527 datatype global_kind = datatype GlobalVarKind.t
30 :    
31 : jhr 3470 datatype cfg = CFG of {
32 :     entry : node, (* the entry node of a graph; not necessarily an ENTRY node *)
33 :     exit : node (* the exit node of a graph; not necessarily an EXIT node. *)
34 :     }
35 :    
36 :     and node = ND of {
37 :     id : Stamp.stamp,
38 :     props : PropList.holder,
39 :     kind : node_kind
40 :     }
41 :    
42 :     and node_kind
43 :     = NULL
44 :     | ENTRY of {
45 :     succ : node ref
46 :     }
47 :     | JOIN of {
48 :     preds : node list ref, (* includes fake control-flow edges *)
49 :     mask : bool list ref, (* true for incoming fake edges *)
50 :     phis : phi list ref, (* data-flow joins corresponding to the edges in preds *)
51 :     succ : node ref
52 :     }
53 :     | COND of {
54 :     pred : node ref,
55 : jhr 3536 cond : var ref, (* the variable being tested (we use a ref to allow rewriting) *)
56 : jhr 3470 trueBranch : node ref,
57 :     falseBranch : node ref
58 :     }
59 : jhr 3473 | FOREACH of { (* foreach-loop; this node combines aspects of the COND
60 :     * and JOIN nodes. *)
61 : jhr 3502 pred : node ref, (* the predecessor *)
62 : jhr 3473 phis : phi list ref, (* phi nodes (as in JOIN) *)
63 :     mask : bool list ref, (* true for incoming fake edges *)
64 :     var : var, (* the loop variable *)
65 : jhr 3536 src : var ref, (* the source of values being iterated over *)
66 : jhr 3502 bodyEntry : node ref, (* the loop body entry node *)
67 :     bodyExit : node ref, (* the loop body exit node *)
68 : jhr 3473 succ : node ref (* the loop-exit edge *)
69 :     }
70 : jhr 3754 | NEXT of { (* a loop-body exit node *)
71 :     pred : node ref, (* the predecessor *)
72 :     succ : node ref (* the FOREACH node *)
73 :     }
74 : jhr 3470 | COM of { (* comment *)
75 :     pred : node ref,
76 :     text : string list,
77 :     succ : node ref
78 :     }
79 :     | ASSIGN of { (* local-variable assignment *)
80 :     pred : node ref,
81 :     stm : assign,
82 :     succ : node ref
83 :     }
84 :     | MASSIGN of { (* multi-assignment *)
85 :     pred : node ref,
86 :     stm : massign,
87 :     succ : node ref
88 :     }
89 :     | GASSIGN of { (* global variable assignment *)
90 :     pred: node ref,
91 :     lhs : global_var,
92 :     rhs : var,
93 :     succ : node ref
94 :     }
95 :     | NEW of { (* create new strand instance *)
96 :     pred : node ref,
97 :     strand : Atom.atom,
98 :     args : var list,
99 :     succ : node ref
100 :     }
101 :     | SAVE of { (* save state variable *)
102 :     pred: node ref,
103 :     lhs : state_var,
104 :     rhs : var,
105 :     succ : node ref
106 :     }
107 :     | EXIT of { (* includes die and stabilize *)
108 :     pred : node ref,
109 :     kind : ExitKind.kind, (* kind of exit node *)
110 :     succ : node option ref (* optional fake control-flow edge for when the EXIT is *)
111 :     (* not the CFG exit node *)
112 :     }
113 :    
114 :     and rhs
115 :     = GLOBAL of global_var (* read global variable *)
116 :     | STATE of state_var (* read strand state variable *)
117 :     | VAR of var
118 :     | LIT of Literal.t
119 :     | OP of Op.rator * var list
120 :     | CONS of var list * Ty.ty (* tensor-value construction *)
121 :     | SEQ of var list * Ty.ty (* sequence-value construction *)
122 :     | EINAPP of Ein.ein * var list
123 :    
124 :     and var = V of {
125 :     name : string, (* name *)
126 :     id : Stamp.stamp, (* unique ID *)
127 :     ty : Ty.ty, (* type *)
128 :     bind : var_bind ref, (* binding *)
129 :     useCnt : int ref, (* count of uses *)
130 :     props : PropList.holder
131 :     }
132 :    
133 :     and var_bind
134 :     = VB_NONE
135 :     | VB_RHS of rhs (* defined by an assignment (includes globals and state variables) *)
136 :     | VB_MULTIOP of int * Op.rator * var list
137 :     (* n'th result of operator in multi-assignment *)
138 :     | VB_PHI of var option list (* defined by a phi node *)
139 :     | VB_PARAM (* parameter to a strand *)
140 : jhr 3522 | VB_ITER (* bound in a foreach loop *)
141 : jhr 3470
142 :     (***** global variables *****)
143 :     and global_var = GV of {
144 :     id : Stamp.stamp, (* variable's unique ID *)
145 :     name : string, (* variable's name *)
146 :     ty : Ty.ty, (* variable's type *)
147 : jhr 3506 kind : global_kind, (* the variable kind *)
148 : jhr 3538 updated : bool, (* true if the global variable is modified in the *)
149 :     (* global-update code *)
150 : jhr 3550 binding : var option ref, (* the local variable used to define this global variable
151 :     * (i.e., in a GASSIGN node). This field will be NONE
152 :     * for mutable variables.
153 :     *)
154 : jhr 3517 useCnt : int ref, (* count of uses *)
155 : jhr 3470 props : PropList.holder
156 :     }
157 :    
158 :     (***** strand state variables *****)
159 :     and state_var = SV of {
160 :     id : Stamp.stamp, (* variable's unique ID *)
161 :     name : string, (* variable's name *)
162 :     ty : Ty.ty, (* variable's type *)
163 :     output : bool, (* true for output variables *)
164 :     props : PropList.holder
165 :     }
166 :    
167 :     withtype assign = (var * rhs)
168 :     and massign = (var list * Op.rator * var list)
169 :     and phi = (var * var option list) (* NONE for fake edges *)
170 :    
171 :     datatype assignment
172 :     = ASSGN of assign
173 :     | MASSGN of massign
174 :     | GASSGN of (global_var * var)
175 :     | SAV of (state_var * var)
176 :    
177 :     (***** Program representation *****)
178 :    
179 : jhr 3505 type input = global_var Inputs.input
180 :    
181 : jhr 3470 datatype program = Program of {
182 :     props : Properties.t list,
183 : jhr 3485 consts : global_var list, (* large constant variables *)
184 : jhr 3505 inputs : input list, (* global input variables *)
185 :     constInit : cfg, (* code that initializes constants and inputs *)
186 : jhr 3485 globals : global_var list, (* other global variables *)
187 : jhr 3470 globalInit : cfg, (* CFG to initialize other globals (if any) *)
188 : jhr 3485 strand : strand, (* the strand definition *)
189 :     create : create, (* initial strand creation *)
190 :     update : cfg option (* optional update code. *)
191 : jhr 3470 }
192 :    
193 :     and strand = Strand of {
194 :     name : Atom.atom,
195 :     params : var list,
196 :     state : state_var list,
197 :     stateInit : cfg,
198 : jhr 3485 initM : cfg option,
199 :     updateM : cfg,
200 :     stabilizeM : cfg option
201 : jhr 3470 }
202 :    
203 : jhr 3485 and create = Create of {
204 :     dim : int option, (* grid dimension; NONE for collections *)
205 :     code : cfg (* the loop nest for creating the strands *)
206 : jhr 3470 }
207 :    
208 :     structure GlobalVar =
209 :     struct
210 : jhr 3538 fun new (kind, isUpdated, name, ty) = GV{
211 : jhr 3470 id = Stamp.new(),
212 :     name = name,
213 :     ty = ty,
214 : jhr 3506 kind = kind,
215 : jhr 3538 updated = isUpdated,
216 : jhr 3550 binding = ref NONE,
217 : jhr 3517 useCnt = ref 0,
218 : jhr 3470 props = PropList.newHolder()
219 :     }
220 :     fun name (GV{name, ...}) = name
221 :     fun uniqueName (GV{id, name, ...}) = name ^ Stamp.toString id
222 : jhr 3506 fun kind (GV{kind, ...}) = kind
223 : jhr 3538 fun isUpdated (GV{updated, ...}) = updated
224 : jhr 3550 fun bindingOf (GV{binding, ...}) = !binding
225 :     fun setBinding (GV{binding, ...}, x) = (binding := SOME x)
226 : jhr 3470 fun ty (GV{ty, ...}) = ty
227 : jhr 3506 fun isInput (GV{kind=InputVar, ...}) = true
228 :     | isInput _ = false
229 : jhr 3517 fun useCount (GV{useCnt, ...}) = !useCnt
230 : jhr 3470 fun same (GV{id=a, ...}, GV{id=b, ...}) = Stamp.same(a, b)
231 :     fun compare (GV{id=a, ...}, GV{id=b, ...}) = Stamp.compare(a, b)
232 :     fun hash (GV{id, ...}) = Stamp.hash id
233 :     fun toString (GV{id, name, ...}) = concat["globals.", name, Stamp.toString id]
234 :     (* properties *)
235 :     fun newProp initFn = PropList.newProp (fn (GV{props, ...}) => props, initFn)
236 :     fun newFlag () = PropList.newFlag (fn (GV{props, ...}) => props)
237 :     (* collections *)
238 :     local
239 :     structure V =
240 :     struct
241 :     type ord_key = global_var
242 :     val compare = compare
243 :     end
244 :     in
245 :     structure Map = RedBlackMapFn (V)
246 :     structure Set = RedBlackSetFn (V)
247 :     end
248 :     structure Tbl = HashTableFn (
249 :     struct
250 :     type hash_key = global_var
251 :     val hashVal = hash
252 :     val sameKey = same
253 :     end)
254 :     end
255 :    
256 :     structure StateVar =
257 :     struct
258 :     fun new (isOut, name, ty) = SV{
259 :     id = Stamp.new(),
260 :     name = name,
261 :     ty = ty,
262 :     output = isOut,
263 :     props = PropList.newHolder()
264 :     }
265 :     fun name (SV{name, ...}) = name
266 :     fun ty (SV{ty, ...}) = ty
267 :     fun isOutput (SV{output, ...}) = output
268 :     fun same (SV{id=a, ...}, SV{id=b, ...}) = Stamp.same(a, b)
269 :     fun compare (SV{id=a, ...}, SV{id=b, ...}) = Stamp.compare(a, b)
270 :     fun hash (SV{id, ...}) = Stamp.hash id
271 :     fun toString (SV{name, ...}) = "self." ^ name
272 :     (* properties *)
273 :     fun newProp initFn = PropList.newProp (fn (SV{props, ...}) => props, initFn)
274 :     fun newFlag () = PropList.newFlag (fn (SV{props, ...}) => props)
275 :     (* collections *)
276 :     local
277 :     structure V =
278 :     struct
279 :     type ord_key = state_var
280 :     val compare = compare
281 :     end
282 :     in
283 :     structure Map = RedBlackMapFn (V)
284 :     structure Set = RedBlackSetFn (V)
285 :     end
286 :     structure Tbl = HashTableFn (
287 :     struct
288 :     type hash_key = state_var
289 :     val hashVal = hash
290 :     val sameKey = same
291 :     end)
292 :     end
293 :    
294 :     structure Var =
295 :     struct
296 :     fun new (name, ty) = V{
297 :     name = name,
298 :     id = Stamp.new(),
299 :     ty = ty,
300 :     bind = ref VB_NONE,
301 :     useCnt = ref 0,
302 :     props = PropList.newHolder()
303 :     }
304 :     fun copy (V{name, ty, ...}) = new (name, ty)
305 :     fun name (V{name, ...}) = name
306 :     fun ty (V{ty, ...}) = ty
307 :     fun binding (V{bind, ...}) = !bind
308 :     fun setBinding (V{bind, ...}, vb) = bind := vb
309 :     fun useCount (V{useCnt, ...}) = !useCnt
310 :     fun same (V{id=a, ...}, V{id=b, ...}) = Stamp.same(a, b)
311 :     fun compare (V{id=a, ...}, V{id=b, ...}) = Stamp.compare(a, b)
312 :     fun hash (V{id, ...}) = Stamp.hash id
313 :     fun toString (V{name, id, ...}) = name ^ Stamp.toString id
314 : jhr 3586 fun getDef x = (case binding x
315 :     of VB_RHS rhs => (case rhs
316 : jhr 3613 of GLOBAL gv => if GlobalVar.isInput gv
317 :     then rhs (* inputs could be different at runtime! *)
318 :     else (case GlobalVar.bindingOf gv
319 :     of SOME x => getDef x
320 :     | NONE => rhs
321 :     (* end case *))
322 : jhr 3586 | VAR x => getDef x
323 :     | _ => rhs
324 :     (* end case *))
325 :     | _ => VAR x
326 :     (* end case *))
327 : jhr 3470 (* properties *)
328 :     fun newProp initFn = PropList.newProp (fn (V{props, ...}) => props, initFn)
329 :     fun newFlag () = PropList.newFlag (fn (V{props, ...}) => props)
330 :     (* collections *)
331 :     local
332 :     structure V =
333 :     struct
334 :     type ord_key = var
335 :     val compare = compare
336 :     end
337 :     in
338 :     structure Map = RedBlackMapFn (V)
339 :     structure Set = RedBlackSetFn (V)
340 :     end
341 :     structure Tbl = HashTableFn (
342 :     struct
343 :     type hash_key = var
344 :     val hashVal = hash
345 :     val sameKey = same
346 :     end)
347 :     end
348 :    
349 :     structure Node =
350 :     struct
351 :     fun id (ND{id, ...}) = id
352 :     fun kind (ND{kind, ...}) = kind
353 :     fun same (ND{id=a, ...}, ND{id=b, ...}) = Stamp.same(a, b)
354 :     fun compare (ND{id=a, ...}, ND{id=b, ...}) = Stamp.compare(a, b)
355 :     fun hash (ND{id, ...}) = Stamp.hash id
356 :     fun toString (ND{id, kind, ...}) = let
357 :     val tag = (case kind
358 :     of NULL => "NULL"
359 :     | ENTRY _ => "ENTRY"
360 :     | JOIN _ => "JOIN"
361 :     | COND _ => "COND"
362 : jhr 3473 | FOREACH _ => "FOREACH"
363 : jhr 3754 | NEXT _ => "NEXT"
364 : jhr 3470 | COM _ => "COM"
365 :     | ASSIGN _ => "ASSIGN"
366 :     | MASSIGN _ => "MASSIGN"
367 :     | GASSIGN _ => "GASSIGN"
368 :     | NEW _ => "NEW"
369 :     | SAVE _ => "SAVE"
370 :     | EXIT{kind, ...} => ExitKind.toString kind
371 :     (* end case *))
372 :     in
373 :     tag ^ Stamp.toString id
374 :     end
375 :     fun new kind = ND{id = Stamp.new(), props = PropList.newHolder(), kind = kind}
376 :     (* variable defs and uses *)
377 :     fun uses (ND{kind, ...}) = (case kind
378 :     of JOIN{phis, ...} => let
379 :     fun add ([], ys) = ys
380 :     | add (SOME x :: xs, ys) = add(xs, x::ys)
381 :     | add (NONE :: xs, ys) = add(xs, ys)
382 :     in
383 :     List.foldr (fn ((_, xs), ys) => add(xs, ys)) [] (!phis)
384 :     end
385 : jhr 3536 | COND{cond, ...} => [!cond]
386 : jhr 3473 | FOREACH{src, phis, ...} => let
387 :     fun add ([], ys) = ys
388 :     | add (SOME x :: xs, ys) = add(xs, x::ys)
389 :     | add (NONE :: xs, ys) = add(xs, ys)
390 :     in
391 : jhr 3536 List.foldr (fn ((_, xs), ys) => add(xs, ys)) [!src] (!phis)
392 : jhr 3473 end
393 : jhr 3754 | NEXT _ => []
394 : jhr 3470 | ASSIGN{stm=(y, rhs), ...} => (case rhs
395 :     of GLOBAL _ => []
396 :     | STATE _ => []
397 :     | VAR x => [x]
398 :     | LIT _ => []
399 :     | OP(_, args) => args
400 :     | CONS(args, _) => args
401 :     | SEQ(args, _) => args
402 :     | EINAPP(_, args) => args
403 :     (* end case *))
404 :     | MASSIGN{stm=(_, _, args), ...} => args
405 :     | GASSIGN{rhs, ...} => [rhs]
406 :     | NEW{args, ...} => args
407 :     | SAVE{rhs, ...} => [rhs]
408 :     | _ => []
409 :     (* end case *))
410 :     fun defs (ND{kind, ...}) = (case kind
411 :     of JOIN{phis, ...} => List.map #1 (!phis)
412 : jhr 3473 | FOREACH{var, phis, ...} => var :: List.map #1 (!phis)
413 : jhr 3470 | ASSIGN{stm=(y, _), ...} => [y]
414 :     | MASSIGN{stm=(ys, _, _), ...} => ys
415 :     | _ => []
416 :     (* end case *))
417 :     val dummy = new NULL
418 :     fun mkENTRY () = new (ENTRY{succ = ref dummy})
419 :     fun mkJOIN phis = new (JOIN{preds = ref [], mask = ref [], phis = ref phis, succ = ref dummy})
420 :     fun mkCOND cond = new (COND{
421 : jhr 3536 pred = ref dummy, cond = ref cond,
422 : jhr 3470 trueBranch = ref dummy, falseBranch = ref dummy
423 :     })
424 : jhr 3522 fun mkFOREACH (var, src) = (
425 :     Var.setBinding (var, VB_ITER);
426 :     new (FOREACH{
427 :     pred = ref dummy,
428 :     phis = ref [], mask = ref [],
429 : jhr 3536 var = var, src = ref src,
430 : jhr 3522 bodyEntry = ref dummy,
431 :     bodyExit = ref dummy,
432 :     succ = ref dummy
433 :     }))
434 : jhr 3754 fun mkNEXT () = new(NEXT{pred = ref dummy, succ = ref dummy})
435 : jhr 3470 fun mkCOM text = new (COM{pred = ref dummy, text = text, succ = ref dummy})
436 :     fun mkASSIGN (lhs, rhs) = (
437 :     Var.setBinding (lhs, VB_RHS rhs);
438 :     new (ASSIGN{pred = ref dummy, stm = (lhs, rhs), succ = ref dummy}))
439 :     fun mkMASSIGN (lhs, rator, args) = let
440 :     fun setB (_, []) = ()
441 :     | setB (i, x::xs) = (
442 :     Var.setBinding (x, VB_MULTIOP(i, rator, args));
443 :     setB (i+1, xs))
444 :     in
445 :     setB (0, lhs);
446 :     new (MASSIGN{pred = ref dummy, stm = (lhs, rator, args), succ = ref dummy})
447 :     end
448 : jhr 3586 fun mkGASSIGN (lhs, rhs) = (
449 :     if not(GlobalVar.isUpdated lhs) then GlobalVar.setBinding(lhs, rhs) else ();
450 :     new (GASSIGN{pred = ref dummy, lhs = lhs, rhs = rhs, succ = ref dummy}))
451 : jhr 3470 fun mkNEW {strand, args} = new (NEW{
452 :     pred = ref dummy, strand = strand, args = args, succ = ref dummy
453 :     })
454 :     fun mkSAVE (lhs, rhs) = new (SAVE{
455 :     pred = ref dummy, lhs = lhs, rhs = rhs, succ = ref dummy
456 :     })
457 : jhr 3505 fun mkEXIT kind = new (EXIT{kind = kind, pred = ref dummy, succ = ref NONE})
458 :     fun mkRETURN () = mkEXIT ExitKind.RETURN
459 :     fun mkACTIVE () = mkEXIT ExitKind.ACTIVE
460 :     fun mkSTABILIZE () = mkEXIT ExitKind.STABILIZE
461 :     fun mkDIE () = mkEXIT ExitKind.DIE
462 :     fun mkUNREACHABLE () = mkEXIT ExitKind.UNREACHABLE
463 : jhr 3470 fun isNULL (ND{kind=NULL, ...}) = true
464 :     | isNULL _ = false
465 :     (* is a node reachable from the CFG entry; UNREACHABLE exit nodes and JOINs with no real
466 :     * predecessors are unreachable.
467 :     *)
468 :     fun isReachable (ND{kind=EXIT{kind=ExitKind.UNREACHABLE, ...}, ...}) = false
469 :     | isReachable (ND{kind=JOIN{mask, ...}, ...}) = List.exists not (!mask)
470 :     | isReachable _ = true
471 :     (* editing node edges *)
472 :     fun hasPred (ND{kind, ...}) = (case kind
473 :     of NULL => false
474 :     | ENTRY _ => false
475 :     | _ => true
476 :     (* end case *))
477 :     fun setPred (nd0 as ND{kind, ...}, nd) = (case kind
478 :     of NULL => raise Fail("setPred on NULL node " ^ toString nd0)
479 :     | ENTRY _ => raise Fail("setPred on ENTRY node " ^ toString nd0)
480 :     | JOIN{preds, ...} => preds := !preds @ [nd] (* assume preds are added in order *)
481 : jhr 3502 | FOREACH{pred, ...} => pred := nd
482 : jhr 3754 | NEXT{pred, ...} => pred := nd
483 : jhr 3470 | COND{pred, ...} => pred := nd
484 :     | COM{pred, ...} => pred := nd
485 :     | ASSIGN{pred, ...} => pred := nd
486 :     | MASSIGN{pred, ...} => pred := nd
487 :     | GASSIGN{pred, ...} => pred := nd
488 :     | NEW{pred, ...} => pred := nd
489 :     | SAVE{pred, ...} => pred := nd
490 :     | EXIT{pred, ...} => pred := nd
491 :     (* end case *))
492 :     fun preds (nd as ND{kind, ...}) = (case kind
493 :     of NULL => [] (*raise Fail("preds on NULL node "^toString nd)*)
494 :     | ENTRY _ => []
495 :     | JOIN{preds, ...} => !preds
496 :     | COND{pred, ...} => [!pred]
497 : jhr 3502 | FOREACH{pred, bodyExit, ...} => [!pred, !bodyExit]
498 : jhr 3754 | NEXT{pred, ...} => [!pred]
499 : jhr 3470 | COM{pred, ...} => [!pred]
500 :     | ASSIGN{pred, ...} => [!pred]
501 :     | MASSIGN{pred, ...} => [!pred]
502 :     | GASSIGN{pred, ...} => [!pred]
503 :     | NEW{pred, ...} => [!pred]
504 :     | SAVE{pred, ...} => [!pred]
505 :     | EXIT{pred, ...} => [!pred]
506 :     (* end case *))
507 :     fun hasSucc (ND{kind, ...}) = (case kind
508 :     of NULL => false
509 :     | ENTRY _ => true
510 :     | JOIN _ => true
511 :     | COND _ => true
512 :     | COM _ => true
513 : jhr 3473 | FOREACH _ => true
514 : jhr 3754 | NEXT _ => true
515 : jhr 3470 | ASSIGN _ => true
516 :     | MASSIGN _ => true
517 :     | GASSIGN _ => true
518 :     | NEW _ => true
519 :     | SAVE _ => true
520 :     | EXIT{succ=ref(SOME _), ...} => true
521 :     | EXIT _ => false
522 :     (* end case *))
523 :     fun setSucc (nd0 as ND{kind, ...}, nd) = (case kind
524 :     of NULL => raise Fail("setSucc on NULL node "^toString nd0)
525 :     | ENTRY{succ} => succ := nd
526 :     | JOIN{succ, ...} => succ := nd
527 :     | COND _ => raise Fail("setSucc on COND node "^toString nd0)
528 : jhr 3501 | FOREACH{succ, ...} => succ := nd
529 : jhr 3754 | NEXT{succ, ...} => succ := nd
530 : jhr 3470 | COM{succ, ...} => succ := nd
531 :     | ASSIGN{succ, ...} => succ := nd
532 :     | MASSIGN{succ, ...} => succ := nd
533 :     | GASSIGN{succ, ...} => succ := nd
534 :     | NEW{succ, ...} => succ := nd
535 :     | SAVE{succ, ...} => succ := nd
536 :     | EXIT{succ, ...} => succ := SOME nd
537 :     (* end case *))
538 :     fun succs (ND{kind, ...}) = (case kind
539 :     of NULL => [] (*raise Fail("succs on NULL node "^toString nd)*)
540 :     | ENTRY{succ} => [!succ]
541 :     | JOIN{succ, ...} => [!succ]
542 :     | COND{trueBranch, falseBranch, ...} => [!trueBranch, !falseBranch]
543 : jhr 3502 | FOREACH{bodyEntry, succ, ...} => [!bodyEntry, !succ]
544 : jhr 3754 | NEXT{succ, ...} => [!succ]
545 : jhr 3470 | COM{succ, ...} => [!succ]
546 :     | ASSIGN{succ, ...} => [!succ]
547 :     | MASSIGN{succ, ...} => [!succ]
548 :     | GASSIGN{succ, ...} => [!succ]
549 :     | NEW{succ, ...} => [!succ]
550 :     | SAVE{succ, ...} => [!succ]
551 :     | EXIT{succ=ref(SOME nd), ...} => [nd]
552 :     | EXIT _ => []
553 :     (* end case *))
554 :     (* QUESTION: should these functions also do the setPred operation? *)
555 :     fun setTrueBranch (ND{kind=COND{trueBranch, ...}, ...}, nd) = trueBranch := nd
556 :     | setTrueBranch (nd, _) = raise Fail("setTrueBranch on " ^ toString nd)
557 :     fun setFalseBranch (ND{kind=COND{falseBranch, ...}, ...}, nd) = falseBranch := nd
558 :     | setFalseBranch (nd, _) = raise Fail("setFalseBranch on " ^ toString nd)
559 : jhr 3502 fun setBodyEntry (ND{kind=FOREACH{bodyEntry, ...}, ...}, nd) = bodyEntry := nd
560 :     | setBodyEntry (nd, _) = raise Fail("setBodyEntry on " ^ toString nd)
561 :     fun setBodyExit (ND{kind=FOREACH{bodyExit, ...}, ...}, nd) = bodyExit := nd
562 :     | setBodyExit (nd, _) = raise Fail("setBodyExit on " ^ toString nd)
563 : jhr 3470 fun setEdgeMask (ND{kind=JOIN{mask, ...}, ...}, mask') = mask := mask'
564 :     | setEdgeMask (nd, _) = raise Fail("setEdgeMask on " ^ toString nd)
565 :     fun addEdge (nd1, nd2) = (
566 :     if hasSucc nd1
567 :     then (
568 :     setSucc (nd1, nd2);
569 :     setPred (nd2, nd1))
570 :     else ())
571 :     (*DEBUG*)handle ex => (
572 :     print(concat["error in addEdge(", toString nd1, ",", toString nd2, ")\n"]);
573 :     raise ex)
574 : jhr 3536 (* FIXME: the names replaceInEdge and replaceOutEdge are backwards! *)
575 : jhr 3502 (* replace the edge src-->oldDst by the edge src-->dst *)
576 : jhr 3470 fun replaceInEdge {src, oldDst, dst} = (
577 :     (* first set the successor of src *)
578 :     case kind src
579 :     of COND{trueBranch, falseBranch, ...} =>
580 :     if same(!trueBranch, oldDst)
581 :     then trueBranch := dst
582 :     else falseBranch := dst
583 : jhr 3502 | FOREACH{bodyEntry, succ, ...} =>
584 :     if same(!bodyEntry, oldDst)
585 :     then bodyEntry := dst
586 :     else succ := dst
587 : jhr 3470 | _ => setSucc (src, dst)
588 :     (* end case *);
589 :     (* then set the predecessor of dst *)
590 : jhr 3536 case kind oldDst
591 :     of FOREACH{bodyExit, pred, ...} =>
592 :     if same(!bodyExit, src)
593 :     then setBodyExit (dst, src)
594 :     else setPred (dst, src)
595 :     | _ => setPred (dst, src)
596 :     (* end case *))
597 : jhr 3470 (*DEBUG*)handle ex => (
598 :     print(concat["error in replaceInEdge(", toString src, ",", toString oldDst, ",", toString dst, ")\n"]);
599 :     raise ex)
600 : jhr 3502 (* replace the edge oldSrc-->dst by the edge src-->dst *)
601 : jhr 3470 fun replaceOutEdge {oldSrc, src, dst} = (
602 :     (* first set the successor of src *)
603 :     case kind oldSrc
604 :     of COND{trueBranch, falseBranch, ...} =>
605 :     if same(!trueBranch, dst)
606 :     then setTrueBranch (src, dst)
607 :     else setFalseBranch (src, dst)
608 : jhr 3502 | FOREACH{bodyEntry, succ, ...} =>
609 :     if same(!bodyEntry, dst)
610 :     then setBodyEntry (src, dst)
611 :     else setSucc (src, dst)
612 : jhr 3470 | _ => setSucc (src, dst)
613 :     (* end case *);
614 :     (* then set the predecessor of dst *)
615 :     case kind dst
616 :     of JOIN{preds, ...} => let
617 :     fun edit [] = raise Fail "replaceOutEdge: cannot find predecessor"
618 :     | edit (nd::nds) = if same(nd, oldSrc) then src::nds else nd::edit nds
619 :     in
620 :     preds := edit (!preds)
621 :     end
622 : jhr 3502 | FOREACH{bodyExit, pred, ...} =>
623 :     if same(!bodyExit, oldSrc)
624 :     then bodyExit := src
625 :     else pred := src
626 : jhr 3470 | _ => setPred (dst, src)
627 :     (* end case *))
628 :     (*DEBUG*)handle ex => (
629 :     print(concat["error in replaceOutEdge(", toString oldSrc, ",", toString src, ",", toString dst, ")\n"]);
630 :     raise ex)
631 :     (* properties *)
632 :     fun newProp initFn =
633 :     PropList.newProp (fn (ND{props, ...}) => props, initFn)
634 :     fun newFlag () =
635 :     PropList.newFlag (fn (ND{props, ...}) => props)
636 :     end
637 :    
638 :     structure CFG =
639 :     struct
640 :     val empty = CFG{entry = Node.dummy, exit = Node.dummy}
641 :    
642 :     fun isEmpty (CFG{entry, exit}) =
643 :     Node.same(entry, exit) andalso Node.isNULL entry
644 :    
645 :     (* create a basic block from a list of assignments *)
646 :     fun mkBlock [] = empty
647 :     | mkBlock (stm::stms) = let
648 :     fun mkNode (ASSGN stm) = Node.mkASSIGN stm
649 :     | mkNode (MASSGN stm) = Node.mkMASSIGN stm
650 :     | mkNode (GASSGN stm) = Node.mkGASSIGN stm
651 :     | mkNode (SAV stm) = Node.mkSAVE stm
652 :     val entry = mkNode stm
653 :     fun f (stm, prev) = let
654 :     val nd = mkNode stm
655 :     in
656 :     Node.addEdge (prev, nd);
657 :     nd
658 :     end
659 :     val exit = List.foldl f entry stms
660 :     in
661 :     CFG{entry = entry, exit = exit}
662 :     end
663 :    
664 :     (* entry/exit nodes of a CFG *)
665 :     fun entry (CFG{entry = nd, ...}) = nd
666 :     fun exit (CFG{exit = nd, ...}) = nd
667 :    
668 :     (* DFS sorting of the graph rooted at the entry to a statement; the resulting list will
669 :     * be in preorder with parents before children.
670 :     *)
671 :     fun sort (CFG{entry, ...}) = let
672 :     val {getFn, setFn} = PropList.newFlag (fn (ND{props, ...}) => props)
673 :     fun dfs (nd, l) =
674 :     if getFn nd
675 :     then l
676 :     else (
677 :     setFn (nd, true);
678 :     nd :: List.foldl dfs l (Node.succs nd))
679 :     val nodes = dfs (entry, [])
680 :     in
681 :     List.app (fn nd => setFn(nd, false)) nodes;
682 :     nodes
683 :     end
684 :    
685 :     (* apply a function to all of the nodes in the graph rooted at the entry to the statement *)
686 :     fun apply (f : node -> unit) (CFG{entry, ...}) = let
687 :     val {getFn, setFn} = Node.newFlag()
688 :     fun dfs (nd, l) =
689 :     if getFn nd
690 :     then l
691 :     else (
692 :     f nd; (* visit *)
693 :     setFn (nd, true);
694 :     nd :: List.foldl dfs l (Node.succs nd))
695 :     val nodes = dfs (entry, [])
696 :     in
697 :     List.app (fn nd => setFn(nd, false)) nodes
698 :     end
699 :    
700 :     (* delete a simple node from a CFG *)
701 :     fun deleteNode (nd as ND{kind, ...}) = let
702 :     val (pred, succ) = (case kind
703 :     of COM{pred = ref pred, succ = ref succ, ...} => (pred, succ)
704 :     | ASSIGN{pred = ref pred, succ = ref succ, ...} => (pred, succ)
705 :     | MASSIGN{pred = ref pred, succ = ref succ, ...} => (pred, succ)
706 :     | GASSIGN{pred = ref pred, succ = ref succ, ...} => (pred, succ)
707 :     | NEW{pred = ref pred, succ = ref succ, ...} => (pred, succ)
708 :     | SAVE{pred = ref pred, succ = ref succ, ...} => (pred, succ)
709 :     | _ => raise Fail(concat["unsupported deleteNode(", Node.toString nd, ")\n"])
710 :     (* end case *))
711 :     in
712 :     (* replace the predecessor edge from succ to nd with an edge from succ to pred *)
713 :     case Node.kind succ
714 :     of JOIN{preds, ...} => let
715 :     fun edit [] = raise Fail "deleteNode: cannot find predecessor"
716 :     | edit (nd'::nds) = if Node.same(nd', nd) then pred::nds else nd'::edit nds
717 :     in
718 :     preds := edit (!preds)
719 :     end
720 : jhr 3536 | FOREACH{pred=pred', bodyExit, ...} =>
721 :     if Node.same(!pred', nd)
722 :     then pred' := pred
723 :     else bodyExit := pred
724 : jhr 3754 | NEXT _ => raise Fail "deleteNode(NEXT)"
725 : jhr 3470 | _ => Node.setPred (succ, pred)
726 :     (* end case *);
727 :     (* replace the successor edge from pred to nd with an edge from pred to succ *)
728 :     case Node.kind pred
729 :     of COND{trueBranch, falseBranch, ...} => (
730 :     (* note that we treat each branch independently, so that we handle the
731 :     * situation where both branches are the same node.
732 :     *)
733 :     if Node.same(!trueBranch, nd)
734 : jhr 3536 then trueBranch := succ
735 : jhr 3470 else ();
736 :     if Node.same(!falseBranch, nd)
737 : jhr 3536 then falseBranch := succ
738 : jhr 3470 else ())
739 : jhr 3536 | FOREACH{bodyEntry, succ=succ', ...} =>
740 :     if Node.same(!bodyEntry, nd)
741 :     then bodyEntry := succ
742 :     else succ' := succ
743 : jhr 3470 | _ => Node.setSucc (pred, succ)
744 :     (* end case *)
745 :     end
746 :     (*DEBUG*)handle ex => (
747 :     print(concat["error in deleteNode(", Node.toString nd, ")\n"]);
748 :     raise ex)
749 :    
750 :     (* replace a simple node in a cfg with a subgraph *)
751 :     fun replaceNode (oldNd as ND{kind, ...}, node) = (case kind
752 :     of ASSIGN{pred, succ, ...} => (
753 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
754 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
755 :     | MASSIGN{pred, succ, ...} => (
756 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
757 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
758 :     | GASSIGN{pred, succ, ...} => (
759 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
760 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
761 :     | NEW{pred, succ, ...} => (
762 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
763 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
764 :     | SAVE{pred, succ, ...} => (
765 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
766 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
767 :     | EXIT{pred, succ=ref NONE, ...} =>
768 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node}
769 :     | _ => raise Fail(concat[
770 :     "unsupported replaceNode(", Node.toString oldNd, ", ", Node.toString node, ")"
771 :     ])
772 :     (* end case *))
773 :    
774 :     (* replace a simple node in a cfg with a subgraph *)
775 :     fun replaceNodeWithCFG (nd as ND{kind, ...}, cfg as CFG{entry, exit}) =
776 :     if isEmpty cfg
777 :     then deleteNode nd
778 :     else (case kind
779 :     of ASSIGN{pred, succ, ...} => (
780 :     Node.replaceInEdge {src = !pred, oldDst = nd, dst = entry};
781 :     Node.replaceOutEdge {oldSrc = nd, src = exit, dst = !succ})
782 :     | MASSIGN{pred, succ, ...} => (
783 :     Node.replaceInEdge {src = !pred, oldDst = nd, dst = entry};
784 :     Node.replaceOutEdge {oldSrc = nd, src = exit, dst = !succ})
785 :     | _ => raise Fail "unsupported replaceNodeWithCFG"
786 :     (* end case *))
787 :    
788 :     (* concatenate two CFGs *)
789 :     fun concat (cfg1 as CFG{entry=e1, exit=x1}, cfg2 as CFG{entry=e2, exit=x2}) =
790 :     if isEmpty cfg1 then cfg2
791 :     else if isEmpty cfg2 then cfg1
792 :     else (
793 :     Node.setSucc (x1, e2);
794 :     Node.setPred (e2, x1);
795 :     CFG{entry = e1, exit = x2})
796 :     (*DEBUG*)handle ex => (
797 :     print(String.concat["error in concat({", Node.toString e1, ",", Node.toString x1,
798 :     "},{", Node.toString e2, ",", Node.toString x2, "})\n"]);
799 :     raise ex)
800 :    
801 :     (* prepend a node to a CFG *)
802 :     fun prependNode (nd, cfg as CFG{entry, exit}) =
803 :     if isEmpty cfg
804 :     then CFG{entry=nd, exit=nd}
805 :     else (
806 :     Node.setSucc (nd, entry);
807 :     Node.setPred (entry, nd);
808 :     CFG{entry=nd, exit=exit})
809 :    
810 :     (* append a node to a CFG *)
811 :     fun appendNode (cfg as CFG{entry, exit}, nd) =
812 :     if isEmpty cfg
813 :     then CFG{entry=nd, exit=nd}
814 :     else (
815 :     Node.setPred (nd, exit);
816 :     Node.setSucc (exit, nd);
817 :     CFG{entry=entry, exit=nd})
818 :    
819 :     (* insert a block of assignments at the beginning of the CFG. If the CFG has an ENTRY
820 :     * node, then the block is inserted immediatly following the entry.
821 :     *)
822 :     fun prependBlock ([], cfg) = cfg
823 :     | prependBlock (stms, cfg as CFG{entry, exit}) = (case entry
824 :     of ND{kind=ENTRY{succ}, ...} => let
825 :     fun mkNode (ASSGN stm) = Node.mkASSIGN stm
826 :     | mkNode (MASSGN stm) = Node.mkMASSIGN stm
827 :     | mkNode (GASSGN stm) = Node.mkGASSIGN stm
828 :     | mkNode (SAV stm) = Node.mkSAVE stm
829 :     fun f (stm, succ) = let
830 :     val nd = mkNode stm
831 :     in
832 :     Node.addEdge (nd, succ);
833 :     nd
834 :     end
835 :     val first = List.foldr f (!succ) stms
836 :     in
837 :     succ := first;
838 :     Node.setPred (first, entry);
839 :     cfg
840 :     end
841 :     | _ => concat(mkBlock stms, cfg)
842 :     (* end case *))
843 :    
844 :     (* insert a block of assignments at the end of the CFG argument If the CFG has an EXIT
845 :     * node, then the block is inserted immediatly before the exit.
846 :     *)
847 :     fun appendBlock (cfg, []) = cfg
848 : jhr 3754 | appendBlock (cfg as CFG{entry, exit}, stms) = let
849 :     fun mkNode (ASSGN stm) = Node.mkASSIGN stm
850 :     | mkNode (MASSGN stm) = Node.mkMASSIGN stm
851 :     | mkNode (GASSGN stm) = Node.mkGASSIGN stm
852 :     | mkNode (SAV stm) = Node.mkSAVE stm
853 :     fun f (stm, prev) = let
854 :     val nd = mkNode stm
855 :     in
856 :     Node.addEdge (prev, nd);
857 :     nd
858 :     end
859 :     in
860 :     case exit
861 :     of ND{kind=EXIT{pred, ...}, ...} => let
862 :     val last = List.foldl f (!pred) stms
863 :     in
864 :     pred := last;
865 :     Node.setSucc(last, exit);
866 :     cfg
867 :     end
868 :     | ND{kind=NEXT{pred, ...}, ...} => let
869 :     val last = List.foldl f (!pred) stms
870 :     in
871 :     pred := last;
872 :     Node.setSucc(last, exit);
873 :     cfg
874 :     end
875 :     | _ => concat(cfg, mkBlock stms)
876 :     (* end case *)
877 :     end
878 : jhr 3470 end
879 :    
880 :     structure RHS =
881 :     struct
882 :     fun vars rhs = (case rhs
883 :     of GLOBAL _ => []
884 :     | STATE _ => []
885 :     | VAR x => [x]
886 :     | LIT _ => []
887 :     | OP(rator, xs) => xs
888 :     | CONS(xs, _) => xs
889 :     | SEQ(xs, _) => xs
890 :     | EINAPP(_, xs) => xs
891 :     (* end case *))
892 :    
893 :     fun map f = let
894 :     fun mapf rhs = (case rhs
895 :     of GLOBAL _ => rhs
896 :     | STATE _ => rhs
897 :     | VAR x => VAR(f x)
898 :     | LIT _ => rhs
899 :     | OP(rator, xs) => OP(rator, List.map f xs)
900 :     | CONS(xs, ty) => CONS(List.map f xs, ty)
901 :     | SEQ(xs, ty) => SEQ(List.map f xs, ty)
902 :     | EINAPP(ein, xs) => EINAPP(ein, List.map f xs)
903 :     (* end case *))
904 :     in
905 :     mapf
906 :     end
907 :    
908 :     fun app f = let
909 :     fun appf rhs = (case rhs
910 :     of GLOBAL _ => ()
911 :     | STATE _ => ()
912 :     | VAR x => f x
913 :     | LIT _ => ()
914 :     | OP(rator, xs) => List.app f xs
915 :     | CONS(xs, _) => List.app f xs
916 :     | SEQ(xs, _) => List.app f xs
917 :     | EINAPP(_, xs) => List.app f xs
918 :     (* end case *))
919 :     in
920 :     appf
921 :     end
922 :    
923 :     (* return a string representation of a rhs *)
924 :     fun toString rhs = (case rhs
925 :     of GLOBAL x => GlobalVar.toString x
926 :     | STATE x => StateVar.toString x
927 :     | VAR x => Var.toString x
928 :     | LIT lit => Literal.toString lit
929 :     | OP(rator, xs) => String.concat [
930 :     Op.toString rator,
931 :     "(", String.concatWithMap "," Var.toString xs, ")"
932 :     ]
933 :     | CONS(xs, ty) => String.concat [
934 :     "<", Ty.toString ty, ">[",
935 :     String.concatWithMap "," Var.toString xs, "]"
936 :     ]
937 :     | SEQ(xs, ty) => String.concat [
938 :     "<", Ty.toString ty, ">{",
939 :     String.concatWithMap "," Var.toString xs, "}"
940 :     ]
941 :     | EINAPP(ein, xs) => String.concat [
942 : jhr 3535 EinPP.toString ein, " (",
943 :     String.concatWithMap "," Var.toString xs, ")"
944 : jhr 3470 ]
945 :     (* end case *))
946 :     end
947 : jhr 3586
948 : jhr 3470 (* return a string representation of a variable binding *)
949 :     fun vbToString VB_NONE = "NONE"
950 :     | vbToString (VB_RHS rhs) = concat["RHS(", RHS.toString rhs, ")"]
951 :     | vbToString (VB_MULTIOP(i, rator, xs)) = concat[
952 :     "MULTIOP(", Op.toString rator,
953 :     "[", String.concatWithMap "," Var.toString xs, "])"
954 :     ]
955 :     | vbToString (VB_PHI xs) = concat[
956 :     "PHI(",
957 :     String.concatWithMap "," (fn NONE => "_" | SOME x => Var.toString x) xs, ")"
958 :     ]
959 :     | vbToString VB_PARAM = "PARAM"
960 : jhr 3522 | vbToString VB_ITER = "ITER"
961 : jhr 3470
962 :     (* return a string representation of a PHI node *)
963 :     fun phiToString (y, xs) = String.concat [
964 :     Ty.toString(Var.ty y), " ", Var.toString y, " = PHI(",
965 :     String.concatWithMap "," (fn NONE => "_" | SOME x => Var.toString x) xs, ")"
966 :     ]
967 :    
968 :     (* return a string representation of an assignment *)
969 :     fun assignToString (y, rhs) =
970 :     String.concat [Ty.toString(Var.ty y), " ", Var.toString y, " = ", RHS.toString rhs]
971 :     fun massignToString (ys, rator, xs) = String.concat [
972 :     "(", String.concatWithMap ","
973 :     (fn y => concat[Ty.toString(Var.ty y), " ", Var.toString y]) ys,
974 :     " = ", Op.toString rator,
975 :     "(", String.concatWithMap "," Var.toString xs, ")"
976 :     ]
977 :     fun assignmentToString (ASSGN asgn) = assignToString asgn
978 :     | assignmentToString (MASSGN masgn) = massignToString masgn
979 :     | assignmentToString (GASSGN(lhs, rhs)) = String.concat[
980 :     GlobalVar.toString lhs, " = ", Var.toString rhs
981 :     ]
982 :     | assignmentToString (SAV(lhs, rhs)) = String.concat[
983 :     StateVar.toString lhs, " = ", Var.toString rhs
984 :     ]
985 :    
986 :     end (* SSAFn *)

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