Debian Codegraph @

lib/mlrisc-lib/MLRISC/ra/cluster-ra.sml

raw
1 (* cluster-ra.sml
2 *
3 * COPYRIGHT (c) 2002 Bell Labs, Lucent Technologies
4 *
5 * This module provides services for the new RA when using the cluster
6 * representation.
7 * The algorithm is adapted from
8 * Algorithm 19.17 from Appel, Modern Compiler Implementation in ML,
9 * Calculation of live ranges in SSA form. We don't directly use SSA
10 * here but the principles are the same.
11 *
12 * -- Allen
13 *)
14
15 functor ClusterRA
16 (structure Asm : INSTRUCTION_EMITTER
17 structure Flowgraph : CONTROL_FLOW_GRAPH (* where I = Asm.I and P = Asm.S.P *)
18 where type I.addressing_mode = Asm.I.addressing_mode
19 and type I.ea = Asm.I.ea
20 and type I.instr = Asm.I.instr
21 and type I.instruction = Asm.I.instruction
22 and type I.operand = Asm.I.operand
23 where type P.Client.pseudo_op = Asm.S.P.Client.pseudo_op
24 and type P.T.Basis.cond = Asm.S.P.T.Basis.cond
25 and type P.T.Basis.div_rounding_mode = Asm.S.P.T.Basis.div_rounding_mode
26 and type P.T.Basis.ext = Asm.S.P.T.Basis.ext
27 and type P.T.Basis.fcond = Asm.S.P.T.Basis.fcond
28 and type P.T.Basis.rounding_mode = Asm.S.P.T.Basis.rounding_mode
29 and type P.T.Constant.const = Asm.S.P.T.Constant.const
30 and type ('s,'r,'f,'c) P.T.Extension.ccx = ('s,'r,'f,'c) Asm.S.P.T.Extension.ccx
31 and type ('s,'r,'f,'c) P.T.Extension.fx = ('s,'r,'f,'c) Asm.S.P.T.Extension.fx
32 and type ('s,'r,'f,'c) P.T.Extension.rx = ('s,'r,'f,'c) Asm.S.P.T.Extension.rx
33 and type ('s,'r,'f,'c) P.T.Extension.sx = ('s,'r,'f,'c) Asm.S.P.T.Extension.sx
34 and type P.T.I.div_rounding_mode = Asm.S.P.T.I.div_rounding_mode
35 and type P.T.Region.region = Asm.S.P.T.Region.region
36 and type P.T.ccexp = Asm.S.P.T.ccexp
37 and type P.T.fexp = Asm.S.P.T.fexp
38 (* and type P.T.labexp = Asm.S.P.T.labexp *)
39 and type P.T.mlrisc = Asm.S.P.T.mlrisc
40 and type P.T.oper = Asm.S.P.T.oper
41 and type P.T.rep = Asm.S.P.T.rep
42 and type P.T.rexp = Asm.S.P.T.rexp
43 and type P.T.stm = Asm.S.P.T.stm
44 structure InsnProps : INSN_PROPERTIES (* where I = Flowgraph.I *)
45 where type I.addressing_mode = Flowgraph.I.addressing_mode
46 and type I.ea = Flowgraph.I.ea
47 and type I.instr = Flowgraph.I.instr
48 and type I.instruction = Flowgraph.I.instruction
49 and type I.operand = Flowgraph.I.operand
50 structure Spill : RA_SPILL (* where I = Flowgraph.I *)
51 where type I.addressing_mode = Flowgraph.I.addressing_mode
52 and type I.ea = Flowgraph.I.ea
53 and type I.instr = Flowgraph.I.instr
54 and type I.instruction = Flowgraph.I.instruction
55 and type I.operand = Flowgraph.I.operand
56 ) : RA_FLOWGRAPH =
57 struct
58 structure CFG = Flowgraph
59 structure I = CFG.I
60 structure G = RAGraph
61 structure Props = InsnProps
62 structure Core = RACore
63 structure A = Array
64 structure UA = Unsafe.Array (* okay, I'm cheating a bit here *)
65 structure Spill = Spill
66
67 open G
68 structure C = I.C
69 structure CB = CellsBasis
70
71 fun isOn(flag,mask) = Word.andb(flag,mask) <> 0w0
72
73 val dump_size = MLRiscControl.mkFlag ("ra-dump-size", "whether to show RA size")
74
75 type flowgraph = CFG.cfg (* flowgraph is a cluster *)
76
77 fun error msg = MLRiscErrorMsg.error("ClusterRA", msg)
78
79 val mode = 0w0
80
81 fun uniqCells s = CB.SortedCells.return(CB.SortedCells.uniq s)
82
83 fun chaseCell(c as CB.CELL{col=ref(CB.MACHINE r),...}) = (c,r)
84 | chaseCell(CB.CELL{col=ref(CB.ALIASED c), ...}) = chaseCell c
85 | chaseCell(c as CB.CELL{col=ref CB.SPILLED, ...}) = (c,~1)
86 | chaseCell(c as CB.CELL{col=ref CB.PSEUDO, id, ...}) = (c,id)
87
88 fun colorOf(CB.CELL{col=ref(CB.MACHINE r),...}) = r
89 | colorOf(CB.CELL{col=ref(CB.ALIASED c), ...}) = colorOf c
90 | colorOf(CB.CELL{col=ref CB.SPILLED, ...}) = ~1
91 | colorOf(CB.CELL{col=ref CB.PSEUDO, id, ...}) = id
92
93 fun chase(NODE{color=ref(ALIASED n), ...}) = chase n
94 | chase n = n
95
96 exception NotThere
97
98 val Asm.S.STREAM{emit,...} = Asm.makeStream []
99
100 fun dumpFlowgraph(txt, cfg as Graph.GRAPH graph, outstrm) = let
101 fun say txt = TextIO.output(outstrm, txt)
102 fun sayPseudo p = (say(CFG.P.toString p); say "\n")
103 val CFG.INFO{data, ...} = #graph_info graph
104 in
105 CFG.dump(outstrm, txt, cfg);
106 app sayPseudo (rev(!data))
107 end
108
109 val annotations = CFG.annotations
110
111 val dummyBlock = CFG.newBlock(~1, ref 0.0)
112
113 val uniq = ListMergeSort.uniqueSort
114 (fn ({block=b1,insn=i1},{block=b2,insn=i2}) =>
115 case Int.compare(b1,b2) of
116 EQUAL => Int.compare(i1,i2)
117 | ord => ord)
118
119 fun services(cfg as Graph.GRAPH graph) = let
120 val CFG.INFO{annotations=clAnns, ...} = #graph_info graph
121 val blocks = #nodes graph ()
122 fun maxBlockId ((id, CFG.BLOCK _)::rest, curr) =
123 if id > curr then maxBlockId(rest, id) else maxBlockId(rest, curr)
124 | maxBlockId([], curr) = curr
125
126 val N = maxBlockId(blocks, #capacity graph ())
127
128 (*
129 * Construct program point
130 *)
131 fun progPt(blknum, instrId) = {block=blknum, insn=instrId}
132 fun blockNum{block,insn} = block
133 fun instrNum{block,insn} = insn
134
135 (* blocks indexed by block id *)
136 val blockTable = A.array(N, (#new_id graph (), dummyBlock))
137
138 (* fill block table *)
139 val _ = List.app (fn b as (nid, _) => Array.update(blockTable, nid, b)) blocks
140
141 val EXIT = (case #exits graph () of [e] => e | _ => error "EXIT")
142
143 (*
144 * Building the interference graph
145 *)
146 fun buildIt (cellkind,
147 G as GRAPH{nodes, dedicated, mode, span, copyTmps, ...}) =
148
149 let (* definitions indexed by block id+instruction id *)
150 val defsTable = A.array(N, A.array(0, [] : node list))
151 val marked = A.array(N, ~1)
152 val addEdge = Core.addEdge G
153
154 (* copies indexed by source
155 * This table maps variable v to the program points where
156 * v is a source of a copy.
157 *)
158 val copyTable = IntHashTable.mkTable(N, NotThere)
159 : {dst:CB.cell,pt:G.programPoint} list IntHashTable.hash_table
160 val lookupCopy = IntHashTable.find copyTable
161 val lookupCopy = fn r => case lookupCopy r of SOME c => c
162 | NONE => []
163 val addCopy = IntHashTable.insert copyTable
164
165 val stamp = ref 0
166
167 (* Allocate the arrays *)
168 fun alloc [] = ()
169 | alloc((id, CFG.BLOCK{insns, ...})::blocks) =
170 (UA.update(defsTable, id, A.array(length(!insns)+1, []));
171 alloc blocks)
172 val _ = alloc blocks
173
174 (*
175 * Remove pseudo use generated by copy temporaries
176 *)
177 fun rmPseudoUses [] = ()
178 | rmPseudoUses(NODE{uses,...}::ns) = (uses := []; rmPseudoUses ns)
179
180 (*
181 * Initialize the definitions before computing the liveness for v.
182 *)
183 fun initialize(v, v', useSites) = let
184 (* First we remove all definitions for all copies
185 * with v as source.
186 * When we have a copy and while we are processing v
187 *
188 * x <- v
189 *
190 * x does not really interfere with v at this point,
191 * so we remove the definition of x temporarily.
192 *)
193 fun markCopies([], trail) = trail
194 | markCopies({pt, dst}::copies, trail) =
195 let val b = blockNum pt
196 val i = instrNum pt
197 val defs = UA.sub(defsTable, b)
198 val nodes = UA.sub(defs, i)
199 fun revAppend([], nodes) = nodes
200 | revAppend(n::ns, nodes) = revAppend(ns, n::nodes)
201 val dstColor = colorOf dst
202 fun removeDst([], nodes') = nodes'
203 | removeDst((d as NODE{number=r,...})::nodes, nodes')=
204 if r = dstColor then revAppend(nodes', nodes)
205 else removeDst(nodes, d::nodes')
206 val nodes' = removeDst(nodes, [])
207 in UA.update(defs, i, nodes');
208 markCopies(copies, (defs, i, nodes)::trail)
209 end
210
211 (*
212 * Then we mark all use sites of v with a fake definition so that
213 * the scanning will terminate correctly at these points.
214 *)
215 fun markUseSites([], trail) = trail
216 | markUseSites(pt::pts, trail) =
217 let val b = blockNum pt
218 val i = instrNum pt
219 val defs = UA.sub(defsTable, b)
220 val nodes = UA.sub(defs, i)
221 in UA.update(defs, i, v'::nodes);
222 markUseSites(pts, (defs, i, nodes)::trail)
223 end
224
225 val copies = lookupCopy v
226 val trail = markCopies(copies, [])
227 val trail = markUseSites(useSites, trail)
228 in trail end
229
230 fun cleanup [] = ()
231 | cleanup ((defs, i, nodes)::trail) =
232 (UA.update(defs, i, nodes); cleanup trail)
233 (*
234 * Perform incremental liveness analysis on register v
235 * and compute the span
236 *)
237 fun liveness(v, v' as NODE{uses, ...}, cellV) = let
238 val st = !stamp
239 val _ = stamp := st + 1
240 fun foreachUseSite([], span) = span
241 | foreachUseSite(u::uses, span) = let
242 val b = blockNum u
243 val i = instrNum u
244 val block as (_, CFG.BLOCK{freq, ...}) = UA.sub(blockTable, b)
245 val span =
246 if i = 0 then liveOutAtBlock(block, span) (* live out *)
247 else let
248 val f = !freq
249 val defs = UA.sub(defsTable, b)
250 in liveOutAtStmt(block, A.length defs, defs, i+1, f, span+f)
251 end
252 in foreachUseSite(uses, span)
253 end
254
255 and visitPred((nid, _), span) =
256 let fun foreachPred([], span) = span
257 | foreachPred(nid::pred, span) = let
258 val span = liveOutAtBlock((nid, #node_info graph nid), span)
259 in foreachPred(pred, span)
260 end
261 in
262 foreachPred(#pred graph nid, span)
263 end
264
265 and liveOutAtStmt(block, nDefs, defs, pos, freq, span) =
266 (* v is live out *)
267 if pos < nDefs then
268 let fun foreachDef([], true) = span
269 | foreachDef([], false) =
270 liveOutAtStmt(block, nDefs, defs,
271 pos+1, freq, span+freq)
272 | foreachDef((d as NODE{number=r, ...})::ds, kill) =
273 if r = v then foreachDef(ds, true)
274 else (addEdge(d, v'); foreachDef(ds, kill))
275 in foreachDef(UA.sub(defs, pos), false)
276 end
277 else visitPred(block, span)
278
279 and liveOutAtBlock(block as (nid, CFG.BLOCK{freq, ...}), span) =
280 (* v is live out at the current block *)
281 if UA.sub(marked, nid) = st then span
282 else let
283 val defs = UA.sub(defsTable, nid)
284 in
285 UA.update(marked, nid, st);
286 liveOutAtStmt(block, A.length defs, defs, 1, !freq, span)
287 end
288
289 val useSites = uniq(!uses)
290 val trail = initialize(v, v', useSites)
291 val span = foreachUseSite (useSites, 0.0)
292 val _ = cleanup trail
293 in
294 span
295 end
296
297 val newNodes = Core.newNodes G
298 val getnode = IntHashTable.lookup nodes
299 val insnDefUse = Props.defUse cellkind
300 val getCell = C.getCellsByKind cellkind
301
302 fun isDedicated r = dedicated r
303
304 (* Remove all dedicated or spilled registers from the list *)
305 fun rmvDedicated regs =
306 let fun loop([], rs') = rs'
307 | loop(r::rs, rs') =
308 let fun rmv(r as CB.CELL{col=ref(CB.PSEUDO), id, ...}) =
309 if isDedicated(id) then loop(rs, rs') else loop(rs, r::rs')
310 | rmv(CB.CELL{col=ref(CB.ALIASED r), ...}) = rmv r
311 | rmv(r as CB.CELL{col=ref(CB.MACHINE col), ...}) =
312 if isDedicated col then loop(rs, rs')
313 else loop(rs, r::rs')
314 | rmv(CB.CELL{col=ref(CB.SPILLED), ...}) = loop(rs,rs')
315 in rmv r
316 end
317 in loop(regs, []) end
318
319 (*
320 * Create parallel move
321 *)
322 fun mkMoves(insn, pt, cost, mv, tmps) =
323 (case insn of
324 I.ANNOTATION{i, ...} =>
325 (* strip away the annotation.
326 * Note: we are assuming annotations cannot change
327 * the semantics of the copies.
328 *)
329 mkMoves(i, pt, cost, mv, tmps)
330 | I.COPY{dst, src, k, ...} =>
331 (* If it is a parallel copy, deal with the copy temporary
332 * properly. If it is a register,
333 * create a pseudo use site just below the end of
334 * the copy instruction. This is to make sure that
335 * the temporary is colored properly. If the copy temporary
336 * doesn't exist or if it has been spilled, do nothing.
337 *)
338 if k = cellkind then
339 let val tmps =
340 case Props.moveTmpR insn of
341 SOME r =>
342 (* Add a pseudo use for tmpR *)
343 (case chase(getnode(colorOf r)) of
344 tmp as NODE{uses,defs=ref [d],...} =>
345 let fun prev{block,insn}={block=block,insn=insn-1}
346 in uses := [prev d];
347 tmp::tmps
348 end
349 | _ => error "mkMoves"
350 )
351 | NONE => tmps
352 fun moves([], [], mv) = mv
353 | moves(d::ds, s::ss, mv) =
354 let val (d, cd) = chaseCell d
355 val (s, cs) = chaseCell s
356 in if isDedicated cd orelse isDedicated cs
357 then moves(ds, ss, mv)
358 else if cd = cs then moves(ds, ss, mv)
359 else
360 let val _ =
361 addCopy(cs, {dst=d, pt=pt}::lookupCopy cs);
362 val dst = chase(getnode cd)
363 val src = chase(getnode cs)
364 in moves(ds, ss, MV{dst=dst, src=src,
365 status=ref WORKLIST,
366 hicount=ref 0,
367 (* kind=REG_TO_REG, *)
368 cost=cost}::mv
369 )
370 end
371 end
372 | moves _ = error "moves"
373 in (moves(dst, src, mv), tmps) end
374 else (mv, tmps)
375 | _ => (mv, tmps)
376 )
377
378 (* Add the nodes first *)
379 fun mkNodes([], mv, tmps) = (mv, tmps)
380 | mkNodes((nid, blk)::blocks, mv, tmps) = let
381 val CFG.BLOCK{insns, freq=ref w, annotations, ...} = blk
382 val succ = #succ graph nid
383 val liveOut = CFG.liveOut blk
384 val dtab = A.sub(defsTable, nid)
385 fun scan([], pt, i, mv, tmps) = (pt, i, mv, tmps)
386 | scan(insn::rest, pt, i, mv, tmps) =
387 let val (d, u) = insnDefUse insn
388 val defs = rmvDedicated d
389 val uses = rmvDedicated u
390 val defs = newNodes{cost=w, pt=pt,
391 defs=defs, uses=uses}
392 val _ = UA.update(dtab, i, defs)
393 val (mv, tmps) = mkMoves(insn, pt, w, mv, tmps)
394 fun next{block,insn} = {block=block,insn=insn+1}
395 in scan(rest,next pt, i+1, mv, tmps)
396 end
397 val (pt, i, mv, tmps) =
398 scan(!insns, progPt(nid,1), 1, mv, tmps)
399 in
400 (* If the block is escaping, then all liveout
401 * registers are considered used here.
402 *)
403 case succ
404 of [id] =>
405 if id = EXIT then let
406 val liveSet = rmvDedicated(
407 uniqCells(getCell(liveOut)))
408 in newNodes{cost=w, pt=progPt(nid, 0),
409 defs=[], uses=liveSet}; ()
410 end
411 else ()
412 | _ => ()
413 (*esac*);
414 mkNodes(blocks, mv, tmps)
415 end
416
417 (* Add the edges *)
418
419 val (moves, tmps) = mkNodes(blocks, [], [])
420 in
421 IntHashTable.appi
422 (let val setSpan : (int * real) -> unit =
423 if isOn(mode,Core.COMPUTE_SPAN) then
424 let val spanMap = IntHashTable.mkTable
425 (IntHashTable.numItems nodes, NotThere)
426 val setSpan = IntHashTable.insert spanMap
427 val _ = span := SOME spanMap
428 in setSpan end
429 else fn _ => ()
430 in fn (v, v' as NODE{cell, color, ...}) =>
431 let fun computeLiveness() =
432 setSpan(v, liveness(v, v', cell))
433 in case !color of
434 PSEUDO => computeLiveness()
435 | COLORED _ => computeLiveness()
436 | MEMREG _ => computeLiveness()
437 | _ => ()
438 end
439 end
440 ) nodes;
441 if isOn(Core.SAVE_COPY_TEMPS, mode) then copyTmps := tmps else ();
442 rmPseudoUses tmps;
443 moves
444 end (* buildIt *)
445
446 (*
447 * Build the interference graph initially.
448 *)
449 fun build(G, cellkind) = let
450 val moves = buildIt(cellkind, G)
451 val i2s = Int.toString
452 in
453 if !dump_size then let
454 val GRAPH{nodes, bitMatrix,...} = G
455 val insns =
456 foldr (fn ((_,CFG.BLOCK{insns,...}),n) => length(!insns) + n) 0 blocks
457 in
458 TextIO.output
459 (!MLRiscControl.debug_stream,
460 "RA #blocks="^i2s N ^
461 " #insns="^i2s insns ^
462 " #nodes="^i2s(IntHashTable.numItems nodes) ^
463 " #edges="^i2s(Core.BM.size(!bitMatrix)) ^
464 " #moves="^i2s(length moves)^"\n")
465 end
466 else ();
467 moves
468 end
469
470 (*
471 * Rebuild the interference graph;
472 * We'll just do it from scratch for now.
473 *)
474 fun rebuild(cellkind, G) =
475 (Core.clearNodes G;
476 buildIt(cellkind, G)
477 )
478
479 (*
480 * Spill a set of nodes and rewrite the flowgraph
481 *)
482 fun spill{copyInstr, spill, spillSrc, spillCopyTmp,
483 reload, reloadDst, renameSrc, graph,
484 cellkind, nodes=nodesToSpill} =
485 let (* Remove the interference graph now *)
486 val _ = Core.clearGraph graph
487
488 (* maps program point to registers to be spilled *)
489 val spillSet = G.PPtHashTable.mkTable(32, NotThere)
490
491 (* maps program point to registers to be reloaded *)
492 val reloadSet = G.PPtHashTable.mkTable(32, NotThere)
493
494 (* maps program point to registers to be killed *)
495 val killSet = G.PPtHashTable.mkTable(32, NotThere)
496
497 val spillRewrite = Spill.spillRewrite
498 { graph=graph,
499 spill=spill,
500 spillSrc=spillSrc,
501 spillCopyTmp=spillCopyTmp,
502 reload=reload,
503 reloadDst=reloadDst,
504 renameSrc=renameSrc,
505 copyInstr=copyInstr,
506 cellkind=cellkind,
507 spillSet=spillSet,
508 reloadSet=reloadSet,
509 killSet=killSet
510 }
511
512 (* set of basic blocks that are affected *)
513 val affectedBlocks = IntHashTable.mkTable(32, NotThere)
514
515 val addAffectedBlocks = IntHashTable.insert affectedBlocks
516
517 fun ins set = let
518 val add = G.PPtHashTable.insert set
519 val look = G.PPtHashTable.find set
520 val look = fn r => case look r of SOME s => s | NONE => []
521 fun enter(r, []) = ()
522 | enter(r, pt::pts) =
523 (add (pt, r::look pt);
524 addAffectedBlocks (blockNum pt, true);
525 enter(r, pts)
526 )
527 in enter
528 end
529
530 val insSpillSet = ins spillSet
531 val insReloadSet = ins reloadSet
532 val insKillSet =
533 let
534 val add = G.PPtHashTable.insert killSet
535 val look = G.PPtHashTable.find killSet
536 val look = fn r => case look r of SOME s => s | NONE => []
537 fun enter(r, []) = ()
538 | enter(r, pt::pts) = (add(pt, r::look pt); enter(r, pts))
539 in enter
540 end
541
542 (* Mark all spill/reload locations *)
543 fun markSpills(G.NODE{color, number, cell, defs, uses, ...}) =
544 let fun spillIt(defs, uses) =
545 (insSpillSet(cell, defs);
546 insReloadSet(cell, uses);
547 (* Definitions but no use! *)
548 case uses of
549 [] => insKillSet(cell, defs)
550 | _ => ()
551 )
552 val d = !defs
553 val u = !uses
554 in
555 case !color
556 of G.SPILLED => spillIt(d,u)
557 | G.SPILL_LOC _ => spillIt(d,u)
558 | G.MEMREG _ => spillIt(d,u)
559 | G.PSEUDO => spillIt(d,u)
560 | _ => ()
561 end
562 val _ = app markSpills nodesToSpill
563
564 (* Rewrite all affected blocks *)
565 fun rewriteAll (blknum, _) = let
566 val (_, CFG.BLOCK{insns as ref instrs, annotations, ...}) =
567 A.sub(blockTable, blknum)
568 val instrs =
569 spillRewrite{pt=progPt(blknum, length instrs),
570 instrs=instrs, annotations=annotations}
571 in
572 insns := instrs
573 end
574
575
576 fun mark(G.NODE{color, ...}) =
577 (case !color
578 of PSEUDO => color := SPILLED
579 | SPILLED => ()
580 | SPILL_LOC _ => ()
581 | ALIASED _ => ()
582 | MEMREG _ => ()
583 | COLORED _ => error "mark: COLORED"
584 | REMOVED => error "mark: REMOVED"
585 (*esac*))
586 in
587 IntHashTable.appi rewriteAll affectedBlocks;
588 app mark nodesToSpill;
589 rebuild(cellkind, graph)
590 end (* spill *)
591 in
592 { build = build,
593 spill = spill,
594 programPoint= fn{block,instr} => progPt(block,instr),
595 blockNum = blockNum,
596 instrNum = instrNum
597 }
598 end
599 end
600