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

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