nir_constant_expressions.py 13.1 KB
Newer Older
1
from __future__ import print_function
2

3
import re
4
5
from nir_opcodes import opcodes
from nir_opcodes import type_has_size, type_size, type_sizes, type_base_type
6
7
8
9
10
11

def type_add_size(type_, size):
    if type_has_size(type_):
        return type_
    return type_ + str(size)

12
def op_bit_sizes(op):
13
    sizes = None
14
    if not type_has_size(op.output_type):
15
16
        sizes = set(type_sizes(op.output_type))

17
18
    for input_type in op.input_types:
        if not type_has_size(input_type):
19
20
21
22
23
24
            if sizes is None:
                sizes = set(type_sizes(input_type))
            else:
                sizes = sizes.intersection(set(type_sizes(input_type)))

    return sorted(list(sizes)) if sizes is not None else None
25

26
def get_const_field(type_):
27
28
29
    if type_size(type_) == 1:
        return 'b'
    elif type_base_type(type_) == 'bool':
30
        return 'i' + str(type_size(type_))
31
32
    elif type_ == "float16":
        return "u16"
33
    else:
34
        return type_base_type(type_)[0] + str(type_size(type_))
35

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
template = """\
/*
 * Copyright (C) 2014 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * Authors:
 *    Jason Ekstrand (jason@jlekstrand.net)
 */

#include <math.h>
64
#include "util/rounding.h" /* for _mesa_roundeven */
65
#include "util/half_float.h"
66
#include "util/bigmath.h"
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "nir_constant_expressions.h"

/**
 * Evaluate one component of packSnorm4x8.
 */
static uint8_t
pack_snorm_1x8(float x)
{
    /* From section 8.4 of the GLSL 4.30 spec:
     *
     *    packSnorm4x8
     *    ------------
     *    The conversion for component c of v to fixed point is done as
     *    follows:
     *
     *      packSnorm4x8: round(clamp(c, -1, +1) * 127.0)
     *
     * We must first cast the float to an int, because casting a negative
     * float to a uint is undefined.
     */
87
88
   return (uint8_t) (int)
          _mesa_roundevenf(CLAMP(x, -1.0f, +1.0f) * 127.0f);
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
}

/**
 * Evaluate one component of packSnorm2x16.
 */
static uint16_t
pack_snorm_1x16(float x)
{
    /* From section 8.4 of the GLSL ES 3.00 spec:
     *
     *    packSnorm2x16
     *    -------------
     *    The conversion for component c of v to fixed point is done as
     *    follows:
     *
     *      packSnorm2x16: round(clamp(c, -1, +1) * 32767.0)
     *
     * We must first cast the float to an int, because casting a negative
     * float to a uint is undefined.
     */
109
110
   return (uint16_t) (int)
          _mesa_roundevenf(CLAMP(x, -1.0f, +1.0f) * 32767.0f);
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
}

/**
 * Evaluate one component of unpackSnorm4x8.
 */
static float
unpack_snorm_1x8(uint8_t u)
{
    /* From section 8.4 of the GLSL 4.30 spec:
     *
     *    unpackSnorm4x8
     *    --------------
     *    The conversion for unpacked fixed-point value f to floating point is
     *    done as follows:
     *
     *       unpackSnorm4x8: clamp(f / 127.0, -1, +1)
     */
   return CLAMP((int8_t) u / 127.0f, -1.0f, +1.0f);
}

/**
 * Evaluate one component of unpackSnorm2x16.
 */
static float
unpack_snorm_1x16(uint16_t u)
{
    /* From section 8.4 of the GLSL ES 3.00 spec:
     *
     *    unpackSnorm2x16
     *    ---------------
     *    The conversion for unpacked fixed-point value f to floating point is
     *    done as follows:
     *
     *       unpackSnorm2x16: clamp(f / 32767.0, -1, +1)
     */
   return CLAMP((int16_t) u / 32767.0f, -1.0f, +1.0f);
}

/**
 * Evaluate one component packUnorm4x8.
 */
static uint8_t
pack_unorm_1x8(float x)
{
    /* From section 8.4 of the GLSL 4.30 spec:
     *
     *    packUnorm4x8
     *    ------------
     *    The conversion for component c of v to fixed point is done as
     *    follows:
     *
     *       packUnorm4x8: round(clamp(c, 0, +1) * 255.0)
     */
164
165
   return (uint8_t) (int)
          _mesa_roundevenf(CLAMP(x, 0.0f, 1.0f) * 255.0f);
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
}

/**
 * Evaluate one component packUnorm2x16.
 */
static uint16_t
pack_unorm_1x16(float x)
{
    /* From section 8.4 of the GLSL ES 3.00 spec:
     *
     *    packUnorm2x16
     *    -------------
     *    The conversion for component c of v to fixed point is done as
     *    follows:
     *
     *       packUnorm2x16: round(clamp(c, 0, +1) * 65535.0)
     */
183
184
   return (uint16_t) (int)
          _mesa_roundevenf(CLAMP(x, 0.0f, 1.0f) * 65535.0f);
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
}

/**
 * Evaluate one component of unpackUnorm4x8.
 */
static float
unpack_unorm_1x8(uint8_t u)
{
    /* From section 8.4 of the GLSL 4.30 spec:
     *
     *    unpackUnorm4x8
     *    --------------
     *    The conversion for unpacked fixed-point value f to floating point is
     *    done as follows:
     *
     *       unpackUnorm4x8: f / 255.0
     */
   return (float) u / 255.0f;
}

/**
 * Evaluate one component of unpackUnorm2x16.
 */
static float
unpack_unorm_1x16(uint16_t u)
{
    /* From section 8.4 of the GLSL ES 3.00 spec:
     *
     *    unpackUnorm2x16
     *    ---------------
     *    The conversion for unpacked fixed-point value f to floating point is
     *    done as follows:
     *
     *       unpackUnorm2x16: f / 65535.0
     */
   return (float) u / 65535.0f;
}

/**
 * Evaluate one component of packHalf2x16.
 */
static uint16_t
pack_half_1x16(float x)
{
   return _mesa_float_to_half(x);
}

/**
 * Evaluate one component of unpackHalf2x16.
 */
static float
unpack_half_1x16(uint16_t u)
{
   return _mesa_half_to_float(u);
}

/* Some typed vector structures to make things like src0.y work */
242
243
typedef int8_t int1_t;
typedef uint8_t uint1_t;
244
typedef float float16_t;
245
246
typedef float float32_t;
typedef double float64_t;
247
typedef bool bool1_t;
248
249
typedef bool bool8_t;
typedef bool bool16_t;
250
typedef bool bool32_t;
251
252
typedef bool bool64_t;
% for type in ["float", "int", "uint", "bool"]:
253
% for width in type_sizes(type):
254
255
256
257
258
struct ${type}${width}_vec {
   ${type}${width}_t x;
   ${type}${width}_t y;
   ${type}${width}_t z;
   ${type}${width}_t w;
259
260
};
% endfor
261
262
% endfor

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
<%def name="evaluate_op(op, bit_size)">
   <%
   output_type = type_add_size(op.output_type, bit_size)
   input_types = [type_add_size(type_, bit_size) for type_ in op.input_types]
   %>

   ## For each non-per-component input, create a variable srcN that
   ## contains x, y, z, and w elements which are filled in with the
   ## appropriately-typed values.
   % for j in range(op.num_inputs):
      % if op.input_sizes[j] == 0:
         <% continue %>
      % elif "src" + str(j) not in op.const_expr:
         ## Avoid unused variable warnings
         <% continue %>
      %endif

      const struct ${input_types[j]}_vec src${j} = {
      % for k in range(op.input_sizes[j]):
282
283
284
285
         % if input_types[j] == "int1":
             /* 1-bit integers use a 0/-1 convention */
             -(int1_t)_src[${j}].b[${k}],
         % elif input_types[j] == "float16":
286
            _mesa_half_to_float(_src[${j}].u16[${k}]),
287
288
289
         % else:
            _src[${j}].${get_const_field(input_types[j])}[${k}],
         % endif
290
      % endfor
291
292
293
294
295
      % for k in range(op.input_sizes[j], 4):
         0,
      % endfor
      };
   % endfor
296

297
298
299
300
301
302
303
304
305
306
307
308
309
   % if op.output_size == 0:
      ## For per-component instructions, we need to iterate over the
      ## components and apply the constant expression one component
      ## at a time.
      for (unsigned _i = 0; _i < num_components; _i++) {
         ## For each per-component input, create a variable srcN that
         ## contains the value of the current (_i'th) component.
         % for j in range(op.num_inputs):
            % if op.input_sizes[j] != 0:
               <% continue %>
            % elif "src" + str(j) not in op.const_expr:
               ## Avoid unused variable warnings
               <% continue %>
310
311
312
            % elif input_types[j] == "int1":
               /* 1-bit integers use a 0/-1 convention */
               const int1_t src${j} = -(int1_t)_src[${j}].b[_i];
313
314
315
            % elif input_types[j] == "float16":
               const float src${j} =
                  _mesa_half_to_float(_src[${j}].u16[_i]);
316
            % else:
317
318
               const ${input_types[j]}_t src${j} =
                  _src[${j}].${get_const_field(input_types[j])}[_i];
319
            % endif
320
         % endfor
321

322
323
324
         ## Create an appropriately-typed variable dst and assign the
         ## result of the const_expr to it.  If const_expr already contains
         ## writes to dst, just include const_expr directly.
325
         % if "dst" in op.const_expr:
326
327
            ${output_type}_t dst;

328
329
            ${op.const_expr}
         % else:
330
331
332
333
334
335
336
            ## Cast to correct type to avoid compiler warning about implicit
            ## conversion happening with UINT_MAX. Note special care on uint1_t.
            <%
               tmp_type = op.const_expr.replace('UINT_MAX', '(%s)' % (output_type.upper() + '_MAX'))
               tmp_type = tmp_type.replace('UINT1_', 'UINT8_')
            %>
            ${output_type}_t dst = ${tmp_type};
337
338
         % endif

339
340
         ## Store the current component of the actual destination to the
         ## value of dst.
341
342
343
344
         % if output_type == "int1" or output_type == "uint1":
            /* 1-bit integers get truncated */
            _dst_val.b[_i] = dst & 1;
         % elif output_type.startswith("bool"):
345
346
            ## Sanitize the C value to a proper NIR 0/-1 bool
            _dst_val.${get_const_field(output_type)}[_i] = -(int)dst;
347
348
         % elif output_type == "float16":
            _dst_val.u16[_i] = _mesa_float_to_half(dst);
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
         % else:
            _dst_val.${get_const_field(output_type)}[_i] = dst;
         % endif
      }
   % else:
      ## In the non-per-component case, create a struct dst with
      ## appropriately-typed elements x, y, z, and w and assign the result
      ## of the const_expr to all components of dst, or include the
      ## const_expr directly if it writes to dst already.
      struct ${output_type}_vec dst;

      % if "dst" in op.const_expr:
         ${op.const_expr}
      % else:
         ## Splat the value to all components.  This way expressions which
         ## write the same value to all components don't need to explicitly
         ## write to dest.  One such example is fnoise which has a
         ## const_expr of 0.0f.
         dst.x = dst.y = dst.z = dst.w = ${op.const_expr};
368
369
      % endif

370
371
372
      ## For each component in the destination, copy the value of dst to
      ## the actual destination.
      % for k in range(op.output_size):
373
374
375
376
         % if output_type == "int1" or output_type == "uint1":
            /* 1-bit integers get truncated */
            _dst_val.b[${k}] = dst.${"xyzw"[k]} & 1;
         % elif output_type.startswith("bool"):
377
378
            ## Sanitize the C value to a proper NIR 0/-1 bool
            _dst_val.${get_const_field(output_type)}[${k}] = -(int)dst.${"xyzw"[k]};
379
380
         % elif output_type == "float16":
            _dst_val.u16[${k}] = _mesa_float_to_half(dst.${"xyzw"[k]});
381
382
383
384
385
386
387
         % else:
            _dst_val.${get_const_field(output_type)}[${k}] = dst.${"xyzw"[k]};
         % endif
      % endfor
   % endif
</%def>

388
% for name, op in sorted(opcodes.items()):
389
static nir_const_value
390
391
evaluate_${name}(MAYBE_UNUSED unsigned num_components,
                 ${"UNUSED" if op_bit_sizes(op) is None else ""} unsigned bit_size,
392
393
394
395
                 MAYBE_UNUSED nir_const_value *_src)
{
   nir_const_value _dst_val = { {0, } };

396
397
398
399
400
401
402
403
   % if op_bit_sizes(op) is not None:
      switch (bit_size) {
      % for bit_size in op_bit_sizes(op):
      case ${bit_size}: {
         ${evaluate_op(op, bit_size)}
         break;
      }
      % endfor
404

405
406
407
408
409
410
      default:
         unreachable("unknown bit width");
      }
   % else:
      ${evaluate_op(op, 0)}
   % endif
411
412
413
414
415
416
417

   return _dst_val;
}
% endfor

nir_const_value
nir_eval_const_opcode(nir_op op, unsigned num_components,
418
                      unsigned bit_width, nir_const_value *src)
419
420
{
   switch (op) {
421
% for name in sorted(opcodes.keys()):
422
   case nir_op_${name}:
423
      return evaluate_${name}(num_components, bit_width, src);
424
425
426
427
428
429
430
431
% endfor
   default:
      unreachable("shouldn't get here");
   }
}"""

from mako.template import Template

432
print(Template(template).render(opcodes=opcodes, type_sizes=type_sizes,
433
434
                                type_has_size=type_has_size,
                                type_add_size=type_add_size,
435
                                op_bit_sizes=op_bit_sizes,
436
                                get_const_field=get_const_field))