436e008b01a778b0ae35d581dec1bf578c3c8868
[mesa.git] / src / util / register_allocate.c
1 /*
2 * Copyright © 2010 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Eric Anholt <eric@anholt.net>
25 *
26 */
27
28 /** @file register_allocate.c
29 *
30 * Graph-coloring register allocator.
31 *
32 * The basic idea of graph coloring is to make a node in a graph for
33 * every thing that needs a register (color) number assigned, and make
34 * edges in the graph between nodes that interfere (can't be allocated
35 * to the same register at the same time).
36 *
37 * During the "simplify" process, any any node with fewer edges than
38 * there are registers means that that edge can get assigned a
39 * register regardless of what its neighbors choose, so that node is
40 * pushed on a stack and removed (with its edges) from the graph.
41 * That likely causes other nodes to become trivially colorable as well.
42 *
43 * Then during the "select" process, nodes are popped off of that
44 * stack, their edges restored, and assigned a color different from
45 * their neighbors. Because they were pushed on the stack only when
46 * they were trivially colorable, any color chosen won't interfere
47 * with the registers to be popped later.
48 *
49 * The downside to most graph coloring is that real hardware often has
50 * limitations, like registers that need to be allocated to a node in
51 * pairs, or aligned on some boundary. This implementation follows
52 * the paper "Retargetable Graph-Coloring Register Allocation for
53 * Irregular Architectures" by Johan Runeson and Sven-Olof Nyström.
54 *
55 * In this system, there are register classes each containing various
56 * registers, and registers may interfere with other registers. For
57 * example, one might have a class of base registers, and a class of
58 * aligned register pairs that would each interfere with their pair of
59 * the base registers. Each node has a register class it needs to be
60 * assigned to. Define p(B) to be the size of register class B, and
61 * q(B,C) to be the number of registers in B that the worst choice
62 * register in C could conflict with. Then, this system replaces the
63 * basic graph coloring test of "fewer edges from this node than there
64 * are registers" with "For this node of class B, the sum of q(B,C)
65 * for each neighbor node of class C is less than pB".
66 *
67 * A nice feature of the pq test is that q(B,C) can be computed once
68 * up front and stored in a 2-dimensional array, so that the cost of
69 * coloring a node is constant with the number of registers. We do
70 * this during ra_set_finalize().
71 */
72
73 #include <stdbool.h>
74
75 #include "ralloc.h"
76 #include "main/imports.h"
77 #include "main/macros.h"
78 #include "main/mtypes.h"
79 #include "util/bitset.h"
80 #include "register_allocate.h"
81
82 #define NO_REG ~0U
83
84 struct ra_reg {
85 BITSET_WORD *conflicts;
86 unsigned int *conflict_list;
87 unsigned int conflict_list_size;
88 unsigned int num_conflicts;
89 };
90
91 struct ra_regs {
92 struct ra_reg *regs;
93 unsigned int count;
94
95 struct ra_class **classes;
96 unsigned int class_count;
97
98 bool round_robin;
99 };
100
101 struct ra_class {
102 /**
103 * Bitset indicating which registers belong to this class.
104 *
105 * (If bit N is set, then register N belongs to this class.)
106 */
107 BITSET_WORD *regs;
108
109 /**
110 * p(B) in Runeson/Nyström paper.
111 *
112 * This is "how many regs are in the set."
113 */
114 unsigned int p;
115
116 /**
117 * q(B,C) (indexed by C, B is this register class) in
118 * Runeson/Nyström paper. This is "how many registers of B could
119 * the worst choice register from C conflict with".
120 */
121 unsigned int *q;
122 };
123
124 struct ra_node {
125 /** @{
126 *
127 * List of which nodes this node interferes with. This should be
128 * symmetric with the other node.
129 */
130 BITSET_WORD *adjacency;
131 unsigned int *adjacency_list;
132 unsigned int adjacency_list_size;
133 unsigned int adjacency_count;
134 /** @} */
135
136 unsigned int class;
137
138 /* Register, if assigned, or NO_REG. */
139 unsigned int reg;
140
141 /**
142 * Set when the node is in the trivially colorable stack. When
143 * set, the adjacency to this node is ignored, to implement the
144 * "remove the edge from the graph" in simplification without
145 * having to actually modify the adjacency_list.
146 */
147 bool in_stack;
148
149 /**
150 * The q total, as defined in the Runeson/Nyström paper, for all the
151 * interfering nodes not in the stack.
152 */
153 unsigned int q_total;
154
155 /* For an implementation that needs register spilling, this is the
156 * approximate cost of spilling this node.
157 */
158 float spill_cost;
159 };
160
161 struct ra_graph {
162 struct ra_regs *regs;
163 /**
164 * the variables that need register allocation.
165 */
166 struct ra_node *nodes;
167 unsigned int count; /**< count of nodes. */
168
169 unsigned int *stack;
170 unsigned int stack_count;
171
172 /**
173 * Tracks the start of the set of optimistically-colored registers in the
174 * stack.
175 */
176 unsigned int stack_optimistic_start;
177 };
178
179 /**
180 * Creates a set of registers for the allocator.
181 *
182 * mem_ctx is a ralloc context for the allocator. The reg set may be freed
183 * using ralloc_free().
184 */
185 struct ra_regs *
186 ra_alloc_reg_set(void *mem_ctx, unsigned int count)
187 {
188 unsigned int i;
189 struct ra_regs *regs;
190
191 regs = rzalloc(mem_ctx, struct ra_regs);
192 regs->count = count;
193 regs->regs = rzalloc_array(regs, struct ra_reg, count);
194
195 for (i = 0; i < count; i++) {
196 regs->regs[i].conflicts = rzalloc_array(regs->regs, BITSET_WORD,
197 BITSET_WORDS(count));
198 BITSET_SET(regs->regs[i].conflicts, i);
199
200 regs->regs[i].conflict_list = ralloc_array(regs->regs, unsigned int, 4);
201 regs->regs[i].conflict_list_size = 4;
202 regs->regs[i].conflict_list[0] = i;
203 regs->regs[i].num_conflicts = 1;
204 }
205
206 return regs;
207 }
208
209 /**
210 * The register allocator by default prefers to allocate low register numbers,
211 * since it was written for hardware (gen4/5 Intel) that is limited in its
212 * multithreadedness by the number of registers used in a given shader.
213 *
214 * However, for hardware without that restriction, densely packed register
215 * allocation can put serious constraints on instruction scheduling. This
216 * function tells the allocator to rotate around the registers if possible as
217 * it allocates the nodes.
218 */
219 void
220 ra_set_allocate_round_robin(struct ra_regs *regs)
221 {
222 regs->round_robin = true;
223 }
224
225 static void
226 ra_add_conflict_list(struct ra_regs *regs, unsigned int r1, unsigned int r2)
227 {
228 struct ra_reg *reg1 = &regs->regs[r1];
229
230 if (reg1->conflict_list_size == reg1->num_conflicts) {
231 reg1->conflict_list_size *= 2;
232 reg1->conflict_list = reralloc(regs->regs, reg1->conflict_list,
233 unsigned int, reg1->conflict_list_size);
234 }
235 reg1->conflict_list[reg1->num_conflicts++] = r2;
236 BITSET_SET(reg1->conflicts, r2);
237 }
238
239 void
240 ra_add_reg_conflict(struct ra_regs *regs, unsigned int r1, unsigned int r2)
241 {
242 if (!BITSET_TEST(regs->regs[r1].conflicts, r2)) {
243 ra_add_conflict_list(regs, r1, r2);
244 ra_add_conflict_list(regs, r2, r1);
245 }
246 }
247
248 /**
249 * Adds a conflict between base_reg and reg, and also between reg and
250 * anything that base_reg conflicts with.
251 *
252 * This can simplify code for setting up multiple register classes
253 * which are aggregates of some base hardware registers, compared to
254 * explicitly using ra_add_reg_conflict.
255 */
256 void
257 ra_add_transitive_reg_conflict(struct ra_regs *regs,
258 unsigned int base_reg, unsigned int reg)
259 {
260 unsigned int i;
261
262 ra_add_reg_conflict(regs, reg, base_reg);
263
264 for (i = 0; i < regs->regs[base_reg].num_conflicts; i++) {
265 ra_add_reg_conflict(regs, reg, regs->regs[base_reg].conflict_list[i]);
266 }
267 }
268
269 unsigned int
270 ra_alloc_reg_class(struct ra_regs *regs)
271 {
272 struct ra_class *class;
273
274 regs->classes = reralloc(regs->regs, regs->classes, struct ra_class *,
275 regs->class_count + 1);
276
277 class = rzalloc(regs, struct ra_class);
278 regs->classes[regs->class_count] = class;
279
280 class->regs = rzalloc_array(class, BITSET_WORD, BITSET_WORDS(regs->count));
281
282 return regs->class_count++;
283 }
284
285 void
286 ra_class_add_reg(struct ra_regs *regs, unsigned int c, unsigned int r)
287 {
288 struct ra_class *class = regs->classes[c];
289
290 BITSET_SET(class->regs, r);
291 class->p++;
292 }
293
294 /**
295 * Returns true if the register belongs to the given class.
296 */
297 static bool
298 reg_belongs_to_class(unsigned int r, struct ra_class *c)
299 {
300 return BITSET_TEST(c->regs, r);
301 }
302
303 /**
304 * Must be called after all conflicts and register classes have been
305 * set up and before the register set is used for allocation.
306 * To avoid costly q value computation, use the q_values paramater
307 * to pass precomputed q values to this function.
308 */
309 void
310 ra_set_finalize(struct ra_regs *regs, unsigned int **q_values)
311 {
312 unsigned int b, c;
313
314 for (b = 0; b < regs->class_count; b++) {
315 regs->classes[b]->q = ralloc_array(regs, unsigned int, regs->class_count);
316 }
317
318 if (q_values) {
319 for (b = 0; b < regs->class_count; b++) {
320 for (c = 0; c < regs->class_count; c++) {
321 regs->classes[b]->q[c] = q_values[b][c];
322 }
323 }
324 } else {
325 /* Compute, for each class B and C, how many regs of B an
326 * allocation to C could conflict with.
327 */
328 for (b = 0; b < regs->class_count; b++) {
329 for (c = 0; c < regs->class_count; c++) {
330 unsigned int rc;
331 int max_conflicts = 0;
332
333 for (rc = 0; rc < regs->count; rc++) {
334 int conflicts = 0;
335 unsigned int i;
336
337 if (!reg_belongs_to_class(rc, regs->classes[c]))
338 continue;
339
340 for (i = 0; i < regs->regs[rc].num_conflicts; i++) {
341 unsigned int rb = regs->regs[rc].conflict_list[i];
342 if (reg_belongs_to_class(rb, regs->classes[b]))
343 conflicts++;
344 }
345 max_conflicts = MAX2(max_conflicts, conflicts);
346 }
347 regs->classes[b]->q[c] = max_conflicts;
348 }
349 }
350 }
351
352 for (b = 0; b < regs->count; b++) {
353 ralloc_free(regs->regs[b].conflict_list);
354 regs->regs[b].conflict_list = NULL;
355 }
356 }
357
358 static void
359 ra_add_node_adjacency(struct ra_graph *g, unsigned int n1, unsigned int n2)
360 {
361 BITSET_SET(g->nodes[n1].adjacency, n2);
362
363 if (n1 != n2) {
364 int n1_class = g->nodes[n1].class;
365 int n2_class = g->nodes[n2].class;
366 g->nodes[n1].q_total += g->regs->classes[n1_class]->q[n2_class];
367 }
368
369 if (g->nodes[n1].adjacency_count >=
370 g->nodes[n1].adjacency_list_size) {
371 g->nodes[n1].adjacency_list_size *= 2;
372 g->nodes[n1].adjacency_list = reralloc(g, g->nodes[n1].adjacency_list,
373 unsigned int,
374 g->nodes[n1].adjacency_list_size);
375 }
376
377 g->nodes[n1].adjacency_list[g->nodes[n1].adjacency_count] = n2;
378 g->nodes[n1].adjacency_count++;
379 }
380
381 struct ra_graph *
382 ra_alloc_interference_graph(struct ra_regs *regs, unsigned int count)
383 {
384 struct ra_graph *g;
385 unsigned int i;
386
387 g = rzalloc(NULL, struct ra_graph);
388 g->regs = regs;
389 g->nodes = rzalloc_array(g, struct ra_node, count);
390 g->count = count;
391
392 g->stack = rzalloc_array(g, unsigned int, count);
393
394 for (i = 0; i < count; i++) {
395 int bitset_count = BITSET_WORDS(count);
396 g->nodes[i].adjacency = rzalloc_array(g, BITSET_WORD, bitset_count);
397
398 g->nodes[i].adjacency_list_size = 4;
399 g->nodes[i].adjacency_list =
400 ralloc_array(g, unsigned int, g->nodes[i].adjacency_list_size);
401 g->nodes[i].adjacency_count = 0;
402 g->nodes[i].q_total = 0;
403
404 ra_add_node_adjacency(g, i, i);
405 g->nodes[i].reg = NO_REG;
406 }
407
408 return g;
409 }
410
411 void
412 ra_set_node_class(struct ra_graph *g,
413 unsigned int n, unsigned int class)
414 {
415 g->nodes[n].class = class;
416 }
417
418 void
419 ra_add_node_interference(struct ra_graph *g,
420 unsigned int n1, unsigned int n2)
421 {
422 if (!BITSET_TEST(g->nodes[n1].adjacency, n2)) {
423 ra_add_node_adjacency(g, n1, n2);
424 ra_add_node_adjacency(g, n2, n1);
425 }
426 }
427
428 static bool
429 pq_test(struct ra_graph *g, unsigned int n)
430 {
431 int n_class = g->nodes[n].class;
432
433 return g->nodes[n].q_total < g->regs->classes[n_class]->p;
434 }
435
436 static void
437 decrement_q(struct ra_graph *g, unsigned int n)
438 {
439 unsigned int i;
440 int n_class = g->nodes[n].class;
441
442 for (i = 0; i < g->nodes[n].adjacency_count; i++) {
443 unsigned int n2 = g->nodes[n].adjacency_list[i];
444 unsigned int n2_class = g->nodes[n2].class;
445
446 if (n != n2 && !g->nodes[n2].in_stack) {
447 assert(g->nodes[n2].q_total >= g->regs->classes[n2_class]->q[n_class]);
448 g->nodes[n2].q_total -= g->regs->classes[n2_class]->q[n_class];
449 }
450 }
451 }
452
453 /**
454 * Simplifies the interference graph by pushing all
455 * trivially-colorable nodes into a stack of nodes to be colored,
456 * removing them from the graph, and rinsing and repeating.
457 *
458 * If we encounter a case where we can't push any nodes on the stack, then
459 * we optimistically choose a node and push it on the stack. We heuristically
460 * push the node with the lowest total q value, since it has the fewest
461 * neighbors and therefore is most likely to be allocated.
462 */
463 static void
464 ra_simplify(struct ra_graph *g)
465 {
466 bool progress = true;
467 unsigned int stack_optimistic_start = UINT_MAX;
468 int i;
469
470 while (progress) {
471 unsigned int best_optimistic_node = ~0;
472 unsigned int lowest_q_total = ~0;
473
474 progress = false;
475
476 for (i = g->count - 1; i >= 0; i--) {
477 if (g->nodes[i].in_stack || g->nodes[i].reg != NO_REG)
478 continue;
479
480 if (pq_test(g, i)) {
481 decrement_q(g, i);
482 g->stack[g->stack_count] = i;
483 g->stack_count++;
484 g->nodes[i].in_stack = true;
485 progress = true;
486 } else {
487 unsigned int new_q_total = g->nodes[i].q_total;
488 if (new_q_total < lowest_q_total) {
489 best_optimistic_node = i;
490 lowest_q_total = new_q_total;
491 }
492 }
493 }
494
495 if (!progress && best_optimistic_node != ~0U) {
496 if (stack_optimistic_start == UINT_MAX)
497 stack_optimistic_start = g->stack_count;
498
499 decrement_q(g, best_optimistic_node);
500 g->stack[g->stack_count] = best_optimistic_node;
501 g->stack_count++;
502 g->nodes[best_optimistic_node].in_stack = true;
503 progress = true;
504 }
505 }
506
507 g->stack_optimistic_start = stack_optimistic_start;
508 }
509
510 /**
511 * Pops nodes from the stack back into the graph, coloring them with
512 * registers as they go.
513 *
514 * If all nodes were trivially colorable, then this must succeed. If
515 * not (optimistic coloring), then it may return false;
516 */
517 static bool
518 ra_select(struct ra_graph *g)
519 {
520 int start_search_reg = 0;
521
522 while (g->stack_count != 0) {
523 unsigned int i;
524 unsigned int ri;
525 unsigned int r = -1;
526 int n = g->stack[g->stack_count - 1];
527 struct ra_class *c = g->regs->classes[g->nodes[n].class];
528
529 /* Find the lowest-numbered reg which is not used by a member
530 * of the graph adjacent to us.
531 */
532 for (ri = 0; ri < g->regs->count; ri++) {
533 r = (start_search_reg + ri) % g->regs->count;
534 if (!reg_belongs_to_class(r, c))
535 continue;
536
537 /* Check if any of our neighbors conflict with this register choice. */
538 for (i = 0; i < g->nodes[n].adjacency_count; i++) {
539 unsigned int n2 = g->nodes[n].adjacency_list[i];
540
541 if (!g->nodes[n2].in_stack &&
542 BITSET_TEST(g->regs->regs[r].conflicts, g->nodes[n2].reg)) {
543 break;
544 }
545 }
546 if (i == g->nodes[n].adjacency_count)
547 break;
548 }
549
550 /* set this to false even if we return here so that
551 * ra_get_best_spill_node() considers this node later.
552 */
553 g->nodes[n].in_stack = false;
554
555 if (ri == g->regs->count)
556 return false;
557
558 g->nodes[n].reg = r;
559 g->stack_count--;
560
561 /* Rotate the starting point except for any nodes above the lowest
562 * optimistically colorable node. The likelihood that we will succeed
563 * at allocating optimistically colorable nodes is highly dependent on
564 * the way that the previous nodes popped off the stack are laid out.
565 * The round-robin strategy increases the fragmentation of the register
566 * file and decreases the number of nearby nodes assigned to the same
567 * color, what increases the likelihood of spilling with respect to the
568 * dense packing strategy.
569 */
570 if (g->regs->round_robin &&
571 g->stack_count - 1 <= g->stack_optimistic_start)
572 start_search_reg = r + 1;
573 }
574
575 return true;
576 }
577
578 bool
579 ra_allocate(struct ra_graph *g)
580 {
581 ra_simplify(g);
582 return ra_select(g);
583 }
584
585 unsigned int
586 ra_get_node_reg(struct ra_graph *g, unsigned int n)
587 {
588 return g->nodes[n].reg;
589 }
590
591 /**
592 * Forces a node to a specific register. This can be used to avoid
593 * creating a register class containing one node when handling data
594 * that must live in a fixed location and is known to not conflict
595 * with other forced register assignment (as is common with shader
596 * input data). These nodes do not end up in the stack during
597 * ra_simplify(), and thus at ra_select() time it is as if they were
598 * the first popped off the stack and assigned their fixed locations.
599 * Nodes that use this function do not need to be assigned a register
600 * class.
601 *
602 * Must be called before ra_simplify().
603 */
604 void
605 ra_set_node_reg(struct ra_graph *g, unsigned int n, unsigned int reg)
606 {
607 g->nodes[n].reg = reg;
608 g->nodes[n].in_stack = false;
609 }
610
611 static float
612 ra_get_spill_benefit(struct ra_graph *g, unsigned int n)
613 {
614 unsigned int j;
615 float benefit = 0;
616 int n_class = g->nodes[n].class;
617
618 /* Define the benefit of eliminating an interference between n, n2
619 * through spilling as q(C, B) / p(C). This is similar to the
620 * "count number of edges" approach of traditional graph coloring,
621 * but takes classes into account.
622 */
623 for (j = 0; j < g->nodes[n].adjacency_count; j++) {
624 unsigned int n2 = g->nodes[n].adjacency_list[j];
625 if (n != n2) {
626 unsigned int n2_class = g->nodes[n2].class;
627 benefit += ((float)g->regs->classes[n_class]->q[n2_class] /
628 g->regs->classes[n_class]->p);
629 }
630 }
631
632 return benefit;
633 }
634
635 /**
636 * Returns a node number to be spilled according to the cost/benefit using
637 * the pq test, or -1 if there are no spillable nodes.
638 */
639 int
640 ra_get_best_spill_node(struct ra_graph *g)
641 {
642 unsigned int best_node = -1;
643 float best_benefit = 0.0;
644 unsigned int n;
645
646 /* Consider any nodes that we colored successfully or the node we failed to
647 * color for spilling. When we failed to color a node in ra_select(), we
648 * only considered these nodes, so spilling any other ones would not result
649 * in us making progress.
650 */
651 for (n = 0; n < g->count; n++) {
652 float cost = g->nodes[n].spill_cost;
653 float benefit;
654
655 if (cost <= 0.0f)
656 continue;
657
658 if (g->nodes[n].in_stack)
659 continue;
660
661 benefit = ra_get_spill_benefit(g, n);
662
663 if (benefit / cost > best_benefit) {
664 best_benefit = benefit / cost;
665 best_node = n;
666 }
667 }
668
669 return best_node;
670 }
671
672 /**
673 * Only nodes with a spill cost set (cost != 0.0) will be considered
674 * for register spilling.
675 */
676 void
677 ra_set_node_spill_cost(struct ra_graph *g, unsigned int n, float cost)
678 {
679 g->nodes[n].spill_cost = cost;
680 }