| 1 |
/* |
| 2 |
* Copyright (C) 2020 Collabora Ltd. |
| 3 |
* SPDX-License-Identifier: MIT |
| 4 |
*/ |
| 5 |
|
| 6 |
#include "bi_builder.h" |
| 7 |
#include "compiler.h" |
| 8 |
|
| 9 |
/* Dead simple constant folding to cleanup compiler frontend patterns. Before |
| 10 |
* adding a new pattern here, check why you need it and whether we can avoid |
| 11 |
* generating the constant BIR at all. */ |
| 12 |
|
| 13 |
static inline uint32_t |
| 14 |
bi_source_value(const bi_instr *I, unsigned s) |
| 15 |
{ |
| 16 |
if (s < I->nr_srcs) |
| 17 |
return bi_apply_swizzle(I->src[s].value, I->src[s].swizzle); |
| 18 |
else |
| 19 |
return 0; |
| 20 |
} |
| 21 |
|
| 22 |
uint32_t |
| 23 |
bi_fold_constant(bi_instr *I, bool *unsupported) |
| 24 |
{ |
| 25 |
/* We can only fold instructions where all sources are constant */ |
| 26 |
bi_foreach_src(I, s) { |
| 27 |
if (I->src[s].type != BI_INDEX_CONSTANT) { |
| 28 |
*unsupported = true; |
| 29 |
return 0; |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
/* Grab the sources */ |
| 34 |
uint32_t a = bi_source_value(I, 0); |
| 35 |
uint32_t b = bi_source_value(I, 1); |
| 36 |
uint32_t c = bi_source_value(I, 2); |
| 37 |
uint32_t d = bi_source_value(I, 3); |
| 38 |
|
| 39 |
/* Evaluate the instruction */ |
| 40 |
switch (I->op) { |
| 41 |
case BI_OPCODE_SWZ_V2I16: |
| 42 |
return a; |
| 43 |
|
| 44 |
case BI_OPCODE_MKVEC_V2I16: |
| 45 |
return (b << 16) | (a & 0xFFFF); |
| 46 |
|
| 47 |
case BI_OPCODE_MKVEC_V4I8: |
| 48 |
return (d << 24) | ((c & 0xFF) << 16) | ((b & 0xFF) << 8) | (a & 0xFF); |
| 49 |
|
| 50 |
case BI_OPCODE_MKVEC_V2I8: |
| 51 |
return (c << 16) | ((b & 0xFF) << 8) | (a & 0xFF); |
| 52 |
|
| 53 |
case BI_OPCODE_LSHIFT_OR_I32: |
| 54 |
if (I->not_result || I->src[0].neg || I->src[1].neg) |
| 55 |
break; |
| 56 |
|
| 57 |
return (a << (c & 0x1F)) | b; |
| 58 |
|
| 59 |
case BI_OPCODE_F32_TO_U32: |
| 60 |
if (I->round == BI_ROUND_NONE) { |
| 61 |
/* Explicitly clamp to prevent undefined behaviour and |
| 62 |
* match hardware rules */ |
| 63 |
float f = uif(a); |
| 64 |
return (f >= 0.0) ? (uint32_t)f : 0; |
| 65 |
} else |
| 66 |
break; |
| 67 |
|
| 68 |
default: |
| 69 |
break; |
| 70 |
} |
| 71 |
|
| 72 |
*unsupported = true; |
| 73 |
return 0; |
| 74 |
} |
| 75 |
|
| 76 |
bool |
| 77 |
bi_opt_constant_fold(bi_context *ctx) |
| 78 |
{ |
| 79 |
bool progress = false; |
| 80 |
|
| 81 |
bi_foreach_instr_global_safe(ctx, ins) { |
| 82 |
bool unsupported = false; |
| 83 |
uint32_t replace = bi_fold_constant(ins, &unsupported); |
| 84 |
if (unsupported) |
| 85 |
continue; |
| 86 |
|
| 87 |
/* Replace with constant move, to be copypropped */ |
| 88 |
assert(ins->nr_dests == 1); |
| 89 |
bi_builder b = bi_init_builder(ctx, bi_after_instr(ins)); |
| 90 |
bi_mov_i32_to(&b, ins->dest[0], bi_imm_u32(replace)); |
| 91 |
bi_remove_instruction(ins); |
| 92 |
progress = true; |
| 93 |
} |
| 94 |
|
| 95 |
return progress; |
| 96 |
} |