Merge commit '8b0fb1c152fe191768953aa8c77b89034a377f83' into vulkan
[mesa.git] / src / compiler / nir / nir_algebraic.py
1 #! /usr/bin/env python
2 #
3 # Copyright (C) 2014 Intel Corporation
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a
6 # copy of this software and associated documentation files (the "Software"),
7 # to deal in the Software without restriction, including without limitation
8 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 # and/or sell copies of the Software, and to permit persons to whom the
10 # Software is furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice (including the next
13 # paragraph) shall be included in all copies or substantial portions of the
14 # Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 # IN THE SOFTWARE.
23 #
24 # Authors:
25 # Jason Ekstrand (jason@jlekstrand.net)
26
27 import itertools
28 import struct
29 import sys
30 import mako.template
31 import re
32
33 # Represents a set of variables, each with a unique id
34 class VarSet(object):
35 def __init__(self):
36 self.names = {}
37 self.ids = itertools.count()
38 self.immutable = False;
39
40 def __getitem__(self, name):
41 if name not in self.names:
42 assert not self.immutable, "Unknown replacement variable: " + name
43 self.names[name] = self.ids.next()
44
45 return self.names[name]
46
47 def lock(self):
48 self.immutable = True
49
50 class Value(object):
51 @staticmethod
52 def create(val, name_base, varset):
53 if isinstance(val, tuple):
54 return Expression(val, name_base, varset)
55 elif isinstance(val, Expression):
56 return val
57 elif isinstance(val, (str, unicode)):
58 return Variable(val, name_base, varset)
59 elif isinstance(val, (bool, int, long, float)):
60 return Constant(val, name_base)
61
62 __template = mako.template.Template("""
63 static const ${val.c_type} ${val.name} = {
64 { ${val.type_enum} },
65 % if isinstance(val, Constant):
66 { ${hex(val)} /* ${val.value} */ },
67 % elif isinstance(val, Variable):
68 ${val.index}, /* ${val.var_name} */
69 ${'true' if val.is_constant else 'false'},
70 nir_type_${ val.required_type or 'invalid' },
71 % elif isinstance(val, Expression):
72 nir_op_${val.opcode},
73 { ${', '.join(src.c_ptr for src in val.sources)} },
74 % endif
75 };""")
76
77 def __init__(self, name, type_str):
78 self.name = name
79 self.type_str = type_str
80
81 @property
82 def type_enum(self):
83 return "nir_search_value_" + self.type_str
84
85 @property
86 def c_type(self):
87 return "nir_search_" + self.type_str
88
89 @property
90 def c_ptr(self):
91 return "&{0}.value".format(self.name)
92
93 def render(self):
94 return self.__template.render(val=self,
95 Constant=Constant,
96 Variable=Variable,
97 Expression=Expression)
98
99 class Constant(Value):
100 def __init__(self, val, name):
101 Value.__init__(self, name, "constant")
102 self.value = val
103
104 def __hex__(self):
105 if isinstance(self.value, (bool)):
106 return 'NIR_TRUE' if self.value else 'NIR_FALSE'
107 if isinstance(self.value, (int, long)):
108 return hex(self.value)
109 elif isinstance(self.value, float):
110 return hex(struct.unpack('I', struct.pack('f', self.value))[0])
111 else:
112 assert False
113
114 _var_name_re = re.compile(r"(?P<const>#)?(?P<name>\w+)(?:@(?P<type>\w+))?")
115
116 class Variable(Value):
117 def __init__(self, val, name, varset):
118 Value.__init__(self, name, "variable")
119
120 m = _var_name_re.match(val)
121 assert m and m.group('name') is not None
122
123 self.var_name = m.group('name')
124 self.is_constant = m.group('const') is not None
125 self.required_type = m.group('type')
126
127 if self.required_type is not None:
128 assert self.required_type in ('float', 'bool', 'int', 'unsigned')
129
130 self.index = varset[self.var_name]
131
132 class Expression(Value):
133 def __init__(self, expr, name_base, varset):
134 Value.__init__(self, name_base, "expression")
135 assert isinstance(expr, tuple)
136
137 self.opcode = expr[0]
138 self.sources = [ Value.create(src, "{0}_{1}".format(name_base, i), varset)
139 for (i, src) in enumerate(expr[1:]) ]
140
141 def render(self):
142 srcs = "\n".join(src.render() for src in self.sources)
143 return srcs + super(Expression, self).render()
144
145 _optimization_ids = itertools.count()
146
147 condition_list = ['true']
148
149 class SearchAndReplace(object):
150 def __init__(self, transform):
151 self.id = _optimization_ids.next()
152
153 search = transform[0]
154 replace = transform[1]
155 if len(transform) > 2:
156 self.condition = transform[2]
157 else:
158 self.condition = 'true'
159
160 if self.condition not in condition_list:
161 condition_list.append(self.condition)
162 self.condition_index = condition_list.index(self.condition)
163
164 varset = VarSet()
165 if isinstance(search, Expression):
166 self.search = search
167 else:
168 self.search = Expression(search, "search{0}".format(self.id), varset)
169
170 varset.lock()
171
172 if isinstance(replace, Value):
173 self.replace = replace
174 else:
175 self.replace = Value.create(replace, "replace{0}".format(self.id), varset)
176
177 _algebraic_pass_template = mako.template.Template("""
178 #include "nir.h"
179 #include "nir_search.h"
180
181 #ifndef NIR_OPT_ALGEBRAIC_STRUCT_DEFS
182 #define NIR_OPT_ALGEBRAIC_STRUCT_DEFS
183
184 struct transform {
185 const nir_search_expression *search;
186 const nir_search_value *replace;
187 unsigned condition_offset;
188 };
189
190 struct opt_state {
191 void *mem_ctx;
192 bool progress;
193 const bool *condition_flags;
194 };
195
196 #endif
197
198 % for (opcode, xform_list) in xform_dict.iteritems():
199 % for xform in xform_list:
200 ${xform.search.render()}
201 ${xform.replace.render()}
202 % endfor
203
204 static const struct transform ${pass_name}_${opcode}_xforms[] = {
205 % for xform in xform_list:
206 { &${xform.search.name}, ${xform.replace.c_ptr}, ${xform.condition_index} },
207 % endfor
208 };
209 % endfor
210
211 static bool
212 ${pass_name}_block(nir_block *block, void *void_state)
213 {
214 struct opt_state *state = void_state;
215
216 nir_foreach_instr_reverse_safe(block, instr) {
217 if (instr->type != nir_instr_type_alu)
218 continue;
219
220 nir_alu_instr *alu = nir_instr_as_alu(instr);
221 if (!alu->dest.dest.is_ssa)
222 continue;
223
224 switch (alu->op) {
225 % for opcode in xform_dict.keys():
226 case nir_op_${opcode}:
227 for (unsigned i = 0; i < ARRAY_SIZE(${pass_name}_${opcode}_xforms); i++) {
228 const struct transform *xform = &${pass_name}_${opcode}_xforms[i];
229 if (state->condition_flags[xform->condition_offset] &&
230 nir_replace_instr(alu, xform->search, xform->replace,
231 state->mem_ctx)) {
232 state->progress = true;
233 break;
234 }
235 }
236 break;
237 % endfor
238 default:
239 break;
240 }
241 }
242
243 return true;
244 }
245
246 static bool
247 ${pass_name}_impl(nir_function_impl *impl, const bool *condition_flags)
248 {
249 struct opt_state state;
250
251 state.mem_ctx = ralloc_parent(impl);
252 state.progress = false;
253 state.condition_flags = condition_flags;
254
255 nir_foreach_block_reverse(impl, ${pass_name}_block, &state);
256
257 if (state.progress)
258 nir_metadata_preserve(impl, nir_metadata_block_index |
259 nir_metadata_dominance);
260
261 return state.progress;
262 }
263
264
265 bool
266 ${pass_name}(nir_shader *shader)
267 {
268 bool progress = false;
269 bool condition_flags[${len(condition_list)}];
270 const nir_shader_compiler_options *options = shader->options;
271
272 % for index, condition in enumerate(condition_list):
273 condition_flags[${index}] = ${condition};
274 % endfor
275
276 nir_foreach_function(shader, function) {
277 if (function->impl)
278 progress |= ${pass_name}_impl(function->impl, condition_flags);
279 }
280
281 return progress;
282 }
283 """)
284
285 class AlgebraicPass(object):
286 def __init__(self, pass_name, transforms):
287 self.xform_dict = {}
288 self.pass_name = pass_name
289
290 for xform in transforms:
291 if not isinstance(xform, SearchAndReplace):
292 xform = SearchAndReplace(xform)
293
294 if xform.search.opcode not in self.xform_dict:
295 self.xform_dict[xform.search.opcode] = []
296
297 self.xform_dict[xform.search.opcode].append(xform)
298
299 def render(self):
300 return _algebraic_pass_template.render(pass_name=self.pass_name,
301 xform_dict=self.xform_dict,
302 condition_list=condition_list)