nir/algebraic: support for power-of-two optimizations
[mesa.git] / src / compiler / nir / nir_search_helpers.h
1 /*
2 * Copyright © 2016 Red Hat
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 * Rob Clark <robclark@freedesktop.org>
25 */
26
27 #ifndef _NIR_SEARCH_HELPERS_
28 #define _NIR_SEARCH_HELPERS_
29
30 #include "nir.h"
31
32 static inline bool
33 __is_power_of_two(unsigned int x)
34 {
35 return ((x != 0) && !(x & (x - 1)));
36 }
37
38 static inline bool
39 is_pos_power_of_two(nir_alu_instr *instr, unsigned src, unsigned num_components,
40 const uint8_t *swizzle)
41 {
42 nir_const_value *val = nir_src_as_const_value(instr->src[src].src);
43
44 /* only constant src's: */
45 if (!val)
46 return false;
47
48 for (unsigned i = 0; i < num_components; i++) {
49 switch (nir_op_infos[instr->op].input_types[src]) {
50 case nir_type_int:
51 if (val->i32[swizzle[i]] < 0)
52 return false;
53 if (!__is_power_of_two(val->i32[swizzle[i]]))
54 return false;
55 break;
56 case nir_type_uint:
57 if (!__is_power_of_two(val->u32[swizzle[i]]))
58 return false;
59 break;
60 default:
61 return false;
62 }
63 }
64
65 return true;
66 }
67
68 static inline bool
69 is_neg_power_of_two(nir_alu_instr *instr, unsigned src, unsigned num_components,
70 const uint8_t *swizzle)
71 {
72 nir_const_value *val = nir_src_as_const_value(instr->src[src].src);
73
74 /* only constant src's: */
75 if (!val)
76 return false;
77
78 for (unsigned i = 0; i < num_components; i++) {
79 switch (nir_op_infos[instr->op].input_types[src]) {
80 case nir_type_int:
81 if (val->i32[swizzle[i]] > 0)
82 return false;
83 if (!__is_power_of_two(abs(val->i32[swizzle[i]])))
84 return false;
85 break;
86 default:
87 return false;
88 }
89 }
90
91 return true;
92 }
93
94 #endif /* _NIR_SEARCH_ */