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

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