1/*
2 * Copyright © 2011 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
24#include "util/register_allocate.h"
25#include "brw_vec4.h"
26#include "brw_cfg.h"
27
28using namespace brw;
29
30namespace brw {
31
32static void
33assign(unsigned int *reg_hw_locations, backend_reg *reg)
34{
35   if (reg->file == VGRF) {
36      reg->nr = reg_hw_locations[reg->nr] + reg->offset / REG_SIZE;
37      reg->offset %= REG_SIZE;
38   }
39}
40
41bool
42vec4_visitor::reg_allocate_trivial()
43{
44   unsigned int hw_reg_mapping[this->alloc.count];
45   bool virtual_grf_used[this->alloc.count];
46   int next;
47
48   /* Calculate which virtual GRFs are actually in use after whatever
49    * optimization passes have occurred.
50    */
51   for (unsigned i = 0; i < this->alloc.count; i++) {
52      virtual_grf_used[i] = false;
53   }
54
55   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
56      if (inst->dst.file == VGRF)
57         virtual_grf_used[inst->dst.nr] = true;
58
59      for (unsigned i = 0; i < 3; i++) {
60	 if (inst->src[i].file == VGRF)
61            virtual_grf_used[inst->src[i].nr] = true;
62      }
63   }
64
65   hw_reg_mapping[0] = this->first_non_payload_grf;
66   next = hw_reg_mapping[0] + this->alloc.sizes[0];
67   for (unsigned i = 1; i < this->alloc.count; i++) {
68      if (virtual_grf_used[i]) {
69	 hw_reg_mapping[i] = next;
70	 next += this->alloc.sizes[i];
71      }
72   }
73   prog_data->total_grf = next;
74
75   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
76      assign(hw_reg_mapping, &inst->dst);
77      assign(hw_reg_mapping, &inst->src[0]);
78      assign(hw_reg_mapping, &inst->src[1]);
79      assign(hw_reg_mapping, &inst->src[2]);
80   }
81
82   if (prog_data->total_grf > max_grf) {
83      fail("Ran out of regs on trivial allocator (%d/%d)\n",
84	   prog_data->total_grf, max_grf);
85      return false;
86   }
87
88   return true;
89}
90
91extern "C" void
92brw_vec4_alloc_reg_set(struct brw_compiler *compiler)
93{
94   int base_reg_count =
95      compiler->devinfo->ver >= 7 ? GFX7_MRF_HACK_START : BRW_MAX_GRF;
96
97   assert(compiler->devinfo->ver < 8);
98
99   /* After running split_virtual_grfs(), almost all VGRFs will be of size 1.
100    * SEND-from-GRF sources cannot be split, so we also need classes for each
101    * potential message length.
102    */
103   const int class_count = MAX_VGRF_SIZE;
104   int class_sizes[MAX_VGRF_SIZE];
105
106   for (int i = 0; i < class_count; i++)
107      class_sizes[i] = i + 1;
108
109
110   ralloc_free(compiler->vec4_reg_set.regs);
111   compiler->vec4_reg_set.regs = ra_alloc_reg_set(compiler, base_reg_count, false);
112   if (compiler->devinfo->ver >= 6)
113      ra_set_allocate_round_robin(compiler->vec4_reg_set.regs);
114   ralloc_free(compiler->vec4_reg_set.classes);
115   compiler->vec4_reg_set.classes = ralloc_array(compiler, struct ra_class *, class_count);
116
117   /* Now, add the registers to their classes, and add the conflicts
118    * between them and the base GRF registers (and also each other).
119    */
120   for (int i = 0; i < class_count; i++) {
121      int class_reg_count = base_reg_count - (class_sizes[i] - 1);
122      compiler->vec4_reg_set.classes[i] =
123         ra_alloc_contig_reg_class(compiler->vec4_reg_set.regs, class_sizes[i]);
124
125      for (int j = 0; j < class_reg_count; j++)
126         ra_class_add_reg(compiler->vec4_reg_set.classes[i], j);
127   }
128
129   ra_set_finalize(compiler->vec4_reg_set.regs, NULL);
130}
131
132void
133vec4_visitor::setup_payload_interference(struct ra_graph *g,
134                                         int first_payload_node,
135                                         int reg_node_count)
136{
137   int payload_node_count = this->first_non_payload_grf;
138
139   for (int i = 0; i < payload_node_count; i++) {
140      /* Mark each payload reg node as being allocated to its physical register.
141       *
142       * The alternative would be to have per-physical register classes, which
143       * would just be silly.
144       */
145      ra_set_node_reg(g, first_payload_node + i, i);
146
147      /* For now, just mark each payload node as interfering with every other
148       * node to be allocated.
149       */
150      for (int j = 0; j < reg_node_count; j++) {
151         ra_add_node_interference(g, first_payload_node + i, j);
152      }
153   }
154}
155
156bool
157vec4_visitor::reg_allocate()
158{
159   unsigned int hw_reg_mapping[alloc.count];
160   int payload_reg_count = this->first_non_payload_grf;
161
162   /* Using the trivial allocator can be useful in debugging undefined
163    * register access as a result of broken optimization passes.
164    */
165   if (0)
166      return reg_allocate_trivial();
167
168   assert(devinfo->ver < 8);
169
170   const vec4_live_variables &live = live_analysis.require();
171   int node_count = alloc.count;
172   int first_payload_node = node_count;
173   node_count += payload_reg_count;
174   struct ra_graph *g =
175      ra_alloc_interference_graph(compiler->vec4_reg_set.regs, node_count);
176
177   for (unsigned i = 0; i < alloc.count; i++) {
178      int size = this->alloc.sizes[i];
179      assert(size >= 1 && size <= MAX_VGRF_SIZE);
180      ra_set_node_class(g, i, compiler->vec4_reg_set.classes[size - 1]);
181
182      for (unsigned j = 0; j < i; j++) {
183	 if (live.vgrfs_interfere(i, j)) {
184	    ra_add_node_interference(g, i, j);
185	 }
186      }
187   }
188
189   /* Certain instructions can't safely use the same register for their
190    * sources and destination.  Add interference.
191    */
192   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
193      if (inst->dst.file == VGRF && inst->has_source_and_destination_hazard()) {
194         for (unsigned i = 0; i < 3; i++) {
195            if (inst->src[i].file == VGRF) {
196               ra_add_node_interference(g, inst->dst.nr, inst->src[i].nr);
197            }
198         }
199      }
200   }
201
202   setup_payload_interference(g, first_payload_node, node_count);
203
204   if (!ra_allocate(g)) {
205      /* Failed to allocate registers.  Spill a reg, and the caller will
206       * loop back into here to try again.
207       */
208      int reg = choose_spill_reg(g);
209      if (this->no_spills) {
210         fail("Failure to register allocate.  Reduce number of live "
211              "values to avoid this.");
212      } else if (reg == -1) {
213         fail("no register to spill\n");
214      } else {
215         spill_reg(reg);
216      }
217      ralloc_free(g);
218      return false;
219   }
220
221   /* Get the chosen virtual registers for each node, and map virtual
222    * regs in the register classes back down to real hardware reg
223    * numbers.
224    */
225   prog_data->total_grf = payload_reg_count;
226   for (unsigned i = 0; i < alloc.count; i++) {
227      hw_reg_mapping[i] = ra_get_node_reg(g, i);
228      prog_data->total_grf = MAX2(prog_data->total_grf,
229				  hw_reg_mapping[i] + alloc.sizes[i]);
230   }
231
232   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
233      assign(hw_reg_mapping, &inst->dst);
234      assign(hw_reg_mapping, &inst->src[0]);
235      assign(hw_reg_mapping, &inst->src[1]);
236      assign(hw_reg_mapping, &inst->src[2]);
237   }
238
239   ralloc_free(g);
240
241   return true;
242}
243
244/**
245 * When we decide to spill a register, instead of blindly spilling every use,
246 * save unspills when the spill register is used (read) in consecutive
247 * instructions. This can potentially save a bunch of unspills that would
248 * have very little impact in register allocation anyway.
249 *
250 * Notice that we need to account for this behavior when spilling a register
251 * and when evaluating spilling costs. This function is designed so it can
252 * be called from both places and avoid repeating the logic.
253 *
254 *  - When we call this function from spill_reg(), we pass in scratch_reg the
255 *    actual unspill/spill register that we want to reuse in the current
256 *    instruction.
257 *
258 *  - When we call this from evaluate_spill_costs(), we pass the register for
259 *    which we are evaluating spilling costs.
260 *
261 * In either case, we check if the previous instructions read scratch_reg until
262 * we find one that writes to it with a compatible mask or does not read/write
263 * scratch_reg at all.
264 */
265static bool
266can_use_scratch_for_source(const vec4_instruction *inst, unsigned i,
267                           unsigned scratch_reg)
268{
269   assert(inst->src[i].file == VGRF);
270   bool prev_inst_read_scratch_reg = false;
271
272   /* See if any previous source in the same instructions reads scratch_reg */
273   for (unsigned n = 0; n < i; n++) {
274      if (inst->src[n].file == VGRF && inst->src[n].nr == scratch_reg)
275         prev_inst_read_scratch_reg = true;
276   }
277
278   /* Now check if previous instructions read/write scratch_reg */
279   for (vec4_instruction *prev_inst = (vec4_instruction *) inst->prev;
280        !prev_inst->is_head_sentinel();
281        prev_inst = (vec4_instruction *) prev_inst->prev) {
282
283      /* If the previous instruction writes to scratch_reg then we can reuse
284       * it if the write is not conditional and the channels we write are
285       * compatible with our read mask
286       */
287      if (prev_inst->dst.file == VGRF && prev_inst->dst.nr == scratch_reg) {
288         return (!prev_inst->predicate || prev_inst->opcode == BRW_OPCODE_SEL) &&
289                (brw_mask_for_swizzle(inst->src[i].swizzle) &
290                 ~prev_inst->dst.writemask) == 0;
291      }
292
293      /* Skip scratch read/writes so that instructions generated by spilling
294       * other registers (that won't read/write scratch_reg) do not stop us from
295       * reusing scratch_reg for this instruction.
296       */
297      if (prev_inst->opcode == SHADER_OPCODE_GFX4_SCRATCH_WRITE ||
298          prev_inst->opcode == SHADER_OPCODE_GFX4_SCRATCH_READ)
299         continue;
300
301      /* If the previous instruction does not write to scratch_reg, then check
302       * if it reads it
303       */
304      int n;
305      for (n = 0; n < 3; n++) {
306         if (prev_inst->src[n].file == VGRF &&
307             prev_inst->src[n].nr == scratch_reg) {
308            prev_inst_read_scratch_reg = true;
309            break;
310         }
311      }
312      if (n == 3) {
313         /* The previous instruction does not read scratch_reg. At this point,
314          * if no previous instruction has read scratch_reg it means that we
315          * will need to unspill it here and we can't reuse it (so we return
316          * false). Otherwise, if we found at least one consecutive instruction
317          * that read scratch_reg, then we know that we got here from
318          * evaluate_spill_costs (since for the spill_reg path any block of
319          * consecutive instructions using scratch_reg must start with a write
320          * to that register, so we would've exited the loop in the check for
321          * the write that we have at the start of this loop), and in that case
322          * it means that we found the point at which the scratch_reg would be
323          * unspilled. Since we always unspill a full vec4, it means that we
324          * have all the channels available and we can just return true to
325          * signal that we can reuse the register in the current instruction
326          * too.
327          */
328         return prev_inst_read_scratch_reg;
329      }
330   }
331
332   return prev_inst_read_scratch_reg;
333}
334
335static inline float
336spill_cost_for_type(enum brw_reg_type type)
337{
338   /* Spilling of a 64-bit register involves emitting 2 32-bit scratch
339    * messages plus the 64b/32b shuffling code.
340    */
341   return type_sz(type) == 8 ? 2.25f : 1.0f;
342}
343
344void
345vec4_visitor::evaluate_spill_costs(float *spill_costs, bool *no_spill)
346{
347   float loop_scale = 1.0;
348
349   unsigned *reg_type_size = (unsigned *)
350      ralloc_size(NULL, this->alloc.count * sizeof(unsigned));
351
352   for (unsigned i = 0; i < this->alloc.count; i++) {
353      spill_costs[i] = 0.0;
354      no_spill[i] = alloc.sizes[i] != 1 && alloc.sizes[i] != 2;
355      reg_type_size[i] = 0;
356   }
357
358   /* Calculate costs for spilling nodes.  Call it a cost of 1 per
359    * spill/unspill we'll have to do, and guess that the insides of
360    * loops run 10 times.
361    */
362   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
363      for (unsigned int i = 0; i < 3; i++) {
364         if (inst->src[i].file == VGRF && !no_spill[inst->src[i].nr]) {
365            /* We will only unspill src[i] it it wasn't unspilled for the
366             * previous instruction, in which case we'll just reuse the scratch
367             * reg for this instruction.
368             */
369            if (!can_use_scratch_for_source(inst, i, inst->src[i].nr)) {
370               spill_costs[inst->src[i].nr] +=
371                  loop_scale * spill_cost_for_type(inst->src[i].type);
372               if (inst->src[i].reladdr ||
373                   inst->src[i].offset >= REG_SIZE)
374                  no_spill[inst->src[i].nr] = true;
375
376               /* We don't support unspills of partial DF reads.
377                *
378                * Our 64-bit unspills are implemented with two 32-bit scratch
379                * messages, each one reading that for both SIMD4x2 threads that
380                * we need to shuffle into correct 64-bit data. Ensure that we
381                * are reading data for both threads.
382                */
383               if (type_sz(inst->src[i].type) == 8 && inst->exec_size != 8)
384                  no_spill[inst->src[i].nr] = true;
385            }
386
387            /* We can't spill registers that mix 32-bit and 64-bit access (that
388             * contain 64-bit data that is operated on via 32-bit instructions)
389             */
390            unsigned type_size = type_sz(inst->src[i].type);
391            if (reg_type_size[inst->src[i].nr] == 0)
392               reg_type_size[inst->src[i].nr] = type_size;
393            else if (reg_type_size[inst->src[i].nr] != type_size)
394               no_spill[inst->src[i].nr] = true;
395         }
396      }
397
398      if (inst->dst.file == VGRF && !no_spill[inst->dst.nr]) {
399         spill_costs[inst->dst.nr] +=
400            loop_scale * spill_cost_for_type(inst->dst.type);
401         if (inst->dst.reladdr || inst->dst.offset >= REG_SIZE)
402            no_spill[inst->dst.nr] = true;
403
404         /* We don't support spills of partial DF writes.
405          *
406          * Our 64-bit spills are implemented with two 32-bit scratch messages,
407          * each one writing that for both SIMD4x2 threads. Ensure that we
408          * are writing data for both threads.
409          */
410         if (type_sz(inst->dst.type) == 8 && inst->exec_size != 8)
411            no_spill[inst->dst.nr] = true;
412
413         /* We can't spill registers that mix 32-bit and 64-bit access (that
414          * contain 64-bit data that is operated on via 32-bit instructions)
415          */
416         unsigned type_size = type_sz(inst->dst.type);
417         if (reg_type_size[inst->dst.nr] == 0)
418            reg_type_size[inst->dst.nr] = type_size;
419         else if (reg_type_size[inst->dst.nr] != type_size)
420            no_spill[inst->dst.nr] = true;
421      }
422
423      switch (inst->opcode) {
424
425      case BRW_OPCODE_DO:
426         loop_scale *= 10;
427         break;
428
429      case BRW_OPCODE_WHILE:
430         loop_scale /= 10;
431         break;
432
433      case SHADER_OPCODE_GFX4_SCRATCH_READ:
434      case SHADER_OPCODE_GFX4_SCRATCH_WRITE:
435      case VEC4_OPCODE_MOV_FOR_SCRATCH:
436         for (int i = 0; i < 3; i++) {
437            if (inst->src[i].file == VGRF)
438               no_spill[inst->src[i].nr] = true;
439         }
440         if (inst->dst.file == VGRF)
441            no_spill[inst->dst.nr] = true;
442         break;
443
444      default:
445         break;
446      }
447   }
448
449   ralloc_free(reg_type_size);
450}
451
452int
453vec4_visitor::choose_spill_reg(struct ra_graph *g)
454{
455   float spill_costs[this->alloc.count];
456   bool no_spill[this->alloc.count];
457
458   evaluate_spill_costs(spill_costs, no_spill);
459
460   for (unsigned i = 0; i < this->alloc.count; i++) {
461      if (!no_spill[i])
462         ra_set_node_spill_cost(g, i, spill_costs[i]);
463   }
464
465   return ra_get_best_spill_node(g);
466}
467
468void
469vec4_visitor::spill_reg(unsigned spill_reg_nr)
470{
471   assert(alloc.sizes[spill_reg_nr] == 1 || alloc.sizes[spill_reg_nr] == 2);
472   unsigned spill_offset = last_scratch;
473   last_scratch += alloc.sizes[spill_reg_nr];
474
475   /* Generate spill/unspill instructions for the objects being spilled. */
476   unsigned scratch_reg = ~0u;
477   foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
478      for (unsigned i = 0; i < 3; i++) {
479         if (inst->src[i].file == VGRF && inst->src[i].nr == spill_reg_nr) {
480            if (scratch_reg == ~0u ||
481                !can_use_scratch_for_source(inst, i, scratch_reg)) {
482               /* We need to unspill anyway so make sure we read the full vec4
483                * in any case. This way, the cached register can be reused
484                * for consecutive instructions that read different channels of
485                * the same vec4.
486                */
487               scratch_reg = alloc.allocate(alloc.sizes[spill_reg_nr]);
488               src_reg temp = inst->src[i];
489               temp.nr = scratch_reg;
490               temp.offset = 0;
491               temp.swizzle = BRW_SWIZZLE_XYZW;
492               emit_scratch_read(block, inst,
493                                 dst_reg(temp), inst->src[i], spill_offset);
494               temp.offset = inst->src[i].offset;
495            }
496            assert(scratch_reg != ~0u);
497            inst->src[i].nr = scratch_reg;
498         }
499      }
500
501      if (inst->dst.file == VGRF && inst->dst.nr == spill_reg_nr) {
502         emit_scratch_write(block, inst, spill_offset);
503         scratch_reg = inst->dst.nr;
504      }
505   }
506
507   invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
508}
509
510} /* namespace brw */
511