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

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