1/*
2 * Copyright © 2019 Valve 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
25#include "aco_builder.h"
26#include "aco_ir.h"
27
28#include "util/u_math.h"
29
30#include <set>
31#include <vector>
32
33namespace aco {
34
35namespace {
36
37enum WQMState : uint8_t {
38   Unspecified = 0,
39   Exact = 1 << 0,
40   WQM = 1 << 1, /* with control flow applied */
41};
42
43enum mask_type : uint8_t {
44   mask_type_global = 1 << 0,
45   mask_type_exact = 1 << 1,
46   mask_type_wqm = 1 << 2,
47   mask_type_loop = 1 << 3, /* active lanes of a loop */
48};
49
50struct wqm_ctx {
51   Program* program;
52   /* state for WQM propagation */
53   std::set<unsigned> worklist;
54   std::vector<bool> branch_wqm; /* true if the branch condition in this block should be in wqm */
55   wqm_ctx(Program* program_)
56       : program(program_), branch_wqm(program->blocks.size())
57   {
58      for (unsigned i = 0; i < program->blocks.size(); i++)
59         worklist.insert(i);
60   }
61};
62
63struct loop_info {
64   Block* loop_header;
65   uint16_t num_exec_masks;
66   bool has_divergent_break;
67   bool has_divergent_continue;
68   bool has_discard; /* has a discard or demote */
69   loop_info(Block* b, uint16_t num, bool breaks, bool cont, bool discard)
70       : loop_header(b), num_exec_masks(num), has_divergent_break(breaks),
71         has_divergent_continue(cont), has_discard(discard)
72   {}
73};
74
75struct block_info {
76   std::vector<std::pair<Operand, uint8_t>>
77      exec; /* Vector of exec masks. Either a temporary or const -1. */
78   std::vector<WQMState> instr_needs;
79   uint8_t block_needs;
80};
81
82struct exec_ctx {
83   Program* program;
84   std::vector<block_info> info;
85   std::vector<loop_info> loop;
86   bool handle_wqm = false;
87   exec_ctx(Program* program_) : program(program_), info(program->blocks.size()) {}
88};
89
90bool
91needs_exact(aco_ptr<Instruction>& instr)
92{
93   if (instr->isMUBUF()) {
94      return instr->mubuf().disable_wqm;
95   } else if (instr->isMTBUF()) {
96      return instr->mtbuf().disable_wqm;
97   } else if (instr->isMIMG()) {
98      return instr->mimg().disable_wqm;
99   } else if (instr->isFlatLike()) {
100      return instr->flatlike().disable_wqm;
101   } else {
102      /* Require Exact for p_jump_to_epilog because if p_exit_early_if is
103       * emitted inside the same block, the main FS will always jump to the PS
104       * epilog without considering the exec mask.
105       */
106      return instr->isEXP() || instr->opcode == aco_opcode::p_jump_to_epilog;
107   }
108}
109
110void
111mark_block_wqm(wqm_ctx& ctx, unsigned block_idx)
112{
113   if (ctx.branch_wqm[block_idx])
114      return;
115
116   for (Block& block : ctx.program->blocks) {
117      if (block.index >= block_idx && block.kind & block_kind_top_level)
118         break;
119      ctx.branch_wqm[block.index] = true;
120      ctx.worklist.insert(block.index);
121   }
122}
123
124void
125get_block_needs(wqm_ctx& ctx, exec_ctx& exec_ctx, Block* block)
126{
127   block_info& info = exec_ctx.info[block->index];
128
129   std::vector<WQMState> instr_needs(block->instructions.size());
130
131   bool propagate_wqm = ctx.branch_wqm[block->index];
132   for (int i = block->instructions.size() - 1; i >= 0; --i) {
133      aco_ptr<Instruction>& instr = block->instructions[i];
134
135      if (instr->opcode == aco_opcode::p_wqm)
136         propagate_wqm = true;
137
138      bool pred_by_exec = needs_exec_mask(instr.get()) ||
139                          instr->opcode == aco_opcode::p_logical_end ||
140                          instr->isBranch();
141
142      if (needs_exact(instr))
143         instr_needs[i] = Exact;
144      else if (propagate_wqm && pred_by_exec)
145         instr_needs[i] = WQM;
146      else
147         instr_needs[i] = Unspecified;
148
149      info.block_needs |= instr_needs[i];
150   }
151
152   info.instr_needs = instr_needs;
153
154   /* for "if (<cond>) <wqm code>" or "while (<cond>) <wqm code>",
155    * <cond> should be computed in WQM */
156   if (info.block_needs & WQM) {
157      mark_block_wqm(ctx, block->index);
158   }
159}
160
161void
162calculate_wqm_needs(exec_ctx& exec_ctx)
163{
164   wqm_ctx ctx(exec_ctx.program);
165
166   while (!ctx.worklist.empty()) {
167      unsigned block_index = *std::prev(ctx.worklist.end());
168      ctx.worklist.erase(std::prev(ctx.worklist.end()));
169
170      Block& block = exec_ctx.program->blocks[block_index];
171      get_block_needs(ctx, exec_ctx, &block);
172   }
173
174   exec_ctx.handle_wqm = true;
175}
176
177Operand
178get_exec_op(Operand t)
179{
180   if (t.isUndefined())
181      return Operand(exec, t.regClass());
182   else
183      return t;
184}
185
186void
187transition_to_WQM(exec_ctx& ctx, Builder bld, unsigned idx)
188{
189   if (ctx.info[idx].exec.back().second & mask_type_wqm)
190      return;
191   if (ctx.info[idx].exec.back().second & mask_type_global) {
192      Operand exec_mask = ctx.info[idx].exec.back().first;
193      if (exec_mask.isUndefined()) {
194         exec_mask = bld.copy(bld.def(bld.lm), Operand(exec, bld.lm));
195         ctx.info[idx].exec.back().first = exec_mask;
196      }
197
198      exec_mask = bld.sop1(Builder::s_wqm, Definition(exec, bld.lm), bld.def(s1, scc),
199                           get_exec_op(exec_mask));
200      ctx.info[idx].exec.emplace_back(exec_mask, mask_type_global | mask_type_wqm);
201      return;
202   }
203   /* otherwise, the WQM mask should be one below the current mask */
204   ctx.info[idx].exec.pop_back();
205   assert(ctx.info[idx].exec.back().second & mask_type_wqm);
206   assert(ctx.info[idx].exec.back().first.size() == bld.lm.size());
207   assert(ctx.info[idx].exec.back().first.isTemp());
208   ctx.info[idx].exec.back().first =
209      bld.copy(Definition(exec, bld.lm), ctx.info[idx].exec.back().first);
210}
211
212void
213transition_to_Exact(exec_ctx& ctx, Builder bld, unsigned idx)
214{
215   if (ctx.info[idx].exec.back().second & mask_type_exact)
216      return;
217   /* We can't remove the loop exec mask, because that can cause exec.size() to
218    * be less than num_exec_masks. The loop exec mask also needs to be kept
219    * around for various uses. */
220   if ((ctx.info[idx].exec.back().second & mask_type_global) &&
221       !(ctx.info[idx].exec.back().second & mask_type_loop)) {
222      ctx.info[idx].exec.pop_back();
223      assert(ctx.info[idx].exec.back().second & mask_type_exact);
224      assert(ctx.info[idx].exec.back().first.size() == bld.lm.size());
225      assert(ctx.info[idx].exec.back().first.isTemp());
226      ctx.info[idx].exec.back().first =
227         bld.copy(Definition(exec, bld.lm), ctx.info[idx].exec.back().first);
228      return;
229   }
230   /* otherwise, we create an exact mask and push to the stack */
231   Operand wqm = ctx.info[idx].exec.back().first;
232   if (wqm.isUndefined()) {
233      wqm = bld.sop1(Builder::s_and_saveexec, bld.def(bld.lm), bld.def(s1, scc),
234                     Definition(exec, bld.lm), ctx.info[idx].exec[0].first, Operand(exec, bld.lm));
235   } else {
236      bld.sop2(Builder::s_and, Definition(exec, bld.lm), bld.def(s1, scc),
237               ctx.info[idx].exec[0].first, wqm);
238   }
239   ctx.info[idx].exec.back().first = Operand(wqm);
240   ctx.info[idx].exec.emplace_back(Operand(bld.lm), mask_type_exact);
241}
242
243unsigned
244add_coupling_code(exec_ctx& ctx, Block* block, std::vector<aco_ptr<Instruction>>& instructions)
245{
246   unsigned idx = block->index;
247   Builder bld(ctx.program, &instructions);
248   std::vector<unsigned>& preds = block->linear_preds;
249
250   /* start block */
251   if (idx == 0) {
252      aco_ptr<Instruction>& startpgm = block->instructions[0];
253      assert(startpgm->opcode == aco_opcode::p_startpgm);
254      bld.insert(std::move(startpgm));
255
256      unsigned count = 1;
257      if (block->instructions[1]->opcode == aco_opcode::p_init_scratch) {
258         bld.insert(std::move(block->instructions[1]));
259         count++;
260      }
261
262      Operand start_exec(bld.lm);
263
264      /* exec seems to need to be manually initialized with combined shaders */
265      if (ctx.program->stage.num_sw_stages() > 1 || ctx.program->stage.hw == HWStage::NGG) {
266         start_exec = Operand::c32_or_c64(-1u, bld.lm == s2);
267         bld.copy(Definition(exec, bld.lm), start_exec);
268      }
269
270      if (ctx.handle_wqm) {
271         ctx.info[0].exec.emplace_back(start_exec, mask_type_global | mask_type_exact);
272         /* if this block needs WQM, initialize already */
273         if (ctx.info[0].block_needs & WQM)
274            transition_to_WQM(ctx, bld, 0);
275      } else {
276         uint8_t mask = mask_type_global;
277         if (ctx.program->needs_wqm) {
278            bld.sop1(Builder::s_wqm, Definition(exec, bld.lm), bld.def(s1, scc),
279                     Operand(exec, bld.lm));
280            mask |= mask_type_wqm;
281         } else {
282            mask |= mask_type_exact;
283         }
284         ctx.info[0].exec.emplace_back(start_exec, mask);
285      }
286
287      return count;
288   }
289
290   /* loop entry block */
291   if (block->kind & block_kind_loop_header) {
292      assert(preds[0] == idx - 1);
293      ctx.info[idx].exec = ctx.info[idx - 1].exec;
294      loop_info& info = ctx.loop.back();
295      while (ctx.info[idx].exec.size() > info.num_exec_masks)
296         ctx.info[idx].exec.pop_back();
297
298      /* create ssa names for outer exec masks */
299      if (info.has_discard) {
300         aco_ptr<Pseudo_instruction> phi;
301         for (int i = 0; i < info.num_exec_masks - 1; i++) {
302            phi.reset(create_instruction<Pseudo_instruction>(aco_opcode::p_linear_phi,
303                                                             Format::PSEUDO, preds.size(), 1));
304            phi->definitions[0] = bld.def(bld.lm);
305            phi->operands[0] = get_exec_op(ctx.info[preds[0]].exec[i].first);
306            ctx.info[idx].exec[i].first = bld.insert(std::move(phi));
307         }
308      }
309
310      /* create ssa name for restore mask */
311      if (info.has_divergent_break) {
312         /* this phi might be trivial but ensures a parallelcopy on the loop header */
313         aco_ptr<Pseudo_instruction> phi{create_instruction<Pseudo_instruction>(
314            aco_opcode::p_linear_phi, Format::PSEUDO, preds.size(), 1)};
315         phi->definitions[0] = bld.def(bld.lm);
316         phi->operands[0] = get_exec_op(ctx.info[preds[0]].exec[info.num_exec_masks - 1].first);
317         ctx.info[idx].exec.back().first = bld.insert(std::move(phi));
318      }
319
320      /* create ssa name for loop active mask */
321      aco_ptr<Pseudo_instruction> phi{create_instruction<Pseudo_instruction>(
322         aco_opcode::p_linear_phi, Format::PSEUDO, preds.size(), 1)};
323      if (info.has_divergent_continue)
324         phi->definitions[0] = bld.def(bld.lm);
325      else
326         phi->definitions[0] = Definition(exec, bld.lm);
327      phi->operands[0] = get_exec_op(ctx.info[preds[0]].exec.back().first);
328      Temp loop_active = bld.insert(std::move(phi));
329
330      if (info.has_divergent_break) {
331         uint8_t mask_type =
332            (ctx.info[idx].exec.back().second & (mask_type_wqm | mask_type_exact)) | mask_type_loop;
333         ctx.info[idx].exec.emplace_back(loop_active, mask_type);
334      } else {
335         ctx.info[idx].exec.back().first = Operand(loop_active);
336         ctx.info[idx].exec.back().second |= mask_type_loop;
337      }
338
339      /* create a parallelcopy to move the active mask to exec */
340      unsigned i = 0;
341      if (info.has_divergent_continue) {
342         while (block->instructions[i]->opcode != aco_opcode::p_logical_start) {
343            bld.insert(std::move(block->instructions[i]));
344            i++;
345         }
346         uint8_t mask_type = ctx.info[idx].exec.back().second & (mask_type_wqm | mask_type_exact);
347         assert(ctx.info[idx].exec.back().first.size() == bld.lm.size());
348         ctx.info[idx].exec.emplace_back(
349            bld.copy(Definition(exec, bld.lm), ctx.info[idx].exec.back().first), mask_type);
350      }
351
352      return i;
353   }
354
355   /* loop exit block */
356   if (block->kind & block_kind_loop_exit) {
357      Block* header = ctx.loop.back().loop_header;
358      loop_info& info = ctx.loop.back();
359
360      for (ASSERTED unsigned pred : preds)
361         assert(ctx.info[pred].exec.size() >= info.num_exec_masks);
362
363      /* fill the loop header phis */
364      std::vector<unsigned>& header_preds = header->linear_preds;
365      int instr_idx = 0;
366      if (info.has_discard) {
367         while (instr_idx < info.num_exec_masks - 1) {
368            aco_ptr<Instruction>& phi = header->instructions[instr_idx];
369            assert(phi->opcode == aco_opcode::p_linear_phi);
370            for (unsigned i = 1; i < phi->operands.size(); i++)
371               phi->operands[i] = get_exec_op(ctx.info[header_preds[i]].exec[instr_idx].first);
372            instr_idx++;
373         }
374      }
375
376      {
377         aco_ptr<Instruction>& phi = header->instructions[instr_idx++];
378         assert(phi->opcode == aco_opcode::p_linear_phi);
379         for (unsigned i = 1; i < phi->operands.size(); i++)
380            phi->operands[i] =
381               get_exec_op(ctx.info[header_preds[i]].exec[info.num_exec_masks - 1].first);
382      }
383
384      if (info.has_divergent_break) {
385         aco_ptr<Instruction>& phi = header->instructions[instr_idx];
386         assert(phi->opcode == aco_opcode::p_linear_phi);
387         for (unsigned i = 1; i < phi->operands.size(); i++)
388            phi->operands[i] =
389               get_exec_op(ctx.info[header_preds[i]].exec[info.num_exec_masks].first);
390      }
391
392      assert(!(block->kind & block_kind_top_level) || info.num_exec_masks <= 2);
393
394      /* create the loop exit phis if not trivial */
395      for (unsigned exec_idx = 0; exec_idx < info.num_exec_masks; exec_idx++) {
396         Operand same = ctx.info[preds[0]].exec[exec_idx].first;
397         uint8_t type = ctx.info[header_preds[0]].exec[exec_idx].second;
398         bool trivial = true;
399
400         for (unsigned i = 1; i < preds.size() && trivial; i++) {
401            if (ctx.info[preds[i]].exec[exec_idx].first != same)
402               trivial = false;
403         }
404
405         if (trivial) {
406            ctx.info[idx].exec.emplace_back(same, type);
407         } else {
408            /* create phi for loop footer */
409            aco_ptr<Pseudo_instruction> phi{create_instruction<Pseudo_instruction>(
410               aco_opcode::p_linear_phi, Format::PSEUDO, preds.size(), 1)};
411            phi->definitions[0] = bld.def(bld.lm);
412            if (exec_idx == info.num_exec_masks - 1u) {
413               phi->definitions[0] = Definition(exec, bld.lm);
414            }
415            for (unsigned i = 0; i < phi->operands.size(); i++)
416               phi->operands[i] = get_exec_op(ctx.info[preds[i]].exec[exec_idx].first);
417            ctx.info[idx].exec.emplace_back(bld.insert(std::move(phi)), type);
418         }
419      }
420
421      assert(ctx.info[idx].exec.size() == info.num_exec_masks);
422      ctx.loop.pop_back();
423
424   } else if (preds.size() == 1) {
425      ctx.info[idx].exec = ctx.info[preds[0]].exec;
426   } else {
427      assert(preds.size() == 2);
428      /* if one of the predecessors ends in exact mask, we pop it from stack */
429      unsigned num_exec_masks =
430         std::min(ctx.info[preds[0]].exec.size(), ctx.info[preds[1]].exec.size());
431
432      if (block->kind & block_kind_merge)
433         num_exec_masks--;
434      if (block->kind & block_kind_top_level)
435         num_exec_masks = std::min(num_exec_masks, 2u);
436
437      /* create phis for diverged exec masks */
438      for (unsigned i = 0; i < num_exec_masks; i++) {
439         /* skip trivial phis */
440         if (ctx.info[preds[0]].exec[i].first == ctx.info[preds[1]].exec[i].first) {
441            Operand t = ctx.info[preds[0]].exec[i].first;
442            /* discard/demote can change the state of the current exec mask */
443            assert(!t.isTemp() ||
444                   ctx.info[preds[0]].exec[i].second == ctx.info[preds[1]].exec[i].second);
445            uint8_t mask = ctx.info[preds[0]].exec[i].second & ctx.info[preds[1]].exec[i].second;
446            ctx.info[idx].exec.emplace_back(t, mask);
447            continue;
448         }
449
450         Temp phi = bld.pseudo(aco_opcode::p_linear_phi, bld.def(bld.lm),
451                               get_exec_op(ctx.info[preds[0]].exec[i].first),
452                               get_exec_op(ctx.info[preds[1]].exec[i].first));
453         uint8_t mask_type = ctx.info[preds[0]].exec[i].second & ctx.info[preds[1]].exec[i].second;
454         ctx.info[idx].exec.emplace_back(phi, mask_type);
455      }
456   }
457
458   unsigned i = 0;
459   while (block->instructions[i]->opcode == aco_opcode::p_phi ||
460          block->instructions[i]->opcode == aco_opcode::p_linear_phi) {
461      bld.insert(std::move(block->instructions[i]));
462      i++;
463   }
464
465   /* try to satisfy the block's needs */
466   if (ctx.handle_wqm) {
467      if (block->kind & block_kind_top_level && ctx.info[idx].exec.size() == 2) {
468         if (ctx.info[idx].block_needs == 0 || ctx.info[idx].block_needs == Exact) {
469            ctx.info[idx].exec.back().second |= mask_type_global;
470            transition_to_Exact(ctx, bld, idx);
471            ctx.handle_wqm = false;
472         }
473      }
474   }
475
476   /* restore exec mask after divergent control flow */
477   if (block->kind & (block_kind_loop_exit | block_kind_merge) &&
478       !ctx.info[idx].exec.back().first.isUndefined()) {
479      Operand restore = ctx.info[idx].exec.back().first;
480      assert(restore.size() == bld.lm.size());
481      bld.copy(Definition(exec, bld.lm), restore);
482      if (!restore.isConstant())
483         ctx.info[idx].exec.back().first = Operand(bld.lm);
484   }
485
486   return i;
487}
488
489/* Avoid live-range splits in Exact mode:
490 * Because the data register of atomic VMEM instructions
491 * is shared between src and dst, it might be necessary
492 * to create live-range splits during RA.
493 * Make the live-range splits explicit in WQM mode.
494 */
495void
496handle_atomic_data(exec_ctx& ctx, Builder& bld, unsigned block_idx, aco_ptr<Instruction>& instr)
497{
498   /* check if this is an atomic VMEM instruction */
499   int idx = -1;
500   if (!instr->isVMEM() || instr->definitions.empty())
501      return;
502   else if (instr->isMIMG())
503      idx = instr->operands[2].isTemp() ? 2 : -1;
504   else if (instr->operands.size() == 4)
505      idx = 3;
506
507   if (idx != -1) {
508      /* insert explicit copy of atomic data in WQM-mode */
509      transition_to_WQM(ctx, bld, block_idx);
510      Temp data = instr->operands[idx].getTemp();
511      data = bld.copy(bld.def(data.regClass()), data);
512      instr->operands[idx].setTemp(data);
513   }
514}
515
516void
517process_instructions(exec_ctx& ctx, Block* block, std::vector<aco_ptr<Instruction>>& instructions,
518                     unsigned idx)
519{
520   WQMState state;
521   if (ctx.info[block->index].exec.back().second & mask_type_wqm) {
522      state = WQM;
523   } else {
524      assert(!ctx.handle_wqm || ctx.info[block->index].exec.back().second & mask_type_exact);
525      state = Exact;
526   }
527
528   /* if the block doesn't need both, WQM and Exact, we can skip processing the instructions */
529   bool process = (ctx.handle_wqm && (ctx.info[block->index].block_needs & state) !=
530                                        (ctx.info[block->index].block_needs & (WQM | Exact))) ||
531                  block->kind & block_kind_uses_discard || block->kind & block_kind_needs_lowering;
532   if (!process) {
533      std::vector<aco_ptr<Instruction>>::iterator it = std::next(block->instructions.begin(), idx);
534      instructions.insert(instructions.end(),
535                          std::move_iterator<std::vector<aco_ptr<Instruction>>::iterator>(it),
536                          std::move_iterator<std::vector<aco_ptr<Instruction>>::iterator>(
537                             block->instructions.end()));
538      return;
539   }
540
541   Builder bld(ctx.program, &instructions);
542
543   for (; idx < block->instructions.size(); idx++) {
544      aco_ptr<Instruction> instr = std::move(block->instructions[idx]);
545
546      WQMState needs = ctx.handle_wqm ? ctx.info[block->index].instr_needs[idx] : Unspecified;
547
548      if (needs == WQM && state != WQM) {
549         transition_to_WQM(ctx, bld, block->index);
550         state = WQM;
551      } else if (needs == Exact) {
552         if (ctx.info[block->index].block_needs & WQM)
553            handle_atomic_data(ctx, bld, block->index, instr);
554         transition_to_Exact(ctx, bld, block->index);
555         state = Exact;
556      }
557
558      if (instr->opcode == aco_opcode::p_discard_if) {
559         Operand current_exec = Operand(exec, bld.lm);
560
561         if (ctx.info[block->index].exec.size() >= 2) {
562            if (needs == WQM) {
563               /* Preserve the WQM mask */
564               ctx.info[block->index].exec[1].second &= ~mask_type_global;
565            } else if (block->kind & block_kind_top_level) {
566               /* Transition to Exact without extra instruction. Since needs != WQM, we won't need
567                * WQM again.
568                */
569               ctx.info[block->index].exec.resize(1);
570               assert(ctx.info[block->index].exec[0].second == (mask_type_exact | mask_type_global));
571               current_exec = get_exec_op(ctx.info[block->index].exec.back().first);
572               ctx.info[block->index].exec[0].first = Operand(bld.lm);
573            }
574         }
575
576         Temp cond, exit_cond;
577         if (instr->operands[0].isConstant()) {
578            assert(instr->operands[0].constantValue() == -1u);
579            /* save condition and set exec to zero */
580            exit_cond = bld.tmp(s1);
581            cond =
582               bld.sop1(Builder::s_and_saveexec, bld.def(bld.lm), bld.scc(Definition(exit_cond)),
583                        Definition(exec, bld.lm), Operand::zero(), Operand(exec, bld.lm));
584         } else {
585            cond = instr->operands[0].getTemp();
586            /* discard from current exec */
587            exit_cond = bld.sop2(Builder::s_andn2, Definition(exec, bld.lm), bld.def(s1, scc),
588                                 current_exec, cond)
589                           .def(1)
590                           .getTemp();
591         }
592
593         /* discard from inner to outer exec mask on stack */
594         int num = ctx.info[block->index].exec.size() - 2;
595         for (int i = num; i >= 0; i--) {
596            Instruction* andn2 = bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.def(s1, scc),
597                                          ctx.info[block->index].exec[i].first, cond);
598            ctx.info[block->index].exec[i].first = Operand(andn2->definitions[0].getTemp());
599            exit_cond = andn2->definitions[1].getTemp();
600         }
601
602         instr->opcode = aco_opcode::p_exit_early_if;
603         instr->operands[0] = bld.scc(exit_cond);
604         assert(!ctx.handle_wqm || (ctx.info[block->index].exec[0].second & mask_type_wqm) == 0);
605
606      } else if (instr->opcode == aco_opcode::p_is_helper) {
607         Definition dst = instr->definitions[0];
608         assert(dst.size() == bld.lm.size());
609         if (state == Exact) {
610            instr.reset(create_instruction<SOP1_instruction>(bld.w64or32(Builder::s_mov),
611                                                             Format::SOP1, 1, 1));
612            instr->operands[0] = Operand::zero();
613            instr->definitions[0] = dst;
614         } else {
615            std::pair<Operand, uint8_t>& exact_mask = ctx.info[block->index].exec[0];
616            assert(exact_mask.second & mask_type_exact);
617
618            instr.reset(create_instruction<SOP2_instruction>(bld.w64or32(Builder::s_andn2),
619                                                             Format::SOP2, 2, 2));
620            instr->operands[0] = Operand(exec, bld.lm); /* current exec */
621            instr->operands[1] = Operand(exact_mask.first);
622            instr->definitions[0] = dst;
623            instr->definitions[1] = bld.def(s1, scc);
624         }
625      } else if (instr->opcode == aco_opcode::p_demote_to_helper) {
626         /* turn demote into discard_if with only exact masks */
627         assert((ctx.info[block->index].exec[0].second & mask_type_exact) &&
628                (ctx.info[block->index].exec[0].second & mask_type_global));
629
630         int num;
631         Temp cond, exit_cond;
632         if (instr->operands[0].isConstant()) {
633            assert(instr->operands[0].constantValue() == -1u);
634            /* transition to exact and set exec to zero */
635            exit_cond = bld.tmp(s1);
636            cond =
637               bld.sop1(Builder::s_and_saveexec, bld.def(bld.lm), bld.scc(Definition(exit_cond)),
638                        Definition(exec, bld.lm), Operand::zero(), Operand(exec, bld.lm));
639
640            num = ctx.info[block->index].exec.size() - 2;
641            if (!(ctx.info[block->index].exec.back().second & mask_type_exact)) {
642               ctx.info[block->index].exec.back().first = Operand(cond);
643               ctx.info[block->index].exec.emplace_back(Operand(bld.lm), mask_type_exact);
644            }
645         } else {
646            /* demote_if: transition to exact */
647            if (block->kind & block_kind_top_level && ctx.info[block->index].exec.size() == 2 &&
648                ctx.info[block->index].exec.back().second & mask_type_global) {
649               /* We don't need to actually copy anything into exact, since the s_andn2
650                * instructions later will do that.
651                */
652               ctx.info[block->index].exec.pop_back();
653            } else {
654               transition_to_Exact(ctx, bld, block->index);
655            }
656            assert(instr->operands[0].isTemp());
657            cond = instr->operands[0].getTemp();
658            num = ctx.info[block->index].exec.size() - 1;
659         }
660
661         for (int i = num; i >= 0; i--) {
662            if (ctx.info[block->index].exec[i].second & mask_type_exact) {
663               Instruction* andn2 =
664                  bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.def(s1, scc),
665                           get_exec_op(ctx.info[block->index].exec[i].first), cond);
666               if (i == (int)ctx.info[block->index].exec.size() - 1)
667                  andn2->definitions[0] = Definition(exec, bld.lm);
668
669               ctx.info[block->index].exec[i].first = Operand(andn2->definitions[0].getTemp());
670               exit_cond = andn2->definitions[1].getTemp();
671            } else {
672               assert(i != 0);
673            }
674         }
675         instr->opcode = aco_opcode::p_exit_early_if;
676         instr->operands[0] = bld.scc(exit_cond);
677         state = Exact;
678
679      } else if (instr->opcode == aco_opcode::p_elect) {
680         bool all_lanes_enabled = ctx.info[block->index].exec.back().first.constantEquals(-1u);
681         Definition dst = instr->definitions[0];
682
683         if (all_lanes_enabled) {
684            bld.copy(Definition(dst), Operand::c32_or_c64(1u, dst.size() == 2));
685         } else {
686            Temp first_lane_idx = bld.sop1(Builder::s_ff1_i32, bld.def(s1), Operand(exec, bld.lm));
687            bld.sop2(Builder::s_lshl, Definition(dst), bld.def(s1, scc),
688                     Operand::c32_or_c64(1u, dst.size() == 2), Operand(first_lane_idx));
689         }
690         instr.reset();
691         continue;
692      }
693
694      bld.insert(std::move(instr));
695   }
696}
697
698void
699add_branch_code(exec_ctx& ctx, Block* block)
700{
701   unsigned idx = block->index;
702   Builder bld(ctx.program, block);
703
704   if (idx == ctx.program->blocks.size() - 1)
705      return;
706
707   /* try to disable wqm handling */
708   if (ctx.handle_wqm && block->kind & block_kind_top_level) {
709      if (ctx.info[idx].exec.size() == 3) {
710         assert(ctx.info[idx].exec[1].second == mask_type_wqm);
711         ctx.info[idx].exec.pop_back();
712      }
713      assert(ctx.info[idx].exec.size() <= 2);
714
715      if (!(ctx.info[idx].instr_needs.back() & WQM)) {
716         /* transition to Exact if the branch doesn't need WQM */
717         aco_ptr<Instruction> branch = std::move(block->instructions.back());
718         block->instructions.pop_back();
719         ctx.info[idx].exec.back().second |= mask_type_global;
720         transition_to_Exact(ctx, bld, idx);
721         bld.insert(std::move(branch));
722         ctx.handle_wqm = false;
723      }
724   }
725
726   if (block->kind & block_kind_loop_preheader) {
727      /* collect information about the succeeding loop */
728      bool has_divergent_break = false;
729      bool has_divergent_continue = false;
730      bool has_discard = false;
731      unsigned loop_nest_depth = ctx.program->blocks[idx + 1].loop_nest_depth;
732
733      for (unsigned i = idx + 1; ctx.program->blocks[i].loop_nest_depth >= loop_nest_depth; i++) {
734         Block& loop_block = ctx.program->blocks[i];
735
736         if (loop_block.kind & block_kind_uses_discard)
737            has_discard = true;
738         if (loop_block.loop_nest_depth != loop_nest_depth)
739            continue;
740
741         if (loop_block.kind & block_kind_uniform)
742            continue;
743         else if (loop_block.kind & block_kind_break)
744            has_divergent_break = true;
745         else if (loop_block.kind & block_kind_continue)
746            has_divergent_continue = true;
747      }
748
749      unsigned num_exec_masks = ctx.info[idx].exec.size();
750      if (block->kind & block_kind_top_level)
751         num_exec_masks = std::min(num_exec_masks, 2u);
752
753      ctx.loop.emplace_back(&ctx.program->blocks[block->linear_succs[0]], num_exec_masks,
754                            has_divergent_break, has_divergent_continue, has_discard);
755   }
756
757   /* For normal breaks, this is the exec mask. For discard+break, it's the
758    * old exec mask before it was zero'd.
759    */
760   Operand break_cond = Operand(exec, bld.lm);
761
762   if (block->kind & block_kind_continue_or_break) {
763      assert(ctx.program->blocks[ctx.program->blocks[block->linear_succs[1]].linear_succs[0]].kind &
764             block_kind_loop_header);
765      assert(ctx.program->blocks[ctx.program->blocks[block->linear_succs[0]].linear_succs[0]].kind &
766             block_kind_loop_exit);
767      assert(block->instructions.back()->opcode == aco_opcode::p_branch);
768      block->instructions.pop_back();
769
770      bool need_parallelcopy = false;
771      while (!(ctx.info[idx].exec.back().second & mask_type_loop)) {
772         ctx.info[idx].exec.pop_back();
773         need_parallelcopy = true;
774      }
775
776      if (need_parallelcopy)
777         ctx.info[idx].exec.back().first =
778            bld.copy(Definition(exec, bld.lm), ctx.info[idx].exec.back().first);
779      bld.branch(aco_opcode::p_cbranch_nz, bld.def(s2), Operand(exec, bld.lm),
780                 block->linear_succs[1], block->linear_succs[0]);
781      return;
782   }
783
784   if (block->kind & block_kind_uniform) {
785      Pseudo_branch_instruction& branch = block->instructions.back()->branch();
786      if (branch.opcode == aco_opcode::p_branch) {
787         branch.target[0] = block->linear_succs[0];
788      } else {
789         branch.target[0] = block->linear_succs[1];
790         branch.target[1] = block->linear_succs[0];
791      }
792      return;
793   }
794
795   if (block->kind & block_kind_branch) {
796      // orig = s_and_saveexec_b64
797      assert(block->linear_succs.size() == 2);
798      assert(block->instructions.back()->opcode == aco_opcode::p_cbranch_z);
799      Temp cond = block->instructions.back()->operands[0].getTemp();
800      block->instructions.pop_back();
801
802      uint8_t mask_type = ctx.info[idx].exec.back().second & (mask_type_wqm | mask_type_exact);
803      if (ctx.info[idx].exec.back().first.constantEquals(-1u)) {
804         bld.copy(Definition(exec, bld.lm), cond);
805      } else {
806         Temp old_exec = bld.sop1(Builder::s_and_saveexec, bld.def(bld.lm), bld.def(s1, scc),
807                                  Definition(exec, bld.lm), cond, Operand(exec, bld.lm));
808
809         ctx.info[idx].exec.back().first = Operand(old_exec);
810      }
811
812      /* add next current exec to the stack */
813      ctx.info[idx].exec.emplace_back(Operand(bld.lm), mask_type);
814
815      bld.branch(aco_opcode::p_cbranch_z, bld.def(s2), Operand(exec, bld.lm),
816                 block->linear_succs[1], block->linear_succs[0]);
817      return;
818   }
819
820   if (block->kind & block_kind_invert) {
821      // exec = s_andn2_b64 (original_exec, exec)
822      assert(block->instructions.back()->opcode == aco_opcode::p_branch);
823      block->instructions.pop_back();
824      assert(ctx.info[idx].exec.size() >= 2);
825      Operand orig_exec = ctx.info[idx].exec[ctx.info[idx].exec.size() - 2].first;
826      bld.sop2(Builder::s_andn2, Definition(exec, bld.lm), bld.def(s1, scc), orig_exec,
827               Operand(exec, bld.lm));
828
829      bld.branch(aco_opcode::p_cbranch_z, bld.def(s2), Operand(exec, bld.lm),
830                 block->linear_succs[1], block->linear_succs[0]);
831      return;
832   }
833
834   if (block->kind & block_kind_break) {
835      // loop_mask = s_andn2_b64 (loop_mask, exec)
836      assert(block->instructions.back()->opcode == aco_opcode::p_branch);
837      block->instructions.pop_back();
838
839      Temp cond = Temp();
840      for (int exec_idx = ctx.info[idx].exec.size() - 2; exec_idx >= 0; exec_idx--) {
841         cond = bld.tmp(s1);
842         Operand exec_mask = ctx.info[idx].exec[exec_idx].first;
843         exec_mask = bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.scc(Definition(cond)),
844                              exec_mask, break_cond);
845         ctx.info[idx].exec[exec_idx].first = exec_mask;
846         if (ctx.info[idx].exec[exec_idx].second & mask_type_loop)
847            break;
848      }
849
850      /* check if the successor is the merge block, otherwise set exec to 0 */
851      // TODO: this could be done better by directly branching to the merge block
852      unsigned succ_idx = ctx.program->blocks[block->linear_succs[1]].linear_succs[0];
853      Block& succ = ctx.program->blocks[succ_idx];
854      if (!(succ.kind & block_kind_invert || succ.kind & block_kind_merge)) {
855         bld.copy(Definition(exec, bld.lm), Operand::zero(bld.lm.bytes()));
856      }
857
858      bld.branch(aco_opcode::p_cbranch_nz, bld.def(s2), bld.scc(cond), block->linear_succs[1],
859                 block->linear_succs[0]);
860      return;
861   }
862
863   if (block->kind & block_kind_continue) {
864      assert(block->instructions.back()->opcode == aco_opcode::p_branch);
865      block->instructions.pop_back();
866
867      Temp cond = Temp();
868      for (int exec_idx = ctx.info[idx].exec.size() - 2; exec_idx >= 0; exec_idx--) {
869         if (ctx.info[idx].exec[exec_idx].second & mask_type_loop)
870            break;
871         cond = bld.tmp(s1);
872         Operand exec_mask = ctx.info[idx].exec[exec_idx].first;
873         exec_mask = bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.scc(Definition(cond)),
874                              exec_mask, Operand(exec, bld.lm));
875         ctx.info[idx].exec[exec_idx].first = exec_mask;
876      }
877      assert(cond != Temp());
878
879      /* check if the successor is the merge block, otherwise set exec to 0 */
880      // TODO: this could be done better by directly branching to the merge block
881      unsigned succ_idx = ctx.program->blocks[block->linear_succs[1]].linear_succs[0];
882      Block& succ = ctx.program->blocks[succ_idx];
883      if (!(succ.kind & block_kind_invert || succ.kind & block_kind_merge)) {
884         bld.copy(Definition(exec, bld.lm), Operand::zero(bld.lm.bytes()));
885      }
886
887      bld.branch(aco_opcode::p_cbranch_nz, bld.def(s2), bld.scc(cond), block->linear_succs[1],
888                 block->linear_succs[0]);
889      return;
890   }
891}
892
893void
894process_block(exec_ctx& ctx, Block* block)
895{
896   std::vector<aco_ptr<Instruction>> instructions;
897   instructions.reserve(block->instructions.size());
898
899   unsigned idx = add_coupling_code(ctx, block, instructions);
900
901   assert(block->index != ctx.program->blocks.size() - 1 ||
902          ctx.info[block->index].exec.size() <= 2);
903
904   process_instructions(ctx, block, instructions, idx);
905
906   block->instructions = std::move(instructions);
907
908   add_branch_code(ctx, block);
909}
910
911} /* end namespace */
912
913void
914insert_exec_mask(Program* program)
915{
916   exec_ctx ctx(program);
917
918   if (program->needs_wqm && program->needs_exact)
919      calculate_wqm_needs(ctx);
920
921   for (Block& block : program->blocks)
922      process_block(ctx, &block);
923}
924
925} // namespace aco
926