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

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