• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2018 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  * Authors:
24  *    Daniel Schürmann (daniel.schuermann@campus.tu-berlin.de)
25  *
26  */
27 
28 #include <algorithm>
29 #include <math.h>
30 
31 #include "aco_ir.h"
32 #include "util/half_float.h"
33 #include "util/memstream.h"
34 #include "util/u_math.h"
35 
36 namespace aco {
37 
38 #ifndef NDEBUG
perfwarn(Program * program,bool cond,const char * msg,Instruction * instr)39 void perfwarn(Program *program, bool cond, const char *msg, Instruction *instr)
40 {
41    if (cond) {
42       char *out;
43       size_t outsize;
44       struct u_memstream mem;
45       u_memstream_open(&mem, &out, &outsize);
46       FILE *const memf = u_memstream_get(&mem);
47 
48       fprintf(memf, "%s: ", msg);
49       aco_print_instr(instr, memf);
50       u_memstream_close(&mem);
51 
52       aco_perfwarn(program, out);
53       free(out);
54 
55       if (debug_flags & DEBUG_PERFWARN)
56          exit(1);
57    }
58 }
59 #endif
60 
61 /**
62  * The optimizer works in 4 phases:
63  * (1) The first pass collects information for each ssa-def,
64  *     propagates reg->reg operands of the same type, inline constants
65  *     and neg/abs input modifiers.
66  * (2) The second pass combines instructions like mad, omod, clamp and
67  *     propagates sgpr's on VALU instructions.
68  *     This pass depends on information collected in the first pass.
69  * (3) The third pass goes backwards, and selects instructions,
70  *     i.e. decides if a mad instruction is profitable and eliminates dead code.
71  * (4) The fourth pass cleans up the sequence: literals get applied and dead
72  *     instructions are removed from the sequence.
73  */
74 
75 
76 struct mad_info {
77    aco_ptr<Instruction> add_instr;
78    uint32_t mul_temp_id;
79    uint16_t literal_idx;
80    bool check_literal;
81 
mad_infoaco::mad_info82    mad_info(aco_ptr<Instruction> instr, uint32_t id)
83    : add_instr(std::move(instr)), mul_temp_id(id), literal_idx(0), check_literal(false) {}
84 };
85 
86 enum Label {
87    label_vec = 1 << 0,
88    label_constant_32bit = 1 << 1,
89    /* label_{abs,neg,mul,omod2,omod4,omod5,clamp} are used for both 16 and
90     * 32-bit operations but this shouldn't cause any issues because we don't
91     * look through any conversions */
92    label_abs = 1 << 2,
93    label_neg = 1 << 3,
94    label_mul = 1 << 4,
95    label_temp = 1 << 5,
96    label_literal = 1 << 6,
97    label_mad = 1 << 7,
98    label_omod2 = 1 << 8,
99    label_omod4 = 1 << 9,
100    label_omod5 = 1 << 10,
101    label_clamp = 1 << 12,
102    label_undefined = 1 << 14,
103    label_vcc = 1 << 15,
104    label_b2f = 1 << 16,
105    label_add_sub = 1 << 17,
106    label_bitwise = 1 << 18,
107    label_minmax = 1 << 19,
108    label_vopc = 1 << 20,
109    label_uniform_bool = 1 << 21,
110    label_constant_64bit = 1 << 22,
111    label_uniform_bitwise = 1 << 23,
112    label_scc_invert = 1 << 24,
113    label_vcc_hint = 1 << 25,
114    label_scc_needed = 1 << 26,
115    label_b2i = 1 << 27,
116    label_constant_16bit = 1 << 29,
117 };
118 
119 static constexpr uint64_t instr_usedef_labels = label_vec | label_mul | label_mad | label_add_sub |
120                                                 label_bitwise | label_uniform_bitwise | label_minmax | label_vopc;
121 static constexpr uint64_t instr_mod_labels = label_omod2 | label_omod4 | label_omod5 | label_clamp;
122 
123 static constexpr uint64_t instr_labels = instr_usedef_labels | instr_mod_labels;
124 static constexpr uint64_t temp_labels = label_abs | label_neg | label_temp | label_vcc | label_b2f | label_uniform_bool |
125                                         label_scc_invert | label_b2i;
126 static constexpr uint32_t val_labels = label_constant_32bit | label_constant_64bit | label_constant_16bit | label_literal;
127 
128 static_assert((instr_labels & temp_labels) == 0, "labels cannot intersect");
129 static_assert((instr_labels & val_labels) == 0, "labels cannot intersect");
130 static_assert((temp_labels & val_labels) == 0, "labels cannot intersect");
131 
132 struct ssa_info {
133    uint64_t label;
134    union {
135       uint32_t val;
136       Temp temp;
137       Instruction* instr;
138    };
139 
ssa_infoaco::ssa_info140    ssa_info() : label(0) {}
141 
add_labelaco::ssa_info142    void add_label(Label new_label)
143    {
144       /* Since all the instr_usedef_labels use instr for the same thing
145        * (indicating the defining instruction), there is usually no need to
146        * clear any other instr labels. */
147       if (new_label & instr_usedef_labels)
148          label &= ~(instr_mod_labels | temp_labels | val_labels); /* instr, temp and val alias */
149 
150       if (new_label & instr_mod_labels) {
151          label &= ~instr_labels;
152          label &= ~(temp_labels | val_labels); /* instr, temp and val alias */
153       }
154 
155       if (new_label & temp_labels) {
156          label &= ~temp_labels;
157          label &= ~(instr_labels | val_labels); /* instr, temp and val alias */
158       }
159 
160       uint32_t const_labels = label_literal | label_constant_32bit | label_constant_64bit | label_constant_16bit;
161       if (new_label & const_labels) {
162          label &= ~val_labels | const_labels;
163          label &= ~(instr_labels | temp_labels); /* instr, temp and val alias */
164       } else if (new_label & val_labels) {
165          label &= ~val_labels;
166          label &= ~(instr_labels | temp_labels); /* instr, temp and val alias */
167       }
168 
169       label |= new_label;
170    }
171 
set_vecaco::ssa_info172    void set_vec(Instruction* vec)
173    {
174       add_label(label_vec);
175       instr = vec;
176    }
177 
is_vecaco::ssa_info178    bool is_vec()
179    {
180       return label & label_vec;
181    }
182 
set_constantaco::ssa_info183    void set_constant(chip_class chip, uint64_t constant)
184    {
185       Operand op16((uint16_t)constant);
186       Operand op32((uint32_t)constant);
187       add_label(label_literal);
188       val = constant;
189 
190       if (chip >= GFX8 && !op16.isLiteral())
191          add_label(label_constant_16bit);
192 
193       if (!op32.isLiteral() || ((uint32_t)constant == 0x3e22f983 && chip >= GFX8))
194          add_label(label_constant_32bit);
195 
196       if (constant <= 64) {
197          add_label(label_constant_64bit);
198       } else if (constant >= 0xFFFFFFFFFFFFFFF0) { /* [-16 .. -1] */
199          add_label(label_constant_64bit);
200       } else if (constant == 0x3FE0000000000000) { /* 0.5 */
201          add_label(label_constant_64bit);
202       } else if (constant == 0xBFE0000000000000) { /* -0.5 */
203          add_label(label_constant_64bit);
204       } else if (constant == 0x3FF0000000000000) { /* 1.0 */
205          add_label(label_constant_64bit);
206       } else if (constant == 0xBFF0000000000000) { /* -1.0 */
207          add_label(label_constant_64bit);
208       } else if (constant == 0x4000000000000000) { /* 2.0 */
209          add_label(label_constant_64bit);
210       } else if (constant == 0xC000000000000000) { /* -2.0 */
211          add_label(label_constant_64bit);
212       } else if (constant == 0x4010000000000000) { /* 4.0 */
213          add_label(label_constant_64bit);
214       } else if (constant == 0xC010000000000000) { /* -4.0 */
215          add_label(label_constant_64bit);
216       }
217 
218       if (label & label_constant_64bit) {
219          val = Operand(constant).constantValue();
220          if (val != constant)
221             label &= ~(label_literal | label_constant_16bit | label_constant_32bit);
222       }
223    }
224 
is_constantaco::ssa_info225    bool is_constant(unsigned bits)
226    {
227       switch (bits) {
228       case 8:
229          return label & label_literal;
230       case 16:
231          return label & label_constant_16bit;
232       case 32:
233          return label & label_constant_32bit;
234       case 64:
235          return label & label_constant_64bit;
236       }
237       return false;
238    }
239 
is_literalaco::ssa_info240    bool is_literal(unsigned bits)
241    {
242       bool is_lit = label & label_literal;
243       switch (bits) {
244       case 8:
245          return false;
246       case 16:
247          return is_lit && ~(label & label_constant_16bit);
248       case 32:
249          return is_lit && ~(label & label_constant_32bit);
250       case 64:
251          return false;
252       }
253       return false;
254    }
255 
is_constant_or_literalaco::ssa_info256    bool is_constant_or_literal(unsigned bits)
257    {
258       if (bits == 64)
259          return label & label_constant_64bit;
260       else
261          return label & label_literal;
262    }
263 
set_absaco::ssa_info264    void set_abs(Temp abs_temp)
265    {
266       add_label(label_abs);
267       temp = abs_temp;
268    }
269 
is_absaco::ssa_info270    bool is_abs()
271    {
272       return label & label_abs;
273    }
274 
set_negaco::ssa_info275    void set_neg(Temp neg_temp)
276    {
277       add_label(label_neg);
278       temp = neg_temp;
279    }
280 
is_negaco::ssa_info281    bool is_neg()
282    {
283       return label & label_neg;
284    }
285 
set_neg_absaco::ssa_info286    void set_neg_abs(Temp neg_abs_temp)
287    {
288       add_label((Label)((uint32_t)label_abs | (uint32_t)label_neg));
289       temp = neg_abs_temp;
290    }
291 
set_mulaco::ssa_info292    void set_mul(Instruction* mul)
293    {
294       add_label(label_mul);
295       instr = mul;
296    }
297 
is_mulaco::ssa_info298    bool is_mul()
299    {
300       return label & label_mul;
301    }
302 
set_tempaco::ssa_info303    void set_temp(Temp tmp)
304    {
305       add_label(label_temp);
306       temp = tmp;
307    }
308 
is_tempaco::ssa_info309    bool is_temp()
310    {
311       return label & label_temp;
312    }
313 
set_madaco::ssa_info314    void set_mad(Instruction* mad, uint32_t mad_info_idx)
315    {
316       add_label(label_mad);
317       mad->pass_flags = mad_info_idx;
318       instr = mad;
319    }
320 
is_madaco::ssa_info321    bool is_mad()
322    {
323       return label & label_mad;
324    }
325 
set_omod2aco::ssa_info326    void set_omod2(Instruction* mul)
327    {
328       add_label(label_omod2);
329       instr = mul;
330    }
331 
is_omod2aco::ssa_info332    bool is_omod2()
333    {
334       return label & label_omod2;
335    }
336 
set_omod4aco::ssa_info337    void set_omod4(Instruction* mul)
338    {
339       add_label(label_omod4);
340       instr = mul;
341    }
342 
is_omod4aco::ssa_info343    bool is_omod4()
344    {
345       return label & label_omod4;
346    }
347 
set_omod5aco::ssa_info348    void set_omod5(Instruction* mul)
349    {
350       add_label(label_omod5);
351       instr = mul;
352    }
353 
is_omod5aco::ssa_info354    bool is_omod5()
355    {
356       return label & label_omod5;
357    }
358 
set_clampaco::ssa_info359    void set_clamp(Instruction *med3)
360    {
361       add_label(label_clamp);
362       instr = med3;
363    }
364 
is_clampaco::ssa_info365    bool is_clamp()
366    {
367       return label & label_clamp;
368    }
369 
set_undefinedaco::ssa_info370    void set_undefined()
371    {
372       add_label(label_undefined);
373    }
374 
is_undefinedaco::ssa_info375    bool is_undefined()
376    {
377       return label & label_undefined;
378    }
379 
set_vccaco::ssa_info380    void set_vcc(Temp vcc)
381    {
382       add_label(label_vcc);
383       temp = vcc;
384    }
385 
is_vccaco::ssa_info386    bool is_vcc()
387    {
388       return label & label_vcc;
389    }
390 
set_b2faco::ssa_info391    void set_b2f(Temp val)
392    {
393       add_label(label_b2f);
394       temp = val;
395    }
396 
is_b2faco::ssa_info397    bool is_b2f()
398    {
399       return label & label_b2f;
400    }
401 
set_add_subaco::ssa_info402    void set_add_sub(Instruction *add_sub_instr)
403    {
404       add_label(label_add_sub);
405       instr = add_sub_instr;
406    }
407 
is_add_subaco::ssa_info408    bool is_add_sub()
409    {
410       return label & label_add_sub;
411    }
412 
set_bitwiseaco::ssa_info413    void set_bitwise(Instruction *bitwise_instr)
414    {
415       add_label(label_bitwise);
416       instr = bitwise_instr;
417    }
418 
is_bitwiseaco::ssa_info419    bool is_bitwise()
420    {
421       return label & label_bitwise;
422    }
423 
set_uniform_bitwiseaco::ssa_info424    void set_uniform_bitwise()
425    {
426       add_label(label_uniform_bitwise);
427    }
428 
is_uniform_bitwiseaco::ssa_info429    bool is_uniform_bitwise()
430    {
431       return label & label_uniform_bitwise;
432    }
433 
set_minmaxaco::ssa_info434    void set_minmax(Instruction *minmax_instr)
435    {
436       add_label(label_minmax);
437       instr = minmax_instr;
438    }
439 
is_minmaxaco::ssa_info440    bool is_minmax()
441    {
442       return label & label_minmax;
443    }
444 
set_vopcaco::ssa_info445    void set_vopc(Instruction *vopc_instr)
446    {
447       add_label(label_vopc);
448       instr = vopc_instr;
449    }
450 
is_vopcaco::ssa_info451    bool is_vopc()
452    {
453       return label & label_vopc;
454    }
455 
set_scc_neededaco::ssa_info456    void set_scc_needed()
457    {
458       add_label(label_scc_needed);
459    }
460 
is_scc_neededaco::ssa_info461    bool is_scc_needed()
462    {
463       return label & label_scc_needed;
464    }
465 
set_scc_invertaco::ssa_info466    void set_scc_invert(Temp scc_inv)
467    {
468       add_label(label_scc_invert);
469       temp = scc_inv;
470    }
471 
is_scc_invertaco::ssa_info472    bool is_scc_invert()
473    {
474       return label & label_scc_invert;
475    }
476 
set_uniform_boolaco::ssa_info477    void set_uniform_bool(Temp uniform_bool)
478    {
479       add_label(label_uniform_bool);
480       temp = uniform_bool;
481    }
482 
is_uniform_boolaco::ssa_info483    bool is_uniform_bool()
484    {
485       return label & label_uniform_bool;
486    }
487 
set_vcc_hintaco::ssa_info488    void set_vcc_hint()
489    {
490       add_label(label_vcc_hint);
491    }
492 
is_vcc_hintaco::ssa_info493    bool is_vcc_hint()
494    {
495       return label & label_vcc_hint;
496    }
497 
set_b2iaco::ssa_info498    void set_b2i(Temp val)
499    {
500       add_label(label_b2i);
501       temp = val;
502    }
503 
is_b2iaco::ssa_info504    bool is_b2i()
505    {
506       return label & label_b2i;
507    }
508 
509 };
510 
511 struct opt_ctx {
512    Program* program;
513    std::vector<aco_ptr<Instruction>> instructions;
514    ssa_info* info;
515    std::pair<uint32_t,Temp> last_literal;
516    std::vector<mad_info> mad_infos;
517    std::vector<uint16_t> uses;
518 };
519 
520 struct CmpInfo {
521    aco_opcode ordered;
522    aco_opcode unordered;
523    aco_opcode ordered_swapped;
524    aco_opcode unordered_swapped;
525    aco_opcode inverse;
526    aco_opcode f32;
527    unsigned size;
528 };
529 
530 ALWAYS_INLINE bool get_cmp_info(aco_opcode op, CmpInfo *info);
531 
can_swap_operands(aco_ptr<Instruction> & instr)532 bool can_swap_operands(aco_ptr<Instruction>& instr)
533 {
534    if (instr->operands[0].isConstant() ||
535        (instr->operands[0].isTemp() && instr->operands[0].getTemp().type() == RegType::sgpr))
536       return false;
537 
538    switch (instr->opcode) {
539    case aco_opcode::v_add_u32:
540    case aco_opcode::v_add_co_u32:
541    case aco_opcode::v_add_co_u32_e64:
542    case aco_opcode::v_add_i32:
543    case aco_opcode::v_add_f16:
544    case aco_opcode::v_add_f32:
545    case aco_opcode::v_mul_f16:
546    case aco_opcode::v_mul_f32:
547    case aco_opcode::v_or_b32:
548    case aco_opcode::v_and_b32:
549    case aco_opcode::v_xor_b32:
550    case aco_opcode::v_max_f16:
551    case aco_opcode::v_max_f32:
552    case aco_opcode::v_min_f16:
553    case aco_opcode::v_min_f32:
554    case aco_opcode::v_max_i32:
555    case aco_opcode::v_min_i32:
556    case aco_opcode::v_max_u32:
557    case aco_opcode::v_min_u32:
558    case aco_opcode::v_max_i16:
559    case aco_opcode::v_min_i16:
560    case aco_opcode::v_max_u16:
561    case aco_opcode::v_min_u16:
562    case aco_opcode::v_max_i16_e64:
563    case aco_opcode::v_min_i16_e64:
564    case aco_opcode::v_max_u16_e64:
565    case aco_opcode::v_min_u16_e64:
566       return true;
567    case aco_opcode::v_sub_f16:
568       instr->opcode = aco_opcode::v_subrev_f16;
569       return true;
570    case aco_opcode::v_sub_f32:
571       instr->opcode = aco_opcode::v_subrev_f32;
572       return true;
573    case aco_opcode::v_sub_co_u32:
574       instr->opcode = aco_opcode::v_subrev_co_u32;
575       return true;
576    case aco_opcode::v_sub_u16:
577       instr->opcode = aco_opcode::v_subrev_u16;
578       return true;
579    case aco_opcode::v_sub_u32:
580       instr->opcode = aco_opcode::v_subrev_u32;
581       return true;
582    default: {
583       CmpInfo info;
584       get_cmp_info(instr->opcode, &info);
585       if (info.ordered == instr->opcode) {
586          instr->opcode = info.ordered_swapped;
587          return true;
588       }
589       if (info.unordered == instr->opcode) {
590          instr->opcode = info.unordered_swapped;
591          return true;
592       }
593       return false;
594    }
595    }
596 }
597 
can_use_VOP3(opt_ctx & ctx,const aco_ptr<Instruction> & instr)598 bool can_use_VOP3(opt_ctx& ctx, const aco_ptr<Instruction>& instr)
599 {
600    if (instr->isVOP3())
601       return true;
602 
603    if (instr->operands.size() && instr->operands[0].isLiteral() && ctx.program->chip_class < GFX10)
604       return false;
605 
606    if (instr->isDPP() || instr->isSDWA())
607       return false;
608 
609    return instr->opcode != aco_opcode::v_madmk_f32 &&
610           instr->opcode != aco_opcode::v_madak_f32 &&
611           instr->opcode != aco_opcode::v_madmk_f16 &&
612           instr->opcode != aco_opcode::v_madak_f16 &&
613           instr->opcode != aco_opcode::v_fmamk_f32 &&
614           instr->opcode != aco_opcode::v_fmaak_f32 &&
615           instr->opcode != aco_opcode::v_fmamk_f16 &&
616           instr->opcode != aco_opcode::v_fmaak_f16 &&
617           instr->opcode != aco_opcode::v_readlane_b32 &&
618           instr->opcode != aco_opcode::v_writelane_b32 &&
619           instr->opcode != aco_opcode::v_readfirstlane_b32;
620 }
621 
can_apply_sgprs(opt_ctx & ctx,aco_ptr<Instruction> & instr)622 bool can_apply_sgprs(opt_ctx& ctx, aco_ptr<Instruction>& instr)
623 {
624    if (instr->isSDWA() && ctx.program->chip_class < GFX9)
625       return false;
626    return instr->opcode != aco_opcode::v_readfirstlane_b32 &&
627           instr->opcode != aco_opcode::v_readlane_b32 &&
628           instr->opcode != aco_opcode::v_readlane_b32_e64 &&
629           instr->opcode != aco_opcode::v_writelane_b32 &&
630           instr->opcode != aco_opcode::v_writelane_b32_e64;
631 }
632 
to_VOP3(opt_ctx & ctx,aco_ptr<Instruction> & instr)633 void to_VOP3(opt_ctx& ctx, aco_ptr<Instruction>& instr)
634 {
635    if (instr->isVOP3())
636       return;
637 
638    aco_ptr<Instruction> tmp = std::move(instr);
639    Format format = asVOP3(tmp->format);
640    instr.reset(create_instruction<VOP3A_instruction>(tmp->opcode, format, tmp->operands.size(), tmp->definitions.size()));
641    std::copy(tmp->operands.cbegin(), tmp->operands.cend(), instr->operands.begin());
642    for (unsigned i = 0; i < instr->definitions.size(); i++) {
643       instr->definitions[i] = tmp->definitions[i];
644       if (instr->definitions[i].isTemp()) {
645          ssa_info& info = ctx.info[instr->definitions[i].tempId()];
646          if (info.label & instr_usedef_labels && info.instr == tmp.get())
647             info.instr = instr.get();
648       }
649    }
650    /* we don't need to update any instr_mod_labels because they either haven't
651     * been applied yet or this instruction isn't dead and so they've been ignored */
652 }
653 
654 /* only covers special cases */
alu_can_accept_constant(aco_opcode opcode,unsigned operand)655 bool alu_can_accept_constant(aco_opcode opcode, unsigned operand)
656 {
657    switch (opcode) {
658    case aco_opcode::v_interp_p2_f32:
659    case aco_opcode::v_mac_f32:
660    case aco_opcode::v_writelane_b32:
661    case aco_opcode::v_writelane_b32_e64:
662    case aco_opcode::v_cndmask_b32:
663       return operand != 2;
664    case aco_opcode::s_addk_i32:
665    case aco_opcode::s_mulk_i32:
666    case aco_opcode::p_wqm:
667    case aco_opcode::p_extract_vector:
668    case aco_opcode::p_split_vector:
669    case aco_opcode::v_readlane_b32:
670    case aco_opcode::v_readlane_b32_e64:
671    case aco_opcode::v_readfirstlane_b32:
672       return operand != 0;
673    default:
674       return true;
675    }
676 }
677 
valu_can_accept_vgpr(aco_ptr<Instruction> & instr,unsigned operand)678 bool valu_can_accept_vgpr(aco_ptr<Instruction>& instr, unsigned operand)
679 {
680    if (instr->opcode == aco_opcode::v_readlane_b32 || instr->opcode == aco_opcode::v_readlane_b32_e64 ||
681        instr->opcode == aco_opcode::v_writelane_b32 || instr->opcode == aco_opcode::v_writelane_b32_e64)
682       return operand != 1;
683    return true;
684 }
685 
686 /* check constant bus and literal limitations */
check_vop3_operands(opt_ctx & ctx,unsigned num_operands,Operand * operands)687 bool check_vop3_operands(opt_ctx& ctx, unsigned num_operands, Operand *operands)
688 {
689    int limit = ctx.program->chip_class >= GFX10 ? 2 : 1;
690    Operand literal32(s1);
691    Operand literal64(s2);
692    unsigned num_sgprs = 0;
693    unsigned sgpr[] = {0, 0};
694 
695    for (unsigned i = 0; i < num_operands; i++) {
696       Operand op = operands[i];
697 
698       if (op.hasRegClass() && op.regClass().type() == RegType::sgpr) {
699          /* two reads of the same SGPR count as 1 to the limit */
700          if (op.tempId() != sgpr[0] && op.tempId() != sgpr[1]) {
701             if (num_sgprs < 2)
702                sgpr[num_sgprs++] = op.tempId();
703             limit--;
704             if (limit < 0)
705                return false;
706          }
707       } else if (op.isLiteral()) {
708          if (ctx.program->chip_class < GFX10)
709             return false;
710 
711          if (!literal32.isUndefined() && literal32.constantValue() != op.constantValue())
712             return false;
713          if (!literal64.isUndefined() && literal64.constantValue() != op.constantValue())
714             return false;
715 
716          /* Any number of 32-bit literals counts as only 1 to the limit. Same
717           * (but separately) for 64-bit literals. */
718          if (op.size() == 1 && literal32.isUndefined()) {
719             limit--;
720             literal32 = op;
721          } else if (op.size() == 2 && literal64.isUndefined()) {
722             limit--;
723             literal64 = op;
724          }
725 
726          if (limit < 0)
727             return false;
728       }
729    }
730 
731    return true;
732 }
733 
parse_base_offset(opt_ctx & ctx,Instruction * instr,unsigned op_index,Temp * base,uint32_t * offset,bool prevent_overflow)734 bool parse_base_offset(opt_ctx &ctx, Instruction* instr, unsigned op_index, Temp *base, uint32_t *offset, bool prevent_overflow)
735 {
736    Operand op = instr->operands[op_index];
737 
738    if (!op.isTemp())
739       return false;
740    Temp tmp = op.getTemp();
741    if (!ctx.info[tmp.id()].is_add_sub())
742       return false;
743 
744    Instruction *add_instr = ctx.info[tmp.id()].instr;
745 
746    switch (add_instr->opcode) {
747    case aco_opcode::v_add_u32:
748    case aco_opcode::v_add_co_u32:
749    case aco_opcode::v_add_co_u32_e64:
750    case aco_opcode::s_add_i32:
751    case aco_opcode::s_add_u32:
752       break;
753    default:
754       return false;
755    }
756    if (prevent_overflow && !add_instr->definitions[0].isNUW())
757       return false;
758 
759    if (add_instr->usesModifiers())
760       return false;
761 
762    for (unsigned i = 0; i < 2; i++) {
763       if (add_instr->operands[i].isConstant()) {
764          *offset = add_instr->operands[i].constantValue();
765       } else if (add_instr->operands[i].isTemp() &&
766                  ctx.info[add_instr->operands[i].tempId()].is_constant_or_literal(32)) {
767          *offset = ctx.info[add_instr->operands[i].tempId()].val;
768       } else {
769          continue;
770       }
771       if (!add_instr->operands[!i].isTemp())
772          continue;
773 
774       uint32_t offset2 = 0;
775       if (parse_base_offset(ctx, add_instr, !i, base, &offset2, prevent_overflow)) {
776          *offset += offset2;
777       } else {
778          *base = add_instr->operands[!i].getTemp();
779       }
780       return true;
781    }
782 
783    return false;
784 }
785 
get_operand_size(aco_ptr<Instruction> & instr,unsigned index)786 unsigned get_operand_size(aco_ptr<Instruction>& instr, unsigned index)
787 {
788    if (instr->format == Format::PSEUDO)
789       return instr->operands[index].bytes() * 8u;
790    else if (instr->opcode == aco_opcode::v_mad_u64_u32 || instr->opcode == aco_opcode::v_mad_i64_i32)
791       return index == 2 ? 64 : 32;
792    else if (instr->isVALU() || instr->isSALU())
793       return instr_info.operand_size[(int)instr->opcode];
794    else
795       return 0;
796 }
797 
get_constant_op(opt_ctx & ctx,ssa_info info,uint32_t bits)798 Operand get_constant_op(opt_ctx &ctx, ssa_info info, uint32_t bits)
799 {
800    if (bits == 8)
801       return Operand((uint8_t)info.val);
802    if (bits == 16)
803       return Operand((uint16_t)info.val);
804    // TODO: this functions shouldn't be needed if we store Operand instead of value.
805    Operand op(info.val, bits == 64);
806    if (info.is_literal(32) && info.val == 0x3e22f983 && ctx.program->chip_class >= GFX8)
807       op.setFixed(PhysReg{248}); /* 1/2 PI can be an inline constant on GFX8+ */
808    return op;
809 }
810 
fixed_to_exec(Operand op)811 bool fixed_to_exec(Operand op)
812 {
813    return op.isFixed() && op.physReg() == exec;
814 }
815 
label_instruction(opt_ctx & ctx,Block & block,aco_ptr<Instruction> & instr)816 void label_instruction(opt_ctx &ctx, Block& block, aco_ptr<Instruction>& instr)
817 {
818    if (instr->isSALU() || instr->isVALU() || instr->format == Format::PSEUDO) {
819       ASSERTED bool all_const = false;
820       for (Operand& op : instr->operands)
821          all_const = all_const && (!op.isTemp() || ctx.info[op.tempId()].is_constant_or_literal(32));
822       perfwarn(ctx.program, all_const, "All instruction operands are constant", instr.get());
823 
824       ASSERTED bool is_copy = instr->opcode == aco_opcode::s_mov_b32 ||
825                               instr->opcode == aco_opcode::s_mov_b64 ||
826                               instr->opcode == aco_opcode::v_mov_b32;
827       perfwarn(ctx.program, is_copy && !instr->usesModifiers(), "Use p_parallelcopy instead", instr.get());
828    }
829 
830    for (unsigned i = 0; i < instr->operands.size(); i++)
831    {
832       if (!instr->operands[i].isTemp())
833          continue;
834 
835       ssa_info info = ctx.info[instr->operands[i].tempId()];
836       /* propagate undef */
837       if (info.is_undefined() && is_phi(instr))
838          instr->operands[i] = Operand(instr->operands[i].regClass());
839       /* propagate reg->reg of same type */
840       if (info.is_temp() && info.temp.regClass() == instr->operands[i].getTemp().regClass()) {
841          instr->operands[i].setTemp(ctx.info[instr->operands[i].tempId()].temp);
842          info = ctx.info[info.temp.id()];
843       }
844 
845       /* SALU / PSEUDO: propagate inline constants */
846       if (instr->isSALU() || instr->format == Format::PSEUDO) {
847          bool is_subdword = false;
848          // TODO: optimize SGPR propagation for subdword pseudo instructions on gfx9+
849          if (instr->format == Format::PSEUDO) {
850             is_subdword = std::any_of(instr->definitions.begin(), instr->definitions.end(),
851                                       [] (const Definition& def) { return def.regClass().is_subdword();});
852             is_subdword = is_subdword || std::any_of(instr->operands.begin(), instr->operands.end(),
853                                                      [] (const Operand& op) { return op.bytes() % 4;});
854             if (is_subdword && ctx.program->chip_class < GFX9)
855                continue;
856          }
857 
858          if (info.is_temp() && info.temp.type() == RegType::sgpr) {
859             instr->operands[i].setTemp(info.temp);
860             info = ctx.info[info.temp.id()];
861          } else if (info.is_temp() && info.temp.type() == RegType::vgpr &&
862                     info.temp.bytes() == instr->operands[i].bytes()) {
863             /* propagate vgpr if it can take it */
864             switch (instr->opcode) {
865             case aco_opcode::p_create_vector:
866             case aco_opcode::p_split_vector:
867             case aco_opcode::p_extract_vector:
868             case aco_opcode::p_phi:
869             case aco_opcode::p_parallelcopy: {
870                const bool all_vgpr = std::none_of(instr->definitions.begin(), instr->definitions.end(),
871                                                   [] (const Definition& def) { return def.getTemp().type() != RegType::vgpr;});
872                if (all_vgpr) {
873                   instr->operands[i] = Operand(info.temp);
874                   info = ctx.info[info.temp.id()];
875                }
876                break;
877             }
878             default:
879                break;
880             }
881          }
882          unsigned bits = get_operand_size(instr, i);
883          if ((info.is_constant(bits) || (info.is_literal(bits) && instr->format == Format::PSEUDO)) &&
884              !instr->operands[i].isFixed() && alu_can_accept_constant(instr->opcode, i)) {
885             instr->operands[i] = get_constant_op(ctx, info, bits);
886             continue;
887          }
888       }
889 
890       /* VALU: propagate neg, abs & inline constants */
891       else if (instr->isVALU()) {
892          if (info.is_temp() && info.temp.type() == RegType::vgpr && valu_can_accept_vgpr(instr, i)) {
893             instr->operands[i].setTemp(info.temp);
894             info = ctx.info[info.temp.id()];
895          }
896          /* applying SGPRs to VOP1 doesn't increase code size and DCE is helped by doing it earlier */
897          if (info.is_temp() && info.temp.type() == RegType::sgpr && can_apply_sgprs(ctx, instr) && instr->operands.size() == 1) {
898             instr->operands[i].setTemp(info.temp);
899             info = ctx.info[info.temp.id()];
900          }
901 
902          /* for instructions other than v_cndmask_b32, the size of the instruction should match the operand size */
903          unsigned can_use_mod = instr->opcode != aco_opcode::v_cndmask_b32 || instr->operands[i].getTemp().bytes() == 4;
904          can_use_mod = can_use_mod && instr_info.can_use_input_modifiers[(int)instr->opcode];
905 
906          if (instr->isSDWA())
907             can_use_mod = can_use_mod && (static_cast<SDWA_instruction*>(instr.get())->sel[i] & sdwa_asuint) == sdwa_udword;
908          else
909             can_use_mod = can_use_mod && (instr->isDPP() || can_use_VOP3(ctx, instr));
910 
911          if (info.is_abs() && can_use_mod) {
912             if (!instr->isDPP() && !instr->isSDWA())
913                to_VOP3(ctx, instr);
914             instr->operands[i] = Operand(info.temp);
915             if (instr->isDPP())
916                static_cast<DPP_instruction*>(instr.get())->abs[i] = true;
917             else if (instr->isSDWA())
918                static_cast<SDWA_instruction*>(instr.get())->abs[i] = true;
919             else
920                static_cast<VOP3A_instruction*>(instr.get())->abs[i] = true;
921          }
922          if (info.is_neg() && instr->opcode == aco_opcode::v_add_f32) {
923             instr->opcode = i ? aco_opcode::v_sub_f32 : aco_opcode::v_subrev_f32;
924             instr->operands[i].setTemp(info.temp);
925             continue;
926          } else if (info.is_neg() && instr->opcode == aco_opcode::v_add_f16) {
927             instr->opcode = i ? aco_opcode::v_sub_f16 : aco_opcode::v_subrev_f16;
928             instr->operands[i].setTemp(info.temp);
929             continue;
930          } else if (info.is_neg() && can_use_mod) {
931             if (!instr->isDPP() && !instr->isSDWA())
932                to_VOP3(ctx, instr);
933             instr->operands[i].setTemp(info.temp);
934             if (instr->isDPP())
935                static_cast<DPP_instruction*>(instr.get())->neg[i] = true;
936             else if (instr->isSDWA())
937                static_cast<SDWA_instruction*>(instr.get())->neg[i] = true;
938             else
939                static_cast<VOP3A_instruction*>(instr.get())->neg[i] = true;
940             continue;
941          }
942          unsigned bits = get_operand_size(instr, i);
943          if (info.is_constant(bits) && alu_can_accept_constant(instr->opcode, i) &&
944              (!instr->isSDWA() || ctx.program->chip_class >= GFX9)) {
945             Operand op = get_constant_op(ctx, info, bits);
946             perfwarn(ctx.program, instr->opcode == aco_opcode::v_cndmask_b32 && i == 2, "v_cndmask_b32 with a constant selector", instr.get());
947             if (i == 0 || instr->isSDWA() || instr->opcode == aco_opcode::v_readlane_b32 ||
948                 instr->opcode == aco_opcode::v_writelane_b32) {
949                instr->operands[i] = op;
950                continue;
951             } else if (!instr->isVOP3() && can_swap_operands(instr)) {
952                instr->operands[i] = instr->operands[0];
953                instr->operands[0] = op;
954                continue;
955             } else if (can_use_VOP3(ctx, instr)) {
956                to_VOP3(ctx, instr);
957                instr->operands[i] = op;
958                continue;
959             }
960          }
961       }
962 
963       /* MUBUF: propagate constants and combine additions */
964       else if (instr->format == Format::MUBUF) {
965          MUBUF_instruction *mubuf = static_cast<MUBUF_instruction *>(instr.get());
966          Temp base;
967          uint32_t offset;
968          while (info.is_temp())
969             info = ctx.info[info.temp.id()];
970 
971          /* According to AMDGPUDAGToDAGISel::SelectMUBUFScratchOffen(), vaddr
972           * overflow for scratch accesses works only on GFX9+ and saddr overflow
973           * never works. Since swizzling is the only thing that separates
974           * scratch accesses and other accesses and swizzling changing how
975           * addressing works significantly, this probably applies to swizzled
976           * MUBUF accesses. */
977          bool vaddr_prevent_overflow = mubuf->swizzled && ctx.program->chip_class < GFX9;
978          bool saddr_prevent_overflow = mubuf->swizzled;
979 
980          if (mubuf->offen && i == 1 && info.is_constant_or_literal(32) && mubuf->offset + info.val < 4096) {
981             assert(!mubuf->idxen);
982             instr->operands[1] = Operand(v1);
983             mubuf->offset += info.val;
984             mubuf->offen = false;
985             continue;
986          } else if (i == 2 && info.is_constant_or_literal(32) && mubuf->offset + info.val < 4096) {
987             instr->operands[2] = Operand((uint32_t) 0);
988             mubuf->offset += info.val;
989             continue;
990          } else if (mubuf->offen && i == 1 && parse_base_offset(ctx, instr.get(), i, &base, &offset, vaddr_prevent_overflow) &&
991                     base.regClass() == v1 && mubuf->offset + offset < 4096) {
992             assert(!mubuf->idxen);
993             instr->operands[1].setTemp(base);
994             mubuf->offset += offset;
995             continue;
996          } else if (i == 2 && parse_base_offset(ctx, instr.get(), i, &base, &offset, saddr_prevent_overflow) &&
997                     base.regClass() == s1 && mubuf->offset + offset < 4096) {
998             instr->operands[i].setTemp(base);
999             mubuf->offset += offset;
1000             continue;
1001          }
1002       }
1003 
1004       /* DS: combine additions */
1005       else if (instr->format == Format::DS) {
1006 
1007          DS_instruction *ds = static_cast<DS_instruction *>(instr.get());
1008          Temp base;
1009          uint32_t offset;
1010          bool has_usable_ds_offset = ctx.program->chip_class >= GFX7;
1011          if (has_usable_ds_offset &&
1012              i == 0 && parse_base_offset(ctx, instr.get(), i, &base, &offset, false) &&
1013              base.regClass() == instr->operands[i].regClass() &&
1014              instr->opcode != aco_opcode::ds_swizzle_b32) {
1015             if (instr->opcode == aco_opcode::ds_write2_b32 || instr->opcode == aco_opcode::ds_read2_b32 ||
1016                 instr->opcode == aco_opcode::ds_write2_b64 || instr->opcode == aco_opcode::ds_read2_b64) {
1017                unsigned mask = (instr->opcode == aco_opcode::ds_write2_b64 || instr->opcode == aco_opcode::ds_read2_b64) ? 0x7 : 0x3;
1018                unsigned shifts = (instr->opcode == aco_opcode::ds_write2_b64 || instr->opcode == aco_opcode::ds_read2_b64) ? 3 : 2;
1019 
1020                if ((offset & mask) == 0 &&
1021                    ds->offset0 + (offset >> shifts) <= 255 &&
1022                    ds->offset1 + (offset >> shifts) <= 255) {
1023                   instr->operands[i].setTemp(base);
1024                   ds->offset0 += offset >> shifts;
1025                   ds->offset1 += offset >> shifts;
1026                }
1027             } else {
1028                if (ds->offset0 + offset <= 65535) {
1029                   instr->operands[i].setTemp(base);
1030                   ds->offset0 += offset;
1031                }
1032             }
1033          }
1034       }
1035 
1036       /* SMEM: propagate constants and combine additions */
1037       else if (instr->format == Format::SMEM) {
1038 
1039          SMEM_instruction *smem = static_cast<SMEM_instruction *>(instr.get());
1040          Temp base;
1041          uint32_t offset;
1042          bool prevent_overflow = smem->operands[0].size() > 2 || smem->prevent_overflow;
1043          if (i == 1 && info.is_constant_or_literal(32) &&
1044              ((ctx.program->chip_class == GFX6 && info.val <= 0x3FF) ||
1045               (ctx.program->chip_class == GFX7 && info.val <= 0xFFFFFFFF) ||
1046               (ctx.program->chip_class >= GFX8 && info.val <= 0xFFFFF))) {
1047             instr->operands[i] = Operand(info.val);
1048             continue;
1049          } else if (i == 1 && parse_base_offset(ctx, instr.get(), i, &base, &offset, prevent_overflow) && base.regClass() == s1 && offset <= 0xFFFFF && ctx.program->chip_class >= GFX9) {
1050             bool soe = smem->operands.size() >= (!smem->definitions.empty() ? 3 : 4);
1051             if (soe &&
1052                 (!ctx.info[smem->operands.back().tempId()].is_constant_or_literal(32) ||
1053                  ctx.info[smem->operands.back().tempId()].val != 0)) {
1054                continue;
1055             }
1056             if (soe) {
1057                smem->operands[1] = Operand(offset);
1058                smem->operands.back() = Operand(base);
1059             } else {
1060                SMEM_instruction *new_instr = create_instruction<SMEM_instruction>(smem->opcode, Format::SMEM, smem->operands.size() + 1, smem->definitions.size());
1061                new_instr->operands[0] = smem->operands[0];
1062                new_instr->operands[1] = Operand(offset);
1063                if (smem->definitions.empty())
1064                   new_instr->operands[2] = smem->operands[2];
1065                new_instr->operands.back() = Operand(base);
1066                if (!smem->definitions.empty())
1067                   new_instr->definitions[0] = smem->definitions[0];
1068                new_instr->sync = smem->sync;
1069                new_instr->glc = smem->glc;
1070                new_instr->dlc = smem->dlc;
1071                new_instr->nv = smem->nv;
1072                new_instr->disable_wqm = smem->disable_wqm;
1073                instr.reset(new_instr);
1074                smem = static_cast<SMEM_instruction *>(instr.get());
1075             }
1076             continue;
1077          }
1078       }
1079 
1080       else if (instr->format == Format::PSEUDO_BRANCH) {
1081          if (ctx.info[instr->operands[0].tempId()].is_scc_invert()) {
1082             /* Flip the branch instruction to get rid of the scc_invert instruction */
1083             instr->opcode = instr->opcode == aco_opcode::p_cbranch_z ? aco_opcode::p_cbranch_nz : aco_opcode::p_cbranch_z;
1084             instr->operands[0].setTemp(ctx.info[instr->operands[0].tempId()].temp);
1085          }
1086       }
1087    }
1088 
1089    /* if this instruction doesn't define anything, return */
1090    if (instr->definitions.empty())
1091       return;
1092 
1093    if ((uint16_t) instr->format & (uint16_t) Format::VOPC) {
1094       ctx.info[instr->definitions[0].tempId()].set_vopc(instr.get());
1095       return;
1096    }
1097 
1098    switch (instr->opcode) {
1099    case aco_opcode::p_create_vector: {
1100       bool copy_prop = instr->operands.size() == 1 && instr->operands[0].isTemp() &&
1101                        instr->operands[0].regClass() == instr->definitions[0].regClass();
1102       if (copy_prop) {
1103          ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[0].getTemp());
1104          break;
1105       }
1106 
1107       /* expand vector operands */
1108       bool accept_subdword = instr->definitions[0].regClass().type() == RegType::vgpr &&
1109                              std::all_of(instr->operands.begin(), instr->operands.end(),
1110                              [&] (const Operand& op) { return !op.isLiteral() &&
1111                              (ctx.program->chip_class >= GFX9 || (op.hasRegClass() && op.regClass().type() == RegType::vgpr));});
1112 
1113       std::vector<Operand> ops;
1114       for (const Operand& op : instr->operands) {
1115          if (!op.isTemp() || !ctx.info[op.tempId()].is_vec()) {
1116             ops.emplace_back(op);
1117             continue;
1118          }
1119          Instruction* vec = ctx.info[op.tempId()].instr;
1120          bool is_subdword = std::any_of(vec->operands.begin(), vec->operands.end(),
1121                                [&] (const Operand& op) { return op.bytes() % 4; } );
1122 
1123          if (accept_subdword || !is_subdword) {
1124             for (const Operand& vec_op : vec->operands) {
1125                ops.emplace_back(vec_op);
1126                if (op.isLiteral() || (ctx.program->chip_class <= GFX8 &&
1127                                       (!op.hasRegClass() || op.regClass().type() == RegType::sgpr)))
1128                   accept_subdword = false;
1129             }
1130          } else {
1131             ops.emplace_back(op);
1132          }
1133       }
1134 
1135       /* combine expanded operands to new vector */
1136       if (ops.size() != instr->operands.size()) {
1137          assert(ops.size() > instr->operands.size());
1138          Definition def = instr->definitions[0];
1139          instr.reset(create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, ops.size(), 1));
1140          for (unsigned i = 0; i < ops.size(); i++) {
1141             if (ops[i].isTemp() && ctx.info[ops[i].tempId()].is_temp() &&
1142                 ctx.info[ops[i].tempId()].temp.type() == def.regClass().type())
1143                ops[i].setTemp(ctx.info[ops[i].tempId()].temp);
1144             instr->operands[i] = ops[i];
1145          }
1146          instr->definitions[0] = def;
1147       } else {
1148          for (unsigned i = 0; i < ops.size(); i++) {
1149             assert(instr->operands[i] == ops[i]);
1150          }
1151       }
1152       ctx.info[instr->definitions[0].tempId()].set_vec(instr.get());
1153       break;
1154    }
1155    case aco_opcode::p_split_vector: {
1156       ssa_info& info = ctx.info[instr->operands[0].tempId()];
1157 
1158       if (info.is_constant_or_literal(32)) {
1159          uint32_t val = info.val;
1160          for (Definition def : instr->definitions) {
1161             uint32_t mask = u_bit_consecutive(0, def.bytes() * 8u);
1162             ctx.info[def.tempId()].set_constant(ctx.program->chip_class, val & mask);
1163             val >>= def.bytes() * 8u;
1164          }
1165          break;
1166       } else if (!info.is_vec()) {
1167          break;
1168       }
1169 
1170       Instruction* vec = ctx.info[instr->operands[0].tempId()].instr;
1171       unsigned split_offset = 0;
1172       unsigned vec_offset = 0;
1173       unsigned vec_index = 0;
1174       for (unsigned i = 0; i < instr->definitions.size(); split_offset += instr->definitions[i++].bytes()) {
1175          while (vec_offset < split_offset && vec_index < vec->operands.size())
1176             vec_offset += vec->operands[vec_index++].bytes();
1177 
1178          if (vec_offset != split_offset || vec->operands[vec_index].bytes() != instr->definitions[i].bytes())
1179             continue;
1180 
1181          Operand vec_op = vec->operands[vec_index];
1182          if (vec_op.isConstant()) {
1183             ctx.info[instr->definitions[i].tempId()].set_constant(ctx.program->chip_class, vec_op.constantValue64());
1184          } else if (vec_op.isUndefined()) {
1185             ctx.info[instr->definitions[i].tempId()].set_undefined();
1186          } else {
1187             assert(vec_op.isTemp());
1188             ctx.info[instr->definitions[i].tempId()].set_temp(vec_op.getTemp());
1189          }
1190       }
1191       break;
1192    }
1193    case aco_opcode::p_extract_vector: { /* mov */
1194       ssa_info& info = ctx.info[instr->operands[0].tempId()];
1195       const unsigned index = instr->operands[1].constantValue();
1196       const unsigned dst_offset = index * instr->definitions[0].bytes();
1197 
1198       if (info.is_constant_or_literal(32)) {
1199          uint32_t mask = u_bit_consecutive(0, instr->definitions[0].bytes() * 8u);
1200          ctx.info[instr->definitions[0].tempId()].set_constant(ctx.program->chip_class, (info.val >> (dst_offset * 8u)) & mask);
1201          break;
1202       } else if (!info.is_vec()) {
1203          break;
1204       }
1205 
1206       /* check if we index directly into a vector element */
1207       Instruction* vec = info.instr;
1208       unsigned offset = 0;
1209 
1210       for (const Operand& op : vec->operands) {
1211          if (offset < dst_offset) {
1212             offset += op.bytes();
1213             continue;
1214          } else if (offset != dst_offset || op.bytes() != instr->definitions[0].bytes()) {
1215             break;
1216          }
1217 
1218          /* convert this extract into a copy instruction */
1219          instr->opcode = aco_opcode::p_parallelcopy;
1220          instr->operands.pop_back();
1221          instr->operands[0] = op;
1222 
1223          if (op.isConstant()) {
1224             ctx.info[instr->definitions[0].tempId()].set_constant(ctx.program->chip_class, op.constantValue64());
1225          } else if (op.isUndefined()) {
1226             ctx.info[instr->definitions[0].tempId()].set_undefined();
1227          } else {
1228             assert(op.isTemp());
1229             ctx.info[instr->definitions[0].tempId()].set_temp(op.getTemp());
1230          }
1231          break;
1232       }
1233       break;
1234    }
1235    case aco_opcode::p_parallelcopy: /* propagate */
1236       if (instr->operands[0].isTemp() && ctx.info[instr->operands[0].tempId()].is_vec() &&
1237           instr->operands[0].regClass() != instr->definitions[0].regClass()) {
1238          /* We might not be able to copy-propagate if it's a SGPR->VGPR copy, so
1239           * duplicate the vector instead.
1240           */
1241          Instruction *vec = ctx.info[instr->operands[0].tempId()].instr;
1242          aco_ptr<Instruction> old_copy = std::move(instr);
1243 
1244          instr.reset(create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, vec->operands.size(), 1));
1245          instr->definitions[0] = old_copy->definitions[0];
1246          std::copy(vec->operands.begin(), vec->operands.end(), instr->operands.begin());
1247          for (unsigned i = 0; i < vec->operands.size(); i++) {
1248             Operand& op = instr->operands[i];
1249             if (op.isTemp() && ctx.info[op.tempId()].is_temp() &&
1250                 ctx.info[op.tempId()].temp.type() == instr->definitions[0].regClass().type())
1251                op.setTemp(ctx.info[op.tempId()].temp);
1252          }
1253          ctx.info[instr->definitions[0].tempId()].set_vec(instr.get());
1254          break;
1255       }
1256       /* fallthrough */
1257    case aco_opcode::p_as_uniform:
1258       if (instr->definitions[0].isFixed()) {
1259          /* don't copy-propagate copies into fixed registers */
1260       } else if (instr->usesModifiers()) {
1261          // TODO
1262       } else if (instr->operands[0].isConstant()) {
1263          ctx.info[instr->definitions[0].tempId()].set_constant(ctx.program->chip_class, instr->operands[0].constantValue64());
1264       } else if (instr->operands[0].isTemp()) {
1265          ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[0].getTemp());
1266       } else {
1267          assert(instr->operands[0].isFixed());
1268       }
1269       break;
1270    case aco_opcode::p_is_helper:
1271       if (!ctx.program->needs_wqm)
1272          ctx.info[instr->definitions[0].tempId()].set_constant(ctx.program->chip_class, 0u);
1273       break;
1274    case aco_opcode::v_mul_f16:
1275    case aco_opcode::v_mul_f32: { /* omod */
1276       ctx.info[instr->definitions[0].tempId()].set_mul(instr.get());
1277 
1278       /* TODO: try to move the negate/abs modifier to the consumer instead */
1279       if (instr->usesModifiers())
1280          break;
1281 
1282       bool fp16 = instr->opcode == aco_opcode::v_mul_f16;
1283 
1284       for (unsigned i = 0; i < 2; i++) {
1285          if (instr->operands[!i].isConstant() && instr->operands[i].isTemp()) {
1286             if (instr->operands[!i].constantValue() == (fp16 ? 0x4000 : 0x40000000)) { /* 2.0 */
1287                ctx.info[instr->operands[i].tempId()].set_omod2(instr.get());
1288             } else if (instr->operands[!i].constantValue() == (fp16 ? 0x4400 : 0x40800000)) { /* 4.0 */
1289                ctx.info[instr->operands[i].tempId()].set_omod4(instr.get());
1290             } else if (instr->operands[!i].constantValue() == (fp16 ? 0x3800 : 0x3f000000)) { /* 0.5 */
1291                ctx.info[instr->operands[i].tempId()].set_omod5(instr.get());
1292             } else if (instr->operands[!i].constantValue() == (fp16 ? 0x3c00 : 0x3f800000) &&
1293                        !(fp16 ? block.fp_mode.must_flush_denorms16_64 : block.fp_mode.must_flush_denorms32)) { /* 1.0 */
1294                ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[i].getTemp());
1295             } else {
1296                continue;
1297             }
1298             break;
1299          }
1300       }
1301       break;
1302    }
1303    case aco_opcode::v_and_b32: { /* abs */
1304       if (!instr->usesModifiers() && instr->operands[1].isTemp() &&
1305           instr->operands[1].getTemp().type() == RegType::vgpr &&
1306           ((instr->definitions[0].bytes() == 4 && instr->operands[0].constantEquals(0x7FFFFFFFu)) ||
1307            (instr->definitions[0].bytes() == 2 && instr->operands[0].constantEquals(0x7FFFu))))
1308          ctx.info[instr->definitions[0].tempId()].set_abs(instr->operands[1].getTemp());
1309       else
1310          ctx.info[instr->definitions[0].tempId()].set_bitwise(instr.get());
1311       break;
1312    }
1313    case aco_opcode::v_xor_b32: { /* neg */
1314       if (!instr->usesModifiers() && instr->operands[1].isTemp() &&
1315           ((instr->definitions[0].bytes() == 4 && instr->operands[0].constantEquals(0x80000000u)) ||
1316            (instr->definitions[0].bytes() == 2 && instr->operands[0].constantEquals(0x8000u)))) {
1317          if (ctx.info[instr->operands[1].tempId()].is_neg()) {
1318             ctx.info[instr->definitions[0].tempId()].set_temp(ctx.info[instr->operands[1].tempId()].temp);
1319          } else if (instr->operands[1].getTemp().type() == RegType::vgpr) {
1320             if (ctx.info[instr->operands[1].tempId()].is_abs()) { /* neg(abs(x)) */
1321                instr->operands[1].setTemp(ctx.info[instr->operands[1].tempId()].temp);
1322                instr->opcode = aco_opcode::v_or_b32;
1323                ctx.info[instr->definitions[0].tempId()].set_neg_abs(instr->operands[1].getTemp());
1324             } else {
1325                ctx.info[instr->definitions[0].tempId()].set_neg(instr->operands[1].getTemp());
1326             }
1327          }
1328       } else {
1329          ctx.info[instr->definitions[0].tempId()].set_bitwise(instr.get());
1330       }
1331       break;
1332    }
1333    case aco_opcode::v_med3_f16:
1334    case aco_opcode::v_med3_f32: { /* clamp */
1335       VOP3A_instruction* vop3 = static_cast<VOP3A_instruction*>(instr.get());
1336       if (vop3->abs[0] || vop3->abs[1] || vop3->abs[2] ||
1337           vop3->neg[0] || vop3->neg[1] || vop3->neg[2] ||
1338           vop3->omod != 0 || vop3->opsel != 0)
1339          break;
1340 
1341       unsigned idx = 0;
1342       bool found_zero = false, found_one = false;
1343       bool is_fp16 = instr->opcode == aco_opcode::v_med3_f16;
1344       for (unsigned i = 0; i < 3; i++)
1345       {
1346          if (instr->operands[i].constantEquals(0))
1347             found_zero = true;
1348          else if (instr->operands[i].constantEquals(is_fp16 ? 0x3c00 : 0x3f800000)) /* 1.0 */
1349             found_one = true;
1350          else
1351             idx = i;
1352       }
1353       if (found_zero && found_one && instr->operands[idx].isTemp())
1354          ctx.info[instr->operands[idx].tempId()].set_clamp(instr.get());
1355       break;
1356    }
1357    case aco_opcode::v_cndmask_b32:
1358       if (instr->operands[0].constantEquals(0) &&
1359           instr->operands[1].constantEquals(0xFFFFFFFF))
1360          ctx.info[instr->definitions[0].tempId()].set_vcc(instr->operands[2].getTemp());
1361       else if (instr->operands[0].constantEquals(0) &&
1362                instr->operands[1].constantEquals(0x3f800000u))
1363          ctx.info[instr->definitions[0].tempId()].set_b2f(instr->operands[2].getTemp());
1364       else if (instr->operands[0].constantEquals(0) &&
1365                instr->operands[1].constantEquals(1))
1366          ctx.info[instr->definitions[0].tempId()].set_b2i(instr->operands[2].getTemp());
1367 
1368       ctx.info[instr->operands[2].tempId()].set_vcc_hint();
1369       break;
1370    case aco_opcode::v_cmp_lg_u32:
1371       if (instr->format == Format::VOPC && /* don't optimize VOP3 / SDWA / DPP */
1372           instr->operands[0].constantEquals(0) &&
1373           instr->operands[1].isTemp() && ctx.info[instr->operands[1].tempId()].is_vcc())
1374          ctx.info[instr->definitions[0].tempId()].set_temp(ctx.info[instr->operands[1].tempId()].temp);
1375       break;
1376    case aco_opcode::p_linear_phi: {
1377       /* lower_bool_phis() can create phis like this */
1378       bool all_same_temp = instr->operands[0].isTemp();
1379       /* this check is needed when moving uniform loop counters out of a divergent loop */
1380       if (all_same_temp)
1381          all_same_temp = instr->definitions[0].regClass() == instr->operands[0].regClass();
1382       for (unsigned i = 1; all_same_temp && (i < instr->operands.size()); i++) {
1383          if (!instr->operands[i].isTemp() || instr->operands[i].tempId() != instr->operands[0].tempId())
1384             all_same_temp = false;
1385       }
1386       if (all_same_temp) {
1387          ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[0].getTemp());
1388       } else {
1389          bool all_undef = instr->operands[0].isUndefined();
1390          for (unsigned i = 1; all_undef && (i < instr->operands.size()); i++) {
1391             if (!instr->operands[i].isUndefined())
1392                all_undef = false;
1393          }
1394          if (all_undef)
1395             ctx.info[instr->definitions[0].tempId()].set_undefined();
1396       }
1397       break;
1398    }
1399    case aco_opcode::v_add_u32:
1400    case aco_opcode::v_add_co_u32:
1401    case aco_opcode::v_add_co_u32_e64:
1402    case aco_opcode::s_add_i32:
1403    case aco_opcode::s_add_u32:
1404    case aco_opcode::v_subbrev_co_u32:
1405       ctx.info[instr->definitions[0].tempId()].set_add_sub(instr.get());
1406       break;
1407    case aco_opcode::s_not_b32:
1408    case aco_opcode::s_not_b64:
1409       if (ctx.info[instr->operands[0].tempId()].is_uniform_bool()) {
1410          ctx.info[instr->definitions[0].tempId()].set_uniform_bitwise();
1411          ctx.info[instr->definitions[1].tempId()].set_scc_invert(ctx.info[instr->operands[0].tempId()].temp);
1412       } else if (ctx.info[instr->operands[0].tempId()].is_uniform_bitwise()) {
1413          ctx.info[instr->definitions[0].tempId()].set_uniform_bitwise();
1414          ctx.info[instr->definitions[1].tempId()].set_scc_invert(ctx.info[instr->operands[0].tempId()].instr->definitions[1].getTemp());
1415       }
1416       ctx.info[instr->definitions[0].tempId()].set_bitwise(instr.get());
1417       break;
1418    case aco_opcode::s_and_b32:
1419    case aco_opcode::s_and_b64:
1420       if (fixed_to_exec(instr->operands[1]) && instr->operands[0].isTemp()) {
1421          if (ctx.info[instr->operands[0].tempId()].is_uniform_bool()) {
1422             /* Try to get rid of the superfluous s_cselect + s_and_b64 that comes from turning a uniform bool into divergent */
1423             ctx.info[instr->definitions[1].tempId()].set_temp(ctx.info[instr->operands[0].tempId()].temp);
1424             ctx.info[instr->definitions[0].tempId()].set_uniform_bool(ctx.info[instr->operands[0].tempId()].temp);
1425             break;
1426          } else if (ctx.info[instr->operands[0].tempId()].is_uniform_bitwise()) {
1427             /* Try to get rid of the superfluous s_and_b64, since the uniform bitwise instruction already produces the same SCC */
1428             ctx.info[instr->definitions[1].tempId()].set_temp(ctx.info[instr->operands[0].tempId()].instr->definitions[1].getTemp());
1429             ctx.info[instr->definitions[0].tempId()].set_uniform_bool(ctx.info[instr->operands[0].tempId()].instr->definitions[1].getTemp());
1430             break;
1431          } else if (ctx.info[instr->operands[0].tempId()].is_vopc()) {
1432             Instruction* vopc_instr = ctx.info[instr->operands[0].tempId()].instr;
1433             /* Remove superfluous s_and when the VOPC instruction uses the same exec and thus already produces the same result */
1434             if (vopc_instr->pass_flags == instr->pass_flags) {
1435                assert(instr->pass_flags > 0);
1436                ctx.info[instr->definitions[0].tempId()].set_temp(vopc_instr->definitions[0].getTemp());
1437                break;
1438             }
1439          }
1440       }
1441       /* fallthrough */
1442    case aco_opcode::s_or_b32:
1443    case aco_opcode::s_or_b64:
1444    case aco_opcode::s_xor_b32:
1445    case aco_opcode::s_xor_b64:
1446       if (std::all_of(instr->operands.begin(), instr->operands.end(), [&ctx](const Operand& op) {
1447                          return op.isTemp() && (ctx.info[op.tempId()].is_uniform_bool() || ctx.info[op.tempId()].is_uniform_bitwise());
1448                       })) {
1449          ctx.info[instr->definitions[0].tempId()].set_uniform_bitwise();
1450       }
1451       /* fallthrough */
1452    case aco_opcode::s_lshl_b32:
1453    case aco_opcode::v_or_b32:
1454    case aco_opcode::v_lshlrev_b32:
1455       ctx.info[instr->definitions[0].tempId()].set_bitwise(instr.get());
1456       break;
1457    case aco_opcode::v_min_f32:
1458    case aco_opcode::v_min_f16:
1459    case aco_opcode::v_min_u32:
1460    case aco_opcode::v_min_i32:
1461    case aco_opcode::v_min_u16:
1462    case aco_opcode::v_min_i16:
1463    case aco_opcode::v_max_f32:
1464    case aco_opcode::v_max_f16:
1465    case aco_opcode::v_max_u32:
1466    case aco_opcode::v_max_i32:
1467    case aco_opcode::v_max_u16:
1468    case aco_opcode::v_max_i16:
1469       ctx.info[instr->definitions[0].tempId()].set_minmax(instr.get());
1470       break;
1471    case aco_opcode::s_cselect_b64:
1472    case aco_opcode::s_cselect_b32:
1473       if (instr->operands[0].constantEquals((unsigned) -1) &&
1474           instr->operands[1].constantEquals(0)) {
1475          /* Found a cselect that operates on a uniform bool that comes from eg. s_cmp */
1476          ctx.info[instr->definitions[0].tempId()].set_uniform_bool(instr->operands[2].getTemp());
1477       }
1478       if (instr->operands[2].isTemp() && ctx.info[instr->operands[2].tempId()].is_scc_invert()) {
1479          /* Flip the operands to get rid of the scc_invert instruction */
1480          std::swap(instr->operands[0], instr->operands[1]);
1481          instr->operands[2].setTemp(ctx.info[instr->operands[2].tempId()].temp);
1482       }
1483       break;
1484    case aco_opcode::p_wqm:
1485       if (instr->operands[0].isTemp() &&
1486           ctx.info[instr->operands[0].tempId()].is_scc_invert()) {
1487          ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[0].getTemp());
1488       }
1489       break;
1490    default:
1491       break;
1492    }
1493 }
1494 
get_cmp_info(aco_opcode op,CmpInfo * info)1495 ALWAYS_INLINE bool get_cmp_info(aco_opcode op, CmpInfo *info)
1496 {
1497    info->ordered = aco_opcode::num_opcodes;
1498    info->unordered = aco_opcode::num_opcodes;
1499    info->ordered_swapped = aco_opcode::num_opcodes;
1500    info->unordered_swapped = aco_opcode::num_opcodes;
1501    switch (op) {
1502    #define CMP2(ord, unord, ord_swap, unord_swap, sz) \
1503    case aco_opcode::v_cmp_##ord##_f##sz:\
1504    case aco_opcode::v_cmp_n##unord##_f##sz:\
1505       info->ordered = aco_opcode::v_cmp_##ord##_f##sz;\
1506       info->unordered = aco_opcode::v_cmp_n##unord##_f##sz;\
1507       info->ordered_swapped = aco_opcode::v_cmp_##ord_swap##_f##sz;\
1508       info->unordered_swapped = aco_opcode::v_cmp_n##unord_swap##_f##sz;\
1509       info->inverse = op == aco_opcode::v_cmp_n##unord##_f##sz ? aco_opcode::v_cmp_##unord##_f##sz : aco_opcode::v_cmp_n##ord##_f##sz;\
1510       info->f32 = op == aco_opcode::v_cmp_##ord##_f##sz ? aco_opcode::v_cmp_##ord##_f32 : aco_opcode::v_cmp_n##unord##_f32;\
1511       info->size = sz;\
1512       return true;
1513    #define CMP(ord, unord, ord_swap, unord_swap) \
1514    CMP2(ord, unord, ord_swap, unord_swap, 16)\
1515    CMP2(ord, unord, ord_swap, unord_swap, 32)\
1516    CMP2(ord, unord, ord_swap, unord_swap, 64)
1517    CMP(lt, /*n*/ge, gt, /*n*/le)
1518    CMP(eq, /*n*/lg, eq, /*n*/lg)
1519    CMP(le, /*n*/gt, ge, /*n*/lt)
1520    CMP(gt, /*n*/le, lt, /*n*/le)
1521    CMP(lg, /*n*/eq, lg, /*n*/eq)
1522    CMP(ge, /*n*/lt, le, /*n*/gt)
1523    #undef CMP
1524    #undef CMP2
1525    #define ORD_TEST(sz) \
1526    case aco_opcode::v_cmp_u_f##sz:\
1527       info->f32 = aco_opcode::v_cmp_u_f32;\
1528       info->inverse = aco_opcode::v_cmp_o_f##sz;\
1529       info->size = sz;\
1530       return true;\
1531    case aco_opcode::v_cmp_o_f##sz:\
1532       info->f32 = aco_opcode::v_cmp_o_f32;\
1533       info->inverse = aco_opcode::v_cmp_u_f##sz;\
1534       info->size = sz;\
1535       return true;
1536    ORD_TEST(16)
1537    ORD_TEST(32)
1538    ORD_TEST(64)
1539    #undef ORD_TEST
1540    default:
1541       return false;
1542    }
1543 }
1544 
get_ordered(aco_opcode op)1545 aco_opcode get_ordered(aco_opcode op)
1546 {
1547    CmpInfo info;
1548    return get_cmp_info(op, &info) ? info.ordered : aco_opcode::num_opcodes;
1549 }
1550 
get_unordered(aco_opcode op)1551 aco_opcode get_unordered(aco_opcode op)
1552 {
1553    CmpInfo info;
1554    return get_cmp_info(op, &info) ? info.unordered : aco_opcode::num_opcodes;
1555 }
1556 
get_inverse(aco_opcode op)1557 aco_opcode get_inverse(aco_opcode op)
1558 {
1559    CmpInfo info;
1560    return get_cmp_info(op, &info) ? info.inverse : aco_opcode::num_opcodes;
1561 }
1562 
get_f32_cmp(aco_opcode op)1563 aco_opcode get_f32_cmp(aco_opcode op)
1564 {
1565    CmpInfo info;
1566    return get_cmp_info(op, &info) ? info.f32 : aco_opcode::num_opcodes;
1567 }
1568 
get_cmp_bitsize(aco_opcode op)1569 unsigned get_cmp_bitsize(aco_opcode op)
1570 {
1571    CmpInfo info;
1572    return get_cmp_info(op, &info) ? info.size : 0;
1573 }
1574 
is_cmp(aco_opcode op)1575 bool is_cmp(aco_opcode op)
1576 {
1577    CmpInfo info;
1578    return get_cmp_info(op, &info) && info.ordered != aco_opcode::num_opcodes;
1579 }
1580 
original_temp_id(opt_ctx & ctx,Temp tmp)1581 unsigned original_temp_id(opt_ctx &ctx, Temp tmp)
1582 {
1583    if (ctx.info[tmp.id()].is_temp())
1584       return ctx.info[tmp.id()].temp.id();
1585    else
1586       return tmp.id();
1587 }
1588 
decrease_uses(opt_ctx & ctx,Instruction * instr)1589 void decrease_uses(opt_ctx &ctx, Instruction* instr)
1590 {
1591    if (!--ctx.uses[instr->definitions[0].tempId()]) {
1592       for (const Operand& op : instr->operands) {
1593          if (op.isTemp())
1594             ctx.uses[op.tempId()]--;
1595       }
1596    }
1597 }
1598 
follow_operand(opt_ctx & ctx,Operand op,bool ignore_uses=false)1599 Instruction *follow_operand(opt_ctx &ctx, Operand op, bool ignore_uses=false)
1600 {
1601    if (!op.isTemp() || !(ctx.info[op.tempId()].label & instr_usedef_labels))
1602       return nullptr;
1603    if (!ignore_uses && ctx.uses[op.tempId()] > 1)
1604       return nullptr;
1605 
1606    Instruction *instr = ctx.info[op.tempId()].instr;
1607 
1608    if (instr->definitions.size() == 2) {
1609       assert(instr->definitions[0].isTemp() && instr->definitions[0].tempId() == op.tempId());
1610       if (instr->definitions[1].isTemp() && ctx.uses[instr->definitions[1].tempId()])
1611          return nullptr;
1612    }
1613 
1614    return instr;
1615 }
1616 
1617 /* s_or_b64(neq(a, a), neq(b, b)) -> v_cmp_u_f32(a, b)
1618  * s_and_b64(eq(a, a), eq(b, b)) -> v_cmp_o_f32(a, b) */
combine_ordering_test(opt_ctx & ctx,aco_ptr<Instruction> & instr)1619 bool combine_ordering_test(opt_ctx &ctx, aco_ptr<Instruction>& instr)
1620 {
1621    if (instr->definitions[0].regClass() != ctx.program->lane_mask)
1622       return false;
1623    if (instr->definitions[1].isTemp() && ctx.uses[instr->definitions[1].tempId()])
1624       return false;
1625 
1626    bool is_or = instr->opcode == aco_opcode::s_or_b64 || instr->opcode == aco_opcode::s_or_b32;
1627 
1628    bool neg[2] = {false, false};
1629    bool abs[2] = {false, false};
1630    uint8_t opsel = 0;
1631    Instruction *op_instr[2];
1632    Temp op[2];
1633 
1634    unsigned bitsize = 0;
1635    for (unsigned i = 0; i < 2; i++) {
1636       op_instr[i] = follow_operand(ctx, instr->operands[i], true);
1637       if (!op_instr[i])
1638          return false;
1639 
1640       aco_opcode expected_cmp = is_or ? aco_opcode::v_cmp_neq_f32 : aco_opcode::v_cmp_eq_f32;
1641       unsigned op_bitsize = get_cmp_bitsize(op_instr[i]->opcode);
1642 
1643       if (get_f32_cmp(op_instr[i]->opcode) != expected_cmp)
1644          return false;
1645       if (bitsize && op_bitsize != bitsize)
1646          return false;
1647       if (!op_instr[i]->operands[0].isTemp() || !op_instr[i]->operands[1].isTemp())
1648          return false;
1649 
1650       if (op_instr[i]->isVOP3()) {
1651          VOP3A_instruction *vop3 = static_cast<VOP3A_instruction*>(op_instr[i]);
1652          if (vop3->neg[0] != vop3->neg[1] || vop3->abs[0] != vop3->abs[1] || vop3->opsel == 1 || vop3->opsel == 2)
1653             return false;
1654          neg[i] = vop3->neg[0];
1655          abs[i] = vop3->abs[0];
1656          opsel |= (vop3->opsel & 1) << i;
1657       } else if (op_instr[i]->isSDWA()) {
1658          return false;
1659       }
1660 
1661       Temp op0 = op_instr[i]->operands[0].getTemp();
1662       Temp op1 = op_instr[i]->operands[1].getTemp();
1663       if (original_temp_id(ctx, op0) != original_temp_id(ctx, op1))
1664          return false;
1665 
1666       op[i] = op1;
1667       bitsize = op_bitsize;
1668    }
1669 
1670    if (op[1].type() == RegType::sgpr)
1671       std::swap(op[0], op[1]);
1672    unsigned num_sgprs = (op[0].type() == RegType::sgpr) + (op[1].type() == RegType::sgpr);
1673    if (num_sgprs > (ctx.program->chip_class >= GFX10 ? 2 : 1))
1674       return false;
1675 
1676    ctx.uses[op[0].id()]++;
1677    ctx.uses[op[1].id()]++;
1678    decrease_uses(ctx, op_instr[0]);
1679    decrease_uses(ctx, op_instr[1]);
1680 
1681    aco_opcode new_op = aco_opcode::num_opcodes;
1682    switch (bitsize) {
1683    case 16:
1684       new_op = is_or ? aco_opcode::v_cmp_u_f16 : aco_opcode::v_cmp_o_f16;
1685       break;
1686    case 32:
1687       new_op = is_or ? aco_opcode::v_cmp_u_f32 : aco_opcode::v_cmp_o_f32;
1688       break;
1689    case 64:
1690       new_op = is_or ? aco_opcode::v_cmp_u_f64 : aco_opcode::v_cmp_o_f64;
1691       break;
1692    }
1693    Instruction *new_instr;
1694    if (neg[0] || neg[1] || abs[0] || abs[1] || opsel || num_sgprs > 1) {
1695       VOP3A_instruction *vop3 = create_instruction<VOP3A_instruction>(new_op, asVOP3(Format::VOPC), 2, 1);
1696       for (unsigned i = 0; i < 2; i++) {
1697          vop3->neg[i] = neg[i];
1698          vop3->abs[i] = abs[i];
1699       }
1700       vop3->opsel = opsel;
1701       new_instr = static_cast<Instruction *>(vop3);
1702    } else {
1703       new_instr = create_instruction<VOPC_instruction>(new_op, Format::VOPC, 2, 1);
1704    }
1705    new_instr->operands[0] = Operand(op[0]);
1706    new_instr->operands[1] = Operand(op[1]);
1707    new_instr->definitions[0] = instr->definitions[0];
1708 
1709    ctx.info[instr->definitions[0].tempId()].label = 0;
1710    ctx.info[instr->definitions[0].tempId()].set_vopc(new_instr);
1711 
1712    instr.reset(new_instr);
1713 
1714    return true;
1715 }
1716 
1717 /* s_or_b64(v_cmp_u_f32(a, b), cmp(a, b)) -> get_unordered(cmp)(a, b)
1718  * s_and_b64(v_cmp_o_f32(a, b), cmp(a, b)) -> get_ordered(cmp)(a, b) */
combine_comparison_ordering(opt_ctx & ctx,aco_ptr<Instruction> & instr)1719 bool combine_comparison_ordering(opt_ctx &ctx, aco_ptr<Instruction>& instr)
1720 {
1721    if (instr->definitions[0].regClass() != ctx.program->lane_mask)
1722       return false;
1723    if (instr->definitions[1].isTemp() && ctx.uses[instr->definitions[1].tempId()])
1724       return false;
1725 
1726    bool is_or = instr->opcode == aco_opcode::s_or_b64 || instr->opcode == aco_opcode::s_or_b32;
1727    aco_opcode expected_nan_test = is_or ? aco_opcode::v_cmp_u_f32 : aco_opcode::v_cmp_o_f32;
1728 
1729    Instruction *nan_test = follow_operand(ctx, instr->operands[0], true);
1730    Instruction *cmp = follow_operand(ctx, instr->operands[1], true);
1731    if (!nan_test || !cmp)
1732       return false;
1733    if (nan_test->isSDWA() || cmp->isSDWA())
1734       return false;
1735 
1736    if (get_f32_cmp(cmp->opcode) == expected_nan_test)
1737       std::swap(nan_test, cmp);
1738    else if (get_f32_cmp(nan_test->opcode) != expected_nan_test)
1739       return false;
1740 
1741    if (!is_cmp(cmp->opcode) || get_cmp_bitsize(cmp->opcode) != get_cmp_bitsize(nan_test->opcode))
1742       return false;
1743 
1744    if (!nan_test->operands[0].isTemp() || !nan_test->operands[1].isTemp())
1745       return false;
1746    if (!cmp->operands[0].isTemp() || !cmp->operands[1].isTemp())
1747       return false;
1748 
1749    unsigned prop_cmp0 = original_temp_id(ctx, cmp->operands[0].getTemp());
1750    unsigned prop_cmp1 = original_temp_id(ctx, cmp->operands[1].getTemp());
1751    unsigned prop_nan0 = original_temp_id(ctx, nan_test->operands[0].getTemp());
1752    unsigned prop_nan1 = original_temp_id(ctx, nan_test->operands[1].getTemp());
1753    if (prop_cmp0 != prop_nan0 && prop_cmp0 != prop_nan1)
1754       return false;
1755    if (prop_cmp1 != prop_nan0 && prop_cmp1 != prop_nan1)
1756       return false;
1757 
1758    ctx.uses[cmp->operands[0].tempId()]++;
1759    ctx.uses[cmp->operands[1].tempId()]++;
1760    decrease_uses(ctx, nan_test);
1761    decrease_uses(ctx, cmp);
1762 
1763    aco_opcode new_op = is_or ? get_unordered(cmp->opcode) : get_ordered(cmp->opcode);
1764    Instruction *new_instr;
1765    if (cmp->isVOP3()) {
1766       VOP3A_instruction *new_vop3 = create_instruction<VOP3A_instruction>(new_op, asVOP3(Format::VOPC), 2, 1);
1767       VOP3A_instruction *cmp_vop3 = static_cast<VOP3A_instruction*>(cmp);
1768       memcpy(new_vop3->abs, cmp_vop3->abs, sizeof(new_vop3->abs));
1769       memcpy(new_vop3->neg, cmp_vop3->neg, sizeof(new_vop3->neg));
1770       new_vop3->clamp = cmp_vop3->clamp;
1771       new_vop3->omod = cmp_vop3->omod;
1772       new_vop3->opsel = cmp_vop3->opsel;
1773       new_instr = new_vop3;
1774    } else {
1775       new_instr = create_instruction<VOPC_instruction>(new_op, Format::VOPC, 2, 1);
1776    }
1777    new_instr->operands[0] = cmp->operands[0];
1778    new_instr->operands[1] = cmp->operands[1];
1779    new_instr->definitions[0] = instr->definitions[0];
1780 
1781    ctx.info[instr->definitions[0].tempId()].label = 0;
1782    ctx.info[instr->definitions[0].tempId()].set_vopc(new_instr);
1783 
1784    instr.reset(new_instr);
1785 
1786    return true;
1787 }
1788 
is_operand_constant(opt_ctx & ctx,Operand op,unsigned bit_size,uint64_t * value)1789 bool is_operand_constant(opt_ctx &ctx, Operand op, unsigned bit_size, uint64_t *value)
1790 {
1791    if (op.isConstant()) {
1792       *value = op.constantValue64();
1793       return true;
1794    } else if (op.isTemp()) {
1795       unsigned id = original_temp_id(ctx, op.getTemp());
1796       if (!ctx.info[id].is_constant_or_literal(bit_size))
1797          return false;
1798       *value = get_constant_op(ctx, ctx.info[id], bit_size).constantValue64();
1799       return true;
1800    }
1801    return false;
1802 }
1803 
is_constant_nan(uint64_t value,unsigned bit_size)1804 bool is_constant_nan(uint64_t value, unsigned bit_size)
1805 {
1806    if (bit_size == 16)
1807       return ((value >> 10) & 0x1f) == 0x1f && (value & 0x3ff);
1808    else if (bit_size == 32)
1809       return ((value >> 23) & 0xff) == 0xff && (value & 0x7fffff);
1810    else
1811       return ((value >> 52) & 0x7ff) == 0x7ff && (value & 0xfffffffffffff);
1812 }
1813 
1814 /* s_or_b64(v_cmp_neq_f32(a, a), cmp(a, #b)) and b is not NaN -> get_unordered(cmp)(a, b)
1815  * s_and_b64(v_cmp_eq_f32(a, a), cmp(a, #b)) and b is not NaN -> get_ordered(cmp)(a, b) */
combine_constant_comparison_ordering(opt_ctx & ctx,aco_ptr<Instruction> & instr)1816 bool combine_constant_comparison_ordering(opt_ctx &ctx, aco_ptr<Instruction>& instr)
1817 {
1818    if (instr->definitions[0].regClass() != ctx.program->lane_mask)
1819       return false;
1820    if (instr->definitions[1].isTemp() && ctx.uses[instr->definitions[1].tempId()])
1821       return false;
1822 
1823    bool is_or = instr->opcode == aco_opcode::s_or_b64 || instr->opcode == aco_opcode::s_or_b32;
1824 
1825    Instruction *nan_test = follow_operand(ctx, instr->operands[0], true);
1826    Instruction *cmp = follow_operand(ctx, instr->operands[1], true);
1827 
1828    if (!nan_test || !cmp)
1829       return false;
1830    if (nan_test->isSDWA() || cmp->isSDWA())
1831       return false;
1832 
1833    aco_opcode expected_nan_test = is_or ? aco_opcode::v_cmp_neq_f32 : aco_opcode::v_cmp_eq_f32;
1834    if (get_f32_cmp(cmp->opcode) == expected_nan_test)
1835       std::swap(nan_test, cmp);
1836    else if (get_f32_cmp(nan_test->opcode) != expected_nan_test)
1837       return false;
1838 
1839    unsigned bit_size = get_cmp_bitsize(cmp->opcode);
1840    if (!is_cmp(cmp->opcode) || get_cmp_bitsize(nan_test->opcode) != bit_size)
1841       return false;
1842 
1843    if (!nan_test->operands[0].isTemp() || !nan_test->operands[1].isTemp())
1844       return false;
1845    if (!cmp->operands[0].isTemp() && !cmp->operands[1].isTemp())
1846       return false;
1847 
1848    unsigned prop_nan0 = original_temp_id(ctx, nan_test->operands[0].getTemp());
1849    unsigned prop_nan1 = original_temp_id(ctx, nan_test->operands[1].getTemp());
1850    if (prop_nan0 != prop_nan1)
1851       return false;
1852 
1853    if (nan_test->isVOP3()) {
1854       VOP3A_instruction *vop3 = static_cast<VOP3A_instruction*>(nan_test);
1855       if (vop3->neg[0] != vop3->neg[1] || vop3->abs[0] != vop3->abs[1] || vop3->opsel == 1 || vop3->opsel == 2)
1856          return false;
1857    }
1858 
1859    int constant_operand = -1;
1860    for (unsigned i = 0; i < 2; i++) {
1861       if (cmp->operands[i].isTemp() && original_temp_id(ctx, cmp->operands[i].getTemp()) == prop_nan0) {
1862          constant_operand = !i;
1863          break;
1864       }
1865    }
1866    if (constant_operand == -1)
1867       return false;
1868 
1869    uint64_t constant_value;
1870    if (!is_operand_constant(ctx, cmp->operands[constant_operand], bit_size, &constant_value))
1871       return false;
1872    if (is_constant_nan(constant_value, bit_size))
1873       return false;
1874 
1875    if (cmp->operands[0].isTemp())
1876       ctx.uses[cmp->operands[0].tempId()]++;
1877    if (cmp->operands[1].isTemp())
1878       ctx.uses[cmp->operands[1].tempId()]++;
1879    decrease_uses(ctx, nan_test);
1880    decrease_uses(ctx, cmp);
1881 
1882    aco_opcode new_op = is_or ? get_unordered(cmp->opcode) : get_ordered(cmp->opcode);
1883    Instruction *new_instr;
1884    if (cmp->isVOP3()) {
1885       VOP3A_instruction *new_vop3 = create_instruction<VOP3A_instruction>(new_op, asVOP3(Format::VOPC), 2, 1);
1886       VOP3A_instruction *cmp_vop3 = static_cast<VOP3A_instruction*>(cmp);
1887       memcpy(new_vop3->abs, cmp_vop3->abs, sizeof(new_vop3->abs));
1888       memcpy(new_vop3->neg, cmp_vop3->neg, sizeof(new_vop3->neg));
1889       new_vop3->clamp = cmp_vop3->clamp;
1890       new_vop3->omod = cmp_vop3->omod;
1891       new_vop3->opsel = cmp_vop3->opsel;
1892       new_instr = new_vop3;
1893    } else {
1894       new_instr = create_instruction<VOPC_instruction>(new_op, Format::VOPC, 2, 1);
1895    }
1896    new_instr->operands[0] = cmp->operands[0];
1897    new_instr->operands[1] = cmp->operands[1];
1898    new_instr->definitions[0] = instr->definitions[0];
1899 
1900    ctx.info[instr->definitions[0].tempId()].label = 0;
1901    ctx.info[instr->definitions[0].tempId()].set_vopc(new_instr);
1902 
1903    instr.reset(new_instr);
1904 
1905    return true;
1906 }
1907 
1908 /* s_andn2(exec, cmp(a, b)) -> get_inverse(cmp)(a, b) */
combine_inverse_comparison(opt_ctx & ctx,aco_ptr<Instruction> & instr)1909 bool combine_inverse_comparison(opt_ctx &ctx, aco_ptr<Instruction>& instr)
1910 {
1911    if (!instr->operands[0].isFixed() || instr->operands[0].physReg() != exec)
1912       return false;
1913    if (ctx.uses[instr->definitions[1].tempId()])
1914       return false;
1915 
1916    Instruction *cmp = follow_operand(ctx, instr->operands[1]);
1917    if (!cmp)
1918       return false;
1919 
1920    aco_opcode new_opcode = get_inverse(cmp->opcode);
1921    if (new_opcode == aco_opcode::num_opcodes)
1922       return false;
1923 
1924    if (cmp->operands[0].isTemp())
1925       ctx.uses[cmp->operands[0].tempId()]++;
1926    if (cmp->operands[1].isTemp())
1927       ctx.uses[cmp->operands[1].tempId()]++;
1928    decrease_uses(ctx, cmp);
1929 
1930    /* This creates a new instruction instead of modifying the existing
1931     * comparison so that the comparison is done with the correct exec mask. */
1932    Instruction *new_instr;
1933    if (cmp->isVOP3()) {
1934       VOP3A_instruction *new_vop3 = create_instruction<VOP3A_instruction>(new_opcode, asVOP3(Format::VOPC), 2, 1);
1935       VOP3A_instruction *cmp_vop3 = static_cast<VOP3A_instruction*>(cmp);
1936       memcpy(new_vop3->abs, cmp_vop3->abs, sizeof(new_vop3->abs));
1937       memcpy(new_vop3->neg, cmp_vop3->neg, sizeof(new_vop3->neg));
1938       new_vop3->clamp = cmp_vop3->clamp;
1939       new_vop3->omod = cmp_vop3->omod;
1940       new_vop3->opsel = cmp_vop3->opsel;
1941       new_instr = new_vop3;
1942    } else if (cmp->isSDWA()) {
1943       SDWA_instruction *new_sdwa = create_instruction<SDWA_instruction>(
1944          new_opcode, (Format)((uint16_t)Format::SDWA | (uint16_t)Format::VOPC), 2, 1);
1945       SDWA_instruction *cmp_sdwa = static_cast<SDWA_instruction*>(cmp);
1946       memcpy(new_sdwa->abs, cmp_sdwa->abs, sizeof(new_sdwa->abs));
1947       memcpy(new_sdwa->sel, cmp_sdwa->sel, sizeof(new_sdwa->sel));
1948       memcpy(new_sdwa->neg, cmp_sdwa->neg, sizeof(new_sdwa->neg));
1949       new_sdwa->dst_sel = cmp_sdwa->dst_sel;
1950       new_sdwa->dst_preserve = cmp_sdwa->dst_preserve;
1951       new_sdwa->clamp = cmp_sdwa->clamp;
1952       new_sdwa->omod = cmp_sdwa->omod;
1953       new_instr = new_sdwa;
1954    } else {
1955       new_instr = create_instruction<VOPC_instruction>(new_opcode, Format::VOPC, 2, 1);
1956    }
1957    new_instr->operands[0] = cmp->operands[0];
1958    new_instr->operands[1] = cmp->operands[1];
1959    new_instr->definitions[0] = instr->definitions[0];
1960 
1961    ctx.info[instr->definitions[0].tempId()].label = 0;
1962    ctx.info[instr->definitions[0].tempId()].set_vopc(new_instr);
1963 
1964    instr.reset(new_instr);
1965 
1966    return true;
1967 }
1968 
1969 /* op1(op2(1, 2), 0) if swap = false
1970  * op1(0, op2(1, 2)) if swap = true */
match_op3_for_vop3(opt_ctx & ctx,aco_opcode op1,aco_opcode op2,Instruction * op1_instr,bool swap,const char * shuffle_str,Operand operands[3],bool neg[3],bool abs[3],uint8_t * opsel,bool * op1_clamp,uint8_t * op1_omod,bool * inbetween_neg,bool * inbetween_abs,bool * inbetween_opsel,bool * precise)1971 bool match_op3_for_vop3(opt_ctx &ctx, aco_opcode op1, aco_opcode op2,
1972                         Instruction* op1_instr, bool swap, const char *shuffle_str,
1973                         Operand operands[3], bool neg[3], bool abs[3], uint8_t *opsel,
1974                         bool *op1_clamp, uint8_t *op1_omod,
1975                         bool *inbetween_neg, bool *inbetween_abs, bool *inbetween_opsel,
1976                         bool *precise)
1977 {
1978    /* checks */
1979    if (op1_instr->opcode != op1)
1980       return false;
1981 
1982    Instruction *op2_instr = follow_operand(ctx, op1_instr->operands[swap]);
1983    if (!op2_instr || op2_instr->opcode != op2)
1984       return false;
1985    if (fixed_to_exec(op2_instr->operands[0]) || fixed_to_exec(op2_instr->operands[1]))
1986       return false;
1987 
1988    VOP3A_instruction *op1_vop3 = op1_instr->isVOP3() ? static_cast<VOP3A_instruction *>(op1_instr) : NULL;
1989    VOP3A_instruction *op2_vop3 = op2_instr->isVOP3() ? static_cast<VOP3A_instruction *>(op2_instr) : NULL;
1990 
1991    if (op1_instr->isSDWA() || op2_instr->isSDWA())
1992       return false;
1993 
1994    /* don't support inbetween clamp/omod */
1995    if (op2_vop3 && (op2_vop3->clamp || op2_vop3->omod))
1996       return false;
1997 
1998    /* get operands and modifiers and check inbetween modifiers */
1999    *op1_clamp = op1_vop3 ? op1_vop3->clamp : false;
2000    *op1_omod = op1_vop3 ? op1_vop3->omod : 0u;
2001 
2002    if (inbetween_neg)
2003       *inbetween_neg = op1_vop3 ? op1_vop3->neg[swap] : false;
2004    else if (op1_vop3 && op1_vop3->neg[swap])
2005       return false;
2006 
2007    if (inbetween_abs)
2008       *inbetween_abs = op1_vop3 ? op1_vop3->abs[swap] : false;
2009    else if (op1_vop3 && op1_vop3->abs[swap])
2010       return false;
2011 
2012    if (inbetween_opsel)
2013       *inbetween_opsel = op1_vop3 ? op1_vop3->opsel & (1 << swap) : false;
2014    else if (op1_vop3 && op1_vop3->opsel & (1 << swap))
2015       return false;
2016 
2017    *precise = op1_instr->definitions[0].isPrecise() ||
2018               op2_instr->definitions[0].isPrecise();
2019 
2020    int shuffle[3];
2021    shuffle[shuffle_str[0] - '0'] = 0;
2022    shuffle[shuffle_str[1] - '0'] = 1;
2023    shuffle[shuffle_str[2] - '0'] = 2;
2024 
2025    operands[shuffle[0]] = op1_instr->operands[!swap];
2026    neg[shuffle[0]] = op1_vop3 ? op1_vop3->neg[!swap] : false;
2027    abs[shuffle[0]] = op1_vop3 ? op1_vop3->abs[!swap] : false;
2028    if (op1_vop3 && op1_vop3->opsel & (1 << !swap))
2029       *opsel |= 1 << shuffle[0];
2030 
2031    for (unsigned i = 0; i < 2; i++) {
2032       operands[shuffle[i + 1]] = op2_instr->operands[i];
2033       neg[shuffle[i + 1]] = op2_vop3 ? op2_vop3->neg[i] : false;
2034       abs[shuffle[i + 1]] = op2_vop3 ? op2_vop3->abs[i] : false;
2035       if (op2_vop3 && op2_vop3->opsel & (1 << i))
2036          *opsel |= 1 << shuffle[i + 1];
2037    }
2038 
2039    /* check operands */
2040    if (!check_vop3_operands(ctx, 3, operands))
2041       return false;
2042 
2043    return true;
2044 }
2045 
create_vop3_for_op3(opt_ctx & ctx,aco_opcode opcode,aco_ptr<Instruction> & instr,Operand operands[3],bool neg[3],bool abs[3],uint8_t opsel,bool clamp,unsigned omod)2046 void create_vop3_for_op3(opt_ctx& ctx, aco_opcode opcode, aco_ptr<Instruction>& instr,
2047                          Operand operands[3], bool neg[3], bool abs[3], uint8_t opsel,
2048                          bool clamp, unsigned omod)
2049 {
2050    VOP3A_instruction *new_instr = create_instruction<VOP3A_instruction>(opcode, Format::VOP3A, 3, 1);
2051    memcpy(new_instr->abs, abs, sizeof(bool[3]));
2052    memcpy(new_instr->neg, neg, sizeof(bool[3]));
2053    new_instr->clamp = clamp;
2054    new_instr->omod = omod;
2055    new_instr->opsel = opsel;
2056    new_instr->operands[0] = operands[0];
2057    new_instr->operands[1] = operands[1];
2058    new_instr->operands[2] = operands[2];
2059    new_instr->definitions[0] = instr->definitions[0];
2060    ctx.info[instr->definitions[0].tempId()].label = 0;
2061 
2062    instr.reset(new_instr);
2063 }
2064 
combine_three_valu_op(opt_ctx & ctx,aco_ptr<Instruction> & instr,aco_opcode op2,aco_opcode new_op,const char * shuffle,uint8_t ops)2065 bool combine_three_valu_op(opt_ctx& ctx, aco_ptr<Instruction>& instr, aco_opcode op2, aco_opcode new_op, const char *shuffle, uint8_t ops)
2066 {
2067    for (unsigned swap = 0; swap < 2; swap++) {
2068       if (!((1 << swap) & ops))
2069          continue;
2070 
2071       Operand operands[3];
2072       bool neg[3], abs[3], clamp, precise;
2073       uint8_t opsel = 0, omod = 0;
2074       if (match_op3_for_vop3(ctx, instr->opcode, op2,
2075                              instr.get(), swap, shuffle,
2076                              operands, neg, abs, &opsel,
2077                              &clamp, &omod, NULL, NULL, NULL, &precise)) {
2078          ctx.uses[instr->operands[swap].tempId()]--;
2079          create_vop3_for_op3(ctx, new_op, instr, operands, neg, abs, opsel, clamp, omod);
2080          return true;
2081       }
2082    }
2083    return false;
2084 }
2085 
combine_minmax(opt_ctx & ctx,aco_ptr<Instruction> & instr,aco_opcode opposite,aco_opcode minmax3)2086 bool combine_minmax(opt_ctx& ctx, aco_ptr<Instruction>& instr, aco_opcode opposite, aco_opcode minmax3)
2087 {
2088    if (combine_three_valu_op(ctx, instr, instr->opcode, minmax3, "012", 1 | 2))
2089       return true;
2090 
2091    /* min(-max(a, b), c) -> min3(c, -a, -b) *
2092     * max(-min(a, b), c) -> max3(c, -a, -b) */
2093    for (unsigned swap = 0; swap < 2; swap++) {
2094       Operand operands[3];
2095       bool neg[3], abs[3], clamp, precise;
2096       uint8_t opsel = 0, omod = 0;
2097       bool inbetween_neg;
2098       if (match_op3_for_vop3(ctx, instr->opcode, opposite,
2099                              instr.get(), swap, "012",
2100                              operands, neg, abs, &opsel,
2101                              &clamp, &omod, &inbetween_neg, NULL, NULL, &precise) &&
2102           inbetween_neg) {
2103          ctx.uses[instr->operands[swap].tempId()]--;
2104          neg[1] = !neg[1];
2105          neg[2] = !neg[2];
2106          create_vop3_for_op3(ctx, minmax3, instr, operands, neg, abs, opsel, clamp, omod);
2107          return true;
2108       }
2109    }
2110    return false;
2111 }
2112 
2113 /* s_not_b32(s_and_b32(a, b)) -> s_nand_b32(a, b)
2114  * s_not_b32(s_or_b32(a, b)) -> s_nor_b32(a, b)
2115  * s_not_b32(s_xor_b32(a, b)) -> s_xnor_b32(a, b)
2116  * s_not_b64(s_and_b64(a, b)) -> s_nand_b64(a, b)
2117  * s_not_b64(s_or_b64(a, b)) -> s_nor_b64(a, b)
2118  * s_not_b64(s_xor_b64(a, b)) -> s_xnor_b64(a, b) */
combine_salu_not_bitwise(opt_ctx & ctx,aco_ptr<Instruction> & instr)2119 bool combine_salu_not_bitwise(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2120 {
2121    /* checks */
2122    if (!instr->operands[0].isTemp())
2123       return false;
2124    if (instr->definitions[1].isTemp() && ctx.uses[instr->definitions[1].tempId()])
2125       return false;
2126 
2127    Instruction *op2_instr = follow_operand(ctx, instr->operands[0]);
2128    if (!op2_instr)
2129       return false;
2130    switch (op2_instr->opcode) {
2131    case aco_opcode::s_and_b32:
2132    case aco_opcode::s_or_b32:
2133    case aco_opcode::s_xor_b32:
2134    case aco_opcode::s_and_b64:
2135    case aco_opcode::s_or_b64:
2136    case aco_opcode::s_xor_b64:
2137       break;
2138    default:
2139       return false;
2140    }
2141 
2142    /* create instruction */
2143    std::swap(instr->definitions[0], op2_instr->definitions[0]);
2144    std::swap(instr->definitions[1], op2_instr->definitions[1]);
2145    ctx.uses[instr->operands[0].tempId()]--;
2146    ctx.info[op2_instr->definitions[0].tempId()].label = 0;
2147 
2148    switch (op2_instr->opcode) {
2149    case aco_opcode::s_and_b32:
2150       op2_instr->opcode = aco_opcode::s_nand_b32;
2151       break;
2152    case aco_opcode::s_or_b32:
2153       op2_instr->opcode = aco_opcode::s_nor_b32;
2154       break;
2155    case aco_opcode::s_xor_b32:
2156       op2_instr->opcode = aco_opcode::s_xnor_b32;
2157       break;
2158    case aco_opcode::s_and_b64:
2159       op2_instr->opcode = aco_opcode::s_nand_b64;
2160       break;
2161    case aco_opcode::s_or_b64:
2162       op2_instr->opcode = aco_opcode::s_nor_b64;
2163       break;
2164    case aco_opcode::s_xor_b64:
2165       op2_instr->opcode = aco_opcode::s_xnor_b64;
2166       break;
2167    default:
2168       break;
2169    }
2170 
2171    return true;
2172 }
2173 
2174 /* s_and_b32(a, s_not_b32(b)) -> s_andn2_b32(a, b)
2175  * s_or_b32(a, s_not_b32(b)) -> s_orn2_b32(a, b)
2176  * s_and_b64(a, s_not_b64(b)) -> s_andn2_b64(a, b)
2177  * s_or_b64(a, s_not_b64(b)) -> s_orn2_b64(a, b) */
combine_salu_n2(opt_ctx & ctx,aco_ptr<Instruction> & instr)2178 bool combine_salu_n2(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2179 {
2180    if (instr->definitions[0].isTemp() && ctx.info[instr->definitions[0].tempId()].is_uniform_bool())
2181       return false;
2182 
2183    for (unsigned i = 0; i < 2; i++) {
2184       Instruction *op2_instr = follow_operand(ctx, instr->operands[i]);
2185       if (!op2_instr || (op2_instr->opcode != aco_opcode::s_not_b32 && op2_instr->opcode != aco_opcode::s_not_b64))
2186          continue;
2187       if (ctx.uses[op2_instr->definitions[1].tempId()] || fixed_to_exec(op2_instr->operands[0]))
2188          continue;
2189 
2190       if (instr->operands[!i].isLiteral() && op2_instr->operands[0].isLiteral() &&
2191           instr->operands[!i].constantValue() != op2_instr->operands[0].constantValue())
2192          continue;
2193 
2194       ctx.uses[instr->operands[i].tempId()]--;
2195       instr->operands[0] = instr->operands[!i];
2196       instr->operands[1] = op2_instr->operands[0];
2197       ctx.info[instr->definitions[0].tempId()].label = 0;
2198 
2199       switch (instr->opcode) {
2200       case aco_opcode::s_and_b32:
2201          instr->opcode = aco_opcode::s_andn2_b32;
2202          break;
2203       case aco_opcode::s_or_b32:
2204          instr->opcode = aco_opcode::s_orn2_b32;
2205          break;
2206       case aco_opcode::s_and_b64:
2207          instr->opcode = aco_opcode::s_andn2_b64;
2208          break;
2209       case aco_opcode::s_or_b64:
2210          instr->opcode = aco_opcode::s_orn2_b64;
2211          break;
2212       default:
2213          break;
2214       }
2215 
2216       return true;
2217    }
2218    return false;
2219 }
2220 
2221 /* s_add_{i32,u32}(a, s_lshl_b32(b, <n>)) -> s_lshl<n>_add_u32(a, b) */
combine_salu_lshl_add(opt_ctx & ctx,aco_ptr<Instruction> & instr)2222 bool combine_salu_lshl_add(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2223 {
2224    if (instr->opcode == aco_opcode::s_add_i32 && ctx.uses[instr->definitions[1].tempId()])
2225       return false;
2226 
2227    for (unsigned i = 0; i < 2; i++) {
2228       Instruction *op2_instr = follow_operand(ctx, instr->operands[i]);
2229       if (!op2_instr || op2_instr->opcode != aco_opcode::s_lshl_b32 ||
2230           ctx.uses[op2_instr->definitions[1].tempId()])
2231          continue;
2232       if (!op2_instr->operands[1].isConstant() || fixed_to_exec(op2_instr->operands[0]))
2233          continue;
2234 
2235       uint32_t shift = op2_instr->operands[1].constantValue();
2236       if (shift < 1 || shift > 4)
2237          continue;
2238 
2239       if (instr->operands[!i].isLiteral() && op2_instr->operands[0].isLiteral() &&
2240           instr->operands[!i].constantValue() != op2_instr->operands[0].constantValue())
2241          continue;
2242 
2243       ctx.uses[instr->operands[i].tempId()]--;
2244       instr->operands[1] = instr->operands[!i];
2245       instr->operands[0] = op2_instr->operands[0];
2246       ctx.info[instr->definitions[0].tempId()].label = 0;
2247 
2248       instr->opcode = ((aco_opcode[]){aco_opcode::s_lshl1_add_u32,
2249                                       aco_opcode::s_lshl2_add_u32,
2250                                       aco_opcode::s_lshl3_add_u32,
2251                                       aco_opcode::s_lshl4_add_u32})[shift - 1];
2252 
2253       return true;
2254    }
2255    return false;
2256 }
2257 
combine_add_sub_b2i(opt_ctx & ctx,aco_ptr<Instruction> & instr,aco_opcode new_op,uint8_t ops)2258 bool combine_add_sub_b2i(opt_ctx& ctx, aco_ptr<Instruction>& instr, aco_opcode new_op, uint8_t ops)
2259 {
2260    if (instr->usesModifiers())
2261       return false;
2262 
2263    for (unsigned i = 0; i < 2; i++) {
2264       if (!((1 << i) & ops))
2265          continue;
2266       if (instr->operands[i].isTemp() &&
2267           ctx.info[instr->operands[i].tempId()].is_b2i() &&
2268           ctx.uses[instr->operands[i].tempId()] == 1) {
2269 
2270          aco_ptr<Instruction> new_instr;
2271          if (instr->operands[!i].isTemp() && instr->operands[!i].getTemp().type() == RegType::vgpr) {
2272             new_instr.reset(create_instruction<VOP2_instruction>(new_op, Format::VOP2, 3, 2));
2273          } else if (ctx.program->chip_class >= GFX10 ||
2274                     (instr->operands[!i].isConstant() && !instr->operands[!i].isLiteral())) {
2275             new_instr.reset(create_instruction<VOP3A_instruction>(new_op, asVOP3(Format::VOP2), 3, 2));
2276          } else {
2277             return false;
2278          }
2279          ctx.uses[instr->operands[i].tempId()]--;
2280          new_instr->definitions[0] = instr->definitions[0];
2281          if (instr->definitions.size() == 2) {
2282             new_instr->definitions[1] = instr->definitions[1];
2283          } else {
2284             new_instr->definitions[1] =
2285                Definition(ctx.program->allocateTmp(ctx.program->lane_mask));
2286             /* Make sure the uses vector is large enough and the number of
2287              * uses properly initialized to 0.
2288              */
2289             ctx.uses.push_back(0);
2290          }
2291          new_instr->definitions[1].setHint(vcc);
2292          new_instr->operands[0] = Operand(0u);
2293          new_instr->operands[1] = instr->operands[!i];
2294          new_instr->operands[2] = Operand(ctx.info[instr->operands[i].tempId()].temp);
2295          instr = std::move(new_instr);
2296          ctx.info[instr->definitions[0].tempId()].set_add_sub(instr.get());
2297          return true;
2298       }
2299    }
2300 
2301    return false;
2302 }
2303 
get_minmax_info(aco_opcode op,aco_opcode * min,aco_opcode * max,aco_opcode * min3,aco_opcode * max3,aco_opcode * med3,bool * some_gfx9_only)2304 bool get_minmax_info(aco_opcode op, aco_opcode *min, aco_opcode *max, aco_opcode *min3, aco_opcode *max3, aco_opcode *med3, bool *some_gfx9_only)
2305 {
2306    switch (op) {
2307    #define MINMAX(type, gfx9) \
2308    case aco_opcode::v_min_##type:\
2309    case aco_opcode::v_max_##type:\
2310    case aco_opcode::v_med3_##type:\
2311       *min = aco_opcode::v_min_##type;\
2312       *max = aco_opcode::v_max_##type;\
2313       *med3 = aco_opcode::v_med3_##type;\
2314       *min3 = aco_opcode::v_min3_##type;\
2315       *max3 = aco_opcode::v_max3_##type;\
2316       *some_gfx9_only = gfx9;\
2317       return true;
2318    MINMAX(f32, false)
2319    MINMAX(u32, false)
2320    MINMAX(i32, false)
2321    MINMAX(f16, true)
2322    MINMAX(u16, true)
2323    MINMAX(i16, true)
2324    #undef MINMAX
2325    default:
2326       return false;
2327    }
2328 }
2329 
2330 /* v_min_{f,u,i}{16,32}(v_max_{f,u,i}{16,32}(a, lb), ub) -> v_med3_{f,u,i}{16,32}(a, lb, ub) when ub > lb
2331  * v_max_{f,u,i}{16,32}(v_min_{f,u,i}{16,32}(a, ub), lb) -> v_med3_{f,u,i}{16,32}(a, lb, ub) when ub > lb */
combine_clamp(opt_ctx & ctx,aco_ptr<Instruction> & instr,aco_opcode min,aco_opcode max,aco_opcode med)2332 bool combine_clamp(opt_ctx& ctx, aco_ptr<Instruction>& instr,
2333                    aco_opcode min, aco_opcode max, aco_opcode med)
2334 {
2335    /* TODO: GLSL's clamp(x, minVal, maxVal) and SPIR-V's
2336     * FClamp(x, minVal, maxVal)/NClamp(x, minVal, maxVal) are undefined if
2337     * minVal > maxVal, which means we can always select it to a v_med3_f32 */
2338    aco_opcode other_op;
2339    if (instr->opcode == min)
2340       other_op = max;
2341    else if (instr->opcode == max)
2342       other_op = min;
2343    else
2344       return false;
2345 
2346    for (unsigned swap = 0; swap < 2; swap++) {
2347       Operand operands[3];
2348       bool neg[3], abs[3], clamp, precise;
2349       uint8_t opsel = 0, omod = 0;
2350       if (match_op3_for_vop3(ctx, instr->opcode, other_op, instr.get(), swap,
2351                              "012", operands, neg, abs, &opsel,
2352                              &clamp, &omod, NULL, NULL, NULL, &precise)) {
2353          /* max(min(src, upper), lower) returns upper if src is NaN, but
2354           * med3(src, lower, upper) returns lower.
2355           */
2356          if (precise && instr->opcode != min)
2357             continue;
2358 
2359          int const0_idx = -1, const1_idx = -1;
2360          uint32_t const0 = 0, const1 = 0;
2361          for (int i = 0; i < 3; i++) {
2362             uint32_t val;
2363             if (operands[i].isConstant()) {
2364                val = operands[i].constantValue();
2365             } else if (operands[i].isTemp() && ctx.info[operands[i].tempId()].is_constant_or_literal(32)) {
2366                val = ctx.info[operands[i].tempId()].val;
2367             } else {
2368                continue;
2369             }
2370             if (const0_idx >= 0) {
2371                const1_idx = i;
2372                const1 = val;
2373             } else {
2374                const0_idx = i;
2375                const0 = val;
2376             }
2377          }
2378          if (const0_idx < 0 || const1_idx < 0)
2379             continue;
2380 
2381          if (opsel & (1 << const0_idx))
2382             const0 >>= 16;
2383          if (opsel & (1 << const1_idx))
2384             const1 >>= 16;
2385 
2386          int lower_idx = const0_idx;
2387          switch (min) {
2388          case aco_opcode::v_min_f32:
2389          case aco_opcode::v_min_f16: {
2390             float const0_f, const1_f;
2391             if (min == aco_opcode::v_min_f32) {
2392                memcpy(&const0_f, &const0, 4);
2393                memcpy(&const1_f, &const1, 4);
2394             } else {
2395                const0_f = _mesa_half_to_float(const0);
2396                const1_f = _mesa_half_to_float(const1);
2397             }
2398             if (abs[const0_idx]) const0_f = fabsf(const0_f);
2399             if (abs[const1_idx]) const1_f = fabsf(const1_f);
2400             if (neg[const0_idx]) const0_f = -const0_f;
2401             if (neg[const1_idx]) const1_f = -const1_f;
2402             lower_idx = const0_f < const1_f ? const0_idx : const1_idx;
2403             break;
2404          }
2405          case aco_opcode::v_min_u32: {
2406             lower_idx = const0 < const1 ? const0_idx : const1_idx;
2407             break;
2408          }
2409          case aco_opcode::v_min_u16: {
2410             lower_idx = (uint16_t)const0 < (uint16_t)const1 ? const0_idx : const1_idx;
2411             break;
2412          }
2413          case aco_opcode::v_min_i32: {
2414             int32_t const0_i = const0 & 0x80000000u ? -2147483648 + (int32_t)(const0 & 0x7fffffffu) : const0;
2415             int32_t const1_i = const1 & 0x80000000u ? -2147483648 + (int32_t)(const1 & 0x7fffffffu) : const1;
2416             lower_idx = const0_i < const1_i ? const0_idx : const1_idx;
2417             break;
2418          }
2419          case aco_opcode::v_min_i16: {
2420             int16_t const0_i = const0 & 0x8000u ? -32768 + (int16_t)(const0 & 0x7fffu) : const0;
2421             int16_t const1_i = const1 & 0x8000u ? -32768 + (int16_t)(const1 & 0x7fffu) : const1;
2422             lower_idx = const0_i < const1_i ? const0_idx : const1_idx;
2423             break;
2424          }
2425          default:
2426             break;
2427          }
2428          int upper_idx = lower_idx == const0_idx ? const1_idx : const0_idx;
2429 
2430          if (instr->opcode == min) {
2431             if (upper_idx != 0 || lower_idx == 0)
2432                return false;
2433          } else {
2434             if (upper_idx == 0 || lower_idx != 0)
2435                return false;
2436          }
2437 
2438          ctx.uses[instr->operands[swap].tempId()]--;
2439          create_vop3_for_op3(ctx, med, instr, operands, neg, abs, opsel, clamp, omod);
2440 
2441          return true;
2442       }
2443    }
2444 
2445    return false;
2446 }
2447 
2448 
apply_sgprs(opt_ctx & ctx,aco_ptr<Instruction> & instr)2449 void apply_sgprs(opt_ctx &ctx, aco_ptr<Instruction>& instr)
2450 {
2451    bool is_shift64 = instr->opcode == aco_opcode::v_lshlrev_b64 ||
2452                      instr->opcode == aco_opcode::v_lshrrev_b64 ||
2453                      instr->opcode == aco_opcode::v_ashrrev_i64;
2454 
2455    /* find candidates and create the set of sgprs already read */
2456    unsigned sgpr_ids[2] = {0, 0};
2457    uint32_t operand_mask = 0;
2458    bool has_literal = false;
2459    for (unsigned i = 0; i < instr->operands.size(); i++) {
2460       if (instr->operands[i].isLiteral())
2461          has_literal = true;
2462       if (!instr->operands[i].isTemp())
2463          continue;
2464       if (instr->operands[i].getTemp().type() == RegType::sgpr) {
2465          if (instr->operands[i].tempId() != sgpr_ids[0])
2466             sgpr_ids[!!sgpr_ids[0]] = instr->operands[i].tempId();
2467       }
2468       ssa_info& info = ctx.info[instr->operands[i].tempId()];
2469       if (info.is_temp() && info.temp.type() == RegType::sgpr)
2470          operand_mask |= 1u << i;
2471    }
2472    unsigned max_sgprs = 1;
2473    if (ctx.program->chip_class >= GFX10 && !is_shift64)
2474       max_sgprs = 2;
2475    if (has_literal)
2476       max_sgprs--;
2477 
2478    unsigned num_sgprs = !!sgpr_ids[0] + !!sgpr_ids[1];
2479 
2480    /* keep on applying sgprs until there is nothing left to be done */
2481    while (operand_mask) {
2482       uint32_t sgpr_idx = 0;
2483       uint32_t sgpr_info_id = 0;
2484       uint32_t mask = operand_mask;
2485       /* choose a sgpr */
2486       while (mask) {
2487          unsigned i = u_bit_scan(&mask);
2488          uint16_t uses = ctx.uses[instr->operands[i].tempId()];
2489          if (sgpr_info_id == 0 || uses < ctx.uses[sgpr_info_id]) {
2490             sgpr_idx = i;
2491             sgpr_info_id = instr->operands[i].tempId();
2492          }
2493       }
2494       operand_mask &= ~(1u << sgpr_idx);
2495 
2496       /* Applying two sgprs require making it VOP3, so don't do it unless it's
2497        * definitively beneficial.
2498        * TODO: this is too conservative because later the use count could be reduced to 1 */
2499       if (num_sgprs && ctx.uses[sgpr_info_id] > 1 && !instr->isVOP3() && !instr->isSDWA())
2500          break;
2501 
2502       Temp sgpr = ctx.info[sgpr_info_id].temp;
2503       bool new_sgpr = sgpr.id() != sgpr_ids[0] && sgpr.id() != sgpr_ids[1];
2504       if (new_sgpr && num_sgprs >= max_sgprs)
2505          continue;
2506 
2507       if (sgpr_idx == 0 || instr->isVOP3() || instr->isSDWA()) {
2508          instr->operands[sgpr_idx] = Operand(sgpr);
2509       } else if (can_swap_operands(instr)) {
2510          instr->operands[sgpr_idx] = instr->operands[0];
2511          instr->operands[0] = Operand(sgpr);
2512          /* swap bits using a 4-entry LUT */
2513          uint32_t swapped = (0x3120 >> (operand_mask & 0x3)) & 0xf;
2514          operand_mask = (operand_mask & ~0x3) | swapped;
2515       } else if (can_use_VOP3(ctx, instr)) {
2516          to_VOP3(ctx, instr);
2517          instr->operands[sgpr_idx] = Operand(sgpr);
2518       } else {
2519          continue;
2520       }
2521 
2522       if (new_sgpr)
2523          sgpr_ids[num_sgprs++] = sgpr.id();
2524       ctx.uses[sgpr_info_id]--;
2525       ctx.uses[sgpr.id()]++;
2526    }
2527 }
2528 
2529 template <typename T>
apply_omod_clamp_helper(opt_ctx & ctx,T * instr,ssa_info & def_info)2530 bool apply_omod_clamp_helper(opt_ctx &ctx, T *instr, ssa_info& def_info)
2531 {
2532    if (!def_info.is_clamp() && (instr->clamp || instr->omod))
2533       return false;
2534 
2535    if (def_info.is_omod2())
2536       instr->omod = 1;
2537    else if (def_info.is_omod4())
2538       instr->omod = 2;
2539    else if (def_info.is_omod5())
2540       instr->omod = 3;
2541    else if (def_info.is_clamp())
2542       instr->clamp = true;
2543 
2544    return true;
2545 }
2546 
2547 /* apply omod / clamp modifiers if the def is used only once and the instruction can have modifiers */
apply_omod_clamp(opt_ctx & ctx,Block & block,aco_ptr<Instruction> & instr)2548 bool apply_omod_clamp(opt_ctx &ctx, Block& block, aco_ptr<Instruction>& instr)
2549 {
2550    if (instr->definitions.empty() || ctx.uses[instr->definitions[0].tempId()] != 1 ||
2551        !instr_info.can_use_output_modifiers[(int)instr->opcode])
2552       return false;
2553 
2554    bool can_vop3 = can_use_VOP3(ctx, instr);
2555    if (!instr->isSDWA() && !can_vop3)
2556       return false;
2557 
2558    /* omod flushes -0 to +0 and has no effect if denormals are enabled */
2559    bool can_use_omod = (can_vop3 || ctx.program->chip_class >= GFX9); /* SDWA omod is GFX9+ */
2560    if (instr->definitions[0].bytes() == 4)
2561       can_use_omod = can_use_omod && block.fp_mode.denorm32 == 0 &&
2562                      !block.fp_mode.preserve_signed_zero_inf_nan32;
2563    else
2564       can_use_omod = can_use_omod && block.fp_mode.denorm16_64 == 0 &&
2565                      !block.fp_mode.preserve_signed_zero_inf_nan16_64;
2566 
2567    ssa_info& def_info = ctx.info[instr->definitions[0].tempId()];
2568 
2569    uint64_t omod_labels = label_omod2 | label_omod4 | label_omod5;
2570    if (!def_info.is_clamp() && !(can_use_omod && (def_info.label & omod_labels)))
2571       return false;
2572    /* if the omod/clamp instruction is dead, then the single user of this
2573     * instruction is a different instruction */
2574    if (!ctx.uses[def_info.instr->definitions[0].tempId()])
2575       return false;
2576 
2577    /* MADs/FMAs are created later, so we don't have to update the original add */
2578    assert(!ctx.info[instr->definitions[0].tempId()].is_mad());
2579 
2580    if (instr->isSDWA()) {
2581       if (!apply_omod_clamp_helper(ctx, static_cast<SDWA_instruction *>(instr.get()), def_info))
2582          return false;
2583    } else {
2584       to_VOP3(ctx, instr);
2585       if (!apply_omod_clamp_helper(ctx, static_cast<VOP3A_instruction *>(instr.get()), def_info))
2586          return false;
2587    }
2588 
2589    std::swap(instr->definitions[0], def_info.instr->definitions[0]);
2590    ctx.info[instr->definitions[0].tempId()].label &= label_clamp;
2591    ctx.uses[def_info.instr->definitions[0].tempId()]--;
2592 
2593    return true;
2594 }
2595 
2596 /* v_and(a, v_subbrev_co(0, 0, vcc)) -> v_cndmask(0, a, vcc) */
combine_and_subbrev(opt_ctx & ctx,aco_ptr<Instruction> & instr)2597 bool combine_and_subbrev(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2598 {
2599    if (instr->usesModifiers())
2600       return false;
2601 
2602    for (unsigned i = 0; i < 2; i++) {
2603       Instruction *op_instr = follow_operand(ctx, instr->operands[i], true);
2604       if (op_instr &&
2605           op_instr->opcode == aco_opcode::v_subbrev_co_u32 &&
2606           op_instr->operands[0].constantEquals(0) &&
2607           op_instr->operands[1].constantEquals(0) &&
2608           !op_instr->usesModifiers()) {
2609 
2610          aco_ptr<Instruction> new_instr;
2611          if (instr->operands[!i].isTemp() && instr->operands[!i].getTemp().type() == RegType::vgpr) {
2612             new_instr.reset(create_instruction<VOP2_instruction>(aco_opcode::v_cndmask_b32, Format::VOP2, 3, 1));
2613          } else if (ctx.program->chip_class >= GFX10 ||
2614                     (instr->operands[!i].isConstant() && !instr->operands[!i].isLiteral())) {
2615             new_instr.reset(create_instruction<VOP3A_instruction>(aco_opcode::v_cndmask_b32, asVOP3(Format::VOP2), 3, 1));
2616          } else {
2617             return false;
2618          }
2619 
2620          ctx.uses[instr->operands[i].tempId()]--;
2621          if (ctx.uses[instr->operands[i].tempId()])
2622             ctx.uses[op_instr->operands[2].tempId()]++;
2623 
2624          new_instr->operands[0] = Operand(0u);
2625          new_instr->operands[1] = instr->operands[!i];
2626          new_instr->operands[2] = Operand(op_instr->operands[2]);
2627          new_instr->definitions[0] = instr->definitions[0];
2628          instr = std::move(new_instr);
2629          ctx.info[instr->definitions[0].tempId()].label = 0;
2630          return true;
2631       }
2632    }
2633 
2634    return false;
2635 }
2636 
2637 // TODO: we could possibly move the whole label_instruction pass to combine_instruction:
2638 // this would mean that we'd have to fix the instruction uses while value propagation
2639 
combine_instruction(opt_ctx & ctx,Block & block,aco_ptr<Instruction> & instr)2640 void combine_instruction(opt_ctx &ctx, Block& block, aco_ptr<Instruction>& instr)
2641 {
2642    if (instr->definitions.empty() || is_dead(ctx.uses, instr.get()))
2643       return;
2644 
2645    if (instr->isVALU()) {
2646       if (can_apply_sgprs(ctx, instr))
2647          apply_sgprs(ctx, instr);
2648       while (apply_omod_clamp(ctx, block, instr)) ;
2649    }
2650 
2651    if (ctx.info[instr->definitions[0].tempId()].is_vcc_hint()) {
2652       instr->definitions[0].setHint(vcc);
2653    }
2654 
2655    if (instr->isSDWA())
2656       return;
2657 
2658    /* TODO: There are still some peephole optimizations that could be done:
2659     * - abs(a - b) -> s_absdiff_i32
2660     * - various patterns for s_bitcmp{0,1}_b32 and s_bitset{0,1}_b32
2661     * - patterns for v_alignbit_b32 and v_alignbyte_b32
2662     * These aren't probably too interesting though.
2663     * There are also patterns for v_cmp_class_f{16,32,64}. This is difficult but
2664     * probably more useful than the previously mentioned optimizations.
2665     * The various comparison optimizations also currently only work with 32-bit
2666     * floats. */
2667 
2668    /* neg(mul(a, b)) -> mul(neg(a), b) */
2669    if (ctx.info[instr->definitions[0].tempId()].is_neg() && ctx.uses[instr->operands[1].tempId()] == 1) {
2670       Temp val = ctx.info[instr->definitions[0].tempId()].temp;
2671 
2672       if (!ctx.info[val.id()].is_mul())
2673          return;
2674 
2675       Instruction* mul_instr = ctx.info[val.id()].instr;
2676 
2677       if (mul_instr->operands[0].isLiteral())
2678          return;
2679       if (mul_instr->isVOP3() && static_cast<VOP3A_instruction*>(mul_instr)->clamp)
2680          return;
2681       if (mul_instr->isSDWA())
2682          return;
2683 
2684       /* convert to mul(neg(a), b) */
2685       ctx.uses[mul_instr->definitions[0].tempId()]--;
2686       Definition def = instr->definitions[0];
2687       /* neg(abs(mul(a, b))) -> mul(neg(abs(a)), abs(b)) */
2688       bool is_abs = ctx.info[instr->definitions[0].tempId()].is_abs();
2689       instr.reset(create_instruction<VOP3A_instruction>(mul_instr->opcode, asVOP3(Format::VOP2), 2, 1));
2690       instr->operands[0] = mul_instr->operands[0];
2691       instr->operands[1] = mul_instr->operands[1];
2692       instr->definitions[0] = def;
2693       VOP3A_instruction* new_mul = static_cast<VOP3A_instruction*>(instr.get());
2694       if (mul_instr->isVOP3()) {
2695          VOP3A_instruction* mul = static_cast<VOP3A_instruction*>(mul_instr);
2696          new_mul->neg[0] = mul->neg[0] && !is_abs;
2697          new_mul->neg[1] = mul->neg[1] && !is_abs;
2698          new_mul->abs[0] = mul->abs[0] || is_abs;
2699          new_mul->abs[1] = mul->abs[1] || is_abs;
2700          new_mul->omod = mul->omod;
2701       }
2702       new_mul->neg[0] ^= true;
2703       new_mul->clamp = false;
2704 
2705       ctx.info[instr->definitions[0].tempId()].set_mul(instr.get());
2706       return;
2707    }
2708 
2709    /* combine mul+add -> mad */
2710    bool mad32 = instr->opcode == aco_opcode::v_add_f32 ||
2711                 instr->opcode == aco_opcode::v_sub_f32 ||
2712                 instr->opcode == aco_opcode::v_subrev_f32;
2713    bool mad16 = instr->opcode == aco_opcode::v_add_f16 ||
2714                 instr->opcode == aco_opcode::v_sub_f16 ||
2715                 instr->opcode == aco_opcode::v_subrev_f16;
2716    if (mad16 || mad32) {
2717       bool need_fma = mad32 ? (block.fp_mode.denorm32 != 0 || ctx.program->chip_class >= GFX10_3) :
2718                               (block.fp_mode.denorm16_64 != 0 || ctx.program->chip_class >= GFX10);
2719       if (need_fma && instr->definitions[0].isPrecise())
2720          return;
2721       if (need_fma && mad32 && !ctx.program->has_fast_fma32)
2722          return;
2723 
2724       uint32_t uses_src0 = UINT32_MAX;
2725       uint32_t uses_src1 = UINT32_MAX;
2726       Instruction* mul_instr = nullptr;
2727       unsigned add_op_idx;
2728       /* check if any of the operands is a multiplication */
2729       ssa_info *op0_info = instr->operands[0].isTemp() ? &ctx.info[instr->operands[0].tempId()] : NULL;
2730       ssa_info *op1_info = instr->operands[1].isTemp() ? &ctx.info[instr->operands[1].tempId()] : NULL;
2731       if (op0_info && op0_info->is_mul() && (!need_fma || !op0_info->instr->definitions[0].isPrecise()))
2732          uses_src0 = ctx.uses[instr->operands[0].tempId()];
2733       if (op1_info && op1_info->is_mul() && (!need_fma || !op1_info->instr->definitions[0].isPrecise()))
2734          uses_src1 = ctx.uses[instr->operands[1].tempId()];
2735 
2736       /* find the 'best' mul instruction to combine with the add */
2737       if (uses_src0 < uses_src1) {
2738          mul_instr = op0_info->instr;
2739          add_op_idx = 1;
2740       } else if (uses_src1 < uses_src0) {
2741          mul_instr = op1_info->instr;
2742          add_op_idx = 0;
2743       } else if (uses_src0 != UINT32_MAX) {
2744          /* tiebreaker: quite random what to pick */
2745          if (op0_info->instr->operands[0].isLiteral()) {
2746             mul_instr = op1_info->instr;
2747             add_op_idx = 0;
2748          } else {
2749             mul_instr = op0_info->instr;
2750             add_op_idx = 1;
2751          }
2752       }
2753       if (mul_instr) {
2754          Operand op[3] = {Operand(v1), Operand(v1), Operand(v1)};
2755          bool neg[3] = {false, false, false};
2756          bool abs[3] = {false, false, false};
2757          unsigned omod = 0;
2758          bool clamp = false;
2759          op[0] = mul_instr->operands[0];
2760          op[1] = mul_instr->operands[1];
2761          op[2] = instr->operands[add_op_idx];
2762          // TODO: would be better to check this before selecting a mul instr?
2763          if (!check_vop3_operands(ctx, 3, op))
2764             return;
2765          if (mul_instr->isSDWA())
2766             return;
2767 
2768          if (mul_instr->isVOP3()) {
2769             VOP3A_instruction* vop3 = static_cast<VOP3A_instruction*> (mul_instr);
2770             neg[0] = vop3->neg[0];
2771             neg[1] = vop3->neg[1];
2772             abs[0] = vop3->abs[0];
2773             abs[1] = vop3->abs[1];
2774             /* we cannot use these modifiers between mul and add */
2775             if (vop3->clamp || vop3->omod)
2776                return;
2777          }
2778 
2779          /* convert to mad */
2780          ctx.uses[mul_instr->definitions[0].tempId()]--;
2781          if (ctx.uses[mul_instr->definitions[0].tempId()]) {
2782             if (op[0].isTemp())
2783                ctx.uses[op[0].tempId()]++;
2784             if (op[1].isTemp())
2785                ctx.uses[op[1].tempId()]++;
2786          }
2787 
2788          if (instr->isVOP3()) {
2789             VOP3A_instruction* vop3 = static_cast<VOP3A_instruction*> (instr.get());
2790             neg[2] = vop3->neg[add_op_idx];
2791             abs[2] = vop3->abs[add_op_idx];
2792             omod = vop3->omod;
2793             clamp = vop3->clamp;
2794             /* abs of the multiplication result */
2795             if (vop3->abs[1 - add_op_idx]) {
2796                neg[0] = false;
2797                neg[1] = false;
2798                abs[0] = true;
2799                abs[1] = true;
2800             }
2801             /* neg of the multiplication result */
2802             neg[1] = neg[1] ^ vop3->neg[1 - add_op_idx];
2803          }
2804          if (instr->opcode == aco_opcode::v_sub_f32 || instr->opcode == aco_opcode::v_sub_f16)
2805             neg[1 + add_op_idx] = neg[1 + add_op_idx] ^ true;
2806          else if (instr->opcode == aco_opcode::v_subrev_f32 || instr->opcode == aco_opcode::v_subrev_f16)
2807             neg[2 - add_op_idx] = neg[2 - add_op_idx] ^ true;
2808 
2809          aco_opcode mad_op = need_fma ? aco_opcode::v_fma_f32 : aco_opcode::v_mad_f32;
2810          if (mad16)
2811             mad_op = need_fma ? (ctx.program->chip_class == GFX8 ? aco_opcode::v_fma_legacy_f16 : aco_opcode::v_fma_f16) :
2812                                 (ctx.program->chip_class == GFX8 ? aco_opcode::v_mad_legacy_f16 : aco_opcode::v_mad_f16);
2813 
2814          aco_ptr<VOP3A_instruction> mad{create_instruction<VOP3A_instruction>(mad_op, Format::VOP3A, 3, 1)};
2815          for (unsigned i = 0; i < 3; i++)
2816          {
2817             mad->operands[i] = op[i];
2818             mad->neg[i] = neg[i];
2819             mad->abs[i] = abs[i];
2820          }
2821          mad->omod = omod;
2822          mad->clamp = clamp;
2823          mad->definitions[0] = instr->definitions[0];
2824 
2825          /* mark this ssa_def to be re-checked for profitability and literals */
2826          ctx.mad_infos.emplace_back(std::move(instr), mul_instr->definitions[0].tempId());
2827          ctx.info[mad->definitions[0].tempId()].set_mad(mad.get(), ctx.mad_infos.size() - 1);
2828          instr.reset(mad.release());
2829          return;
2830       }
2831    }
2832    /* v_mul_f32(v_cndmask_b32(0, 1.0, cond), a) -> v_cndmask_b32(0, a, cond) */
2833    else if (instr->opcode == aco_opcode::v_mul_f32 && !instr->isVOP3()) {
2834       for (unsigned i = 0; i < 2; i++) {
2835          if (instr->operands[i].isTemp() && ctx.info[instr->operands[i].tempId()].is_b2f() &&
2836              ctx.uses[instr->operands[i].tempId()] == 1 &&
2837              instr->operands[!i].isTemp() && instr->operands[!i].getTemp().type() == RegType::vgpr) {
2838             ctx.uses[instr->operands[i].tempId()]--;
2839             ctx.uses[ctx.info[instr->operands[i].tempId()].temp.id()]++;
2840 
2841             aco_ptr<VOP2_instruction> new_instr{create_instruction<VOP2_instruction>(aco_opcode::v_cndmask_b32, Format::VOP2, 3, 1)};
2842             new_instr->operands[0] = Operand(0u);
2843             new_instr->operands[1] = instr->operands[!i];
2844             new_instr->operands[2] = Operand(ctx.info[instr->operands[i].tempId()].temp);
2845             new_instr->definitions[0] = instr->definitions[0];
2846             instr.reset(new_instr.release());
2847             ctx.info[instr->definitions[0].tempId()].label = 0;
2848             return;
2849          }
2850       }
2851    } else if (instr->opcode == aco_opcode::v_or_b32 && ctx.program->chip_class >= GFX9) {
2852       if (combine_three_valu_op(ctx, instr, aco_opcode::s_or_b32, aco_opcode::v_or3_b32, "012", 1 | 2)) ;
2853       else if (combine_three_valu_op(ctx, instr, aco_opcode::v_or_b32, aco_opcode::v_or3_b32, "012", 1 | 2)) ;
2854       else if (combine_three_valu_op(ctx, instr, aco_opcode::s_and_b32, aco_opcode::v_and_or_b32, "120", 1 | 2)) ;
2855       else if (combine_three_valu_op(ctx, instr, aco_opcode::v_and_b32, aco_opcode::v_and_or_b32, "120", 1 | 2)) ;
2856       else if (combine_three_valu_op(ctx, instr, aco_opcode::s_lshl_b32, aco_opcode::v_lshl_or_b32, "120", 1 | 2)) ;
2857       else combine_three_valu_op(ctx, instr, aco_opcode::v_lshlrev_b32, aco_opcode::v_lshl_or_b32, "210", 1 | 2);
2858    } else if (instr->opcode == aco_opcode::v_xor_b32 && ctx.program->chip_class >= GFX10) {
2859       if (combine_three_valu_op(ctx, instr, aco_opcode::v_xor_b32, aco_opcode::v_xor3_b32, "012", 1 | 2)) ;
2860       else combine_three_valu_op(ctx, instr, aco_opcode::s_xor_b32, aco_opcode::v_xor3_b32, "012", 1 | 2);
2861    } else if (instr->opcode == aco_opcode::v_add_u32) {
2862       if (combine_add_sub_b2i(ctx, instr, aco_opcode::v_addc_co_u32, 1 | 2)) ;
2863       else if (ctx.program->chip_class >= GFX9 && !instr->usesModifiers()) {
2864          if (combine_three_valu_op(ctx, instr, aco_opcode::s_xor_b32, aco_opcode::v_xad_u32, "120", 1 | 2)) ;
2865          else if (combine_three_valu_op(ctx, instr, aco_opcode::v_xor_b32, aco_opcode::v_xad_u32, "120", 1 | 2)) ;
2866          else if (combine_three_valu_op(ctx, instr, aco_opcode::s_add_i32, aco_opcode::v_add3_u32, "012", 1 | 2)) ;
2867          else if (combine_three_valu_op(ctx, instr, aco_opcode::s_add_u32, aco_opcode::v_add3_u32, "012", 1 | 2)) ;
2868          else if (combine_three_valu_op(ctx, instr, aco_opcode::v_add_u32, aco_opcode::v_add3_u32, "012", 1 | 2)) ;
2869          else if (combine_three_valu_op(ctx, instr, aco_opcode::s_lshl_b32, aco_opcode::v_lshl_add_u32, "120", 1 | 2)) ;
2870          else combine_three_valu_op(ctx, instr, aco_opcode::v_lshlrev_b32, aco_opcode::v_lshl_add_u32, "210", 1 | 2);
2871       }
2872    } else if (instr->opcode == aco_opcode::v_add_co_u32 ||
2873               instr->opcode == aco_opcode::v_add_co_u32_e64) {
2874       combine_add_sub_b2i(ctx, instr, aco_opcode::v_addc_co_u32, 1 | 2);
2875    } else if (instr->opcode == aco_opcode::v_sub_u32 ||
2876               instr->opcode == aco_opcode::v_sub_co_u32 ||
2877               instr->opcode == aco_opcode::v_sub_co_u32_e64) {
2878       combine_add_sub_b2i(ctx, instr, aco_opcode::v_subbrev_co_u32, 2);
2879    } else if (instr->opcode == aco_opcode::v_subrev_u32 ||
2880               instr->opcode == aco_opcode::v_subrev_co_u32 ||
2881               instr->opcode == aco_opcode::v_subrev_co_u32_e64) {
2882       combine_add_sub_b2i(ctx, instr, aco_opcode::v_subbrev_co_u32, 1);
2883    } else if (instr->opcode == aco_opcode::v_lshlrev_b32 && ctx.program->chip_class >= GFX9) {
2884       combine_three_valu_op(ctx, instr, aco_opcode::v_add_u32, aco_opcode::v_add_lshl_u32, "120", 2);
2885    } else if ((instr->opcode == aco_opcode::s_add_u32 || instr->opcode == aco_opcode::s_add_i32) && ctx.program->chip_class >= GFX9) {
2886       combine_salu_lshl_add(ctx, instr);
2887    } else if (instr->opcode == aco_opcode::s_not_b32 || instr->opcode == aco_opcode::s_not_b64) {
2888       combine_salu_not_bitwise(ctx, instr);
2889    } else if (instr->opcode == aco_opcode::s_and_b32 || instr->opcode == aco_opcode::s_or_b32 ||
2890               instr->opcode == aco_opcode::s_and_b64 || instr->opcode == aco_opcode::s_or_b64) {
2891       if (combine_ordering_test(ctx, instr)) ;
2892       else if (combine_comparison_ordering(ctx, instr)) ;
2893       else if (combine_constant_comparison_ordering(ctx, instr)) ;
2894       else combine_salu_n2(ctx, instr);
2895    } else if (instr->opcode == aco_opcode::v_and_b32) {
2896       combine_and_subbrev(ctx, instr);
2897    } else {
2898       aco_opcode min, max, min3, max3, med3;
2899       bool some_gfx9_only;
2900       if (get_minmax_info(instr->opcode, &min, &max, &min3, &max3, &med3, &some_gfx9_only) &&
2901           (!some_gfx9_only || ctx.program->chip_class >= GFX9)) {
2902          if (combine_minmax(ctx, instr, instr->opcode == min ? max : min, instr->opcode == min ? min3 : max3)) ;
2903          else combine_clamp(ctx, instr, min, max, med3);
2904       }
2905    }
2906 
2907    /* do this after combine_salu_n2() */
2908    if (instr->opcode == aco_opcode::s_andn2_b32 || instr->opcode == aco_opcode::s_andn2_b64)
2909       combine_inverse_comparison(ctx, instr);
2910 }
2911 
to_uniform_bool_instr(opt_ctx & ctx,aco_ptr<Instruction> & instr)2912 bool to_uniform_bool_instr(opt_ctx &ctx, aco_ptr<Instruction> &instr)
2913 {
2914    switch (instr->opcode) {
2915       case aco_opcode::s_and_b32:
2916       case aco_opcode::s_and_b64:
2917          instr->opcode = aco_opcode::s_and_b32;
2918          break;
2919       case aco_opcode::s_or_b32:
2920       case aco_opcode::s_or_b64:
2921          instr->opcode = aco_opcode::s_or_b32;
2922          break;
2923       case aco_opcode::s_xor_b32:
2924       case aco_opcode::s_xor_b64:
2925          instr->opcode = aco_opcode::s_absdiff_i32;
2926          break;
2927       default:
2928          /* Don't transform other instructions. They are very unlikely to appear here. */
2929          return false;
2930    }
2931 
2932    for (Operand &op : instr->operands) {
2933       ctx.uses[op.tempId()]--;
2934 
2935       if (ctx.info[op.tempId()].is_uniform_bool()) {
2936          /* Just use the uniform boolean temp. */
2937          op.setTemp(ctx.info[op.tempId()].temp);
2938       } else if (ctx.info[op.tempId()].is_uniform_bitwise()) {
2939          /* Use the SCC definition of the predecessor instruction.
2940           * This allows the predecessor to get picked up by the same optimization (if it has no divergent users),
2941           * and it also makes sure that the current instruction will keep working even if the predecessor won't be transformed.
2942           */
2943          Instruction *pred_instr = ctx.info[op.tempId()].instr;
2944          assert(pred_instr->definitions.size() >= 2);
2945          assert(pred_instr->definitions[1].isFixed() && pred_instr->definitions[1].physReg() == scc);
2946          op.setTemp(pred_instr->definitions[1].getTemp());
2947       } else {
2948          unreachable("Invalid operand on uniform bitwise instruction.");
2949       }
2950 
2951       ctx.uses[op.tempId()]++;
2952    }
2953 
2954    instr->definitions[0].setTemp(Temp(instr->definitions[0].tempId(), s1));
2955    assert(instr->operands[0].regClass() == s1);
2956    assert(instr->operands[1].regClass() == s1);
2957    return true;
2958 }
2959 
select_instruction(opt_ctx & ctx,aco_ptr<Instruction> & instr)2960 void select_instruction(opt_ctx &ctx, aco_ptr<Instruction>& instr)
2961 {
2962    const uint32_t threshold = 4;
2963 
2964    if (is_dead(ctx.uses, instr.get())) {
2965       instr.reset();
2966       return;
2967    }
2968 
2969    /* convert split_vector into a copy or extract_vector if only one definition is ever used */
2970    if (instr->opcode == aco_opcode::p_split_vector) {
2971       unsigned num_used = 0;
2972       unsigned idx = 0;
2973       unsigned split_offset = 0;
2974       for (unsigned i = 0, offset = 0; i < instr->definitions.size(); offset += instr->definitions[i++].bytes()) {
2975          if (ctx.uses[instr->definitions[i].tempId()]) {
2976             num_used++;
2977             idx = i;
2978             split_offset = offset;
2979          }
2980       }
2981       bool done = false;
2982       if (num_used == 1 && ctx.info[instr->operands[0].tempId()].is_vec() &&
2983           ctx.uses[instr->operands[0].tempId()] == 1) {
2984          Instruction *vec = ctx.info[instr->operands[0].tempId()].instr;
2985 
2986          unsigned off = 0;
2987          Operand op;
2988          for (Operand& vec_op : vec->operands) {
2989             if (off == split_offset) {
2990                op = vec_op;
2991                break;
2992             }
2993             off += vec_op.bytes();
2994          }
2995          if (off != instr->operands[0].bytes() && op.bytes() == instr->definitions[idx].bytes()) {
2996             ctx.uses[instr->operands[0].tempId()]--;
2997             for (Operand& vec_op : vec->operands) {
2998                if (vec_op.isTemp())
2999                   ctx.uses[vec_op.tempId()]--;
3000             }
3001             if (op.isTemp())
3002                ctx.uses[op.tempId()]++;
3003 
3004             aco_ptr<Pseudo_instruction> extract{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, 1, 1)};
3005             extract->operands[0] = op;
3006             extract->definitions[0] = instr->definitions[idx];
3007             instr.reset(extract.release());
3008 
3009             done = true;
3010          }
3011       }
3012 
3013       if (!done && num_used == 1 &&
3014           instr->operands[0].bytes() % instr->definitions[idx].bytes() == 0 &&
3015           split_offset % instr->definitions[idx].bytes() == 0) {
3016          aco_ptr<Pseudo_instruction> extract{create_instruction<Pseudo_instruction>(aco_opcode::p_extract_vector, Format::PSEUDO, 2, 1)};
3017          extract->operands[0] = instr->operands[0];
3018          extract->operands[1] = Operand((uint32_t) split_offset / instr->definitions[idx].bytes());
3019          extract->definitions[0] = instr->definitions[idx];
3020          instr.reset(extract.release());
3021       }
3022    }
3023 
3024    mad_info* mad_info = NULL;
3025    if (!instr->definitions.empty() && ctx.info[instr->definitions[0].tempId()].is_mad()) {
3026       mad_info = &ctx.mad_infos[ctx.info[instr->definitions[0].tempId()].instr->pass_flags];
3027       /* re-check mad instructions */
3028       if (ctx.uses[mad_info->mul_temp_id]) {
3029          ctx.uses[mad_info->mul_temp_id]++;
3030          if (instr->operands[0].isTemp())
3031             ctx.uses[instr->operands[0].tempId()]--;
3032          if (instr->operands[1].isTemp())
3033             ctx.uses[instr->operands[1].tempId()]--;
3034          instr.swap(mad_info->add_instr);
3035          mad_info = NULL;
3036       }
3037       /* check literals */
3038       else if (!instr->usesModifiers()) {
3039          /* FMA can only take literals on GFX10+ */
3040          if ((instr->opcode == aco_opcode::v_fma_f32 || instr->opcode == aco_opcode::v_fma_f16) &&
3041              ctx.program->chip_class < GFX10)
3042             return;
3043 
3044          bool sgpr_used = false;
3045          uint32_t literal_idx = 0;
3046          uint32_t literal_uses = UINT32_MAX;
3047          for (unsigned i = 0; i < instr->operands.size(); i++)
3048          {
3049             if (instr->operands[i].isConstant() && i > 0) {
3050                literal_uses = UINT32_MAX;
3051                break;
3052             }
3053             if (!instr->operands[i].isTemp())
3054                continue;
3055             unsigned bits = get_operand_size(instr, i);
3056             /* if one of the operands is sgpr, we cannot add a literal somewhere else on pre-GFX10 or operands other than the 1st */
3057             if (instr->operands[i].getTemp().type() == RegType::sgpr && (i > 0 || ctx.program->chip_class < GFX10)) {
3058                if (!sgpr_used && ctx.info[instr->operands[i].tempId()].is_literal(bits)) {
3059                   literal_uses = ctx.uses[instr->operands[i].tempId()];
3060                   literal_idx = i;
3061                } else {
3062                   literal_uses = UINT32_MAX;
3063                }
3064                sgpr_used = true;
3065                /* don't break because we still need to check constants */
3066             } else if (!sgpr_used &&
3067                        ctx.info[instr->operands[i].tempId()].is_literal(bits) &&
3068                        ctx.uses[instr->operands[i].tempId()] < literal_uses) {
3069                literal_uses = ctx.uses[instr->operands[i].tempId()];
3070                literal_idx = i;
3071             }
3072          }
3073 
3074          /* Limit the number of literals to apply to not increase the code
3075           * size too much, but always apply literals for v_mad->v_madak
3076           * because both instructions are 64-bit and this doesn't increase
3077           * code size.
3078           * TODO: try to apply the literals earlier to lower the number of
3079           * uses below threshold
3080           */
3081          if (literal_uses < threshold || literal_idx == 2) {
3082             ctx.uses[instr->operands[literal_idx].tempId()]--;
3083             mad_info->check_literal = true;
3084             mad_info->literal_idx = literal_idx;
3085             return;
3086          }
3087       }
3088    }
3089 
3090    /* Mark SCC needed, so the uniform boolean transformation won't swap the definitions when it isn't beneficial */
3091    if (instr->format == Format::PSEUDO_BRANCH &&
3092        instr->operands.size() &&
3093        instr->operands[0].isTemp() &&
3094        instr->operands[0].isFixed() &&
3095        instr->operands[0].physReg() == scc) {
3096       ctx.info[instr->operands[0].tempId()].set_scc_needed();
3097       return;
3098    } else if ((instr->opcode == aco_opcode::s_cselect_b64 ||
3099                instr->opcode == aco_opcode::s_cselect_b32) &&
3100               instr->operands[2].isTemp()) {
3101       ctx.info[instr->operands[2].tempId()].set_scc_needed();
3102    }
3103 
3104    /* check for literals */
3105    if (!instr->isSALU() && !instr->isVALU())
3106       return;
3107 
3108    /* Transform uniform bitwise boolean operations to 32-bit when there are no divergent uses. */
3109    if (instr->definitions.size() &&
3110        ctx.uses[instr->definitions[0].tempId()] == 0 &&
3111        ctx.info[instr->definitions[0].tempId()].is_uniform_bitwise()) {
3112       bool transform_done = to_uniform_bool_instr(ctx, instr);
3113 
3114       if (transform_done && !ctx.info[instr->definitions[1].tempId()].is_scc_needed()) {
3115          /* Swap the two definition IDs in order to avoid overusing the SCC. This reduces extra moves generated by RA. */
3116          uint32_t def0_id = instr->definitions[0].getTemp().id();
3117          uint32_t def1_id = instr->definitions[1].getTemp().id();
3118          instr->definitions[0].setTemp(Temp(def1_id, s1));
3119          instr->definitions[1].setTemp(Temp(def0_id, s1));
3120       }
3121 
3122       return;
3123    }
3124 
3125    if (instr->isSDWA() || instr->isDPP() || (instr->isVOP3() && ctx.program->chip_class < GFX10))
3126       return; /* some encodings can't ever take literals */
3127 
3128    /* we do not apply the literals yet as we don't know if it is profitable */
3129    Operand current_literal(s1);
3130 
3131    unsigned literal_id = 0;
3132    unsigned literal_uses = UINT32_MAX;
3133    Operand literal(s1);
3134    unsigned num_operands = 1;
3135    if (instr->isSALU() || (ctx.program->chip_class >= GFX10 && can_use_VOP3(ctx, instr)))
3136       num_operands = instr->operands.size();
3137    /* catch VOP2 with a 3rd SGPR operand (e.g. v_cndmask_b32, v_addc_co_u32) */
3138    else if (instr->isVALU() && instr->operands.size() >= 3)
3139       return;
3140 
3141    unsigned sgpr_ids[2] = {0, 0};
3142    bool is_literal_sgpr = false;
3143    uint32_t mask = 0;
3144 
3145    /* choose a literal to apply */
3146    for (unsigned i = 0; i < num_operands; i++) {
3147       Operand op = instr->operands[i];
3148       unsigned bits = get_operand_size(instr, i);
3149 
3150       if (instr->isVALU() && op.isTemp() && op.getTemp().type() == RegType::sgpr &&
3151           op.tempId() != sgpr_ids[0])
3152          sgpr_ids[!!sgpr_ids[0]] = op.tempId();
3153 
3154       if (op.isLiteral()) {
3155          current_literal = op;
3156          continue;
3157       } else if (!op.isTemp() || !ctx.info[op.tempId()].is_literal(bits)) {
3158          continue;
3159       }
3160 
3161       if (!alu_can_accept_constant(instr->opcode, i))
3162          continue;
3163 
3164       if (ctx.uses[op.tempId()] < literal_uses) {
3165          is_literal_sgpr = op.getTemp().type() == RegType::sgpr;
3166          mask = 0;
3167          literal = Operand(ctx.info[op.tempId()].val);
3168          literal_uses = ctx.uses[op.tempId()];
3169          literal_id = op.tempId();
3170       }
3171 
3172       mask |= (op.tempId() == literal_id) << i;
3173    }
3174 
3175 
3176    /* don't go over the constant bus limit */
3177    bool is_shift64 = instr->opcode == aco_opcode::v_lshlrev_b64 ||
3178                      instr->opcode == aco_opcode::v_lshrrev_b64 ||
3179                      instr->opcode == aco_opcode::v_ashrrev_i64;
3180    unsigned const_bus_limit = instr->isVALU() ? 1 : UINT32_MAX;
3181    if (ctx.program->chip_class >= GFX10 && !is_shift64)
3182       const_bus_limit = 2;
3183 
3184    unsigned num_sgprs = !!sgpr_ids[0] + !!sgpr_ids[1];
3185    if (num_sgprs == const_bus_limit && !is_literal_sgpr)
3186       return;
3187 
3188    if (literal_id && literal_uses < threshold &&
3189        (current_literal.isUndefined() ||
3190         (current_literal.size() == literal.size() &&
3191          current_literal.constantValue() == literal.constantValue()))) {
3192       /* mark the literal to be applied */
3193       while (mask) {
3194          unsigned i = u_bit_scan(&mask);
3195          if (instr->operands[i].isTemp() && instr->operands[i].tempId() == literal_id)
3196             ctx.uses[instr->operands[i].tempId()]--;
3197       }
3198    }
3199 }
3200 
3201 
apply_literals(opt_ctx & ctx,aco_ptr<Instruction> & instr)3202 void apply_literals(opt_ctx &ctx, aco_ptr<Instruction>& instr)
3203 {
3204    /* Cleanup Dead Instructions */
3205    if (!instr)
3206       return;
3207 
3208    /* apply literals on MAD */
3209    if (!instr->definitions.empty() && ctx.info[instr->definitions[0].tempId()].is_mad()) {
3210       mad_info* info = &ctx.mad_infos[ctx.info[instr->definitions[0].tempId()].instr->pass_flags];
3211       if (info->check_literal &&
3212           (ctx.uses[instr->operands[info->literal_idx].tempId()] == 0 || info->literal_idx == 2)) {
3213          aco_ptr<Instruction> new_mad;
3214 
3215          aco_opcode new_op = info->literal_idx == 2 ? aco_opcode::v_madak_f32 : aco_opcode::v_madmk_f32;
3216          if (instr->opcode == aco_opcode::v_fma_f32)
3217             new_op = info->literal_idx == 2 ? aco_opcode::v_fmaak_f32 : aco_opcode::v_fmamk_f32;
3218          else if (instr->opcode == aco_opcode::v_mad_f16 || instr->opcode == aco_opcode::v_mad_legacy_f16)
3219             new_op = info->literal_idx == 2 ? aco_opcode::v_madak_f16 : aco_opcode::v_madmk_f16;
3220          else if (instr->opcode == aco_opcode::v_fma_f16)
3221             new_op = info->literal_idx == 2 ? aco_opcode::v_fmaak_f16 : aco_opcode::v_fmamk_f16;
3222 
3223          new_mad.reset(create_instruction<VOP2_instruction>(new_op, Format::VOP2, 3, 1));
3224          if (info->literal_idx == 2) { /* add literal -> madak */
3225             new_mad->operands[0] = instr->operands[0];
3226             new_mad->operands[1] = instr->operands[1];
3227          } else { /* mul literal -> madmk */
3228             new_mad->operands[0] = instr->operands[1 - info->literal_idx];
3229             new_mad->operands[1] = instr->operands[2];
3230          }
3231          new_mad->operands[2] = Operand(ctx.info[instr->operands[info->literal_idx].tempId()].val);
3232          new_mad->definitions[0] = instr->definitions[0];
3233          ctx.instructions.emplace_back(std::move(new_mad));
3234          return;
3235       }
3236    }
3237 
3238    /* apply literals on other SALU/VALU */
3239    if (instr->isSALU() || instr->isVALU()) {
3240       for (unsigned i = 0; i < instr->operands.size(); i++) {
3241          Operand op = instr->operands[i];
3242          unsigned bits = get_operand_size(instr, i);
3243          if (op.isTemp() && ctx.info[op.tempId()].is_literal(bits) && ctx.uses[op.tempId()] == 0) {
3244             Operand literal(ctx.info[op.tempId()].val);
3245             if (instr->isVALU() && i > 0)
3246                to_VOP3(ctx, instr);
3247             instr->operands[i] = literal;
3248          }
3249       }
3250    }
3251 
3252    ctx.instructions.emplace_back(std::move(instr));
3253 }
3254 
3255 
optimize(Program * program)3256 void optimize(Program* program)
3257 {
3258    opt_ctx ctx;
3259    ctx.program = program;
3260    std::vector<ssa_info> info(program->peekAllocationId());
3261    ctx.info = info.data();
3262 
3263    /* 1. Bottom-Up DAG pass (forward) to label all ssa-defs */
3264    for (Block& block : program->blocks) {
3265       for (aco_ptr<Instruction>& instr : block.instructions)
3266          label_instruction(ctx, block, instr);
3267    }
3268 
3269    ctx.uses = dead_code_analysis(program);
3270 
3271    /* 2. Combine v_mad, omod, clamp and propagate sgpr on VALU instructions */
3272    for (Block& block : program->blocks) {
3273       for (aco_ptr<Instruction>& instr : block.instructions)
3274          combine_instruction(ctx, block, instr);
3275    }
3276 
3277    /* 3. Top-Down DAG pass (backward) to select instructions (includes DCE) */
3278    for (std::vector<Block>::reverse_iterator it = program->blocks.rbegin(); it != program->blocks.rend(); ++it) {
3279       Block* block = &(*it);
3280       for (std::vector<aco_ptr<Instruction>>::reverse_iterator it = block->instructions.rbegin(); it != block->instructions.rend(); ++it)
3281          select_instruction(ctx, *it);
3282    }
3283 
3284    /* 4. Add literals to instructions */
3285    for (Block& block : program->blocks) {
3286       ctx.instructions.clear();
3287       for (aco_ptr<Instruction>& instr : block.instructions)
3288          apply_literals(ctx, instr);
3289       block.instructions.swap(ctx.instructions);
3290    }
3291 
3292 }
3293 
3294 }
3295