Debian Codegraph @

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

raw
1 (*
2 * This is the new register allocator based on
3 * the 'iterated register coalescing' scheme described
4 * in POPL'96, and TOPLAS v18 #3, pp 325-353.
5 *
6 * Now with numerous extensions:
7 *
8 * 0. Dead copy elimination (optional)
9 * 1. Priority based coalescing
10 * 2. Priority based freezing
11 * 3. Priority based spilling
12 * 4. Biased selection (optional)
13 * 5. Spill Coalescing (optional)
14 * 6. Spill Propagation (optional)
15 * 7. Spill Coloring (optional)
16 *
17 * For details, please see the paper from
18 *
19 * http://cm.bell-labs.com/cm/cs/what/smlnj/compiler-notes/index.html
20 *
21 * The basic structure of this register allocator is as follows:
22 * 1. RAGraph. This module enscapsulates the interference graph
23 * datatype (adjacency list + interference graph + node table)
24 * and contains nothing architecture specific.
25 * 2. RACore. This module implements the main part of the iterated
26 * coalescing algorithm, with frequency enhancements.
27 * 3. RA_FLOWGRAPH. This register allocator is parameterized
28 * with respect to this signature. This basically abstracts out
29 * the representation of the program flowgraph, and provide
30 * a few services to the main allocator, such as building the
31 * interference graph, rewriting the flowgraph after spilling,
32 * and rebuilding the interference graph after spilling.
33 * This module is responsible for caching any information necessary
34 * to make spilling fast.
35 * 4. This functor. This functor drives the entire process.
36 *
37 * -- Allen Leung ([email protected])
38 *)
39
40 functor RegisterAllocator (
41 structure SpillHeuristics : RA_SPILL_HEURISTICS
42 structure Flowgraph : RA_FLOWGRAPH (* where C = CellsBasis *)
43 ) : RA =
44 struct
45
46 structure F = Flowgraph
47 structure I = F.I
48 structure Core = RACore
49 structure C = I.C
50 structure G = Core.G
51 structure CB = CellsBasis
52
53 type getreg = { pref : CB.cell_id list,
54 stamp : int,
55 proh : int Array.array
56 } -> CB.cell_id
57
58 type mode = word
59
60 datatype spillLoc = datatype G.spillLoc
61
62 type raClient =
63 { cellkind : CB.cellkind, (* kind of register *)
64 spillProh : CB.cell list, (* don't spill these *)
65 memRegs : CB.cell list, (* memory registers *)
66 K : int, (* number of colors *)
67 dedicated : int -> bool, (* dedicated registers *)
68 getreg : getreg, (* how to find a color *)
69 copyInstr : F.Spill.copyInstr, (* how to make a copy *)
70 spill : F.Spill.spill, (* spill callback *)
71 spillSrc : F.Spill.spillSrc, (* spill callback *)
72 spillCopyTmp : F.Spill.spillCopyTmp, (* spill callback *)
73 reload : F.Spill.reload, (* reload callback *)
74 reloadDst : F.Spill.reloadDst, (* reload callback *)
75 renameSrc : F.Spill.renameSrc, (* rename callback *)
76 mode : mode (* mode *)
77 }
78
79 val debug = false
80
81 val NO_OPTIMIZATION = 0wx0
82 val DEAD_COPY_ELIM = Core.DEAD_COPY_ELIM
83 val BIASED_SELECTION = Core.BIASED_SELECTION
84 val HAS_PARALLEL_COPIES = Core.HAS_PARALLEL_COPIES
85 val SPILL_COALESCING = 0wx100
86 val SPILL_COLORING = 0wx200
87 val SPILL_PROPAGATION = 0wx400
88
89 fun isOn(flag, mask) = Word.andb(flag,mask) <> 0w0
90
91 open G
92 structure C = I.C
93
94 fun error msg = MLRiscErrorMsg.error("RegisterAllocator",msg)
95
96 (*
97 * Debugging flags + counters
98 *)
99 val cfg_before_ra = MLRiscControl.mkFlag ("dump-cfg-before-ra",
100 "whether CFG is shown before RA")
101 val cfg_after_ra = MLRiscControl.mkFlag ("dump-cfg-after-ra",
102 "whether CFG is shown after RA")
103 val cfg_after_spill = MLRiscControl.mkFlag ("dump-cfg-after-spilling",
104 "whether CFG is shown after spill phase")
105 val cfg_before_ras = MLRiscControl.mkFlag ("dump-cfg-before-all-ra",
106 "whether CFG is shown before all RA")
107 val cfg_after_ras = MLRiscControl.mkFlag ("dump-cfg-after-all-ra",
108 "whether CFG is shown after all RA")
109 val dump_graph = MLRiscControl.mkFlag ("dump-interference-graph",
110 "whether interference graph is shown")
111 val debug_spill = MLRiscControl.mkFlag ("ra-debug-spilling",
112 "debug mode for spill phase")
113 val ra_count = MLRiscControl.mkCounter ("ra-count", "RA counter")
114 val rebuild_count = MLRiscControl.mkCounter ("ra-rebuild", "RA build counter")
115
116 (*
117 val count_dead = MLRiscControl.getFlag "ra-count-dead-code"
118 val dead = MLRiscControl.getCounter "ra-dead-code"
119 *)
120 val debug_stream = MLRiscControl.debug_stream
121
122 (*
123 * Optimization flags
124 *)
125 (*
126 val rematerialization = MLRiscControl.getFlag "ra-rematerialization"
127 *)
128
129 exception NodeTable
130
131 val i2s = Int.toString
132
133 (* This array is used for getreg.
134 * We allocate it once.
135 *)
136 val proh = Array.array(C.firstPseudo, ~1)
137
138 (*
139 * Register allocator.
140 * spillProh is a list of registers that are not candidates for spills.
141 *)
142 fun ra params flowgraph =
143 let
144 (* Flowgraph methods *)
145 val {build=buildMethod, spill=spillMethod, ...} = F.services flowgraph
146
147 (* global spill location counter *)
148 (* Note: spillLoc cannot be zero as negative locations are
149 * returned to the client to indicate spill locations.
150 *)
151 val spillLoc=ref 1
152
153 (* How to dump the flowgraph *)
154 fun dumpFlowgraph (flag, title) =
155 if !flag then F.dumpFlowgraph(title, flowgraph,!debug_stream) else ()
156
157 (* Main function *)
158 fun regalloc{getreg, K, dedicated, copyInstr,
159 spill, spillSrc, spillCopyTmp, renameSrc,
160 reload, reloadDst, spillProh, cellkind, mode,
161 memRegs} =
162 let val numCell = C.numCell cellkind ()
163 in if numCell = 0
164 then ()
165 else
166 let (* the nodes table *)
167 val nodes = IntHashTable.mkTable(numCell,NodeTable)
168 val mode = if isOn(HAS_PARALLEL_COPIES, mode) then
169 Word.orb(Core.SAVE_COPY_TEMPS, mode)
170 else mode
171 (* create an empty interference graph *)
172 val G = G.newGraph{nodes=nodes,
173 K=K,
174 dedicated=dedicated,
175 numRegs=numCell,
176 maxRegs=C.maxCell,
177 showReg=CellsBasis.toString,
178 getreg=getreg,
179 getpair=fn _ => error "getpair",
180 firstPseudoR=C.firstPseudo,
181 proh=proh,
182 mode=Word.orb(Flowgraph.mode,
183 Word.orb(mode,SpillHeuristics.mode)),
184 spillLoc=spillLoc,
185 memRegs=memRegs
186 }
187 val G.GRAPH{spilledRegs, pseudoCount, spillFlag, ...} = G
188
189 val hasBeenSpilled = IntHashTable.find spilledRegs
190 val hasBeenSpilled =
191 fn r => case hasBeenSpilled r of SOME _ => true | NONE => false
192
193 fun logGraph(header,G) =
194 if !dump_graph then
195 (TextIO.output(!debug_stream,
196 "-------------"^header^"-----------\n");
197 Core.dumpGraph G (!debug_stream)
198 )
199 else ()
200
201 (*
202 * Build the interference graph
203 *)
204 fun buildGraph(G) =
205 let val _ = if debug then print "build..." else ()
206 val moves = buildMethod(G,cellkind)
207 val worklists =
208 (Core.initWorkLists G) {moves=moves}
209 in logGraph("build",G);
210 if debug then
211 let val G.GRAPH{bitMatrix=ref(G.BM.BM{elems, ...}), ...} = G
212 in print ("done: nodes="^i2s(IntHashTable.numItems nodes)^
213 " edges="^i2s(!elems)^
214 " moves="^i2s(length moves)^
215 "\n")
216 end else ();
217 worklists
218 end
219
220 (*
221 * Potential spill phase
222 *)
223 fun chooseVictim{spillWkl} =
224 let fun dumpSpillCandidates(spillWkl) =
225 (print "Spill candidates:\n";
226 app (fn n => print(Core.show G n^" ")) spillWkl;
227 print "\n"
228 )
229 (* Initialize if it is the first time we spill *)
230 val _ = if !spillFlag then () else SpillHeuristics.init()
231 (* Choose a node *)
232 val {node,cost,spillWkl} =
233 SpillHeuristics.chooseSpillNode
234 {graph=G, hasBeenSpilled=hasBeenSpilled,
235 spillWkl=spillWkl}
236 handle SpillHeuristics.NoCandidate =>
237 (Core.dumpGraph G (!debug_stream);
238 dumpSpillCandidates(spillWkl);
239 error ("chooseVictim")
240 )
241 in if !debug_spill then
242 (case node of
243 NONE => ()
244 | SOME(best as NODE{defs,uses,...}) =>
245 print("Spilling node "^Core.show G best^
246 " cost="^Real.toString cost^
247 " defs="^i2s(length(!defs))^
248 " uses="^i2s(length(!uses))^"\n"
249 )
250 ) else ();
251 {node=node,cost=cost,spillWkl=spillWkl}
252 end
253
254 (*
255 * Mark spill nodes
256 *)
257 fun markSpillNodes nodesToSpill =
258 let val marker = SPILLED
259 fun loop [] = ()
260 | loop(NODE{color, ...}::ns) = (color := marker; loop ns)
261 in loop nodesToSpill end
262
263 (* Mark nodes that are immediately aliased to mem regs;
264 * These are nodes that need also to be spilled
265 *)
266 fun markMemRegs [] = ()
267 | markMemRegs(NODE{number=r, color as ref(ALIASED
268 (NODE{color=ref(col as MEMREG _), ...})), ...}::ns) =
269 (color := col;
270 markMemRegs ns)
271 | markMemRegs(_::ns) = markMemRegs ns
272
273 (*
274 * Actual spill phase.
275 * Insert spill node and incrementally
276 * update the interference graph.
277 *)
278 fun actualSpills{spills} =
279 let val _ = if debug then print "spill..." else ();
280 val _ = if isOn(mode,
281 SPILL_COALESCING+
282 SPILL_PROPAGATION+
283 SPILL_COLORING) then
284 markSpillNodes spills
285 else ()
286 val _ = if isOn(mode,SPILL_PROPAGATION+SPILL_COALESCING) then
287 Core.initMemMoves G
288 else ()
289 val _ = logGraph("actual spill",G);
290 val {simplifyWkl,freezeWkl,moveWkl,spillWkl} =
291 Core.initWorkLists G
292 {moves=spillMethod{graph=G, cellkind=cellkind,
293 spill=spill, spillSrc=spillSrc,
294 spillCopyTmp=spillCopyTmp,
295 renameSrc=renameSrc,
296 reload=reload, reloadDst=reloadDst,
297 copyInstr=copyInstr, nodes=spills
298 }
299 }
300 val _ = dumpFlowgraph(cfg_after_spill,"after spilling")
301 in logGraph("rebuild",G);
302 if debug then print "done\n" else ();
303 rebuild_count := !rebuild_count + 1;
304 (simplifyWkl, moveWkl, freezeWkl, spillWkl, [])
305 end
306
307 (*
308 * Main loop of the algorithm
309 *)
310 fun main(G) =
311 let
312
313 (* Main loop *)
314 fun loop(simplifyWkl,moveWkl,freezeWkl,spillWkl,stack) =
315 let val iteratedCoal = Core.iteratedCoalescing G
316 val potentialSpill = Core.potentialSpillNode G
317 (* simplify/coalesce/freeze/potential spill phases
318 * simplifyWkl -- non-move related nodes with low degree
319 * moveWkl -- moves to be considered for coalescing
320 * freezeWkl -- move related nodes (with low degree)
321 * spillWkl -- potential spill nodes
322 * stack -- simplified nodes
323 *)
324 fun iterate(simplifyWkl,moveWkl,freezeWkl,spillWkl,stack) =
325 let (* perform iterated coalescing *)
326 val {stack} = iteratedCoal{simplifyWkl=simplifyWkl,
327 moveWkl=moveWkl,
328 freezeWkl=freezeWkl,
329 stack=stack}
330 in case spillWkl of
331 [] => stack (* nothing to spill *)
332 | _ =>
333 if !pseudoCount = 0 (* all nodes simplified *)
334 then stack
335 else
336 let val {node,cost,spillWkl} =
337 chooseVictim{spillWkl=spillWkl}
338 in case node of
339 SOME node => (* spill node and continue *)
340 let val _ = if debug then print "-" else ()
341 val {moveWkl,freezeWkl,stack} =
342 potentialSpill{node=node,
343 cost=cost,
344 stack=stack}
345 in iterate([],moveWkl,freezeWkl,spillWkl,stack)
346 end
347 | NONE => stack (* nothing to spill *)
348 end
349 end
350
351 val {spills} =
352 if K = 0 then
353 {spills=spillWkl}
354 else
355 let (* simplify the nodes *)
356 val stack = iterate
357 (simplifyWkl,moveWkl,freezeWkl,spillWkl,stack)
358 (* color the nodes *)
359 in (Core.select G) {stack=stack}
360 end
361 in (* check for actual spills *)
362 case spills of
363 [] => ()
364 | spills => loop(actualSpills{spills=spills})
365 end
366
367 val {simplifyWkl, moveWkl, freezeWkl, spillWkl} = buildGraph G
368
369 in loop(simplifyWkl, moveWkl, freezeWkl, spillWkl, [])
370 end
371
372 fun initSpillProh(cells) =
373 let val markAsSpilled = IntHashTable.insert spilledRegs
374 fun mark r = markAsSpilled(CellsBasis.registerId r,true)
375 in app mark cells end
376
377 in dumpFlowgraph(cfg_before_ra,"before register allocation");
378 initSpillProh spillProh;
379 main(G); (* main loop *)
380 (* update the colors for all cells *)
381 logGraph("done",G);
382 Core.updateCellColors G;
383 Core.markDeadCopiesAsSpilled G;
384 ra_count := !ra_count + 1;
385 dumpFlowgraph(cfg_after_ra,"after register allocation");
386 (* Clean up spilling *)
387 SpillHeuristics.init()
388 end
389 end
390
391 fun regallocs [] = ()
392 | regallocs(p::ps) = (regalloc p; regallocs ps)
393
394 in dumpFlowgraph(cfg_before_ras,"before register allocation");
395 regallocs params;
396 dumpFlowgraph(cfg_after_ras,"after register allocation");
397 flowgraph
398 end
399
400 end