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

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