efb6bee25117cee68a96d9852717d544245e72e5
[mesa.git] / src / gallium / drivers / llvmpipe / lp_state_fs.c
1 /**************************************************************************
2 *
3 * Copyright 2009 VMware, Inc.
4 * Copyright 2007 VMware, Inc.
5 * All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the
9 * "Software"), to deal in the Software without restriction, including
10 * without limitation the rights to use, copy, modify, merge, publish,
11 * distribute, sub license, and/or sell copies of the Software, and to
12 * permit persons to whom the Software is furnished to do so, subject to
13 * the following conditions:
14 *
15 * The above copyright notice and this permission notice (including the
16 * next paragraph) shall be included in all copies or substantial portions
17 * of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
22 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
23 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 *
27 **************************************************************************/
28
29 /**
30 * @file
31 * Code generate the whole fragment pipeline.
32 *
33 * The fragment pipeline consists of the following stages:
34 * - early depth test
35 * - fragment shader
36 * - alpha test
37 * - depth/stencil test
38 * - blending
39 *
40 * This file has only the glue to assemble the fragment pipeline. The actual
41 * plumbing of converting Gallium state into LLVM IR is done elsewhere, in the
42 * lp_bld_*.[ch] files, and in a complete generic and reusable way. Here we
43 * muster the LLVM JIT execution engine to create a function that follows an
44 * established binary interface and that can be called from C directly.
45 *
46 * A big source of complexity here is that we often want to run different
47 * stages with different precisions and data types and precisions. For example,
48 * the fragment shader needs typically to be done in floats, but the
49 * depth/stencil test and blending is better done in the type that most closely
50 * matches the depth/stencil and color buffer respectively.
51 *
52 * Since the width of a SIMD vector register stays the same regardless of the
53 * element type, different types imply different number of elements, so we must
54 * code generate more instances of the stages with larger types to be able to
55 * feed/consume the stages with smaller types.
56 *
57 * @author Jose Fonseca <jfonseca@vmware.com>
58 */
59
60 #include <limits.h>
61 #include "pipe/p_defines.h"
62 #include "util/u_inlines.h"
63 #include "util/u_memory.h"
64 #include "util/u_pointer.h"
65 #include "util/format/u_format.h"
66 #include "util/u_dump.h"
67 #include "util/u_string.h"
68 #include "util/simple_list.h"
69 #include "util/u_dual_blend.h"
70 #include "util/os_time.h"
71 #include "pipe/p_shader_tokens.h"
72 #include "draw/draw_context.h"
73 #include "tgsi/tgsi_dump.h"
74 #include "tgsi/tgsi_scan.h"
75 #include "tgsi/tgsi_parse.h"
76 #include "gallivm/lp_bld_type.h"
77 #include "gallivm/lp_bld_const.h"
78 #include "gallivm/lp_bld_conv.h"
79 #include "gallivm/lp_bld_init.h"
80 #include "gallivm/lp_bld_intr.h"
81 #include "gallivm/lp_bld_logic.h"
82 #include "gallivm/lp_bld_tgsi.h"
83 #include "gallivm/lp_bld_nir.h"
84 #include "gallivm/lp_bld_swizzle.h"
85 #include "gallivm/lp_bld_flow.h"
86 #include "gallivm/lp_bld_debug.h"
87 #include "gallivm/lp_bld_arit.h"
88 #include "gallivm/lp_bld_bitarit.h"
89 #include "gallivm/lp_bld_pack.h"
90 #include "gallivm/lp_bld_format.h"
91 #include "gallivm/lp_bld_quad.h"
92 #include "gallivm/lp_bld_gather.h"
93
94 #include "lp_bld_alpha.h"
95 #include "lp_bld_blend.h"
96 #include "lp_bld_depth.h"
97 #include "lp_bld_interp.h"
98 #include "lp_context.h"
99 #include "lp_debug.h"
100 #include "lp_perf.h"
101 #include "lp_setup.h"
102 #include "lp_state.h"
103 #include "lp_tex_sample.h"
104 #include "lp_flush.h"
105 #include "lp_state_fs.h"
106 #include "lp_rast.h"
107 #include "nir/nir_to_tgsi_info.h"
108
109 #include "lp_screen.h"
110 #include "compiler/nir/nir_serialize.h"
111 #include "util/mesa-sha1.h"
112 /** Fragment shader number (for debugging) */
113 static unsigned fs_no = 0;
114
115 static void
116 load_unswizzled_block(struct gallivm_state *gallivm,
117 LLVMValueRef base_ptr,
118 LLVMValueRef stride,
119 unsigned block_width,
120 unsigned block_height,
121 LLVMValueRef* dst,
122 struct lp_type dst_type,
123 unsigned dst_count,
124 unsigned dst_alignment,
125 LLVMValueRef x_offset,
126 LLVMValueRef y_offset,
127 bool fb_fetch_twiddle);
128 /**
129 * Checks if a format description is an arithmetic format
130 *
131 * A format which has irregular channel sizes such as R3_G3_B2 or R5_G6_B5.
132 */
133 static inline boolean
134 is_arithmetic_format(const struct util_format_description *format_desc)
135 {
136 boolean arith = false;
137 unsigned i;
138
139 for (i = 0; i < format_desc->nr_channels; ++i) {
140 arith |= format_desc->channel[i].size != format_desc->channel[0].size;
141 arith |= (format_desc->channel[i].size % 8) != 0;
142 }
143
144 return arith;
145 }
146
147 /**
148 * Checks if this format requires special handling due to required expansion
149 * to floats for blending, and furthermore has "natural" packed AoS -> unpacked
150 * SoA conversion.
151 */
152 static inline boolean
153 format_expands_to_float_soa(const struct util_format_description *format_desc)
154 {
155 if (format_desc->format == PIPE_FORMAT_R11G11B10_FLOAT ||
156 format_desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB) {
157 return true;
158 }
159 return false;
160 }
161
162
163 /**
164 * Retrieves the type representing the memory layout for a format
165 *
166 * e.g. RGBA16F = 4x half-float and R3G3B2 = 1x byte
167 */
168 static inline void
169 lp_mem_type_from_format_desc(const struct util_format_description *format_desc,
170 struct lp_type* type)
171 {
172 unsigned i;
173 unsigned chan;
174
175 if (format_expands_to_float_soa(format_desc)) {
176 /* just make this a uint with width of block */
177 type->floating = false;
178 type->fixed = false;
179 type->sign = false;
180 type->norm = false;
181 type->width = format_desc->block.bits;
182 type->length = 1;
183 return;
184 }
185
186 for (i = 0; i < 4; i++)
187 if (format_desc->channel[i].type != UTIL_FORMAT_TYPE_VOID)
188 break;
189 chan = i;
190
191 memset(type, 0, sizeof(struct lp_type));
192 type->floating = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FLOAT;
193 type->fixed = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FIXED;
194 type->sign = format_desc->channel[chan].type != UTIL_FORMAT_TYPE_UNSIGNED;
195 type->norm = format_desc->channel[chan].normalized;
196
197 if (is_arithmetic_format(format_desc)) {
198 type->width = 0;
199 type->length = 1;
200
201 for (i = 0; i < format_desc->nr_channels; ++i) {
202 type->width += format_desc->channel[i].size;
203 }
204 } else {
205 type->width = format_desc->channel[chan].size;
206 type->length = format_desc->nr_channels;
207 }
208 }
209
210 /**
211 * Expand the relevant bits of mask_input to a n*4-dword mask for the
212 * n*four pixels in n 2x2 quads. This will set the n*four elements of the
213 * quad mask vector to 0 or ~0.
214 * Grouping is 01, 23 for 2 quad mode hence only 0 and 2 are valid
215 * quad arguments with fs length 8.
216 *
217 * \param first_quad which quad(s) of the quad group to test, in [0,3]
218 * \param mask_input bitwise mask for the whole 4x4 stamp
219 */
220 static LLVMValueRef
221 generate_quad_mask(struct gallivm_state *gallivm,
222 struct lp_type fs_type,
223 unsigned first_quad,
224 unsigned sample,
225 LLVMValueRef mask_input) /* int64 */
226 {
227 LLVMBuilderRef builder = gallivm->builder;
228 struct lp_type mask_type;
229 LLVMTypeRef i32t = LLVMInt32TypeInContext(gallivm->context);
230 LLVMValueRef bits[16];
231 LLVMValueRef mask, bits_vec;
232 int shift, i;
233
234 /*
235 * XXX: We'll need a different path for 16 x u8
236 */
237 assert(fs_type.width == 32);
238 assert(fs_type.length <= ARRAY_SIZE(bits));
239 mask_type = lp_int_type(fs_type);
240
241 /*
242 * mask_input >>= (quad * 4)
243 */
244 switch (first_quad) {
245 case 0:
246 shift = 0;
247 break;
248 case 1:
249 assert(fs_type.length == 4);
250 shift = 2;
251 break;
252 case 2:
253 shift = 8;
254 break;
255 case 3:
256 assert(fs_type.length == 4);
257 shift = 10;
258 break;
259 default:
260 assert(0);
261 shift = 0;
262 }
263
264 mask_input = LLVMBuildLShr(builder, mask_input, lp_build_const_int64(gallivm, 16 * sample), "");
265 mask_input = LLVMBuildTrunc(builder, mask_input,
266 i32t, "");
267 mask_input = LLVMBuildAnd(builder, mask_input, lp_build_const_int32(gallivm, 0xffff), "");
268
269 mask_input = LLVMBuildLShr(builder,
270 mask_input,
271 LLVMConstInt(i32t, shift, 0),
272 "");
273
274 /*
275 * mask = { mask_input & (1 << i), for i in [0,3] }
276 */
277 mask = lp_build_broadcast(gallivm,
278 lp_build_vec_type(gallivm, mask_type),
279 mask_input);
280
281 for (i = 0; i < fs_type.length / 4; i++) {
282 unsigned j = 2 * (i % 2) + (i / 2) * 8;
283 bits[4*i + 0] = LLVMConstInt(i32t, 1ULL << (j + 0), 0);
284 bits[4*i + 1] = LLVMConstInt(i32t, 1ULL << (j + 1), 0);
285 bits[4*i + 2] = LLVMConstInt(i32t, 1ULL << (j + 4), 0);
286 bits[4*i + 3] = LLVMConstInt(i32t, 1ULL << (j + 5), 0);
287 }
288 bits_vec = LLVMConstVector(bits, fs_type.length);
289 mask = LLVMBuildAnd(builder, mask, bits_vec, "");
290
291 /*
292 * mask = mask == bits ? ~0 : 0
293 */
294 mask = lp_build_compare(gallivm,
295 mask_type, PIPE_FUNC_EQUAL,
296 mask, bits_vec);
297
298 return mask;
299 }
300
301
302 #define EARLY_DEPTH_TEST 0x1
303 #define LATE_DEPTH_TEST 0x2
304 #define EARLY_DEPTH_WRITE 0x4
305 #define LATE_DEPTH_WRITE 0x8
306
307 static int
308 find_output_by_semantic( const struct tgsi_shader_info *info,
309 unsigned semantic,
310 unsigned index )
311 {
312 int i;
313
314 for (i = 0; i < info->num_outputs; i++)
315 if (info->output_semantic_name[i] == semantic &&
316 info->output_semantic_index[i] == index)
317 return i;
318
319 return -1;
320 }
321
322
323 /**
324 * Fetch the specified lp_jit_viewport structure for a given viewport_index.
325 */
326 static LLVMValueRef
327 lp_llvm_viewport(LLVMValueRef context_ptr,
328 struct gallivm_state *gallivm,
329 LLVMValueRef viewport_index)
330 {
331 LLVMBuilderRef builder = gallivm->builder;
332 LLVMValueRef ptr;
333 LLVMValueRef res;
334 struct lp_type viewport_type =
335 lp_type_float_vec(32, 32 * LP_JIT_VIEWPORT_NUM_FIELDS);
336
337 ptr = lp_jit_context_viewports(gallivm, context_ptr);
338 ptr = LLVMBuildPointerCast(builder, ptr,
339 LLVMPointerType(lp_build_vec_type(gallivm, viewport_type), 0), "");
340
341 res = lp_build_pointer_get(builder, ptr, viewport_index);
342
343 return res;
344 }
345
346
347 static LLVMValueRef
348 lp_build_depth_clamp(struct gallivm_state *gallivm,
349 LLVMBuilderRef builder,
350 struct lp_type type,
351 LLVMValueRef context_ptr,
352 LLVMValueRef thread_data_ptr,
353 LLVMValueRef z)
354 {
355 LLVMValueRef viewport, min_depth, max_depth;
356 LLVMValueRef viewport_index;
357 struct lp_build_context f32_bld;
358
359 assert(type.floating);
360 lp_build_context_init(&f32_bld, gallivm, type);
361
362 /*
363 * Assumes clamping of the viewport index will occur in setup/gs. Value
364 * is passed through the rasterization stage via lp_rast_shader_inputs.
365 *
366 * See: draw_clamp_viewport_idx and lp_clamp_viewport_idx for clamping
367 * semantics.
368 */
369 viewport_index = lp_jit_thread_data_raster_state_viewport_index(gallivm,
370 thread_data_ptr);
371
372 /*
373 * Load the min and max depth from the lp_jit_context.viewports
374 * array of lp_jit_viewport structures.
375 */
376 viewport = lp_llvm_viewport(context_ptr, gallivm, viewport_index);
377
378 /* viewports[viewport_index].min_depth */
379 min_depth = LLVMBuildExtractElement(builder, viewport,
380 lp_build_const_int32(gallivm, LP_JIT_VIEWPORT_MIN_DEPTH), "");
381 min_depth = lp_build_broadcast_scalar(&f32_bld, min_depth);
382
383 /* viewports[viewport_index].max_depth */
384 max_depth = LLVMBuildExtractElement(builder, viewport,
385 lp_build_const_int32(gallivm, LP_JIT_VIEWPORT_MAX_DEPTH), "");
386 max_depth = lp_build_broadcast_scalar(&f32_bld, max_depth);
387
388 /*
389 * Clamp to the min and max depth values for the given viewport.
390 */
391 return lp_build_clamp(&f32_bld, z, min_depth, max_depth);
392 }
393
394 static void
395 lp_build_sample_alpha_to_coverage(struct gallivm_state *gallivm,
396 struct lp_type type,
397 unsigned coverage_samples,
398 LLVMValueRef num_loop,
399 LLVMValueRef loop_counter,
400 LLVMValueRef coverage_mask_store,
401 LLVMValueRef alpha)
402 {
403 struct lp_build_context bld;
404 LLVMBuilderRef builder = gallivm->builder;
405 float step = 1.0 / coverage_samples;
406
407 lp_build_context_init(&bld, gallivm, type);
408 for (unsigned s = 0; s < coverage_samples; s++) {
409 LLVMValueRef alpha_ref_value = lp_build_const_vec(gallivm, type, step * s);
410 LLVMValueRef test = lp_build_cmp(&bld, PIPE_FUNC_GREATER, alpha, alpha_ref_value);
411
412 LLVMValueRef s_mask_idx = LLVMBuildMul(builder, lp_build_const_int32(gallivm, s), num_loop, "");
413 s_mask_idx = LLVMBuildAdd(builder, s_mask_idx, loop_counter, "");
414 LLVMValueRef s_mask_ptr = LLVMBuildGEP(builder, coverage_mask_store, &s_mask_idx, 1, "");
415 LLVMValueRef s_mask = LLVMBuildLoad(builder, s_mask_ptr, "");
416 s_mask = LLVMBuildAnd(builder, s_mask, test, "");
417 LLVMBuildStore(builder, s_mask, s_mask_ptr);
418 }
419 };
420
421 struct lp_build_fs_llvm_iface {
422 struct lp_build_fs_iface base;
423 struct lp_build_interp_soa_context *interp;
424 struct lp_build_for_loop_state *loop_state;
425 LLVMValueRef mask_store;
426 LLVMValueRef sample_id;
427 LLVMValueRef color_ptr_ptr;
428 LLVMValueRef color_stride_ptr;
429 LLVMValueRef color_sample_stride_ptr;
430 const struct lp_fragment_shader_variant_key *key;
431 };
432
433 static LLVMValueRef fs_interp(const struct lp_build_fs_iface *iface,
434 struct lp_build_context *bld,
435 unsigned attrib, unsigned chan,
436 bool centroid, bool sample,
437 LLVMValueRef attrib_indir,
438 LLVMValueRef offsets[2])
439 {
440 struct lp_build_fs_llvm_iface *fs_iface = (struct lp_build_fs_llvm_iface *)iface;
441 struct lp_build_interp_soa_context *interp = fs_iface->interp;
442 unsigned loc = TGSI_INTERPOLATE_LOC_CENTER;
443 if (centroid)
444 loc = TGSI_INTERPOLATE_LOC_CENTROID;
445 if (sample)
446 loc = TGSI_INTERPOLATE_LOC_SAMPLE;
447
448 return lp_build_interp_soa(interp, bld->gallivm, fs_iface->loop_state->counter,
449 fs_iface->mask_store,
450 attrib, chan, loc, attrib_indir, offsets);
451 }
452
453 static void fs_fb_fetch(const struct lp_build_fs_iface *iface,
454 struct lp_build_context *bld,
455 unsigned cbuf,
456 LLVMValueRef result[4])
457 {
458 struct lp_build_fs_llvm_iface *fs_iface = (struct lp_build_fs_llvm_iface *)iface;
459 struct gallivm_state *gallivm = bld->gallivm;
460 LLVMBuilderRef builder = gallivm->builder;
461 const struct lp_fragment_shader_variant_key *key = fs_iface->key;
462 LLVMValueRef index = lp_build_const_int32(gallivm, cbuf);
463 LLVMValueRef color_ptr = LLVMBuildLoad(builder, LLVMBuildGEP(builder, fs_iface->color_ptr_ptr, &index, 1, ""), "");
464 LLVMValueRef stride = LLVMBuildLoad(builder, LLVMBuildGEP(builder, fs_iface->color_stride_ptr, &index, 1, ""), "");
465
466 LLVMValueRef dst[4 * 4];
467 enum pipe_format cbuf_format = key->cbuf_format[cbuf];
468 const struct util_format_description* out_format_desc = util_format_description(cbuf_format);
469 struct lp_type dst_type;
470 unsigned block_size = bld->type.length;
471 unsigned block_height = key->resource_1d ? 1 : 2;
472 unsigned block_width = block_size / block_height;
473
474 lp_mem_type_from_format_desc(out_format_desc, &dst_type);
475
476 struct lp_type blend_type;
477 memset(&blend_type, 0, sizeof blend_type);
478 blend_type.floating = FALSE; /* values are integers */
479 blend_type.sign = FALSE; /* values are unsigned */
480 blend_type.norm = TRUE; /* values are in [0,1] or [-1,1] */
481 blend_type.width = 8; /* 8-bit ubyte values */
482 blend_type.length = 16; /* 16 elements per vector */
483
484 uint32_t dst_alignment;
485 /*
486 * Compute the alignment of the destination pointer in bytes
487 * We fetch 1-4 pixels, if the format has pot alignment then those fetches
488 * are always aligned by MIN2(16, fetch_width) except for buffers (not
489 * 1d tex but can't distinguish here) so need to stick with per-pixel
490 * alignment in this case.
491 */
492 if (key->resource_1d) {
493 dst_alignment = (out_format_desc->block.bits + 7)/(out_format_desc->block.width * 8);
494 }
495 else {
496 dst_alignment = dst_type.length * dst_type.width / 8;
497 }
498 /* Force power-of-two alignment by extracting only the least-significant-bit */
499 dst_alignment = 1 << (ffs(dst_alignment) - 1);
500 /*
501 * Resource base and stride pointers are aligned to 16 bytes, so that's
502 * the maximum alignment we can guarantee
503 */
504 dst_alignment = MIN2(16, dst_alignment);
505
506 LLVMTypeRef blend_vec_type = lp_build_vec_type(gallivm, blend_type);
507 color_ptr = LLVMBuildBitCast(builder, color_ptr, LLVMPointerType(blend_vec_type, 0), "");
508
509 if (key->multisample) {
510 LLVMValueRef sample_stride = LLVMBuildLoad(builder,
511 LLVMBuildGEP(builder, fs_iface->color_sample_stride_ptr,
512 &index, 1, ""), "");
513 LLVMValueRef sample_offset = LLVMBuildMul(builder, sample_stride, fs_iface->sample_id, "");
514 color_ptr = LLVMBuildGEP(builder, color_ptr, &sample_offset, 1, "");
515 }
516 /* fragment shader executes on 4x4 blocks. depending on vector width it can execute 2 or 4 iterations.
517 * only move to the next row once the top row has completed 8 wide 1 iteration, 4 wide 2 iterations */
518 LLVMValueRef x_offset = NULL, y_offset = NULL;
519 if (!key->resource_1d) {
520 LLVMValueRef counter = fs_iface->loop_state->counter;
521
522 if (block_size == 4) {
523 x_offset = LLVMBuildShl(builder,
524 LLVMBuildAnd(builder, fs_iface->loop_state->counter, lp_build_const_int32(gallivm, 1), ""),
525 lp_build_const_int32(gallivm, 1), "");
526 counter = LLVMBuildLShr(builder, fs_iface->loop_state->counter, lp_build_const_int32(gallivm, 1), "");
527 }
528 y_offset = LLVMBuildMul(builder, counter, lp_build_const_int32(gallivm, 2), "");
529 }
530 load_unswizzled_block(gallivm, color_ptr, stride, block_width, block_height, dst, dst_type, block_size, dst_alignment, x_offset, y_offset, true);
531
532 for (unsigned i = 0; i < block_size; i++) {
533 dst[i] = LLVMBuildBitCast(builder, dst[i], LLVMInt32TypeInContext(gallivm->context), "");
534 }
535 LLVMValueRef packed = lp_build_gather_values(gallivm, dst, block_size);
536
537 struct lp_type texel_type = bld->type;
538 if (out_format_desc->colorspace == UTIL_FORMAT_COLORSPACE_RGB &&
539 out_format_desc->channel[0].pure_integer) {
540 if (out_format_desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED) {
541 texel_type = lp_type_int_vec(bld->type.width, bld->type.width * bld->type.length);
542 }
543 else if (out_format_desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED) {
544 texel_type = lp_type_uint_vec(bld->type.width, bld->type.width * bld->type.length);
545 }
546 }
547 lp_build_unpack_rgba_soa(gallivm, out_format_desc,
548 texel_type,
549 packed, result);
550 }
551
552 /**
553 * Generate the fragment shader, depth/stencil test, and alpha tests.
554 */
555 static void
556 generate_fs_loop(struct gallivm_state *gallivm,
557 struct lp_fragment_shader *shader,
558 const struct lp_fragment_shader_variant_key *key,
559 LLVMBuilderRef builder,
560 struct lp_type type,
561 LLVMValueRef context_ptr,
562 LLVMValueRef sample_pos_array,
563 LLVMValueRef num_loop,
564 struct lp_build_interp_soa_context *interp,
565 const struct lp_build_sampler_soa *sampler,
566 const struct lp_build_image_soa *image,
567 LLVMValueRef mask_store,
568 LLVMValueRef (*out_color)[4],
569 LLVMValueRef depth_base_ptr,
570 LLVMValueRef depth_stride,
571 LLVMValueRef depth_sample_stride,
572 LLVMValueRef color_ptr_ptr,
573 LLVMValueRef color_stride_ptr,
574 LLVMValueRef color_sample_stride_ptr,
575 LLVMValueRef facing,
576 LLVMValueRef thread_data_ptr)
577 {
578 const struct util_format_description *zs_format_desc = NULL;
579 const struct tgsi_token *tokens = shader->base.tokens;
580 struct lp_type int_type = lp_int_type(type);
581 LLVMTypeRef vec_type, int_vec_type;
582 LLVMValueRef mask_ptr = NULL, mask_val = NULL;
583 LLVMValueRef consts_ptr, num_consts_ptr;
584 LLVMValueRef ssbo_ptr, num_ssbo_ptr;
585 LLVMValueRef z;
586 LLVMValueRef z_value, s_value;
587 LLVMValueRef z_fb, s_fb;
588 LLVMValueRef depth_ptr;
589 LLVMValueRef stencil_refs[2];
590 LLVMValueRef outputs[PIPE_MAX_SHADER_OUTPUTS][TGSI_NUM_CHANNELS];
591 LLVMValueRef zs_samples = lp_build_const_int32(gallivm, key->zsbuf_nr_samples);
592 struct lp_build_for_loop_state loop_state, sample_loop_state;
593 struct lp_build_mask_context mask;
594 /*
595 * TODO: figure out if simple_shader optimization is really worthwile to
596 * keep. Disabled because it may hide some real bugs in the (depth/stencil)
597 * code since tests tend to take another codepath than real shaders.
598 */
599 boolean simple_shader = (shader->info.base.file_count[TGSI_FILE_SAMPLER] == 0 &&
600 shader->info.base.num_inputs < 3 &&
601 shader->info.base.num_instructions < 8) && 0;
602 const boolean dual_source_blend = key->blend.rt[0].blend_enable &&
603 util_blend_state_is_dual(&key->blend, 0);
604 const bool post_depth_coverage = shader->info.base.properties[TGSI_PROPERTY_FS_POST_DEPTH_COVERAGE];
605 unsigned attrib;
606 unsigned chan;
607 unsigned cbuf;
608 unsigned depth_mode;
609
610 struct lp_bld_tgsi_system_values system_values;
611
612 memset(&system_values, 0, sizeof(system_values));
613
614 /* truncate then sign extend. */
615 system_values.front_facing = LLVMBuildTrunc(gallivm->builder, facing, LLVMInt1TypeInContext(gallivm->context), "");
616 system_values.front_facing = LLVMBuildSExt(gallivm->builder, system_values.front_facing, LLVMInt32TypeInContext(gallivm->context), "");
617
618 if (key->depth.enabled ||
619 key->stencil[0].enabled) {
620
621 zs_format_desc = util_format_description(key->zsbuf_format);
622 assert(zs_format_desc);
623
624 if (shader->info.base.properties[TGSI_PROPERTY_FS_EARLY_DEPTH_STENCIL])
625 depth_mode = EARLY_DEPTH_TEST | EARLY_DEPTH_WRITE;
626 else if (!shader->info.base.writes_z && !shader->info.base.writes_stencil) {
627 if (shader->info.base.writes_memory)
628 depth_mode = LATE_DEPTH_TEST | LATE_DEPTH_WRITE;
629 else if (key->alpha.enabled ||
630 key->blend.alpha_to_coverage ||
631 shader->info.base.uses_kill ||
632 shader->info.base.writes_samplemask) {
633 /* With alpha test and kill, can do the depth test early
634 * and hopefully eliminate some quads. But need to do a
635 * special deferred depth write once the final mask value
636 * is known. This only works though if there's either no
637 * stencil test or the stencil value isn't written.
638 */
639 if (key->stencil[0].enabled && (key->stencil[0].writemask ||
640 (key->stencil[1].enabled &&
641 key->stencil[1].writemask)))
642 depth_mode = LATE_DEPTH_TEST | LATE_DEPTH_WRITE;
643 else
644 depth_mode = EARLY_DEPTH_TEST | LATE_DEPTH_WRITE;
645 }
646 else
647 depth_mode = EARLY_DEPTH_TEST | EARLY_DEPTH_WRITE;
648 }
649 else {
650 depth_mode = LATE_DEPTH_TEST | LATE_DEPTH_WRITE;
651 }
652
653 if (!(key->depth.enabled && key->depth.writemask) &&
654 !(key->stencil[0].enabled && (key->stencil[0].writemask ||
655 (key->stencil[1].enabled &&
656 key->stencil[1].writemask))))
657 depth_mode &= ~(LATE_DEPTH_WRITE | EARLY_DEPTH_WRITE);
658 }
659 else {
660 depth_mode = 0;
661 }
662
663 vec_type = lp_build_vec_type(gallivm, type);
664 int_vec_type = lp_build_vec_type(gallivm, int_type);
665
666 stencil_refs[0] = lp_jit_context_stencil_ref_front_value(gallivm, context_ptr);
667 stencil_refs[1] = lp_jit_context_stencil_ref_back_value(gallivm, context_ptr);
668 /* convert scalar stencil refs into vectors */
669 stencil_refs[0] = lp_build_broadcast(gallivm, int_vec_type, stencil_refs[0]);
670 stencil_refs[1] = lp_build_broadcast(gallivm, int_vec_type, stencil_refs[1]);
671
672 consts_ptr = lp_jit_context_constants(gallivm, context_ptr);
673 num_consts_ptr = lp_jit_context_num_constants(gallivm, context_ptr);
674
675 ssbo_ptr = lp_jit_context_ssbos(gallivm, context_ptr);
676 num_ssbo_ptr = lp_jit_context_num_ssbos(gallivm, context_ptr);
677
678 memset(outputs, 0, sizeof outputs);
679
680 /* Allocate color storage for each fragment sample */
681 LLVMValueRef color_store_size = num_loop;
682 if (key->min_samples > 1)
683 color_store_size = LLVMBuildMul(builder, num_loop, lp_build_const_int32(gallivm, key->min_samples), "");
684
685 for(cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
686 for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
687 out_color[cbuf][chan] = lp_build_array_alloca(gallivm,
688 lp_build_vec_type(gallivm,
689 type),
690 color_store_size, "color");
691 }
692 }
693 if (dual_source_blend) {
694 assert(key->nr_cbufs <= 1);
695 for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
696 out_color[1][chan] = lp_build_array_alloca(gallivm,
697 lp_build_vec_type(gallivm,
698 type),
699 color_store_size, "color1");
700 }
701 }
702
703 lp_build_for_loop_begin(&loop_state, gallivm,
704 lp_build_const_int32(gallivm, 0),
705 LLVMIntULT,
706 num_loop,
707 lp_build_const_int32(gallivm, 1));
708
709 LLVMValueRef sample_mask_in;
710 if (key->multisample) {
711 sample_mask_in = lp_build_const_int_vec(gallivm, type, 0);
712 /* create shader execution mask by combining all sample masks. */
713 for (unsigned s = 0; s < key->coverage_samples; s++) {
714 LLVMValueRef s_mask_idx = LLVMBuildMul(builder, num_loop, lp_build_const_int32(gallivm, s), "");
715 s_mask_idx = LLVMBuildAdd(builder, s_mask_idx, loop_state.counter, "");
716 LLVMValueRef s_mask = lp_build_pointer_get(builder, mask_store, s_mask_idx);
717 if (s == 0)
718 mask_val = s_mask;
719 else
720 mask_val = LLVMBuildOr(builder, s_mask, mask_val, "");
721
722 LLVMValueRef mask_in = LLVMBuildAnd(builder, s_mask, lp_build_const_int_vec(gallivm, type, (1 << s)), "");
723 sample_mask_in = LLVMBuildOr(builder, sample_mask_in, mask_in, "");
724 }
725 } else {
726 sample_mask_in = lp_build_const_int_vec(gallivm, type, 1);
727 mask_ptr = LLVMBuildGEP(builder, mask_store,
728 &loop_state.counter, 1, "mask_ptr");
729 mask_val = LLVMBuildLoad(builder, mask_ptr, "");
730
731 LLVMValueRef mask_in = LLVMBuildAnd(builder, mask_val, lp_build_const_int_vec(gallivm, type, 1), "");
732 sample_mask_in = LLVMBuildOr(builder, sample_mask_in, mask_in, "");
733 }
734
735 /* 'mask' will control execution based on quad's pixel alive/killed state */
736 lp_build_mask_begin(&mask, gallivm, type, mask_val);
737
738 if (!(depth_mode & EARLY_DEPTH_TEST) && !simple_shader)
739 lp_build_mask_check(&mask);
740
741 /* Create storage for recombining sample masks after early Z pass. */
742 LLVMValueRef s_mask_or = lp_build_alloca(gallivm, lp_build_int_vec_type(gallivm, type), "cov_mask_early_depth");
743 LLVMBuildStore(builder, LLVMConstNull(lp_build_int_vec_type(gallivm, type)), s_mask_or);
744
745 /* Create storage for post depth sample mask */
746 LLVMValueRef post_depth_sample_mask_in = NULL;
747 if (post_depth_coverage)
748 post_depth_sample_mask_in = lp_build_alloca(gallivm, int_vec_type, "post_depth_sample_mask_in");
749
750 LLVMValueRef s_mask = NULL, s_mask_ptr = NULL;
751 LLVMValueRef z_sample_value_store = NULL, s_sample_value_store = NULL;
752 LLVMValueRef z_fb_store = NULL, s_fb_store = NULL;
753 LLVMTypeRef z_type = NULL, z_fb_type = NULL;
754
755 /* Run early depth once per sample */
756 if (key->multisample) {
757
758 if (zs_format_desc) {
759 struct lp_type zs_type = lp_depth_type(zs_format_desc, type.length);
760 struct lp_type z_type = zs_type;
761 struct lp_type s_type = zs_type;
762 if (zs_format_desc->block.bits < type.width)
763 z_type.width = type.width;
764 if (zs_format_desc->block.bits == 8)
765 s_type.width = type.width;
766
767 else if (zs_format_desc->block.bits > 32) {
768 z_type.width = z_type.width / 2;
769 s_type.width = s_type.width / 2;
770 s_type.floating = 0;
771 }
772 z_sample_value_store = lp_build_array_alloca(gallivm, lp_build_int_vec_type(gallivm, type),
773 zs_samples, "z_sample_store");
774 s_sample_value_store = lp_build_array_alloca(gallivm, lp_build_int_vec_type(gallivm, type),
775 zs_samples, "s_sample_store");
776 z_fb_store = lp_build_array_alloca(gallivm, lp_build_vec_type(gallivm, z_type),
777 zs_samples, "z_fb_store");
778 s_fb_store = lp_build_array_alloca(gallivm, lp_build_vec_type(gallivm, s_type),
779 zs_samples, "s_fb_store");
780 }
781 lp_build_for_loop_begin(&sample_loop_state, gallivm,
782 lp_build_const_int32(gallivm, 0),
783 LLVMIntULT, lp_build_const_int32(gallivm, key->coverage_samples),
784 lp_build_const_int32(gallivm, 1));
785
786 LLVMValueRef s_mask_idx = LLVMBuildMul(builder, sample_loop_state.counter, num_loop, "");
787 s_mask_idx = LLVMBuildAdd(builder, s_mask_idx, loop_state.counter, "");
788 s_mask_ptr = LLVMBuildGEP(builder, mask_store, &s_mask_idx, 1, "");
789
790 s_mask = LLVMBuildLoad(builder, s_mask_ptr, "");
791 s_mask = LLVMBuildAnd(builder, s_mask, mask_val, "");
792 }
793
794
795 /* for multisample Z needs to be interpolated at sample points for testing. */
796 lp_build_interp_soa_update_pos_dyn(interp, gallivm, loop_state.counter, key->multisample ? sample_loop_state.counter : NULL);
797 z = interp->pos[2];
798
799 depth_ptr = depth_base_ptr;
800 if (key->multisample) {
801 LLVMValueRef sample_offset = LLVMBuildMul(builder, sample_loop_state.counter, depth_sample_stride, "");
802 depth_ptr = LLVMBuildGEP(builder, depth_ptr, &sample_offset, 1, "");
803 }
804
805 if (depth_mode & EARLY_DEPTH_TEST) {
806 /*
807 * Clamp according to ARB_depth_clamp semantics.
808 */
809 if (key->depth_clamp) {
810 z = lp_build_depth_clamp(gallivm, builder, type, context_ptr,
811 thread_data_ptr, z);
812 }
813 lp_build_depth_stencil_load_swizzled(gallivm, type,
814 zs_format_desc, key->resource_1d,
815 depth_ptr, depth_stride,
816 &z_fb, &s_fb, loop_state.counter);
817 lp_build_depth_stencil_test(gallivm,
818 &key->depth,
819 key->stencil,
820 type,
821 zs_format_desc,
822 key->multisample ? NULL : &mask,
823 &s_mask,
824 stencil_refs,
825 z, z_fb, s_fb,
826 facing,
827 &z_value, &s_value,
828 !simple_shader && !key->multisample);
829
830 if (depth_mode & EARLY_DEPTH_WRITE) {
831 lp_build_depth_stencil_write_swizzled(gallivm, type,
832 zs_format_desc, key->resource_1d,
833 NULL, NULL, NULL, loop_state.counter,
834 depth_ptr, depth_stride,
835 z_value, s_value);
836 }
837 /*
838 * Note mask check if stencil is enabled must be after ds write not after
839 * stencil test otherwise new stencil values may not get written if all
840 * fragments got killed by depth/stencil test.
841 */
842 if (!simple_shader && key->stencil[0].enabled && !key->multisample)
843 lp_build_mask_check(&mask);
844
845 if (key->multisample) {
846 z_fb_type = LLVMTypeOf(z_fb);
847 z_type = LLVMTypeOf(z_value);
848 lp_build_pointer_set(builder, z_sample_value_store, sample_loop_state.counter, LLVMBuildBitCast(builder, z_value, lp_build_int_vec_type(gallivm, type), ""));
849 lp_build_pointer_set(builder, s_sample_value_store, sample_loop_state.counter, LLVMBuildBitCast(builder, s_value, lp_build_int_vec_type(gallivm, type), ""));
850 lp_build_pointer_set(builder, z_fb_store, sample_loop_state.counter, z_fb);
851 lp_build_pointer_set(builder, s_fb_store, sample_loop_state.counter, s_fb);
852 }
853 }
854
855 if (key->multisample) {
856 /*
857 * Store the post-early Z coverage mask.
858 * Recombine the resulting coverage masks post early Z into the fragment
859 * shader execution mask.
860 */
861 LLVMValueRef tmp_s_mask_or = LLVMBuildLoad(builder, s_mask_or, "");
862 tmp_s_mask_or = LLVMBuildOr(builder, tmp_s_mask_or, s_mask, "");
863 LLVMBuildStore(builder, tmp_s_mask_or, s_mask_or);
864
865 if (post_depth_coverage) {
866 LLVMValueRef mask_bit_idx = LLVMBuildShl(builder, lp_build_const_int32(gallivm, 1), sample_loop_state.counter, "");
867 LLVMValueRef post_depth_mask_in = LLVMBuildLoad(builder, post_depth_sample_mask_in, "");
868 mask_bit_idx = LLVMBuildAnd(builder, s_mask, lp_build_broadcast(gallivm, int_vec_type, mask_bit_idx), "");
869 post_depth_mask_in = LLVMBuildOr(builder, post_depth_mask_in, mask_bit_idx, "");
870 LLVMBuildStore(builder, post_depth_mask_in, post_depth_sample_mask_in);
871 }
872
873 LLVMBuildStore(builder, s_mask, s_mask_ptr);
874
875 lp_build_for_loop_end(&sample_loop_state);
876
877 /* recombined all the coverage masks in the shader exec mask. */
878 tmp_s_mask_or = LLVMBuildLoad(builder, s_mask_or, "");
879 lp_build_mask_update(&mask, tmp_s_mask_or);
880
881 if (key->min_samples == 1) {
882 /* for multisample Z needs to be re interpolated at pixel center */
883 lp_build_interp_soa_update_pos_dyn(interp, gallivm, loop_state.counter, NULL);
884 lp_build_mask_update(&mask, tmp_s_mask_or);
885 }
886 } else {
887 if (post_depth_coverage) {
888 LLVMValueRef post_depth_mask_in = LLVMBuildAnd(builder, lp_build_mask_value(&mask), lp_build_const_int_vec(gallivm, type, 1), "");
889 LLVMBuildStore(builder, post_depth_mask_in, post_depth_sample_mask_in);
890 }
891 }
892
893 LLVMValueRef out_sample_mask_storage = NULL;
894 if (shader->info.base.writes_samplemask) {
895 out_sample_mask_storage = lp_build_alloca(gallivm, int_vec_type, "write_mask");
896 if (key->min_samples > 1)
897 LLVMBuildStore(builder, LLVMConstNull(int_vec_type), out_sample_mask_storage);
898 }
899
900 if (post_depth_coverage) {
901 system_values.sample_mask_in = LLVMBuildLoad(builder, post_depth_sample_mask_in, "");
902 }
903 else
904 system_values.sample_mask_in = sample_mask_in;
905 if (key->multisample && key->min_samples > 1) {
906 lp_build_for_loop_begin(&sample_loop_state, gallivm,
907 lp_build_const_int32(gallivm, 0),
908 LLVMIntULT,
909 lp_build_const_int32(gallivm, key->min_samples),
910 lp_build_const_int32(gallivm, 1));
911
912 LLVMValueRef s_mask_idx = LLVMBuildMul(builder, sample_loop_state.counter, num_loop, "");
913 s_mask_idx = LLVMBuildAdd(builder, s_mask_idx, loop_state.counter, "");
914 s_mask_ptr = LLVMBuildGEP(builder, mask_store, &s_mask_idx, 1, "");
915 s_mask = LLVMBuildLoad(builder, s_mask_ptr, "");
916 lp_build_mask_force(&mask, s_mask);
917 lp_build_interp_soa_update_pos_dyn(interp, gallivm, loop_state.counter, sample_loop_state.counter);
918 system_values.sample_id = sample_loop_state.counter;
919 system_values.sample_mask_in = LLVMBuildAnd(builder, system_values.sample_mask_in,
920 lp_build_broadcast(gallivm, int_vec_type,
921 LLVMBuildShl(builder, lp_build_const_int32(gallivm, 1), sample_loop_state.counter, "")), "");
922 } else {
923 system_values.sample_id = lp_build_const_int32(gallivm, 0);
924
925 }
926 system_values.sample_pos = sample_pos_array;
927
928 lp_build_interp_soa_update_inputs_dyn(interp, gallivm, loop_state.counter, mask_store, sample_loop_state.counter);
929
930 struct lp_build_fs_llvm_iface fs_iface = {
931 .base.interp_fn = fs_interp,
932 .base.fb_fetch = fs_fb_fetch,
933 .interp = interp,
934 .loop_state = &loop_state,
935 .sample_id = system_values.sample_id,
936 .mask_store = mask_store,
937 .color_ptr_ptr = color_ptr_ptr,
938 .color_stride_ptr = color_stride_ptr,
939 .color_sample_stride_ptr = color_sample_stride_ptr,
940 .key = key,
941 };
942
943 struct lp_build_tgsi_params params;
944 memset(&params, 0, sizeof(params));
945
946 params.type = type;
947 params.mask = &mask;
948 params.fs_iface = &fs_iface.base;
949 params.consts_ptr = consts_ptr;
950 params.const_sizes_ptr = num_consts_ptr;
951 params.system_values = &system_values;
952 params.inputs = interp->inputs;
953 params.context_ptr = context_ptr;
954 params.thread_data_ptr = thread_data_ptr;
955 params.sampler = sampler;
956 params.info = &shader->info.base;
957 params.ssbo_ptr = ssbo_ptr;
958 params.ssbo_sizes_ptr = num_ssbo_ptr;
959 params.image = image;
960
961 /* Build the actual shader */
962 if (shader->base.type == PIPE_SHADER_IR_TGSI)
963 lp_build_tgsi_soa(gallivm, tokens, &params,
964 outputs);
965 else
966 lp_build_nir_soa(gallivm, shader->base.ir.nir, &params,
967 outputs);
968
969 /* Alpha test */
970 if (key->alpha.enabled) {
971 int color0 = find_output_by_semantic(&shader->info.base,
972 TGSI_SEMANTIC_COLOR,
973 0);
974
975 if (color0 != -1 && outputs[color0][3]) {
976 const struct util_format_description *cbuf_format_desc;
977 LLVMValueRef alpha = LLVMBuildLoad(builder, outputs[color0][3], "alpha");
978 LLVMValueRef alpha_ref_value;
979
980 alpha_ref_value = lp_jit_context_alpha_ref_value(gallivm, context_ptr);
981 alpha_ref_value = lp_build_broadcast(gallivm, vec_type, alpha_ref_value);
982
983 cbuf_format_desc = util_format_description(key->cbuf_format[0]);
984
985 lp_build_alpha_test(gallivm, key->alpha.func, type, cbuf_format_desc,
986 &mask, alpha, alpha_ref_value,
987 (depth_mode & LATE_DEPTH_TEST) != 0);
988 }
989 }
990
991 /* Emulate Alpha to Coverage with Alpha test */
992 if (key->blend.alpha_to_coverage) {
993 int color0 = find_output_by_semantic(&shader->info.base,
994 TGSI_SEMANTIC_COLOR,
995 0);
996
997 if (color0 != -1 && outputs[color0][3]) {
998 LLVMValueRef alpha = LLVMBuildLoad(builder, outputs[color0][3], "alpha");
999
1000 if (!key->multisample) {
1001 lp_build_alpha_to_coverage(gallivm, type,
1002 &mask, alpha,
1003 (depth_mode & LATE_DEPTH_TEST) != 0);
1004 } else {
1005 lp_build_sample_alpha_to_coverage(gallivm, type, key->coverage_samples, num_loop,
1006 loop_state.counter,
1007 mask_store, alpha);
1008 }
1009 }
1010 }
1011 if (key->blend.alpha_to_one && key->multisample) {
1012 for (attrib = 0; attrib < shader->info.base.num_outputs; ++attrib) {
1013 unsigned cbuf = shader->info.base.output_semantic_index[attrib];
1014 if ((shader->info.base.output_semantic_name[attrib] == TGSI_SEMANTIC_COLOR) &&
1015 ((cbuf < key->nr_cbufs) || (cbuf == 1 && dual_source_blend)))
1016 if (outputs[cbuf][3]) {
1017 LLVMBuildStore(builder, lp_build_const_vec(gallivm, type, 1.0), outputs[cbuf][3]);
1018 }
1019 }
1020 }
1021 if (shader->info.base.writes_samplemask) {
1022 LLVMValueRef output_smask = NULL;
1023 int smaski = find_output_by_semantic(&shader->info.base,
1024 TGSI_SEMANTIC_SAMPLEMASK,
1025 0);
1026 struct lp_build_context smask_bld;
1027 lp_build_context_init(&smask_bld, gallivm, int_type);
1028
1029 assert(smaski >= 0);
1030 output_smask = LLVMBuildLoad(builder, outputs[smaski][0], "smask");
1031 output_smask = LLVMBuildBitCast(builder, output_smask, smask_bld.vec_type, "");
1032
1033 if (key->min_samples > 1) {
1034 /* only the bit corresponding to this sample is to be used. */
1035 LLVMValueRef tmp_mask = LLVMBuildLoad(builder, out_sample_mask_storage, "tmp_mask");
1036 LLVMValueRef out_smask_idx = LLVMBuildShl(builder, lp_build_const_int32(gallivm, 1), sample_loop_state.counter, "");
1037 LLVMValueRef smask_bit = LLVMBuildAnd(builder, output_smask, lp_build_broadcast(gallivm, int_vec_type, out_smask_idx), "");
1038 output_smask = LLVMBuildOr(builder, tmp_mask, smask_bit, "");
1039 }
1040
1041 LLVMBuildStore(builder, output_smask, out_sample_mask_storage);
1042 }
1043
1044 /* Color write - per fragment sample */
1045 for (attrib = 0; attrib < shader->info.base.num_outputs; ++attrib)
1046 {
1047 unsigned cbuf = shader->info.base.output_semantic_index[attrib];
1048 if ((shader->info.base.output_semantic_name[attrib] == TGSI_SEMANTIC_COLOR) &&
1049 ((cbuf < key->nr_cbufs) || (cbuf == 1 && dual_source_blend)))
1050 {
1051 for(chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
1052 if(outputs[attrib][chan]) {
1053 /* XXX: just initialize outputs to point at colors[] and
1054 * skip this.
1055 */
1056 LLVMValueRef out = LLVMBuildLoad(builder, outputs[attrib][chan], "");
1057 LLVMValueRef color_ptr;
1058 LLVMValueRef color_idx = loop_state.counter;
1059 if (key->min_samples > 1)
1060 color_idx = LLVMBuildAdd(builder, color_idx,
1061 LLVMBuildMul(builder, sample_loop_state.counter, num_loop, ""), "");
1062 color_ptr = LLVMBuildGEP(builder, out_color[cbuf][chan],
1063 &color_idx, 1, "");
1064 lp_build_name(out, "color%u.%c", attrib, "rgba"[chan]);
1065 LLVMBuildStore(builder, out, color_ptr);
1066 }
1067 }
1068 }
1069 }
1070
1071 if (key->multisample && key->min_samples > 1) {
1072 LLVMBuildStore(builder, lp_build_mask_value(&mask), s_mask_ptr);
1073 lp_build_for_loop_end(&sample_loop_state);
1074 }
1075
1076 if (key->multisample) {
1077 /* execute depth test for each sample */
1078 lp_build_for_loop_begin(&sample_loop_state, gallivm,
1079 lp_build_const_int32(gallivm, 0),
1080 LLVMIntULT, lp_build_const_int32(gallivm, key->coverage_samples),
1081 lp_build_const_int32(gallivm, 1));
1082
1083 /* load the per-sample coverage mask */
1084 LLVMValueRef s_mask_idx = LLVMBuildMul(builder, sample_loop_state.counter, num_loop, "");
1085 s_mask_idx = LLVMBuildAdd(builder, s_mask_idx, loop_state.counter, "");
1086 s_mask_ptr = LLVMBuildGEP(builder, mask_store, &s_mask_idx, 1, "");
1087
1088 /* combine the execution mask post fragment shader with the coverage mask. */
1089 s_mask = LLVMBuildLoad(builder, s_mask_ptr, "");
1090 if (key->min_samples == 1)
1091 s_mask = LLVMBuildAnd(builder, s_mask, lp_build_mask_value(&mask), "");
1092
1093 /* if the shader writes sample mask use that */
1094 if (shader->info.base.writes_samplemask) {
1095 LLVMValueRef out_smask_idx = LLVMBuildShl(builder, lp_build_const_int32(gallivm, 1), sample_loop_state.counter, "");
1096 out_smask_idx = lp_build_broadcast(gallivm, int_vec_type, out_smask_idx);
1097 LLVMValueRef output_smask = LLVMBuildLoad(builder, out_sample_mask_storage, "");
1098 LLVMValueRef smask_bit = LLVMBuildAnd(builder, output_smask, out_smask_idx, "");
1099 LLVMValueRef cmp = LLVMBuildICmp(builder, LLVMIntNE, smask_bit, lp_build_const_int_vec(gallivm, int_type, 0), "");
1100 smask_bit = LLVMBuildSExt(builder, cmp, int_vec_type, "");
1101
1102 s_mask = LLVMBuildAnd(builder, s_mask, smask_bit, "");
1103 }
1104 }
1105
1106 depth_ptr = depth_base_ptr;
1107 if (key->multisample) {
1108 LLVMValueRef sample_offset = LLVMBuildMul(builder, sample_loop_state.counter, depth_sample_stride, "");
1109 depth_ptr = LLVMBuildGEP(builder, depth_ptr, &sample_offset, 1, "");
1110 }
1111
1112 /* Late Z test */
1113 if (depth_mode & LATE_DEPTH_TEST) {
1114 int pos0 = find_output_by_semantic(&shader->info.base,
1115 TGSI_SEMANTIC_POSITION,
1116 0);
1117 int s_out = find_output_by_semantic(&shader->info.base,
1118 TGSI_SEMANTIC_STENCIL,
1119 0);
1120 if (pos0 != -1 && outputs[pos0][2]) {
1121 z = LLVMBuildLoad(builder, outputs[pos0][2], "output.z");
1122 }
1123 /*
1124 * Clamp according to ARB_depth_clamp semantics.
1125 */
1126 if (key->depth_clamp) {
1127 z = lp_build_depth_clamp(gallivm, builder, type, context_ptr,
1128 thread_data_ptr, z);
1129 }
1130
1131 if (s_out != -1 && outputs[s_out][1]) {
1132 /* there's only one value, and spec says to discard additional bits */
1133 LLVMValueRef s_max_mask = lp_build_const_int_vec(gallivm, int_type, 255);
1134 stencil_refs[0] = LLVMBuildLoad(builder, outputs[s_out][1], "output.s");
1135 stencil_refs[0] = LLVMBuildBitCast(builder, stencil_refs[0], int_vec_type, "");
1136 stencil_refs[0] = LLVMBuildAnd(builder, stencil_refs[0], s_max_mask, "");
1137 stencil_refs[1] = stencil_refs[0];
1138 }
1139
1140 lp_build_depth_stencil_load_swizzled(gallivm, type,
1141 zs_format_desc, key->resource_1d,
1142 depth_ptr, depth_stride,
1143 &z_fb, &s_fb, loop_state.counter);
1144
1145 lp_build_depth_stencil_test(gallivm,
1146 &key->depth,
1147 key->stencil,
1148 type,
1149 zs_format_desc,
1150 key->multisample ? NULL : &mask,
1151 &s_mask,
1152 stencil_refs,
1153 z, z_fb, s_fb,
1154 facing,
1155 &z_value, &s_value,
1156 !simple_shader);
1157 /* Late Z write */
1158 if (depth_mode & LATE_DEPTH_WRITE) {
1159 lp_build_depth_stencil_write_swizzled(gallivm, type,
1160 zs_format_desc, key->resource_1d,
1161 NULL, NULL, NULL, loop_state.counter,
1162 depth_ptr, depth_stride,
1163 z_value, s_value);
1164 }
1165 }
1166 else if ((depth_mode & EARLY_DEPTH_TEST) &&
1167 (depth_mode & LATE_DEPTH_WRITE))
1168 {
1169 /* Need to apply a reduced mask to the depth write. Reload the
1170 * depth value, update from zs_value with the new mask value and
1171 * write that out.
1172 */
1173 if (key->multisample) {
1174 z_value = LLVMBuildBitCast(builder, lp_build_pointer_get(builder, z_sample_value_store, sample_loop_state.counter), z_type, "");;
1175 s_value = lp_build_pointer_get(builder, s_sample_value_store, sample_loop_state.counter);
1176 z_fb = LLVMBuildBitCast(builder, lp_build_pointer_get(builder, z_fb_store, sample_loop_state.counter), z_fb_type, "");
1177 s_fb = lp_build_pointer_get(builder, s_fb_store, sample_loop_state.counter);
1178 }
1179 lp_build_depth_stencil_write_swizzled(gallivm, type,
1180 zs_format_desc, key->resource_1d,
1181 key->multisample ? s_mask : lp_build_mask_value(&mask), z_fb, s_fb, loop_state.counter,
1182 depth_ptr, depth_stride,
1183 z_value, s_value);
1184 }
1185
1186 if (key->occlusion_count) {
1187 LLVMValueRef counter = lp_jit_thread_data_counter(gallivm, thread_data_ptr);
1188 lp_build_name(counter, "counter");
1189
1190 lp_build_occlusion_count(gallivm, type,
1191 key->multisample ? s_mask : lp_build_mask_value(&mask), counter);
1192 }
1193
1194 if (key->multisample) {
1195 /* store the sample mask for this loop */
1196 LLVMBuildStore(builder, s_mask, s_mask_ptr);
1197 lp_build_for_loop_end(&sample_loop_state);
1198 }
1199
1200 mask_val = lp_build_mask_end(&mask);
1201 if (!key->multisample)
1202 LLVMBuildStore(builder, mask_val, mask_ptr);
1203 lp_build_for_loop_end(&loop_state);
1204 }
1205
1206
1207 /**
1208 * This function will reorder pixels from the fragment shader SoA to memory layout AoS
1209 *
1210 * Fragment Shader outputs pixels in small 2x2 blocks
1211 * e.g. (0, 0), (1, 0), (0, 1), (1, 1) ; (2, 0) ...
1212 *
1213 * However in memory pixels are stored in rows
1214 * e.g. (0, 0), (1, 0), (2, 0), (3, 0) ; (0, 1) ...
1215 *
1216 * @param type fragment shader type (4x or 8x float)
1217 * @param num_fs number of fs_src
1218 * @param is_1d whether we're outputting to a 1d resource
1219 * @param dst_channels number of output channels
1220 * @param fs_src output from fragment shader
1221 * @param dst pointer to store result
1222 * @param pad_inline is channel padding inline or at end of row
1223 * @return the number of dsts
1224 */
1225 static int
1226 generate_fs_twiddle(struct gallivm_state *gallivm,
1227 struct lp_type type,
1228 unsigned num_fs,
1229 unsigned dst_channels,
1230 LLVMValueRef fs_src[][4],
1231 LLVMValueRef* dst,
1232 bool pad_inline)
1233 {
1234 LLVMValueRef src[16];
1235
1236 bool swizzle_pad;
1237 bool twiddle;
1238 bool split;
1239
1240 unsigned pixels = type.length / 4;
1241 unsigned reorder_group;
1242 unsigned src_channels;
1243 unsigned src_count;
1244 unsigned i;
1245
1246 src_channels = dst_channels < 3 ? dst_channels : 4;
1247 src_count = num_fs * src_channels;
1248
1249 assert(pixels == 2 || pixels == 1);
1250 assert(num_fs * src_channels <= ARRAY_SIZE(src));
1251
1252 /*
1253 * Transpose from SoA -> AoS
1254 */
1255 for (i = 0; i < num_fs; ++i) {
1256 lp_build_transpose_aos_n(gallivm, type, &fs_src[i][0], src_channels, &src[i * src_channels]);
1257 }
1258
1259 /*
1260 * Pick transformation options
1261 */
1262 swizzle_pad = false;
1263 twiddle = false;
1264 split = false;
1265 reorder_group = 0;
1266
1267 if (dst_channels == 1) {
1268 twiddle = true;
1269
1270 if (pixels == 2) {
1271 split = true;
1272 }
1273 } else if (dst_channels == 2) {
1274 if (pixels == 1) {
1275 reorder_group = 1;
1276 }
1277 } else if (dst_channels > 2) {
1278 if (pixels == 1) {
1279 reorder_group = 2;
1280 } else {
1281 twiddle = true;
1282 }
1283
1284 if (!pad_inline && dst_channels == 3 && pixels > 1) {
1285 swizzle_pad = true;
1286 }
1287 }
1288
1289 /*
1290 * Split the src in half
1291 */
1292 if (split) {
1293 for (i = num_fs; i > 0; --i) {
1294 src[(i - 1)*2 + 1] = lp_build_extract_range(gallivm, src[i - 1], 4, 4);
1295 src[(i - 1)*2 + 0] = lp_build_extract_range(gallivm, src[i - 1], 0, 4);
1296 }
1297
1298 src_count *= 2;
1299 type.length = 4;
1300 }
1301
1302 /*
1303 * Ensure pixels are in memory order
1304 */
1305 if (reorder_group) {
1306 /* Twiddle pixels by reordering the array, e.g.:
1307 *
1308 * src_count = 8 -> 0 2 1 3 4 6 5 7
1309 * src_count = 16 -> 0 1 4 5 2 3 6 7 8 9 12 13 10 11 14 15
1310 */
1311 const unsigned reorder_sw[] = { 0, 2, 1, 3 };
1312
1313 for (i = 0; i < src_count; ++i) {
1314 unsigned group = i / reorder_group;
1315 unsigned block = (group / 4) * 4 * reorder_group;
1316 unsigned j = block + (reorder_sw[group % 4] * reorder_group) + (i % reorder_group);
1317 dst[i] = src[j];
1318 }
1319 } else if (twiddle) {
1320 /* Twiddle pixels across elements of array */
1321 /*
1322 * XXX: we should avoid this in some cases, but would need to tell
1323 * lp_build_conv to reorder (or deal with it ourselves).
1324 */
1325 lp_bld_quad_twiddle(gallivm, type, src, src_count, dst);
1326 } else {
1327 /* Do nothing */
1328 memcpy(dst, src, sizeof(LLVMValueRef) * src_count);
1329 }
1330
1331 /*
1332 * Moves any padding between pixels to the end
1333 * e.g. RGBXRGBX -> RGBRGBXX
1334 */
1335 if (swizzle_pad) {
1336 unsigned char swizzles[16];
1337 unsigned elems = pixels * dst_channels;
1338
1339 for (i = 0; i < type.length; ++i) {
1340 if (i < elems)
1341 swizzles[i] = i % dst_channels + (i / dst_channels) * 4;
1342 else
1343 swizzles[i] = LP_BLD_SWIZZLE_DONTCARE;
1344 }
1345
1346 for (i = 0; i < src_count; ++i) {
1347 dst[i] = lp_build_swizzle_aos_n(gallivm, dst[i], swizzles, type.length, type.length);
1348 }
1349 }
1350
1351 return src_count;
1352 }
1353
1354
1355 /*
1356 * Untwiddle and transpose, much like the above.
1357 * However, this is after conversion, so we get packed vectors.
1358 * At this time only handle 4x16i8 rgba / 2x16i8 rg / 1x16i8 r data,
1359 * the vectors will look like:
1360 * r0r1r4r5r2r3r6r7r8r9r12... (albeit color channels may
1361 * be swizzled here). Extending to 16bit should be trivial.
1362 * Should also be extended to handle twice wide vectors with AVX2...
1363 */
1364 static void
1365 fs_twiddle_transpose(struct gallivm_state *gallivm,
1366 struct lp_type type,
1367 LLVMValueRef *src,
1368 unsigned src_count,
1369 LLVMValueRef *dst)
1370 {
1371 unsigned i, j;
1372 struct lp_type type64, type16, type32;
1373 LLVMTypeRef type64_t, type8_t, type16_t, type32_t;
1374 LLVMBuilderRef builder = gallivm->builder;
1375 LLVMValueRef tmp[4], shuf[8];
1376 for (j = 0; j < 2; j++) {
1377 shuf[j*4 + 0] = lp_build_const_int32(gallivm, j*4 + 0);
1378 shuf[j*4 + 1] = lp_build_const_int32(gallivm, j*4 + 2);
1379 shuf[j*4 + 2] = lp_build_const_int32(gallivm, j*4 + 1);
1380 shuf[j*4 + 3] = lp_build_const_int32(gallivm, j*4 + 3);
1381 }
1382
1383 assert(src_count == 4 || src_count == 2 || src_count == 1);
1384 assert(type.width == 8);
1385 assert(type.length == 16);
1386
1387 type8_t = lp_build_vec_type(gallivm, type);
1388
1389 type64 = type;
1390 type64.length /= 8;
1391 type64.width *= 8;
1392 type64_t = lp_build_vec_type(gallivm, type64);
1393
1394 type16 = type;
1395 type16.length /= 2;
1396 type16.width *= 2;
1397 type16_t = lp_build_vec_type(gallivm, type16);
1398
1399 type32 = type;
1400 type32.length /= 4;
1401 type32.width *= 4;
1402 type32_t = lp_build_vec_type(gallivm, type32);
1403
1404 lp_build_transpose_aos_n(gallivm, type, src, src_count, tmp);
1405
1406 if (src_count == 1) {
1407 /* transpose was no-op, just untwiddle */
1408 LLVMValueRef shuf_vec;
1409 shuf_vec = LLVMConstVector(shuf, 8);
1410 tmp[0] = LLVMBuildBitCast(builder, src[0], type16_t, "");
1411 tmp[0] = LLVMBuildShuffleVector(builder, tmp[0], tmp[0], shuf_vec, "");
1412 dst[0] = LLVMBuildBitCast(builder, tmp[0], type8_t, "");
1413 } else if (src_count == 2) {
1414 LLVMValueRef shuf_vec;
1415 shuf_vec = LLVMConstVector(shuf, 4);
1416
1417 for (i = 0; i < 2; i++) {
1418 tmp[i] = LLVMBuildBitCast(builder, tmp[i], type32_t, "");
1419 tmp[i] = LLVMBuildShuffleVector(builder, tmp[i], tmp[i], shuf_vec, "");
1420 dst[i] = LLVMBuildBitCast(builder, tmp[i], type8_t, "");
1421 }
1422 } else {
1423 for (j = 0; j < 2; j++) {
1424 LLVMValueRef lo, hi, lo2, hi2;
1425 /*
1426 * Note that if we only really have 3 valid channels (rgb)
1427 * and we don't need alpha we could substitute a undef here
1428 * for the respective channel (causing llvm to drop conversion
1429 * for alpha).
1430 */
1431 /* we now have rgba0rgba1rgba4rgba5 etc, untwiddle */
1432 lo2 = LLVMBuildBitCast(builder, tmp[j*2], type64_t, "");
1433 hi2 = LLVMBuildBitCast(builder, tmp[j*2 + 1], type64_t, "");
1434 lo = lp_build_interleave2(gallivm, type64, lo2, hi2, 0);
1435 hi = lp_build_interleave2(gallivm, type64, lo2, hi2, 1);
1436 dst[j*2] = LLVMBuildBitCast(builder, lo, type8_t, "");
1437 dst[j*2 + 1] = LLVMBuildBitCast(builder, hi, type8_t, "");
1438 }
1439 }
1440 }
1441
1442
1443 /**
1444 * Load an unswizzled block of pixels from memory
1445 */
1446 static void
1447 load_unswizzled_block(struct gallivm_state *gallivm,
1448 LLVMValueRef base_ptr,
1449 LLVMValueRef stride,
1450 unsigned block_width,
1451 unsigned block_height,
1452 LLVMValueRef* dst,
1453 struct lp_type dst_type,
1454 unsigned dst_count,
1455 unsigned dst_alignment,
1456 LLVMValueRef x_offset,
1457 LLVMValueRef y_offset,
1458 bool fb_fetch_twiddle)
1459 {
1460 LLVMBuilderRef builder = gallivm->builder;
1461 unsigned row_size = dst_count / block_height;
1462 unsigned i;
1463
1464 /* Ensure block exactly fits into dst */
1465 assert((block_width * block_height) % dst_count == 0);
1466
1467 for (i = 0; i < dst_count; ++i) {
1468 unsigned x = i % row_size;
1469 unsigned y = i / row_size;
1470
1471 if (block_height == 2 && dst_count == 8 && fb_fetch_twiddle) {
1472 /* remap the raw slots into the fragment shader execution mode. */
1473 /* this math took me way too long to work out, I'm sure it's overkill. */
1474 x = (i & 1) + ((i >> 2) << 1);
1475 y = (i & 2) >> 1;
1476 }
1477
1478 LLVMValueRef x_val;
1479 if (x_offset) {
1480 x_val = lp_build_const_int32(gallivm, x);
1481 if (x_offset)
1482 x_val = LLVMBuildAdd(builder, x_val, x_offset, "");
1483 x_val = LLVMBuildMul(builder, x_val, lp_build_const_int32(gallivm, (dst_type.width / 8) * dst_type.length), "");
1484 } else
1485 x_val = lp_build_const_int32(gallivm, x * (dst_type.width / 8) * dst_type.length);
1486
1487 LLVMValueRef bx = x_val;
1488
1489 LLVMValueRef y_val = lp_build_const_int32(gallivm, y);
1490 if (y_offset)
1491 y_val = LLVMBuildAdd(builder, y_val, y_offset, "");
1492 LLVMValueRef by = LLVMBuildMul(builder, y_val, stride, "");
1493
1494 LLVMValueRef gep[2];
1495 LLVMValueRef dst_ptr;
1496
1497 gep[0] = lp_build_const_int32(gallivm, 0);
1498 gep[1] = LLVMBuildAdd(builder, bx, by, "");
1499
1500 dst_ptr = LLVMBuildGEP(builder, base_ptr, gep, 2, "");
1501 dst_ptr = LLVMBuildBitCast(builder, dst_ptr,
1502 LLVMPointerType(lp_build_vec_type(gallivm, dst_type), 0), "");
1503
1504 dst[i] = LLVMBuildLoad(builder, dst_ptr, "");
1505
1506 LLVMSetAlignment(dst[i], dst_alignment);
1507 }
1508 }
1509
1510
1511 /**
1512 * Store an unswizzled block of pixels to memory
1513 */
1514 static void
1515 store_unswizzled_block(struct gallivm_state *gallivm,
1516 LLVMValueRef base_ptr,
1517 LLVMValueRef stride,
1518 unsigned block_width,
1519 unsigned block_height,
1520 LLVMValueRef* src,
1521 struct lp_type src_type,
1522 unsigned src_count,
1523 unsigned src_alignment)
1524 {
1525 LLVMBuilderRef builder = gallivm->builder;
1526 unsigned row_size = src_count / block_height;
1527 unsigned i;
1528
1529 /* Ensure src exactly fits into block */
1530 assert((block_width * block_height) % src_count == 0);
1531
1532 for (i = 0; i < src_count; ++i) {
1533 unsigned x = i % row_size;
1534 unsigned y = i / row_size;
1535
1536 LLVMValueRef bx = lp_build_const_int32(gallivm, x * (src_type.width / 8) * src_type.length);
1537 LLVMValueRef by = LLVMBuildMul(builder, lp_build_const_int32(gallivm, y), stride, "");
1538
1539 LLVMValueRef gep[2];
1540 LLVMValueRef src_ptr;
1541
1542 gep[0] = lp_build_const_int32(gallivm, 0);
1543 gep[1] = LLVMBuildAdd(builder, bx, by, "");
1544
1545 src_ptr = LLVMBuildGEP(builder, base_ptr, gep, 2, "");
1546 src_ptr = LLVMBuildBitCast(builder, src_ptr,
1547 LLVMPointerType(lp_build_vec_type(gallivm, src_type), 0), "");
1548
1549 src_ptr = LLVMBuildStore(builder, src[i], src_ptr);
1550
1551 LLVMSetAlignment(src_ptr, src_alignment);
1552 }
1553 }
1554
1555
1556
1557 /**
1558 * Retrieves the type for a format which is usable in the blending code.
1559 *
1560 * e.g. RGBA16F = 4x float, R3G3B2 = 3x byte
1561 */
1562 static inline void
1563 lp_blend_type_from_format_desc(const struct util_format_description *format_desc,
1564 struct lp_type* type)
1565 {
1566 unsigned i;
1567 unsigned chan;
1568
1569 if (format_expands_to_float_soa(format_desc)) {
1570 /* always use ordinary floats for blending */
1571 type->floating = true;
1572 type->fixed = false;
1573 type->sign = true;
1574 type->norm = false;
1575 type->width = 32;
1576 type->length = 4;
1577 return;
1578 }
1579
1580 for (i = 0; i < 4; i++)
1581 if (format_desc->channel[i].type != UTIL_FORMAT_TYPE_VOID)
1582 break;
1583 chan = i;
1584
1585 memset(type, 0, sizeof(struct lp_type));
1586 type->floating = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FLOAT;
1587 type->fixed = format_desc->channel[chan].type == UTIL_FORMAT_TYPE_FIXED;
1588 type->sign = format_desc->channel[chan].type != UTIL_FORMAT_TYPE_UNSIGNED;
1589 type->norm = format_desc->channel[chan].normalized;
1590 type->width = format_desc->channel[chan].size;
1591 type->length = format_desc->nr_channels;
1592
1593 for (i = 1; i < format_desc->nr_channels; ++i) {
1594 if (format_desc->channel[i].size > type->width)
1595 type->width = format_desc->channel[i].size;
1596 }
1597
1598 if (type->floating) {
1599 type->width = 32;
1600 } else {
1601 if (type->width <= 8) {
1602 type->width = 8;
1603 } else if (type->width <= 16) {
1604 type->width = 16;
1605 } else {
1606 type->width = 32;
1607 }
1608 }
1609
1610 if (is_arithmetic_format(format_desc) && type->length == 3) {
1611 type->length = 4;
1612 }
1613 }
1614
1615
1616 /**
1617 * Scale a normalized value from src_bits to dst_bits.
1618 *
1619 * The exact calculation is
1620 *
1621 * dst = iround(src * dst_mask / src_mask)
1622 *
1623 * or with integer rounding
1624 *
1625 * dst = src * (2*dst_mask + sign(src)*src_mask) / (2*src_mask)
1626 *
1627 * where
1628 *
1629 * src_mask = (1 << src_bits) - 1
1630 * dst_mask = (1 << dst_bits) - 1
1631 *
1632 * but we try to avoid division and multiplication through shifts.
1633 */
1634 static inline LLVMValueRef
1635 scale_bits(struct gallivm_state *gallivm,
1636 int src_bits,
1637 int dst_bits,
1638 LLVMValueRef src,
1639 struct lp_type src_type)
1640 {
1641 LLVMBuilderRef builder = gallivm->builder;
1642 LLVMValueRef result = src;
1643
1644 if (dst_bits < src_bits) {
1645 int delta_bits = src_bits - dst_bits;
1646
1647 if (delta_bits <= dst_bits) {
1648 /*
1649 * Approximate the rescaling with a single shift.
1650 *
1651 * This gives the wrong rounding.
1652 */
1653
1654 result = LLVMBuildLShr(builder,
1655 src,
1656 lp_build_const_int_vec(gallivm, src_type, delta_bits),
1657 "");
1658
1659 } else {
1660 /*
1661 * Try more accurate rescaling.
1662 */
1663
1664 /*
1665 * Drop the least significant bits to make space for the multiplication.
1666 *
1667 * XXX: A better approach would be to use a wider integer type as intermediate. But
1668 * this is enough to convert alpha from 16bits -> 2 when rendering to
1669 * PIPE_FORMAT_R10G10B10A2_UNORM.
1670 */
1671 result = LLVMBuildLShr(builder,
1672 src,
1673 lp_build_const_int_vec(gallivm, src_type, dst_bits),
1674 "");
1675
1676
1677 result = LLVMBuildMul(builder,
1678 result,
1679 lp_build_const_int_vec(gallivm, src_type, (1LL << dst_bits) - 1),
1680 "");
1681
1682 /*
1683 * Add a rounding term before the division.
1684 *
1685 * TODO: Handle signed integers too.
1686 */
1687 if (!src_type.sign) {
1688 result = LLVMBuildAdd(builder,
1689 result,
1690 lp_build_const_int_vec(gallivm, src_type, (1LL << (delta_bits - 1))),
1691 "");
1692 }
1693
1694 /*
1695 * Approximate the division by src_mask with a src_bits shift.
1696 *
1697 * Given the src has already been shifted by dst_bits, all we need
1698 * to do is to shift by the difference.
1699 */
1700
1701 result = LLVMBuildLShr(builder,
1702 result,
1703 lp_build_const_int_vec(gallivm, src_type, delta_bits),
1704 "");
1705 }
1706
1707 } else if (dst_bits > src_bits) {
1708 /* Scale up bits */
1709 int db = dst_bits - src_bits;
1710
1711 /* Shift left by difference in bits */
1712 result = LLVMBuildShl(builder,
1713 src,
1714 lp_build_const_int_vec(gallivm, src_type, db),
1715 "");
1716
1717 if (db <= src_bits) {
1718 /* Enough bits in src to fill the remainder */
1719 LLVMValueRef lower = LLVMBuildLShr(builder,
1720 src,
1721 lp_build_const_int_vec(gallivm, src_type, src_bits - db),
1722 "");
1723
1724 result = LLVMBuildOr(builder, result, lower, "");
1725 } else if (db > src_bits) {
1726 /* Need to repeatedly copy src bits to fill remainder in dst */
1727 unsigned n;
1728
1729 for (n = src_bits; n < dst_bits; n *= 2) {
1730 LLVMValueRef shuv = lp_build_const_int_vec(gallivm, src_type, n);
1731
1732 result = LLVMBuildOr(builder,
1733 result,
1734 LLVMBuildLShr(builder, result, shuv, ""),
1735 "");
1736 }
1737 }
1738 }
1739
1740 return result;
1741 }
1742
1743 /**
1744 * If RT is a smallfloat (needing denorms) format
1745 */
1746 static inline int
1747 have_smallfloat_format(struct lp_type dst_type,
1748 enum pipe_format format)
1749 {
1750 return ((dst_type.floating && dst_type.width != 32) ||
1751 /* due to format handling hacks this format doesn't have floating set
1752 * here (and actually has width set to 32 too) so special case this. */
1753 (format == PIPE_FORMAT_R11G11B10_FLOAT));
1754 }
1755
1756
1757 /**
1758 * Convert from memory format to blending format
1759 *
1760 * e.g. GL_R3G3B2 is 1 byte in memory but 3 bytes for blending
1761 */
1762 static void
1763 convert_to_blend_type(struct gallivm_state *gallivm,
1764 unsigned block_size,
1765 const struct util_format_description *src_fmt,
1766 struct lp_type src_type,
1767 struct lp_type dst_type,
1768 LLVMValueRef* src, // and dst
1769 unsigned num_srcs)
1770 {
1771 LLVMValueRef *dst = src;
1772 LLVMBuilderRef builder = gallivm->builder;
1773 struct lp_type blend_type;
1774 struct lp_type mem_type;
1775 unsigned i, j;
1776 unsigned pixels = block_size / num_srcs;
1777 bool is_arith;
1778
1779 /*
1780 * full custom path for packed floats and srgb formats - none of the later
1781 * functions would do anything useful, and given the lp_type representation they
1782 * can't be fixed. Should really have some SoA blend path for these kind of
1783 * formats rather than hacking them in here.
1784 */
1785 if (format_expands_to_float_soa(src_fmt)) {
1786 LLVMValueRef tmpsrc[4];
1787 /*
1788 * This is pretty suboptimal for this case blending in SoA would be much
1789 * better, since conversion gets us SoA values so need to convert back.
1790 */
1791 assert(src_type.width == 32 || src_type.width == 16);
1792 assert(dst_type.floating);
1793 assert(dst_type.width == 32);
1794 assert(dst_type.length % 4 == 0);
1795 assert(num_srcs % 4 == 0);
1796
1797 if (src_type.width == 16) {
1798 /* expand 4x16bit values to 4x32bit */
1799 struct lp_type type32x4 = src_type;
1800 LLVMTypeRef ltype32x4;
1801 unsigned num_fetch = dst_type.length == 8 ? num_srcs / 2 : num_srcs / 4;
1802 type32x4.width = 32;
1803 ltype32x4 = lp_build_vec_type(gallivm, type32x4);
1804 for (i = 0; i < num_fetch; i++) {
1805 src[i] = LLVMBuildZExt(builder, src[i], ltype32x4, "");
1806 }
1807 src_type.width = 32;
1808 }
1809 for (i = 0; i < 4; i++) {
1810 tmpsrc[i] = src[i];
1811 }
1812 for (i = 0; i < num_srcs / 4; i++) {
1813 LLVMValueRef tmpsoa[4];
1814 LLVMValueRef tmps = tmpsrc[i];
1815 if (dst_type.length == 8) {
1816 LLVMValueRef shuffles[8];
1817 unsigned j;
1818 /* fetch was 4 values but need 8-wide output values */
1819 tmps = lp_build_concat(gallivm, &tmpsrc[i * 2], src_type, 2);
1820 /*
1821 * for 8-wide aos transpose would give us wrong order not matching
1822 * incoming converted fs values and mask. ARGH.
1823 */
1824 for (j = 0; j < 4; j++) {
1825 shuffles[j] = lp_build_const_int32(gallivm, j * 2);
1826 shuffles[j + 4] = lp_build_const_int32(gallivm, j * 2 + 1);
1827 }
1828 tmps = LLVMBuildShuffleVector(builder, tmps, tmps,
1829 LLVMConstVector(shuffles, 8), "");
1830 }
1831 if (src_fmt->format == PIPE_FORMAT_R11G11B10_FLOAT) {
1832 lp_build_r11g11b10_to_float(gallivm, tmps, tmpsoa);
1833 }
1834 else {
1835 lp_build_unpack_rgba_soa(gallivm, src_fmt, dst_type, tmps, tmpsoa);
1836 }
1837 lp_build_transpose_aos(gallivm, dst_type, tmpsoa, &src[i * 4]);
1838 }
1839 return;
1840 }
1841
1842 lp_mem_type_from_format_desc(src_fmt, &mem_type);
1843 lp_blend_type_from_format_desc(src_fmt, &blend_type);
1844
1845 /* Is the format arithmetic */
1846 is_arith = blend_type.length * blend_type.width != mem_type.width * mem_type.length;
1847 is_arith &= !(mem_type.width == 16 && mem_type.floating);
1848
1849 /* Pad if necessary */
1850 if (!is_arith && src_type.length < dst_type.length) {
1851 for (i = 0; i < num_srcs; ++i) {
1852 dst[i] = lp_build_pad_vector(gallivm, src[i], dst_type.length);
1853 }
1854
1855 src_type.length = dst_type.length;
1856 }
1857
1858 /* Special case for half-floats */
1859 if (mem_type.width == 16 && mem_type.floating) {
1860 assert(blend_type.width == 32 && blend_type.floating);
1861 lp_build_conv_auto(gallivm, src_type, &dst_type, dst, num_srcs, dst);
1862 is_arith = false;
1863 }
1864
1865 if (!is_arith) {
1866 return;
1867 }
1868
1869 src_type.width = blend_type.width * blend_type.length;
1870 blend_type.length *= pixels;
1871 src_type.length *= pixels / (src_type.length / mem_type.length);
1872
1873 for (i = 0; i < num_srcs; ++i) {
1874 LLVMValueRef chans[4];
1875 LLVMValueRef res = NULL;
1876
1877 dst[i] = LLVMBuildZExt(builder, src[i], lp_build_vec_type(gallivm, src_type), "");
1878
1879 for (j = 0; j < src_fmt->nr_channels; ++j) {
1880 unsigned mask = 0;
1881 unsigned sa = src_fmt->channel[j].shift;
1882 #if UTIL_ARCH_LITTLE_ENDIAN
1883 unsigned from_lsb = j;
1884 #else
1885 unsigned from_lsb = src_fmt->nr_channels - j - 1;
1886 #endif
1887
1888 mask = (1 << src_fmt->channel[j].size) - 1;
1889
1890 /* Extract bits from source */
1891 chans[j] = LLVMBuildLShr(builder,
1892 dst[i],
1893 lp_build_const_int_vec(gallivm, src_type, sa),
1894 "");
1895
1896 chans[j] = LLVMBuildAnd(builder,
1897 chans[j],
1898 lp_build_const_int_vec(gallivm, src_type, mask),
1899 "");
1900
1901 /* Scale bits */
1902 if (src_type.norm) {
1903 chans[j] = scale_bits(gallivm, src_fmt->channel[j].size,
1904 blend_type.width, chans[j], src_type);
1905 }
1906
1907 /* Insert bits into correct position */
1908 chans[j] = LLVMBuildShl(builder,
1909 chans[j],
1910 lp_build_const_int_vec(gallivm, src_type, from_lsb * blend_type.width),
1911 "");
1912
1913 if (j == 0) {
1914 res = chans[j];
1915 } else {
1916 res = LLVMBuildOr(builder, res, chans[j], "");
1917 }
1918 }
1919
1920 dst[i] = LLVMBuildBitCast(builder, res, lp_build_vec_type(gallivm, blend_type), "");
1921 }
1922 }
1923
1924
1925 /**
1926 * Convert from blending format to memory format
1927 *
1928 * e.g. GL_R3G3B2 is 3 bytes for blending but 1 byte in memory
1929 */
1930 static void
1931 convert_from_blend_type(struct gallivm_state *gallivm,
1932 unsigned block_size,
1933 const struct util_format_description *src_fmt,
1934 struct lp_type src_type,
1935 struct lp_type dst_type,
1936 LLVMValueRef* src, // and dst
1937 unsigned num_srcs)
1938 {
1939 LLVMValueRef* dst = src;
1940 unsigned i, j, k;
1941 struct lp_type mem_type;
1942 struct lp_type blend_type;
1943 LLVMBuilderRef builder = gallivm->builder;
1944 unsigned pixels = block_size / num_srcs;
1945 bool is_arith;
1946
1947 /*
1948 * full custom path for packed floats and srgb formats - none of the later
1949 * functions would do anything useful, and given the lp_type representation they
1950 * can't be fixed. Should really have some SoA blend path for these kind of
1951 * formats rather than hacking them in here.
1952 */
1953 if (format_expands_to_float_soa(src_fmt)) {
1954 /*
1955 * This is pretty suboptimal for this case blending in SoA would be much
1956 * better - we need to transpose the AoS values back to SoA values for
1957 * conversion/packing.
1958 */
1959 assert(src_type.floating);
1960 assert(src_type.width == 32);
1961 assert(src_type.length % 4 == 0);
1962 assert(dst_type.width == 32 || dst_type.width == 16);
1963
1964 for (i = 0; i < num_srcs / 4; i++) {
1965 LLVMValueRef tmpsoa[4], tmpdst;
1966 lp_build_transpose_aos(gallivm, src_type, &src[i * 4], tmpsoa);
1967 /* really really need SoA here */
1968
1969 if (src_fmt->format == PIPE_FORMAT_R11G11B10_FLOAT) {
1970 tmpdst = lp_build_float_to_r11g11b10(gallivm, tmpsoa);
1971 }
1972 else {
1973 tmpdst = lp_build_float_to_srgb_packed(gallivm, src_fmt,
1974 src_type, tmpsoa);
1975 }
1976
1977 if (src_type.length == 8) {
1978 LLVMValueRef tmpaos, shuffles[8];
1979 unsigned j;
1980 /*
1981 * for 8-wide aos transpose has given us wrong order not matching
1982 * output order. HMPF. Also need to split the output values manually.
1983 */
1984 for (j = 0; j < 4; j++) {
1985 shuffles[j * 2] = lp_build_const_int32(gallivm, j);
1986 shuffles[j * 2 + 1] = lp_build_const_int32(gallivm, j + 4);
1987 }
1988 tmpaos = LLVMBuildShuffleVector(builder, tmpdst, tmpdst,
1989 LLVMConstVector(shuffles, 8), "");
1990 src[i * 2] = lp_build_extract_range(gallivm, tmpaos, 0, 4);
1991 src[i * 2 + 1] = lp_build_extract_range(gallivm, tmpaos, 4, 4);
1992 }
1993 else {
1994 src[i] = tmpdst;
1995 }
1996 }
1997 if (dst_type.width == 16) {
1998 struct lp_type type16x8 = dst_type;
1999 struct lp_type type32x4 = dst_type;
2000 LLVMTypeRef ltype16x4, ltypei64, ltypei128;
2001 unsigned num_fetch = src_type.length == 8 ? num_srcs / 2 : num_srcs / 4;
2002 type16x8.length = 8;
2003 type32x4.width = 32;
2004 ltypei128 = LLVMIntTypeInContext(gallivm->context, 128);
2005 ltypei64 = LLVMIntTypeInContext(gallivm->context, 64);
2006 ltype16x4 = lp_build_vec_type(gallivm, dst_type);
2007 /* We could do vector truncation but it doesn't generate very good code */
2008 for (i = 0; i < num_fetch; i++) {
2009 src[i] = lp_build_pack2(gallivm, type32x4, type16x8,
2010 src[i], lp_build_zero(gallivm, type32x4));
2011 src[i] = LLVMBuildBitCast(builder, src[i], ltypei128, "");
2012 src[i] = LLVMBuildTrunc(builder, src[i], ltypei64, "");
2013 src[i] = LLVMBuildBitCast(builder, src[i], ltype16x4, "");
2014 }
2015 }
2016 return;
2017 }
2018
2019 lp_mem_type_from_format_desc(src_fmt, &mem_type);
2020 lp_blend_type_from_format_desc(src_fmt, &blend_type);
2021
2022 is_arith = (blend_type.length * blend_type.width != mem_type.width * mem_type.length);
2023
2024 /* Special case for half-floats */
2025 if (mem_type.width == 16 && mem_type.floating) {
2026 int length = dst_type.length;
2027 assert(blend_type.width == 32 && blend_type.floating);
2028
2029 dst_type.length = src_type.length;
2030
2031 lp_build_conv_auto(gallivm, src_type, &dst_type, dst, num_srcs, dst);
2032
2033 dst_type.length = length;
2034 is_arith = false;
2035 }
2036
2037 /* Remove any padding */
2038 if (!is_arith && (src_type.length % mem_type.length)) {
2039 src_type.length -= (src_type.length % mem_type.length);
2040
2041 for (i = 0; i < num_srcs; ++i) {
2042 dst[i] = lp_build_extract_range(gallivm, dst[i], 0, src_type.length);
2043 }
2044 }
2045
2046 /* No bit arithmetic to do */
2047 if (!is_arith) {
2048 return;
2049 }
2050
2051 src_type.length = pixels;
2052 src_type.width = blend_type.length * blend_type.width;
2053 dst_type.length = pixels;
2054
2055 for (i = 0; i < num_srcs; ++i) {
2056 LLVMValueRef chans[4];
2057 LLVMValueRef res = NULL;
2058
2059 dst[i] = LLVMBuildBitCast(builder, src[i], lp_build_vec_type(gallivm, src_type), "");
2060
2061 for (j = 0; j < src_fmt->nr_channels; ++j) {
2062 unsigned mask = 0;
2063 unsigned sa = src_fmt->channel[j].shift;
2064 unsigned sz_a = src_fmt->channel[j].size;
2065 #if UTIL_ARCH_LITTLE_ENDIAN
2066 unsigned from_lsb = j;
2067 #else
2068 unsigned from_lsb = src_fmt->nr_channels - j - 1;
2069 #endif
2070
2071 assert(blend_type.width > src_fmt->channel[j].size);
2072
2073 for (k = 0; k < blend_type.width; ++k) {
2074 mask |= 1 << k;
2075 }
2076
2077 /* Extract bits */
2078 chans[j] = LLVMBuildLShr(builder,
2079 dst[i],
2080 lp_build_const_int_vec(gallivm, src_type,
2081 from_lsb * blend_type.width),
2082 "");
2083
2084 chans[j] = LLVMBuildAnd(builder,
2085 chans[j],
2086 lp_build_const_int_vec(gallivm, src_type, mask),
2087 "");
2088
2089 /* Scale down bits */
2090 if (src_type.norm) {
2091 chans[j] = scale_bits(gallivm, blend_type.width,
2092 src_fmt->channel[j].size, chans[j], src_type);
2093 } else if (!src_type.floating && sz_a < blend_type.width) {
2094 LLVMValueRef mask_val = lp_build_const_int_vec(gallivm, src_type, (1UL << sz_a) - 1);
2095 LLVMValueRef mask = LLVMBuildICmp(builder, LLVMIntUGT, chans[j], mask_val, "");
2096 chans[j] = LLVMBuildSelect(builder, mask, mask_val, chans[j], "");
2097 }
2098
2099 /* Insert bits */
2100 chans[j] = LLVMBuildShl(builder,
2101 chans[j],
2102 lp_build_const_int_vec(gallivm, src_type, sa),
2103 "");
2104
2105 sa += src_fmt->channel[j].size;
2106
2107 if (j == 0) {
2108 res = chans[j];
2109 } else {
2110 res = LLVMBuildOr(builder, res, chans[j], "");
2111 }
2112 }
2113
2114 assert (dst_type.width != 24);
2115
2116 dst[i] = LLVMBuildTrunc(builder, res, lp_build_vec_type(gallivm, dst_type), "");
2117 }
2118 }
2119
2120
2121 /**
2122 * Convert alpha to same blend type as src
2123 */
2124 static void
2125 convert_alpha(struct gallivm_state *gallivm,
2126 struct lp_type row_type,
2127 struct lp_type alpha_type,
2128 const unsigned block_size,
2129 const unsigned block_height,
2130 const unsigned src_count,
2131 const unsigned dst_channels,
2132 const bool pad_inline,
2133 LLVMValueRef* src_alpha)
2134 {
2135 LLVMBuilderRef builder = gallivm->builder;
2136 unsigned i, j;
2137 unsigned length = row_type.length;
2138 row_type.length = alpha_type.length;
2139
2140 /* Twiddle the alpha to match pixels */
2141 lp_bld_quad_twiddle(gallivm, alpha_type, src_alpha, block_height, src_alpha);
2142
2143 /*
2144 * TODO this should use single lp_build_conv call for
2145 * src_count == 1 && dst_channels == 1 case (dropping the concat below)
2146 */
2147 for (i = 0; i < block_height; ++i) {
2148 lp_build_conv(gallivm, alpha_type, row_type, &src_alpha[i], 1, &src_alpha[i], 1);
2149 }
2150
2151 alpha_type = row_type;
2152 row_type.length = length;
2153
2154 /* If only one channel we can only need the single alpha value per pixel */
2155 if (src_count == 1 && dst_channels == 1) {
2156
2157 lp_build_concat_n(gallivm, alpha_type, src_alpha, block_height, src_alpha, src_count);
2158 } else {
2159 /* If there are more srcs than rows then we need to split alpha up */
2160 if (src_count > block_height) {
2161 for (i = src_count; i > 0; --i) {
2162 unsigned pixels = block_size / src_count;
2163 unsigned idx = i - 1;
2164
2165 src_alpha[idx] = lp_build_extract_range(gallivm, src_alpha[(idx * pixels) / 4],
2166 (idx * pixels) % 4, pixels);
2167 }
2168 }
2169
2170 /* If there is a src for each pixel broadcast the alpha across whole row */
2171 if (src_count == block_size) {
2172 for (i = 0; i < src_count; ++i) {
2173 src_alpha[i] = lp_build_broadcast(gallivm,
2174 lp_build_vec_type(gallivm, row_type), src_alpha[i]);
2175 }
2176 } else {
2177 unsigned pixels = block_size / src_count;
2178 unsigned channels = pad_inline ? TGSI_NUM_CHANNELS : dst_channels;
2179 unsigned alpha_span = 1;
2180 LLVMValueRef shuffles[LP_MAX_VECTOR_LENGTH];
2181
2182 /* Check if we need 2 src_alphas for our shuffles */
2183 if (pixels > alpha_type.length) {
2184 alpha_span = 2;
2185 }
2186
2187 /* Broadcast alpha across all channels, e.g. a1a2 to a1a1a1a1a2a2a2a2 */
2188 for (j = 0; j < row_type.length; ++j) {
2189 if (j < pixels * channels) {
2190 shuffles[j] = lp_build_const_int32(gallivm, j / channels);
2191 } else {
2192 shuffles[j] = LLVMGetUndef(LLVMInt32TypeInContext(gallivm->context));
2193 }
2194 }
2195
2196 for (i = 0; i < src_count; ++i) {
2197 unsigned idx1 = i, idx2 = i;
2198
2199 if (alpha_span > 1){
2200 idx1 *= alpha_span;
2201 idx2 = idx1 + 1;
2202 }
2203
2204 src_alpha[i] = LLVMBuildShuffleVector(builder,
2205 src_alpha[idx1],
2206 src_alpha[idx2],
2207 LLVMConstVector(shuffles, row_type.length),
2208 "");
2209 }
2210 }
2211 }
2212 }
2213
2214
2215 /**
2216 * Generates the blend function for unswizzled colour buffers
2217 * Also generates the read & write from colour buffer
2218 */
2219 static void
2220 generate_unswizzled_blend(struct gallivm_state *gallivm,
2221 unsigned rt,
2222 struct lp_fragment_shader_variant *variant,
2223 enum pipe_format out_format,
2224 unsigned int num_fs,
2225 struct lp_type fs_type,
2226 LLVMValueRef* fs_mask,
2227 LLVMValueRef fs_out_color[PIPE_MAX_COLOR_BUFS][TGSI_NUM_CHANNELS][4],
2228 LLVMValueRef context_ptr,
2229 LLVMValueRef color_ptr,
2230 LLVMValueRef stride,
2231 unsigned partial_mask,
2232 boolean do_branch)
2233 {
2234 const unsigned alpha_channel = 3;
2235 const unsigned block_width = LP_RASTER_BLOCK_SIZE;
2236 const unsigned block_height = LP_RASTER_BLOCK_SIZE;
2237 const unsigned block_size = block_width * block_height;
2238 const unsigned lp_integer_vector_width = 128;
2239
2240 LLVMBuilderRef builder = gallivm->builder;
2241 LLVMValueRef fs_src[4][TGSI_NUM_CHANNELS];
2242 LLVMValueRef fs_src1[4][TGSI_NUM_CHANNELS];
2243 LLVMValueRef src_alpha[4 * 4];
2244 LLVMValueRef src1_alpha[4 * 4] = { NULL };
2245 LLVMValueRef src_mask[4 * 4];
2246 LLVMValueRef src[4 * 4];
2247 LLVMValueRef src1[4 * 4];
2248 LLVMValueRef dst[4 * 4];
2249 LLVMValueRef blend_color;
2250 LLVMValueRef blend_alpha;
2251 LLVMValueRef i32_zero;
2252 LLVMValueRef check_mask;
2253 LLVMValueRef undef_src_val;
2254
2255 struct lp_build_mask_context mask_ctx;
2256 struct lp_type mask_type;
2257 struct lp_type blend_type;
2258 struct lp_type row_type;
2259 struct lp_type dst_type;
2260 struct lp_type ls_type;
2261
2262 unsigned char swizzle[TGSI_NUM_CHANNELS];
2263 unsigned vector_width;
2264 unsigned src_channels = TGSI_NUM_CHANNELS;
2265 unsigned dst_channels;
2266 unsigned dst_count;
2267 unsigned src_count;
2268 unsigned i, j;
2269
2270 const struct util_format_description* out_format_desc = util_format_description(out_format);
2271
2272 unsigned dst_alignment;
2273
2274 bool pad_inline = is_arithmetic_format(out_format_desc);
2275 bool has_alpha = false;
2276 const boolean dual_source_blend = variant->key.blend.rt[0].blend_enable &&
2277 util_blend_state_is_dual(&variant->key.blend, 0);
2278
2279 const boolean is_1d = variant->key.resource_1d;
2280 boolean twiddle_after_convert = FALSE;
2281 unsigned num_fullblock_fs = is_1d ? 2 * num_fs : num_fs;
2282 LLVMValueRef fpstate = 0;
2283
2284 /* Get type from output format */
2285 lp_blend_type_from_format_desc(out_format_desc, &row_type);
2286 lp_mem_type_from_format_desc(out_format_desc, &dst_type);
2287
2288 /*
2289 * Technically this code should go into lp_build_smallfloat_to_float
2290 * and lp_build_float_to_smallfloat but due to the
2291 * http://llvm.org/bugs/show_bug.cgi?id=6393
2292 * llvm reorders the mxcsr intrinsics in a way that breaks the code.
2293 * So the ordering is important here and there shouldn't be any
2294 * llvm ir instrunctions in this function before
2295 * this, otherwise half-float format conversions won't work
2296 * (again due to llvm bug #6393).
2297 */
2298 if (have_smallfloat_format(dst_type, out_format)) {
2299 /* We need to make sure that denorms are ok for half float
2300 conversions */
2301 fpstate = lp_build_fpstate_get(gallivm);
2302 lp_build_fpstate_set_denorms_zero(gallivm, FALSE);
2303 }
2304
2305 mask_type = lp_int32_vec4_type();
2306 mask_type.length = fs_type.length;
2307
2308 for (i = num_fs; i < num_fullblock_fs; i++) {
2309 fs_mask[i] = lp_build_zero(gallivm, mask_type);
2310 }
2311
2312 /* Do not bother executing code when mask is empty.. */
2313 if (do_branch) {
2314 check_mask = LLVMConstNull(lp_build_int_vec_type(gallivm, mask_type));
2315
2316 for (i = 0; i < num_fullblock_fs; ++i) {
2317 check_mask = LLVMBuildOr(builder, check_mask, fs_mask[i], "");
2318 }
2319
2320 lp_build_mask_begin(&mask_ctx, gallivm, mask_type, check_mask);
2321 lp_build_mask_check(&mask_ctx);
2322 }
2323
2324 partial_mask |= !variant->opaque;
2325 i32_zero = lp_build_const_int32(gallivm, 0);
2326
2327 undef_src_val = lp_build_undef(gallivm, fs_type);
2328
2329 row_type.length = fs_type.length;
2330 vector_width = dst_type.floating ? lp_native_vector_width : lp_integer_vector_width;
2331
2332 /* Compute correct swizzle and count channels */
2333 memset(swizzle, LP_BLD_SWIZZLE_DONTCARE, TGSI_NUM_CHANNELS);
2334 dst_channels = 0;
2335
2336 for (i = 0; i < TGSI_NUM_CHANNELS; ++i) {
2337 /* Ensure channel is used */
2338 if (out_format_desc->swizzle[i] >= TGSI_NUM_CHANNELS) {
2339 continue;
2340 }
2341
2342 /* Ensure not already written to (happens in case with GL_ALPHA) */
2343 if (swizzle[out_format_desc->swizzle[i]] < TGSI_NUM_CHANNELS) {
2344 continue;
2345 }
2346
2347 /* Ensure we havn't already found all channels */
2348 if (dst_channels >= out_format_desc->nr_channels) {
2349 continue;
2350 }
2351
2352 swizzle[out_format_desc->swizzle[i]] = i;
2353 ++dst_channels;
2354
2355 if (i == alpha_channel) {
2356 has_alpha = true;
2357 }
2358 }
2359
2360 if (format_expands_to_float_soa(out_format_desc)) {
2361 /*
2362 * the code above can't work for layout_other
2363 * for srgb it would sort of work but we short-circuit swizzles, etc.
2364 * as that is done as part of unpack / pack.
2365 */
2366 dst_channels = 4; /* HACK: this is fake 4 really but need it due to transpose stuff later */
2367 has_alpha = true;
2368 swizzle[0] = 0;
2369 swizzle[1] = 1;
2370 swizzle[2] = 2;
2371 swizzle[3] = 3;
2372 pad_inline = true; /* HACK: prevent rgbxrgbx->rgbrgbxx conversion later */
2373 }
2374
2375 /* If 3 channels then pad to include alpha for 4 element transpose */
2376 if (dst_channels == 3) {
2377 assert (!has_alpha);
2378 for (i = 0; i < TGSI_NUM_CHANNELS; i++) {
2379 if (swizzle[i] > TGSI_NUM_CHANNELS)
2380 swizzle[i] = 3;
2381 }
2382 if (out_format_desc->nr_channels == 4) {
2383 dst_channels = 4;
2384 /*
2385 * We use alpha from the color conversion, not separate one.
2386 * We had to include it for transpose, hence it will get converted
2387 * too (albeit when doing transpose after conversion, that would
2388 * no longer be the case necessarily).
2389 * (It works only with 4 channel dsts, e.g. rgbx formats, because
2390 * otherwise we really have padding, not alpha, included.)
2391 */
2392 has_alpha = true;
2393 }
2394 }
2395
2396 /*
2397 * Load shader output
2398 */
2399 for (i = 0; i < num_fullblock_fs; ++i) {
2400 /* Always load alpha for use in blending */
2401 LLVMValueRef alpha;
2402 if (i < num_fs) {
2403 alpha = LLVMBuildLoad(builder, fs_out_color[rt][alpha_channel][i], "");
2404 }
2405 else {
2406 alpha = undef_src_val;
2407 }
2408
2409 /* Load each channel */
2410 for (j = 0; j < dst_channels; ++j) {
2411 assert(swizzle[j] < 4);
2412 if (i < num_fs) {
2413 fs_src[i][j] = LLVMBuildLoad(builder, fs_out_color[rt][swizzle[j]][i], "");
2414 }
2415 else {
2416 fs_src[i][j] = undef_src_val;
2417 }
2418 }
2419
2420 /* If 3 channels then pad to include alpha for 4 element transpose */
2421 /*
2422 * XXX If we include that here maybe could actually use it instead of
2423 * separate alpha for blending?
2424 * (Difficult though we actually convert pad channels, not alpha.)
2425 */
2426 if (dst_channels == 3 && !has_alpha) {
2427 fs_src[i][3] = alpha;
2428 }
2429
2430 /* We split the row_mask and row_alpha as we want 128bit interleave */
2431 if (fs_type.length == 8) {
2432 src_mask[i*2 + 0] = lp_build_extract_range(gallivm, fs_mask[i],
2433 0, src_channels);
2434 src_mask[i*2 + 1] = lp_build_extract_range(gallivm, fs_mask[i],
2435 src_channels, src_channels);
2436
2437 src_alpha[i*2 + 0] = lp_build_extract_range(gallivm, alpha, 0, src_channels);
2438 src_alpha[i*2 + 1] = lp_build_extract_range(gallivm, alpha,
2439 src_channels, src_channels);
2440 } else {
2441 src_mask[i] = fs_mask[i];
2442 src_alpha[i] = alpha;
2443 }
2444 }
2445 if (dual_source_blend) {
2446 /* same as above except different src/dst, skip masks and comments... */
2447 for (i = 0; i < num_fullblock_fs; ++i) {
2448 LLVMValueRef alpha;
2449 if (i < num_fs) {
2450 alpha = LLVMBuildLoad(builder, fs_out_color[1][alpha_channel][i], "");
2451 }
2452 else {
2453 alpha = undef_src_val;
2454 }
2455
2456 for (j = 0; j < dst_channels; ++j) {
2457 assert(swizzle[j] < 4);
2458 if (i < num_fs) {
2459 fs_src1[i][j] = LLVMBuildLoad(builder, fs_out_color[1][swizzle[j]][i], "");
2460 }
2461 else {
2462 fs_src1[i][j] = undef_src_val;
2463 }
2464 }
2465 if (dst_channels == 3 && !has_alpha) {
2466 fs_src1[i][3] = alpha;
2467 }
2468 if (fs_type.length == 8) {
2469 src1_alpha[i*2 + 0] = lp_build_extract_range(gallivm, alpha, 0, src_channels);
2470 src1_alpha[i*2 + 1] = lp_build_extract_range(gallivm, alpha,
2471 src_channels, src_channels);
2472 } else {
2473 src1_alpha[i] = alpha;
2474 }
2475 }
2476 }
2477
2478 if (util_format_is_pure_integer(out_format)) {
2479 /*
2480 * In this case fs_type was really ints or uints disguised as floats,
2481 * fix that up now.
2482 */
2483 fs_type.floating = 0;
2484 fs_type.sign = dst_type.sign;
2485 for (i = 0; i < num_fullblock_fs; ++i) {
2486 for (j = 0; j < dst_channels; ++j) {
2487 fs_src[i][j] = LLVMBuildBitCast(builder, fs_src[i][j],
2488 lp_build_vec_type(gallivm, fs_type), "");
2489 }
2490 if (dst_channels == 3 && !has_alpha) {
2491 fs_src[i][3] = LLVMBuildBitCast(builder, fs_src[i][3],
2492 lp_build_vec_type(gallivm, fs_type), "");
2493 }
2494 }
2495 }
2496
2497 /*
2498 * We actually should generally do conversion first (for non-1d cases)
2499 * when the blend format is 8 or 16 bits. The reason is obvious,
2500 * there's 2 or 4 times less vectors to deal with for the interleave...
2501 * Albeit for the AVX (not AVX2) case there's no benefit with 16 bit
2502 * vectors (as it can do 32bit unpack with 256bit vectors, but 8/16bit
2503 * unpack only with 128bit vectors).
2504 * Note: for 16bit sizes really need matching pack conversion code
2505 */
2506 if (!is_1d && dst_channels != 3 && dst_type.width == 8) {
2507 twiddle_after_convert = TRUE;
2508 }
2509
2510 /*
2511 * Pixel twiddle from fragment shader order to memory order
2512 */
2513 if (!twiddle_after_convert) {
2514 src_count = generate_fs_twiddle(gallivm, fs_type, num_fullblock_fs,
2515 dst_channels, fs_src, src, pad_inline);
2516 if (dual_source_blend) {
2517 generate_fs_twiddle(gallivm, fs_type, num_fullblock_fs, dst_channels,
2518 fs_src1, src1, pad_inline);
2519 }
2520 } else {
2521 src_count = num_fullblock_fs * dst_channels;
2522 /*
2523 * We reorder things a bit here, so the cases for 4-wide and 8-wide
2524 * (AVX) turn out the same later when untwiddling/transpose (albeit
2525 * for true AVX2 path untwiddle needs to be different).
2526 * For now just order by colors first (so we can use unpack later).
2527 */
2528 for (j = 0; j < num_fullblock_fs; j++) {
2529 for (i = 0; i < dst_channels; i++) {
2530 src[i*num_fullblock_fs + j] = fs_src[j][i];
2531 if (dual_source_blend) {
2532 src1[i*num_fullblock_fs + j] = fs_src1[j][i];
2533 }
2534 }
2535 }
2536 }
2537
2538 src_channels = dst_channels < 3 ? dst_channels : 4;
2539 if (src_count != num_fullblock_fs * src_channels) {
2540 unsigned ds = src_count / (num_fullblock_fs * src_channels);
2541 row_type.length /= ds;
2542 fs_type.length = row_type.length;
2543 }
2544
2545 blend_type = row_type;
2546 mask_type.length = 4;
2547
2548 /* Convert src to row_type */
2549 if (dual_source_blend) {
2550 struct lp_type old_row_type = row_type;
2551 lp_build_conv_auto(gallivm, fs_type, &row_type, src, src_count, src);
2552 src_count = lp_build_conv_auto(gallivm, fs_type, &old_row_type, src1, src_count, src1);
2553 }
2554 else {
2555 src_count = lp_build_conv_auto(gallivm, fs_type, &row_type, src, src_count, src);
2556 }
2557
2558 /* If the rows are not an SSE vector, combine them to become SSE size! */
2559 if ((row_type.width * row_type.length) % 128) {
2560 unsigned bits = row_type.width * row_type.length;
2561 unsigned combined;
2562
2563 assert(src_count >= (vector_width / bits));
2564
2565 dst_count = src_count / (vector_width / bits);
2566
2567 combined = lp_build_concat_n(gallivm, row_type, src, src_count, src, dst_count);
2568 if (dual_source_blend) {
2569 lp_build_concat_n(gallivm, row_type, src1, src_count, src1, dst_count);
2570 }
2571
2572 row_type.length *= combined;
2573 src_count /= combined;
2574
2575 bits = row_type.width * row_type.length;
2576 assert(bits == 128 || bits == 256);
2577 }
2578
2579 if (twiddle_after_convert) {
2580 fs_twiddle_transpose(gallivm, row_type, src, src_count, src);
2581 if (dual_source_blend) {
2582 fs_twiddle_transpose(gallivm, row_type, src1, src_count, src1);
2583 }
2584 }
2585
2586 /*
2587 * Blend Colour conversion
2588 */
2589 blend_color = lp_jit_context_f_blend_color(gallivm, context_ptr);
2590 blend_color = LLVMBuildPointerCast(builder, blend_color,
2591 LLVMPointerType(lp_build_vec_type(gallivm, fs_type), 0), "");
2592 blend_color = LLVMBuildLoad(builder, LLVMBuildGEP(builder, blend_color,
2593 &i32_zero, 1, ""), "");
2594
2595 /* Convert */
2596 lp_build_conv(gallivm, fs_type, blend_type, &blend_color, 1, &blend_color, 1);
2597
2598 if (out_format_desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB) {
2599 /*
2600 * since blending is done with floats, there was no conversion.
2601 * However, the rules according to fixed point renderbuffers still
2602 * apply, that is we must clamp inputs to 0.0/1.0.
2603 * (This would apply to separate alpha conversion too but we currently
2604 * force has_alpha to be true.)
2605 * TODO: should skip this with "fake" blend, since post-blend conversion
2606 * will clamp anyway.
2607 * TODO: could also skip this if fragment color clamping is enabled. We
2608 * don't support it natively so it gets baked into the shader however, so
2609 * can't really tell here.
2610 */
2611 struct lp_build_context f32_bld;
2612 assert(row_type.floating);
2613 lp_build_context_init(&f32_bld, gallivm, row_type);
2614 for (i = 0; i < src_count; i++) {
2615 src[i] = lp_build_clamp_zero_one_nanzero(&f32_bld, src[i]);
2616 }
2617 if (dual_source_blend) {
2618 for (i = 0; i < src_count; i++) {
2619 src1[i] = lp_build_clamp_zero_one_nanzero(&f32_bld, src1[i]);
2620 }
2621 }
2622 /* probably can't be different than row_type but better safe than sorry... */
2623 lp_build_context_init(&f32_bld, gallivm, blend_type);
2624 blend_color = lp_build_clamp(&f32_bld, blend_color, f32_bld.zero, f32_bld.one);
2625 }
2626
2627 /* Extract alpha */
2628 blend_alpha = lp_build_extract_broadcast(gallivm, blend_type, row_type, blend_color, lp_build_const_int32(gallivm, 3));
2629
2630 /* Swizzle to appropriate channels, e.g. from RGBA to BGRA BGRA */
2631 pad_inline &= (dst_channels * (block_size / src_count) * row_type.width) != vector_width;
2632 if (pad_inline) {
2633 /* Use all 4 channels e.g. from RGBA RGBA to RGxx RGxx */
2634 blend_color = lp_build_swizzle_aos_n(gallivm, blend_color, swizzle, TGSI_NUM_CHANNELS, row_type.length);
2635 } else {
2636 /* Only use dst_channels e.g. RGBA RGBA to RG RG xxxx */
2637 blend_color = lp_build_swizzle_aos_n(gallivm, blend_color, swizzle, dst_channels, row_type.length);
2638 }
2639
2640 /*
2641 * Mask conversion
2642 */
2643 lp_bld_quad_twiddle(gallivm, mask_type, &src_mask[0], block_height, &src_mask[0]);
2644
2645 if (src_count < block_height) {
2646 lp_build_concat_n(gallivm, mask_type, src_mask, 4, src_mask, src_count);
2647 } else if (src_count > block_height) {
2648 for (i = src_count; i > 0; --i) {
2649 unsigned pixels = block_size / src_count;
2650 unsigned idx = i - 1;
2651
2652 src_mask[idx] = lp_build_extract_range(gallivm, src_mask[(idx * pixels) / 4],
2653 (idx * pixels) % 4, pixels);
2654 }
2655 }
2656
2657 assert(mask_type.width == 32);
2658
2659 for (i = 0; i < src_count; ++i) {
2660 unsigned pixels = block_size / src_count;
2661 unsigned pixel_width = row_type.width * dst_channels;
2662
2663 if (pixel_width == 24) {
2664 mask_type.width = 8;
2665 mask_type.length = vector_width / mask_type.width;
2666 } else {
2667 mask_type.length = pixels;
2668 mask_type.width = row_type.width * dst_channels;
2669
2670 /*
2671 * If mask_type width is smaller than 32bit, this doesn't quite
2672 * generate the most efficient code (could use some pack).
2673 */
2674 src_mask[i] = LLVMBuildIntCast(builder, src_mask[i],
2675 lp_build_int_vec_type(gallivm, mask_type), "");
2676
2677 mask_type.length *= dst_channels;
2678 mask_type.width /= dst_channels;
2679 }
2680
2681 src_mask[i] = LLVMBuildBitCast(builder, src_mask[i],
2682 lp_build_int_vec_type(gallivm, mask_type), "");
2683 src_mask[i] = lp_build_pad_vector(gallivm, src_mask[i], row_type.length);
2684 }
2685
2686 /*
2687 * Alpha conversion
2688 */
2689 if (!has_alpha) {
2690 struct lp_type alpha_type = fs_type;
2691 alpha_type.length = 4;
2692 convert_alpha(gallivm, row_type, alpha_type,
2693 block_size, block_height,
2694 src_count, dst_channels,
2695 pad_inline, src_alpha);
2696 if (dual_source_blend) {
2697 convert_alpha(gallivm, row_type, alpha_type,
2698 block_size, block_height,
2699 src_count, dst_channels,
2700 pad_inline, src1_alpha);
2701 }
2702 }
2703
2704
2705 /*
2706 * Load dst from memory
2707 */
2708 if (src_count < block_height) {
2709 dst_count = block_height;
2710 } else {
2711 dst_count = src_count;
2712 }
2713
2714 dst_type.length *= block_size / dst_count;
2715
2716 if (format_expands_to_float_soa(out_format_desc)) {
2717 /*
2718 * we need multiple values at once for the conversion, so can as well
2719 * load them vectorized here too instead of concatenating later.
2720 * (Still need concatenation later for 8-wide vectors).
2721 */
2722 dst_count = block_height;
2723 dst_type.length = block_width;
2724 }
2725
2726 /*
2727 * Compute the alignment of the destination pointer in bytes
2728 * We fetch 1-4 pixels, if the format has pot alignment then those fetches
2729 * are always aligned by MIN2(16, fetch_width) except for buffers (not
2730 * 1d tex but can't distinguish here) so need to stick with per-pixel
2731 * alignment in this case.
2732 */
2733 if (is_1d) {
2734 dst_alignment = (out_format_desc->block.bits + 7)/(out_format_desc->block.width * 8);
2735 }
2736 else {
2737 dst_alignment = dst_type.length * dst_type.width / 8;
2738 }
2739 /* Force power-of-two alignment by extracting only the least-significant-bit */
2740 dst_alignment = 1 << (ffs(dst_alignment) - 1);
2741 /*
2742 * Resource base and stride pointers are aligned to 16 bytes, so that's
2743 * the maximum alignment we can guarantee
2744 */
2745 dst_alignment = MIN2(16, dst_alignment);
2746
2747 ls_type = dst_type;
2748
2749 if (dst_count > src_count) {
2750 if ((dst_type.width == 8 || dst_type.width == 16) &&
2751 util_is_power_of_two_or_zero(dst_type.length) &&
2752 dst_type.length * dst_type.width < 128) {
2753 /*
2754 * Never try to load values as 4xi8 which we will then
2755 * concatenate to larger vectors. This gives llvm a real
2756 * headache (the problem is the type legalizer (?) will
2757 * try to load that as 4xi8 zext to 4xi32 to fill the vector,
2758 * then the shuffles to concatenate are more or less impossible
2759 * - llvm is easily capable of generating a sequence of 32
2760 * pextrb/pinsrb instructions for that. Albeit it appears to
2761 * be fixed in llvm 4.0. So, load and concatenate with 32bit
2762 * width to avoid the trouble (16bit seems not as bad, llvm
2763 * probably recognizes the load+shuffle as only one shuffle
2764 * is necessary, but we can do just the same anyway).
2765 */
2766 ls_type.length = dst_type.length * dst_type.width / 32;
2767 ls_type.width = 32;
2768 }
2769 }
2770
2771 if (is_1d) {
2772 load_unswizzled_block(gallivm, color_ptr, stride, block_width, 1,
2773 dst, ls_type, dst_count / 4, dst_alignment, NULL, NULL, false);
2774 for (i = dst_count / 4; i < dst_count; i++) {
2775 dst[i] = lp_build_undef(gallivm, ls_type);
2776 }
2777
2778 }
2779 else {
2780 load_unswizzled_block(gallivm, color_ptr, stride, block_width, block_height,
2781 dst, ls_type, dst_count, dst_alignment, NULL, NULL, false);
2782 }
2783
2784
2785 /*
2786 * Convert from dst/output format to src/blending format.
2787 *
2788 * This is necessary as we can only read 1 row from memory at a time,
2789 * so the minimum dst_count will ever be at this point is 4.
2790 *
2791 * With, for example, R8 format you can have all 16 pixels in a 128 bit vector,
2792 * this will take the 4 dsts and combine them into 1 src so we can perform blending
2793 * on all 16 pixels in that single vector at once.
2794 */
2795 if (dst_count > src_count) {
2796 if (ls_type.length != dst_type.length && ls_type.length == 1) {
2797 LLVMTypeRef elem_type = lp_build_elem_type(gallivm, ls_type);
2798 LLVMTypeRef ls_vec_type = LLVMVectorType(elem_type, 1);
2799 for (i = 0; i < dst_count; i++) {
2800 dst[i] = LLVMBuildBitCast(builder, dst[i], ls_vec_type, "");
2801 }
2802 }
2803
2804 lp_build_concat_n(gallivm, ls_type, dst, 4, dst, src_count);
2805
2806 if (ls_type.length != dst_type.length) {
2807 struct lp_type tmp_type = dst_type;
2808 tmp_type.length = dst_type.length * 4 / src_count;
2809 for (i = 0; i < src_count; i++) {
2810 dst[i] = LLVMBuildBitCast(builder, dst[i],
2811 lp_build_vec_type(gallivm, tmp_type), "");
2812 }
2813 }
2814 }
2815
2816 /*
2817 * Blending
2818 */
2819 /* XXX this is broken for RGB8 formats -
2820 * they get expanded from 12 to 16 elements (to include alpha)
2821 * by convert_to_blend_type then reduced to 15 instead of 12
2822 * by convert_from_blend_type (a simple fix though breaks A8...).
2823 * R16G16B16 also crashes differently however something going wrong
2824 * inside llvm handling npot vector sizes seemingly.
2825 * It seems some cleanup could be done here (like skipping conversion/blend
2826 * when not needed).
2827 */
2828 convert_to_blend_type(gallivm, block_size, out_format_desc, dst_type,
2829 row_type, dst, src_count);
2830
2831 /*
2832 * FIXME: Really should get logic ops / masks out of generic blend / row
2833 * format. Logic ops will definitely not work on the blend float format
2834 * used for SRGB here and I think OpenGL expects this to work as expected
2835 * (that is incoming values converted to srgb then logic op applied).
2836 */
2837 for (i = 0; i < src_count; ++i) {
2838 dst[i] = lp_build_blend_aos(gallivm,
2839 &variant->key.blend,
2840 out_format,
2841 row_type,
2842 rt,
2843 src[i],
2844 has_alpha ? NULL : src_alpha[i],
2845 src1[i],
2846 has_alpha ? NULL : src1_alpha[i],
2847 dst[i],
2848 partial_mask ? src_mask[i] : NULL,
2849 blend_color,
2850 has_alpha ? NULL : blend_alpha,
2851 swizzle,
2852 pad_inline ? 4 : dst_channels);
2853 }
2854
2855 convert_from_blend_type(gallivm, block_size, out_format_desc,
2856 row_type, dst_type, dst, src_count);
2857
2858 /* Split the blend rows back to memory rows */
2859 if (dst_count > src_count) {
2860 row_type.length = dst_type.length * (dst_count / src_count);
2861
2862 if (src_count == 1) {
2863 dst[1] = lp_build_extract_range(gallivm, dst[0], row_type.length / 2, row_type.length / 2);
2864 dst[0] = lp_build_extract_range(gallivm, dst[0], 0, row_type.length / 2);
2865
2866 row_type.length /= 2;
2867 src_count *= 2;
2868 }
2869
2870 dst[3] = lp_build_extract_range(gallivm, dst[1], row_type.length / 2, row_type.length / 2);
2871 dst[2] = lp_build_extract_range(gallivm, dst[1], 0, row_type.length / 2);
2872 dst[1] = lp_build_extract_range(gallivm, dst[0], row_type.length / 2, row_type.length / 2);
2873 dst[0] = lp_build_extract_range(gallivm, dst[0], 0, row_type.length / 2);
2874
2875 row_type.length /= 2;
2876 src_count *= 2;
2877 }
2878
2879 /*
2880 * Store blend result to memory
2881 */
2882 if (is_1d) {
2883 store_unswizzled_block(gallivm, color_ptr, stride, block_width, 1,
2884 dst, dst_type, dst_count / 4, dst_alignment);
2885 }
2886 else {
2887 store_unswizzled_block(gallivm, color_ptr, stride, block_width, block_height,
2888 dst, dst_type, dst_count, dst_alignment);
2889 }
2890
2891 if (have_smallfloat_format(dst_type, out_format)) {
2892 lp_build_fpstate_set(gallivm, fpstate);
2893 }
2894
2895 if (do_branch) {
2896 lp_build_mask_end(&mask_ctx);
2897 }
2898 }
2899
2900
2901 /**
2902 * Generate the runtime callable function for the whole fragment pipeline.
2903 * Note that the function which we generate operates on a block of 16
2904 * pixels at at time. The block contains 2x2 quads. Each quad contains
2905 * 2x2 pixels.
2906 */
2907 static void
2908 generate_fragment(struct llvmpipe_context *lp,
2909 struct lp_fragment_shader *shader,
2910 struct lp_fragment_shader_variant *variant,
2911 unsigned partial_mask)
2912 {
2913 struct gallivm_state *gallivm = variant->gallivm;
2914 struct lp_fragment_shader_variant_key *key = &variant->key;
2915 struct lp_shader_input inputs[PIPE_MAX_SHADER_INPUTS];
2916 char func_name[64];
2917 struct lp_type fs_type;
2918 struct lp_type blend_type;
2919 LLVMTypeRef fs_elem_type;
2920 LLVMTypeRef blend_vec_type;
2921 LLVMTypeRef arg_types[15];
2922 LLVMTypeRef func_type;
2923 LLVMTypeRef int32_type = LLVMInt32TypeInContext(gallivm->context);
2924 LLVMTypeRef int8_type = LLVMInt8TypeInContext(gallivm->context);
2925 LLVMValueRef context_ptr;
2926 LLVMValueRef x;
2927 LLVMValueRef y;
2928 LLVMValueRef a0_ptr;
2929 LLVMValueRef dadx_ptr;
2930 LLVMValueRef dady_ptr;
2931 LLVMValueRef color_ptr_ptr;
2932 LLVMValueRef stride_ptr;
2933 LLVMValueRef color_sample_stride_ptr;
2934 LLVMValueRef depth_ptr;
2935 LLVMValueRef depth_stride;
2936 LLVMValueRef depth_sample_stride;
2937 LLVMValueRef mask_input;
2938 LLVMValueRef thread_data_ptr;
2939 LLVMBasicBlockRef block;
2940 LLVMBuilderRef builder;
2941 struct lp_build_sampler_soa *sampler;
2942 struct lp_build_image_soa *image;
2943 struct lp_build_interp_soa_context interp;
2944 LLVMValueRef fs_mask[(16 / 4) * LP_MAX_SAMPLES];
2945 LLVMValueRef fs_out_color[LP_MAX_SAMPLES][PIPE_MAX_COLOR_BUFS][TGSI_NUM_CHANNELS][16 / 4];
2946 LLVMValueRef function;
2947 LLVMValueRef facing;
2948 unsigned num_fs;
2949 unsigned i;
2950 unsigned chan;
2951 unsigned cbuf;
2952 boolean cbuf0_write_all;
2953 const boolean dual_source_blend = key->blend.rt[0].blend_enable &&
2954 util_blend_state_is_dual(&key->blend, 0);
2955
2956 assert(lp_native_vector_width / 32 >= 4);
2957
2958 /* Adjust color input interpolation according to flatshade state:
2959 */
2960 memcpy(inputs, shader->inputs, shader->info.base.num_inputs * sizeof inputs[0]);
2961 for (i = 0; i < shader->info.base.num_inputs; i++) {
2962 if (inputs[i].interp == LP_INTERP_COLOR) {
2963 if (key->flatshade)
2964 inputs[i].interp = LP_INTERP_CONSTANT;
2965 else
2966 inputs[i].interp = LP_INTERP_PERSPECTIVE;
2967 }
2968 }
2969
2970 /* check if writes to cbuf[0] are to be copied to all cbufs */
2971 cbuf0_write_all =
2972 shader->info.base.properties[TGSI_PROPERTY_FS_COLOR0_WRITES_ALL_CBUFS];
2973
2974 /* TODO: actually pick these based on the fs and color buffer
2975 * characteristics. */
2976
2977 memset(&fs_type, 0, sizeof fs_type);
2978 fs_type.floating = TRUE; /* floating point values */
2979 fs_type.sign = TRUE; /* values are signed */
2980 fs_type.norm = FALSE; /* values are not limited to [0,1] or [-1,1] */
2981 fs_type.width = 32; /* 32-bit float */
2982 fs_type.length = MIN2(lp_native_vector_width / 32, 16); /* n*4 elements per vector */
2983
2984 memset(&blend_type, 0, sizeof blend_type);
2985 blend_type.floating = FALSE; /* values are integers */
2986 blend_type.sign = FALSE; /* values are unsigned */
2987 blend_type.norm = TRUE; /* values are in [0,1] or [-1,1] */
2988 blend_type.width = 8; /* 8-bit ubyte values */
2989 blend_type.length = 16; /* 16 elements per vector */
2990
2991 /*
2992 * Generate the function prototype. Any change here must be reflected in
2993 * lp_jit.h's lp_jit_frag_func function pointer type, and vice-versa.
2994 */
2995
2996 fs_elem_type = lp_build_elem_type(gallivm, fs_type);
2997
2998 blend_vec_type = lp_build_vec_type(gallivm, blend_type);
2999
3000 snprintf(func_name, sizeof(func_name), "fs_variant_%s",
3001 partial_mask ? "partial" : "whole");
3002
3003 arg_types[0] = variant->jit_context_ptr_type; /* context */
3004 arg_types[1] = int32_type; /* x */
3005 arg_types[2] = int32_type; /* y */
3006 arg_types[3] = int32_type; /* facing */
3007 arg_types[4] = LLVMPointerType(fs_elem_type, 0); /* a0 */
3008 arg_types[5] = LLVMPointerType(fs_elem_type, 0); /* dadx */
3009 arg_types[6] = LLVMPointerType(fs_elem_type, 0); /* dady */
3010 arg_types[7] = LLVMPointerType(LLVMPointerType(int8_type, 0), 0); /* color */
3011 arg_types[8] = LLVMPointerType(int8_type, 0); /* depth */
3012 arg_types[9] = LLVMInt64TypeInContext(gallivm->context); /* mask_input */
3013 arg_types[10] = variant->jit_thread_data_ptr_type; /* per thread data */
3014 arg_types[11] = LLVMPointerType(int32_type, 0); /* stride */
3015 arg_types[12] = int32_type; /* depth_stride */
3016 arg_types[13] = LLVMPointerType(int32_type, 0); /* color sample strides */
3017 arg_types[14] = int32_type; /* depth sample stride */
3018
3019 func_type = LLVMFunctionType(LLVMVoidTypeInContext(gallivm->context),
3020 arg_types, ARRAY_SIZE(arg_types), 0);
3021
3022 function = LLVMAddFunction(gallivm->module, func_name, func_type);
3023 LLVMSetFunctionCallConv(function, LLVMCCallConv);
3024
3025 variant->function[partial_mask] = function;
3026
3027 /* XXX: need to propagate noalias down into color param now we are
3028 * passing a pointer-to-pointer?
3029 */
3030 for(i = 0; i < ARRAY_SIZE(arg_types); ++i)
3031 if(LLVMGetTypeKind(arg_types[i]) == LLVMPointerTypeKind)
3032 lp_add_function_attr(function, i + 1, LP_FUNC_ATTR_NOALIAS);
3033
3034 if (variant->gallivm->cache->data_size)
3035 return;
3036
3037 context_ptr = LLVMGetParam(function, 0);
3038 x = LLVMGetParam(function, 1);
3039 y = LLVMGetParam(function, 2);
3040 facing = LLVMGetParam(function, 3);
3041 a0_ptr = LLVMGetParam(function, 4);
3042 dadx_ptr = LLVMGetParam(function, 5);
3043 dady_ptr = LLVMGetParam(function, 6);
3044 color_ptr_ptr = LLVMGetParam(function, 7);
3045 depth_ptr = LLVMGetParam(function, 8);
3046 mask_input = LLVMGetParam(function, 9);
3047 thread_data_ptr = LLVMGetParam(function, 10);
3048 stride_ptr = LLVMGetParam(function, 11);
3049 depth_stride = LLVMGetParam(function, 12);
3050 color_sample_stride_ptr = LLVMGetParam(function, 13);
3051 depth_sample_stride = LLVMGetParam(function, 14);
3052
3053 lp_build_name(context_ptr, "context");
3054 lp_build_name(x, "x");
3055 lp_build_name(y, "y");
3056 lp_build_name(a0_ptr, "a0");
3057 lp_build_name(dadx_ptr, "dadx");
3058 lp_build_name(dady_ptr, "dady");
3059 lp_build_name(color_ptr_ptr, "color_ptr_ptr");
3060 lp_build_name(depth_ptr, "depth");
3061 lp_build_name(mask_input, "mask_input");
3062 lp_build_name(thread_data_ptr, "thread_data");
3063 lp_build_name(stride_ptr, "stride_ptr");
3064 lp_build_name(depth_stride, "depth_stride");
3065 lp_build_name(color_sample_stride_ptr, "color_sample_stride_ptr");
3066 lp_build_name(depth_sample_stride, "depth_sample_stride");
3067
3068 /*
3069 * Function body
3070 */
3071
3072 block = LLVMAppendBasicBlockInContext(gallivm->context, function, "entry");
3073 builder = gallivm->builder;
3074 assert(builder);
3075 LLVMPositionBuilderAtEnd(builder, block);
3076
3077 /*
3078 * Must not count ps invocations if there's a null shader.
3079 * (It would be ok to count with null shader if there's d/s tests,
3080 * but only if there's d/s buffers too, which is different
3081 * to implicit rasterization disable which must not depend
3082 * on the d/s buffers.)
3083 * Could use popcount on mask, but pixel accuracy is not required.
3084 * Could disable if there's no stats query, but maybe not worth it.
3085 */
3086 if (shader->info.base.num_instructions > 1) {
3087 LLVMValueRef invocs, val;
3088 invocs = lp_jit_thread_data_invocations(gallivm, thread_data_ptr);
3089 val = LLVMBuildLoad(builder, invocs, "");
3090 val = LLVMBuildAdd(builder, val,
3091 LLVMConstInt(LLVMInt64TypeInContext(gallivm->context), 1, 0),
3092 "invoc_count");
3093 LLVMBuildStore(builder, val, invocs);
3094 }
3095
3096 /* code generated texture sampling */
3097 sampler = lp_llvm_sampler_soa_create(key->samplers, key->nr_samplers);
3098 image = lp_llvm_image_soa_create(lp_fs_variant_key_images(key), key->nr_images);
3099
3100 num_fs = 16 / fs_type.length; /* number of loops per 4x4 stamp */
3101 /* for 1d resources only run "upper half" of stamp */
3102 if (key->resource_1d)
3103 num_fs /= 2;
3104
3105 {
3106 LLVMValueRef num_loop = lp_build_const_int32(gallivm, num_fs);
3107 LLVMTypeRef mask_type = lp_build_int_vec_type(gallivm, fs_type);
3108 LLVMValueRef num_loop_samp = lp_build_const_int32(gallivm, num_fs * key->coverage_samples);
3109 LLVMValueRef mask_store = lp_build_array_alloca(gallivm, mask_type,
3110 num_loop_samp, "mask_store");
3111
3112 LLVMTypeRef flt_type = LLVMFloatTypeInContext(gallivm->context);
3113 LLVMValueRef glob_sample_pos = LLVMAddGlobal(gallivm->module, LLVMArrayType(flt_type, key->coverage_samples * 2), "");
3114 LLVMValueRef sample_pos_array;
3115
3116 if (key->multisample && key->coverage_samples == 4) {
3117 LLVMValueRef sample_pos_arr[8];
3118 for (unsigned i = 0; i < 4; i++) {
3119 sample_pos_arr[i * 2] = LLVMConstReal(flt_type, lp_sample_pos_4x[i][0]);
3120 sample_pos_arr[i * 2 + 1] = LLVMConstReal(flt_type, lp_sample_pos_4x[i][1]);
3121 }
3122 sample_pos_array = LLVMConstArray(LLVMFloatTypeInContext(gallivm->context), sample_pos_arr, 8);
3123 } else {
3124 LLVMValueRef sample_pos_arr[2];
3125 sample_pos_arr[0] = LLVMConstReal(flt_type, 0.5);
3126 sample_pos_arr[1] = LLVMConstReal(flt_type, 0.5);
3127 sample_pos_array = LLVMConstArray(LLVMFloatTypeInContext(gallivm->context), sample_pos_arr, 2);
3128 }
3129 LLVMSetInitializer(glob_sample_pos, sample_pos_array);
3130
3131 LLVMValueRef color_store[PIPE_MAX_COLOR_BUFS][TGSI_NUM_CHANNELS];
3132 boolean pixel_center_integer =
3133 shader->info.base.properties[TGSI_PROPERTY_FS_COORD_PIXEL_CENTER];
3134
3135 /*
3136 * The shader input interpolation info is not explicitely baked in the
3137 * shader key, but everything it derives from (TGSI, and flatshade) is
3138 * already included in the shader key.
3139 */
3140 lp_build_interp_soa_init(&interp,
3141 gallivm,
3142 shader->info.base.num_inputs,
3143 inputs,
3144 pixel_center_integer,
3145 key->coverage_samples, glob_sample_pos,
3146 num_loop,
3147 key->depth_clamp,
3148 builder, fs_type,
3149 a0_ptr, dadx_ptr, dady_ptr,
3150 x, y);
3151
3152 for (i = 0; i < num_fs; i++) {
3153 if (key->multisample) {
3154 LLVMValueRef smask_val = LLVMBuildLoad(builder, lp_jit_context_sample_mask(gallivm, context_ptr), "");
3155
3156 /*
3157 * For multisampling, extract the per-sample mask from the incoming 64-bit mask,
3158 * store to the per sample mask storage. Or all of them together to generate
3159 * the fragment shader mask. (sample shading TODO).
3160 * Take the incoming state coverage mask into account.
3161 */
3162 for (unsigned s = 0; s < key->coverage_samples; s++) {
3163 LLVMValueRef sindexi = lp_build_const_int32(gallivm, i + (s * num_fs));
3164 LLVMValueRef sample_mask_ptr = LLVMBuildGEP(builder, mask_store,
3165 &sindexi, 1, "sample_mask_ptr");
3166 LLVMValueRef s_mask = generate_quad_mask(gallivm, fs_type,
3167 i*fs_type.length/4, s, mask_input);
3168
3169 LLVMValueRef smask_bit = LLVMBuildAnd(builder, smask_val, lp_build_const_int32(gallivm, (1 << s)), "");
3170 LLVMValueRef cmp = LLVMBuildICmp(builder, LLVMIntNE, smask_bit, lp_build_const_int32(gallivm, 0), "");
3171 smask_bit = LLVMBuildSExt(builder, cmp, int32_type, "");
3172 smask_bit = lp_build_broadcast(gallivm, mask_type, smask_bit);
3173
3174 s_mask = LLVMBuildAnd(builder, s_mask, smask_bit, "");
3175 LLVMBuildStore(builder, s_mask, sample_mask_ptr);
3176 }
3177 } else {
3178 LLVMValueRef mask;
3179 LLVMValueRef indexi = lp_build_const_int32(gallivm, i);
3180 LLVMValueRef mask_ptr = LLVMBuildGEP(builder, mask_store,
3181 &indexi, 1, "mask_ptr");
3182
3183 if (partial_mask) {
3184 mask = generate_quad_mask(gallivm, fs_type,
3185 i*fs_type.length/4, 0, mask_input);
3186 }
3187 else {
3188 mask = lp_build_const_int_vec(gallivm, fs_type, ~0);
3189 }
3190 LLVMBuildStore(builder, mask, mask_ptr);
3191 }
3192 }
3193
3194 generate_fs_loop(gallivm,
3195 shader, key,
3196 builder,
3197 fs_type,
3198 context_ptr,
3199 glob_sample_pos,
3200 num_loop,
3201 &interp,
3202 sampler,
3203 image,
3204 mask_store, /* output */
3205 color_store,
3206 depth_ptr,
3207 depth_stride,
3208 depth_sample_stride,
3209 color_ptr_ptr,
3210 stride_ptr,
3211 color_sample_stride_ptr,
3212 facing,
3213 thread_data_ptr);
3214
3215 for (i = 0; i < num_fs; i++) {
3216 LLVMValueRef ptr;
3217 for (unsigned s = 0; s < key->coverage_samples; s++) {
3218 int idx = (i + (s * num_fs));
3219 LLVMValueRef sindexi = lp_build_const_int32(gallivm, idx);
3220 ptr = LLVMBuildGEP(builder, mask_store, &sindexi, 1, "");
3221
3222 fs_mask[idx] = LLVMBuildLoad(builder, ptr, "smask");
3223 }
3224
3225 for (unsigned s = 0; s < key->min_samples; s++) {
3226 /* This is fucked up need to reorganize things */
3227 int idx = s * num_fs + i;
3228 LLVMValueRef sindexi = lp_build_const_int32(gallivm, idx);
3229 for (cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
3230 for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
3231 ptr = LLVMBuildGEP(builder,
3232 color_store[cbuf * !cbuf0_write_all][chan],
3233 &sindexi, 1, "");
3234 fs_out_color[s][cbuf][chan][i] = ptr;
3235 }
3236 }
3237 if (dual_source_blend) {
3238 /* only support one dual source blend target hence always use output 1 */
3239 for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
3240 ptr = LLVMBuildGEP(builder,
3241 color_store[1][chan],
3242 &sindexi, 1, "");
3243 fs_out_color[s][1][chan][i] = ptr;
3244 }
3245 }
3246 }
3247 }
3248 }
3249
3250 sampler->destroy(sampler);
3251 image->destroy(image);
3252 /* Loop over color outputs / color buffers to do blending.
3253 */
3254 for(cbuf = 0; cbuf < key->nr_cbufs; cbuf++) {
3255 if (key->cbuf_format[cbuf] != PIPE_FORMAT_NONE) {
3256 LLVMValueRef color_ptr;
3257 LLVMValueRef stride;
3258 LLVMValueRef sample_stride = NULL;
3259 LLVMValueRef index = lp_build_const_int32(gallivm, cbuf);
3260
3261 boolean do_branch = ((key->depth.enabled
3262 || key->stencil[0].enabled
3263 || key->alpha.enabled)
3264 && !shader->info.base.uses_kill);
3265
3266 color_ptr = LLVMBuildLoad(builder,
3267 LLVMBuildGEP(builder, color_ptr_ptr,
3268 &index, 1, ""),
3269 "");
3270
3271 stride = LLVMBuildLoad(builder,
3272 LLVMBuildGEP(builder, stride_ptr, &index, 1, ""),
3273 "");
3274
3275 if (key->multisample)
3276 sample_stride = LLVMBuildLoad(builder,
3277 LLVMBuildGEP(builder, color_sample_stride_ptr,
3278 &index, 1, ""), "");
3279
3280 for (unsigned s = 0; s < key->cbuf_nr_samples[cbuf]; s++) {
3281 unsigned mask_idx = num_fs * (key->multisample ? s : 0);
3282 unsigned out_idx = key->min_samples == 1 ? 0 : s;
3283 LLVMValueRef out_ptr = color_ptr;;
3284
3285 if (key->multisample) {
3286 LLVMValueRef sample_offset = LLVMBuildMul(builder, sample_stride, lp_build_const_int32(gallivm, s), "");
3287 out_ptr = LLVMBuildGEP(builder, out_ptr, &sample_offset, 1, "");
3288 }
3289 out_ptr = LLVMBuildBitCast(builder, out_ptr, LLVMPointerType(blend_vec_type, 0), "");
3290
3291 lp_build_name(out_ptr, "color_ptr%d", cbuf);
3292
3293 generate_unswizzled_blend(gallivm, cbuf, variant,
3294 key->cbuf_format[cbuf],
3295 num_fs, fs_type, &fs_mask[mask_idx], fs_out_color[out_idx],
3296 context_ptr, out_ptr, stride,
3297 partial_mask, do_branch);
3298 }
3299 }
3300 }
3301
3302 LLVMBuildRetVoid(builder);
3303
3304 gallivm_verify_function(gallivm, function);
3305 }
3306
3307
3308 static void
3309 dump_fs_variant_key(struct lp_fragment_shader_variant_key *key)
3310 {
3311 unsigned i;
3312
3313 debug_printf("fs variant %p:\n", (void *) key);
3314
3315 if (key->flatshade) {
3316 debug_printf("flatshade = 1\n");
3317 }
3318 if (key->multisample) {
3319 debug_printf("multisample = 1\n");
3320 debug_printf("coverage samples = %d\n", key->coverage_samples);
3321 debug_printf("min samples = %d\n", key->min_samples);
3322 }
3323 for (i = 0; i < key->nr_cbufs; ++i) {
3324 debug_printf("cbuf_format[%u] = %s\n", i, util_format_name(key->cbuf_format[i]));
3325 debug_printf("cbuf nr_samples[%u] = %d\n", i, key->cbuf_nr_samples[i]);
3326 }
3327 if (key->depth.enabled || key->stencil[0].enabled) {
3328 debug_printf("depth.format = %s\n", util_format_name(key->zsbuf_format));
3329 debug_printf("depth nr_samples = %d\n", key->zsbuf_nr_samples);
3330 }
3331 if (key->depth.enabled) {
3332 debug_printf("depth.func = %s\n", util_str_func(key->depth.func, TRUE));
3333 debug_printf("depth.writemask = %u\n", key->depth.writemask);
3334 }
3335
3336 for (i = 0; i < 2; ++i) {
3337 if (key->stencil[i].enabled) {
3338 debug_printf("stencil[%u].func = %s\n", i, util_str_func(key->stencil[i].func, TRUE));
3339 debug_printf("stencil[%u].fail_op = %s\n", i, util_str_stencil_op(key->stencil[i].fail_op, TRUE));
3340 debug_printf("stencil[%u].zpass_op = %s\n", i, util_str_stencil_op(key->stencil[i].zpass_op, TRUE));
3341 debug_printf("stencil[%u].zfail_op = %s\n", i, util_str_stencil_op(key->stencil[i].zfail_op, TRUE));
3342 debug_printf("stencil[%u].valuemask = 0x%x\n", i, key->stencil[i].valuemask);
3343 debug_printf("stencil[%u].writemask = 0x%x\n", i, key->stencil[i].writemask);
3344 }
3345 }
3346
3347 if (key->alpha.enabled) {
3348 debug_printf("alpha.func = %s\n", util_str_func(key->alpha.func, TRUE));
3349 }
3350
3351 if (key->occlusion_count) {
3352 debug_printf("occlusion_count = 1\n");
3353 }
3354
3355 if (key->blend.logicop_enable) {
3356 debug_printf("blend.logicop_func = %s\n", util_str_logicop(key->blend.logicop_func, TRUE));
3357 }
3358 else if (key->blend.rt[0].blend_enable) {
3359 debug_printf("blend.rgb_func = %s\n", util_str_blend_func (key->blend.rt[0].rgb_func, TRUE));
3360 debug_printf("blend.rgb_src_factor = %s\n", util_str_blend_factor(key->blend.rt[0].rgb_src_factor, TRUE));
3361 debug_printf("blend.rgb_dst_factor = %s\n", util_str_blend_factor(key->blend.rt[0].rgb_dst_factor, TRUE));
3362 debug_printf("blend.alpha_func = %s\n", util_str_blend_func (key->blend.rt[0].alpha_func, TRUE));
3363 debug_printf("blend.alpha_src_factor = %s\n", util_str_blend_factor(key->blend.rt[0].alpha_src_factor, TRUE));
3364 debug_printf("blend.alpha_dst_factor = %s\n", util_str_blend_factor(key->blend.rt[0].alpha_dst_factor, TRUE));
3365 }
3366 debug_printf("blend.colormask = 0x%x\n", key->blend.rt[0].colormask);
3367 if (key->blend.alpha_to_coverage) {
3368 debug_printf("blend.alpha_to_coverage is enabled\n");
3369 }
3370 for (i = 0; i < key->nr_samplers; ++i) {
3371 const struct lp_static_sampler_state *sampler = &key->samplers[i].sampler_state;
3372 debug_printf("sampler[%u] = \n", i);
3373 debug_printf(" .wrap = %s %s %s\n",
3374 util_str_tex_wrap(sampler->wrap_s, TRUE),
3375 util_str_tex_wrap(sampler->wrap_t, TRUE),
3376 util_str_tex_wrap(sampler->wrap_r, TRUE));
3377 debug_printf(" .min_img_filter = %s\n",
3378 util_str_tex_filter(sampler->min_img_filter, TRUE));
3379 debug_printf(" .min_mip_filter = %s\n",
3380 util_str_tex_mipfilter(sampler->min_mip_filter, TRUE));
3381 debug_printf(" .mag_img_filter = %s\n",
3382 util_str_tex_filter(sampler->mag_img_filter, TRUE));
3383 if (sampler->compare_mode != PIPE_TEX_COMPARE_NONE)
3384 debug_printf(" .compare_func = %s\n", util_str_func(sampler->compare_func, TRUE));
3385 debug_printf(" .normalized_coords = %u\n", sampler->normalized_coords);
3386 debug_printf(" .min_max_lod_equal = %u\n", sampler->min_max_lod_equal);
3387 debug_printf(" .lod_bias_non_zero = %u\n", sampler->lod_bias_non_zero);
3388 debug_printf(" .apply_min_lod = %u\n", sampler->apply_min_lod);
3389 debug_printf(" .apply_max_lod = %u\n", sampler->apply_max_lod);
3390 }
3391 for (i = 0; i < key->nr_sampler_views; ++i) {
3392 const struct lp_static_texture_state *texture = &key->samplers[i].texture_state;
3393 debug_printf("texture[%u] = \n", i);
3394 debug_printf(" .format = %s\n",
3395 util_format_name(texture->format));
3396 debug_printf(" .target = %s\n",
3397 util_str_tex_target(texture->target, TRUE));
3398 debug_printf(" .level_zero_only = %u\n",
3399 texture->level_zero_only);
3400 debug_printf(" .pot = %u %u %u\n",
3401 texture->pot_width,
3402 texture->pot_height,
3403 texture->pot_depth);
3404 }
3405 struct lp_image_static_state *images = lp_fs_variant_key_images(key);
3406 for (i = 0; i < key->nr_images; ++i) {
3407 const struct lp_static_texture_state *image = &images[i].image_state;
3408 debug_printf("image[%u] = \n", i);
3409 debug_printf(" .format = %s\n",
3410 util_format_name(image->format));
3411 debug_printf(" .target = %s\n",
3412 util_str_tex_target(image->target, TRUE));
3413 debug_printf(" .level_zero_only = %u\n",
3414 image->level_zero_only);
3415 debug_printf(" .pot = %u %u %u\n",
3416 image->pot_width,
3417 image->pot_height,
3418 image->pot_depth);
3419 }
3420 }
3421
3422
3423 void
3424 lp_debug_fs_variant(struct lp_fragment_shader_variant *variant)
3425 {
3426 debug_printf("llvmpipe: Fragment shader #%u variant #%u:\n",
3427 variant->shader->no, variant->no);
3428 if (variant->shader->base.type == PIPE_SHADER_IR_TGSI)
3429 tgsi_dump(variant->shader->base.tokens, 0);
3430 else
3431 nir_print_shader(variant->shader->base.ir.nir, stderr);
3432 dump_fs_variant_key(&variant->key);
3433 debug_printf("variant->opaque = %u\n", variant->opaque);
3434 debug_printf("\n");
3435 }
3436
3437 static void
3438 lp_fs_get_ir_cache_key(struct lp_fragment_shader_variant *variant,
3439 unsigned char ir_sha1_cache_key[20])
3440 {
3441 struct blob blob = { 0 };
3442 unsigned ir_size;
3443 void *ir_binary;
3444
3445 blob_init(&blob);
3446 nir_serialize(&blob, variant->shader->base.ir.nir, true);
3447 ir_binary = blob.data;
3448 ir_size = blob.size;
3449
3450 struct mesa_sha1 ctx;
3451 _mesa_sha1_init(&ctx);
3452 _mesa_sha1_update(&ctx, &variant->key, variant->shader->variant_key_size);
3453 _mesa_sha1_update(&ctx, ir_binary, ir_size);
3454 _mesa_sha1_final(&ctx, ir_sha1_cache_key);
3455
3456 blob_finish(&blob);
3457 }
3458
3459 /**
3460 * Generate a new fragment shader variant from the shader code and
3461 * other state indicated by the key.
3462 */
3463 static struct lp_fragment_shader_variant *
3464 generate_variant(struct llvmpipe_context *lp,
3465 struct lp_fragment_shader *shader,
3466 const struct lp_fragment_shader_variant_key *key)
3467 {
3468 struct llvmpipe_screen *screen = llvmpipe_screen(lp->pipe.screen);
3469 struct lp_fragment_shader_variant *variant;
3470 const struct util_format_description *cbuf0_format_desc = NULL;
3471 boolean fullcolormask;
3472 char module_name[64];
3473 unsigned char ir_sha1_cache_key[20];
3474 struct lp_cached_code cached = { 0 };
3475 bool needs_caching = false;
3476 variant = MALLOC(sizeof *variant + shader->variant_key_size - sizeof variant->key);
3477 if (!variant)
3478 return NULL;
3479
3480 memset(variant, 0, sizeof(*variant));
3481 snprintf(module_name, sizeof(module_name), "fs%u_variant%u",
3482 shader->no, shader->variants_created);
3483
3484 pipe_reference_init(&variant->reference, 1);
3485 lp_fs_reference(lp, &variant->shader, shader);
3486
3487 memcpy(&variant->key, key, shader->variant_key_size);
3488
3489 if (shader->base.ir.nir) {
3490 lp_fs_get_ir_cache_key(variant, ir_sha1_cache_key);
3491
3492 lp_disk_cache_find_shader(screen, &cached, ir_sha1_cache_key);
3493 if (!cached.data_size)
3494 needs_caching = true;
3495 }
3496 variant->gallivm = gallivm_create(module_name, lp->context, &cached);
3497 if (!variant->gallivm) {
3498 FREE(variant);
3499 return NULL;
3500 }
3501
3502 variant->list_item_global.base = variant;
3503 variant->list_item_local.base = variant;
3504 variant->no = shader->variants_created++;
3505
3506
3507
3508 /*
3509 * Determine whether we are touching all channels in the color buffer.
3510 */
3511 fullcolormask = FALSE;
3512 if (key->nr_cbufs == 1) {
3513 cbuf0_format_desc = util_format_description(key->cbuf_format[0]);
3514 fullcolormask = util_format_colormask_full(cbuf0_format_desc, key->blend.rt[0].colormask);
3515 }
3516
3517 variant->opaque =
3518 !key->blend.logicop_enable &&
3519 !key->blend.rt[0].blend_enable &&
3520 fullcolormask &&
3521 !key->stencil[0].enabled &&
3522 !key->alpha.enabled &&
3523 !key->multisample &&
3524 !key->blend.alpha_to_coverage &&
3525 !key->depth.enabled &&
3526 !shader->info.base.uses_kill &&
3527 !shader->info.base.writes_samplemask
3528 ? TRUE : FALSE;
3529
3530 if ((LP_DEBUG & DEBUG_FS) || (gallivm_debug & GALLIVM_DEBUG_IR)) {
3531 lp_debug_fs_variant(variant);
3532 }
3533
3534 lp_jit_init_types(variant);
3535
3536 if (variant->jit_function[RAST_EDGE_TEST] == NULL)
3537 generate_fragment(lp, shader, variant, RAST_EDGE_TEST);
3538
3539 if (variant->jit_function[RAST_WHOLE] == NULL) {
3540 if (variant->opaque) {
3541 /* Specialized shader, which doesn't need to read the color buffer. */
3542 generate_fragment(lp, shader, variant, RAST_WHOLE);
3543 }
3544 }
3545
3546 /*
3547 * Compile everything
3548 */
3549
3550 gallivm_compile_module(variant->gallivm);
3551
3552 variant->nr_instrs += lp_build_count_ir_module(variant->gallivm->module);
3553
3554 if (variant->function[RAST_EDGE_TEST]) {
3555 variant->jit_function[RAST_EDGE_TEST] = (lp_jit_frag_func)
3556 gallivm_jit_function(variant->gallivm,
3557 variant->function[RAST_EDGE_TEST]);
3558 }
3559
3560 if (variant->function[RAST_WHOLE]) {
3561 variant->jit_function[RAST_WHOLE] = (lp_jit_frag_func)
3562 gallivm_jit_function(variant->gallivm,
3563 variant->function[RAST_WHOLE]);
3564 } else if (!variant->jit_function[RAST_WHOLE]) {
3565 variant->jit_function[RAST_WHOLE] = variant->jit_function[RAST_EDGE_TEST];
3566 }
3567
3568 if (needs_caching) {
3569 lp_disk_cache_insert_shader(screen, &cached, ir_sha1_cache_key);
3570 }
3571
3572 gallivm_free_ir(variant->gallivm);
3573
3574 return variant;
3575 }
3576
3577
3578 static void *
3579 llvmpipe_create_fs_state(struct pipe_context *pipe,
3580 const struct pipe_shader_state *templ)
3581 {
3582 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3583 struct lp_fragment_shader *shader;
3584 int nr_samplers;
3585 int nr_sampler_views;
3586 int nr_images;
3587 int i;
3588
3589 shader = CALLOC_STRUCT(lp_fragment_shader);
3590 if (!shader)
3591 return NULL;
3592
3593 pipe_reference_init(&shader->reference, 1);
3594 shader->no = fs_no++;
3595 make_empty_list(&shader->variants);
3596
3597 shader->base.type = templ->type;
3598 if (templ->type == PIPE_SHADER_IR_TGSI) {
3599 /* get/save the summary info for this shader */
3600 lp_build_tgsi_info(templ->tokens, &shader->info);
3601
3602 /* we need to keep a local copy of the tokens */
3603 shader->base.tokens = tgsi_dup_tokens(templ->tokens);
3604 } else {
3605 shader->base.ir.nir = templ->ir.nir;
3606 nir_tgsi_scan_shader(templ->ir.nir, &shader->info.base, true);
3607 }
3608
3609 shader->draw_data = draw_create_fragment_shader(llvmpipe->draw, templ);
3610 if (shader->draw_data == NULL) {
3611 FREE((void *) shader->base.tokens);
3612 FREE(shader);
3613 return NULL;
3614 }
3615
3616 nr_samplers = shader->info.base.file_max[TGSI_FILE_SAMPLER] + 1;
3617 nr_sampler_views = shader->info.base.file_max[TGSI_FILE_SAMPLER_VIEW] + 1;
3618 nr_images = shader->info.base.file_max[TGSI_FILE_IMAGE] + 1;
3619 shader->variant_key_size = lp_fs_variant_key_size(MAX2(nr_samplers, nr_sampler_views), nr_images);
3620
3621 for (i = 0; i < shader->info.base.num_inputs; i++) {
3622 shader->inputs[i].usage_mask = shader->info.base.input_usage_mask[i];
3623 shader->inputs[i].cyl_wrap = shader->info.base.input_cylindrical_wrap[i];
3624 shader->inputs[i].location = shader->info.base.input_interpolate_loc[i];
3625
3626 switch (shader->info.base.input_interpolate[i]) {
3627 case TGSI_INTERPOLATE_CONSTANT:
3628 shader->inputs[i].interp = LP_INTERP_CONSTANT;
3629 break;
3630 case TGSI_INTERPOLATE_LINEAR:
3631 shader->inputs[i].interp = LP_INTERP_LINEAR;
3632 break;
3633 case TGSI_INTERPOLATE_PERSPECTIVE:
3634 shader->inputs[i].interp = LP_INTERP_PERSPECTIVE;
3635 break;
3636 case TGSI_INTERPOLATE_COLOR:
3637 shader->inputs[i].interp = LP_INTERP_COLOR;
3638 break;
3639 default:
3640 assert(0);
3641 break;
3642 }
3643
3644 switch (shader->info.base.input_semantic_name[i]) {
3645 case TGSI_SEMANTIC_FACE:
3646 shader->inputs[i].interp = LP_INTERP_FACING;
3647 break;
3648 case TGSI_SEMANTIC_POSITION:
3649 /* Position was already emitted above
3650 */
3651 shader->inputs[i].interp = LP_INTERP_POSITION;
3652 shader->inputs[i].src_index = 0;
3653 continue;
3654 }
3655
3656 /* XXX this is a completely pointless index map... */
3657 shader->inputs[i].src_index = i+1;
3658 }
3659
3660 if (LP_DEBUG & DEBUG_TGSI) {
3661 unsigned attrib;
3662 debug_printf("llvmpipe: Create fragment shader #%u %p:\n",
3663 shader->no, (void *) shader);
3664 tgsi_dump(templ->tokens, 0);
3665 debug_printf("usage masks:\n");
3666 for (attrib = 0; attrib < shader->info.base.num_inputs; ++attrib) {
3667 unsigned usage_mask = shader->info.base.input_usage_mask[attrib];
3668 debug_printf(" IN[%u].%s%s%s%s\n",
3669 attrib,
3670 usage_mask & TGSI_WRITEMASK_X ? "x" : "",
3671 usage_mask & TGSI_WRITEMASK_Y ? "y" : "",
3672 usage_mask & TGSI_WRITEMASK_Z ? "z" : "",
3673 usage_mask & TGSI_WRITEMASK_W ? "w" : "");
3674 }
3675 debug_printf("\n");
3676 }
3677
3678 return shader;
3679 }
3680
3681
3682 static void
3683 llvmpipe_bind_fs_state(struct pipe_context *pipe, void *fs)
3684 {
3685 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3686 struct lp_fragment_shader *lp_fs = (struct lp_fragment_shader *)fs;
3687 if (llvmpipe->fs == lp_fs)
3688 return;
3689
3690 draw_bind_fragment_shader(llvmpipe->draw,
3691 (lp_fs ? lp_fs->draw_data : NULL));
3692
3693 lp_fs_reference(llvmpipe, &llvmpipe->fs, lp_fs);
3694
3695 /* invalidate the setup link, NEW_FS will make it update */
3696 lp_setup_set_fs_variant(llvmpipe->setup, NULL);
3697 llvmpipe->dirty |= LP_NEW_FS;
3698 }
3699
3700
3701 /**
3702 * Remove shader variant from two lists: the shader's variant list
3703 * and the context's variant list.
3704 */
3705
3706 static
3707 void llvmpipe_remove_shader_variant(struct llvmpipe_context *lp,
3708 struct lp_fragment_shader_variant *variant)
3709 {
3710 if ((LP_DEBUG & DEBUG_FS) || (gallivm_debug & GALLIVM_DEBUG_IR)) {
3711 debug_printf("llvmpipe: del fs #%u var %u v created %u v cached %u "
3712 "v total cached %u inst %u total inst %u\n",
3713 variant->shader->no, variant->no,
3714 variant->shader->variants_created,
3715 variant->shader->variants_cached,
3716 lp->nr_fs_variants, variant->nr_instrs, lp->nr_fs_instrs);
3717 }
3718
3719 /* remove from shader's list */
3720 remove_from_list(&variant->list_item_local);
3721 variant->shader->variants_cached--;
3722
3723 /* remove from context's list */
3724 remove_from_list(&variant->list_item_global);
3725 lp->nr_fs_variants--;
3726 lp->nr_fs_instrs -= variant->nr_instrs;
3727 }
3728
3729 void
3730 llvmpipe_destroy_shader_variant(struct llvmpipe_context *lp,
3731 struct lp_fragment_shader_variant *variant)
3732 {
3733 gallivm_destroy(variant->gallivm);
3734
3735 lp_fs_reference(lp, &variant->shader, NULL);
3736
3737 FREE(variant);
3738 }
3739
3740 void
3741 llvmpipe_destroy_fs(struct llvmpipe_context *llvmpipe,
3742 struct lp_fragment_shader *shader)
3743 {
3744 /* Delete draw module's data */
3745 draw_delete_fragment_shader(llvmpipe->draw, shader->draw_data);
3746
3747 if (shader->base.ir.nir)
3748 ralloc_free(shader->base.ir.nir);
3749 assert(shader->variants_cached == 0);
3750 FREE((void *) shader->base.tokens);
3751 FREE(shader);
3752 }
3753
3754 static void
3755 llvmpipe_delete_fs_state(struct pipe_context *pipe, void *fs)
3756 {
3757 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3758 struct lp_fragment_shader *shader = fs;
3759 struct lp_fs_variant_list_item *li;
3760
3761 /* Delete all the variants */
3762 li = first_elem(&shader->variants);
3763 while(!at_end(&shader->variants, li)) {
3764 struct lp_fs_variant_list_item *next = next_elem(li);
3765 struct lp_fragment_shader_variant *variant;
3766 variant = li->base;
3767 llvmpipe_remove_shader_variant(llvmpipe, li->base);
3768 lp_fs_variant_reference(llvmpipe, &variant, NULL);
3769 li = next;
3770 }
3771
3772 lp_fs_reference(llvmpipe, &shader, NULL);
3773 }
3774
3775 static void
3776 llvmpipe_set_constant_buffer(struct pipe_context *pipe,
3777 enum pipe_shader_type shader, uint index,
3778 const struct pipe_constant_buffer *cb)
3779 {
3780 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3781 struct pipe_resource *constants = cb ? cb->buffer : NULL;
3782
3783 assert(shader < PIPE_SHADER_TYPES);
3784 assert(index < ARRAY_SIZE(llvmpipe->constants[shader]));
3785
3786 /* note: reference counting */
3787 util_copy_constant_buffer(&llvmpipe->constants[shader][index], cb);
3788
3789 if (constants) {
3790 if (!(constants->bind & PIPE_BIND_CONSTANT_BUFFER)) {
3791 debug_printf("Illegal set constant without bind flag\n");
3792 constants->bind |= PIPE_BIND_CONSTANT_BUFFER;
3793 }
3794 }
3795
3796 if (shader == PIPE_SHADER_VERTEX ||
3797 shader == PIPE_SHADER_GEOMETRY ||
3798 shader == PIPE_SHADER_TESS_CTRL ||
3799 shader == PIPE_SHADER_TESS_EVAL) {
3800 /* Pass the constants to the 'draw' module */
3801 const unsigned size = cb ? cb->buffer_size : 0;
3802 const ubyte *data;
3803
3804 if (constants) {
3805 data = (ubyte *) llvmpipe_resource_data(constants);
3806 }
3807 else if (cb && cb->user_buffer) {
3808 data = (ubyte *) cb->user_buffer;
3809 }
3810 else {
3811 data = NULL;
3812 }
3813
3814 if (data)
3815 data += cb->buffer_offset;
3816
3817 draw_set_mapped_constant_buffer(llvmpipe->draw, shader,
3818 index, data, size);
3819 }
3820 else if (shader == PIPE_SHADER_COMPUTE)
3821 llvmpipe->cs_dirty |= LP_CSNEW_CONSTANTS;
3822 else
3823 llvmpipe->dirty |= LP_NEW_FS_CONSTANTS;
3824
3825 if (cb && cb->user_buffer) {
3826 pipe_resource_reference(&constants, NULL);
3827 }
3828 }
3829
3830 static void
3831 llvmpipe_set_shader_buffers(struct pipe_context *pipe,
3832 enum pipe_shader_type shader, unsigned start_slot,
3833 unsigned count, const struct pipe_shader_buffer *buffers,
3834 unsigned writable_bitmask)
3835 {
3836 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3837 unsigned i, idx;
3838 for (i = start_slot, idx = 0; i < start_slot + count; i++, idx++) {
3839 const struct pipe_shader_buffer *buffer = buffers ? &buffers[idx] : NULL;
3840
3841 util_copy_shader_buffer(&llvmpipe->ssbos[shader][i], buffer);
3842
3843 if (shader == PIPE_SHADER_VERTEX ||
3844 shader == PIPE_SHADER_GEOMETRY ||
3845 shader == PIPE_SHADER_TESS_CTRL ||
3846 shader == PIPE_SHADER_TESS_EVAL) {
3847 const unsigned size = buffer ? buffer->buffer_size : 0;
3848 const ubyte *data = NULL;
3849 if (buffer && buffer->buffer)
3850 data = (ubyte *) llvmpipe_resource_data(buffer->buffer);
3851 if (data)
3852 data += buffer->buffer_offset;
3853 draw_set_mapped_shader_buffer(llvmpipe->draw, shader,
3854 i, data, size);
3855 } else if (shader == PIPE_SHADER_COMPUTE) {
3856 llvmpipe->cs_dirty |= LP_CSNEW_SSBOS;
3857 } else if (shader == PIPE_SHADER_FRAGMENT) {
3858 llvmpipe->dirty |= LP_NEW_FS_SSBOS;
3859 }
3860 }
3861 }
3862
3863 static void
3864 llvmpipe_set_shader_images(struct pipe_context *pipe,
3865 enum pipe_shader_type shader, unsigned start_slot,
3866 unsigned count, const struct pipe_image_view *images)
3867 {
3868 struct llvmpipe_context *llvmpipe = llvmpipe_context(pipe);
3869 unsigned i, idx;
3870
3871 draw_flush(llvmpipe->draw);
3872 for (i = start_slot, idx = 0; i < start_slot + count; i++, idx++) {
3873 const struct pipe_image_view *image = images ? &images[idx] : NULL;
3874
3875 util_copy_image_view(&llvmpipe->images[shader][i], image);
3876 }
3877
3878 llvmpipe->num_images[shader] = start_slot + count;
3879 if (shader == PIPE_SHADER_VERTEX ||
3880 shader == PIPE_SHADER_GEOMETRY ||
3881 shader == PIPE_SHADER_TESS_CTRL ||
3882 shader == PIPE_SHADER_TESS_EVAL) {
3883 draw_set_images(llvmpipe->draw,
3884 shader,
3885 llvmpipe->images[shader],
3886 start_slot + count);
3887 } else if (shader == PIPE_SHADER_COMPUTE)
3888 llvmpipe->cs_dirty |= LP_CSNEW_IMAGES;
3889 else
3890 llvmpipe->dirty |= LP_NEW_FS_IMAGES;
3891 }
3892
3893 /**
3894 * Return the blend factor equivalent to a destination alpha of one.
3895 */
3896 static inline unsigned
3897 force_dst_alpha_one(unsigned factor, boolean clamped_zero)
3898 {
3899 switch(factor) {
3900 case PIPE_BLENDFACTOR_DST_ALPHA:
3901 return PIPE_BLENDFACTOR_ONE;
3902 case PIPE_BLENDFACTOR_INV_DST_ALPHA:
3903 return PIPE_BLENDFACTOR_ZERO;
3904 case PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE:
3905 if (clamped_zero)
3906 return PIPE_BLENDFACTOR_ZERO;
3907 else
3908 return PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE;
3909 }
3910
3911 return factor;
3912 }
3913
3914
3915 /**
3916 * We need to generate several variants of the fragment pipeline to match
3917 * all the combinations of the contributing state atoms.
3918 *
3919 * TODO: there is actually no reason to tie this to context state -- the
3920 * generated code could be cached globally in the screen.
3921 */
3922 static struct lp_fragment_shader_variant_key *
3923 make_variant_key(struct llvmpipe_context *lp,
3924 struct lp_fragment_shader *shader,
3925 char *store)
3926 {
3927 unsigned i;
3928 struct lp_fragment_shader_variant_key *key;
3929
3930 key = (struct lp_fragment_shader_variant_key *)store;
3931
3932 memset(key, 0, offsetof(struct lp_fragment_shader_variant_key, samplers[1]));
3933
3934 if (lp->framebuffer.zsbuf) {
3935 enum pipe_format zsbuf_format = lp->framebuffer.zsbuf->format;
3936 const struct util_format_description *zsbuf_desc =
3937 util_format_description(zsbuf_format);
3938
3939 if (lp->depth_stencil->depth.enabled &&
3940 util_format_has_depth(zsbuf_desc)) {
3941 key->zsbuf_format = zsbuf_format;
3942 memcpy(&key->depth, &lp->depth_stencil->depth, sizeof key->depth);
3943 }
3944 if (lp->depth_stencil->stencil[0].enabled &&
3945 util_format_has_stencil(zsbuf_desc)) {
3946 key->zsbuf_format = zsbuf_format;
3947 memcpy(&key->stencil, &lp->depth_stencil->stencil, sizeof key->stencil);
3948 }
3949 if (llvmpipe_resource_is_1d(lp->framebuffer.zsbuf->texture)) {
3950 key->resource_1d = TRUE;
3951 }
3952 key->zsbuf_nr_samples = util_res_sample_count(lp->framebuffer.zsbuf->texture);
3953 }
3954
3955 /*
3956 * Propagate the depth clamp setting from the rasterizer state.
3957 * depth_clip == 0 implies depth clamping is enabled.
3958 *
3959 * When clip_halfz is enabled, then always clamp the depth values.
3960 *
3961 * XXX: This is incorrect for GL, but correct for d3d10 (depth
3962 * clamp is always active in d3d10, regardless if depth clip is
3963 * enabled or not).
3964 * (GL has an always-on [0,1] clamp on fs depth output instead
3965 * to ensure the depth values stay in range. Doesn't look like
3966 * we do that, though...)
3967 */
3968 if (lp->rasterizer->clip_halfz) {
3969 key->depth_clamp = 1;
3970 } else {
3971 key->depth_clamp = (lp->rasterizer->depth_clip_near == 0) ? 1 : 0;
3972 }
3973
3974 /* alpha test only applies if render buffer 0 is non-integer (or does not exist) */
3975 if (!lp->framebuffer.nr_cbufs ||
3976 !lp->framebuffer.cbufs[0] ||
3977 !util_format_is_pure_integer(lp->framebuffer.cbufs[0]->format)) {
3978 key->alpha.enabled = lp->depth_stencil->alpha.enabled;
3979 }
3980 if(key->alpha.enabled)
3981 key->alpha.func = lp->depth_stencil->alpha.func;
3982 /* alpha.ref_value is passed in jit_context */
3983
3984 key->flatshade = lp->rasterizer->flatshade;
3985 key->multisample = lp->rasterizer->multisample;
3986 if (lp->active_occlusion_queries && !lp->queries_disabled) {
3987 key->occlusion_count = TRUE;
3988 }
3989
3990 if (lp->framebuffer.nr_cbufs) {
3991 memcpy(&key->blend, lp->blend, sizeof key->blend);
3992 }
3993
3994 key->coverage_samples = 1;
3995 key->min_samples = 1;
3996 if (key->multisample) {
3997 key->coverage_samples = util_framebuffer_get_num_samples(&lp->framebuffer);
3998 key->min_samples = lp->min_samples == 1 ? 1 : key->coverage_samples;
3999 }
4000 key->nr_cbufs = lp->framebuffer.nr_cbufs;
4001
4002 if (!key->blend.independent_blend_enable) {
4003 /* we always need independent blend otherwise the fixups below won't work */
4004 for (i = 1; i < key->nr_cbufs; i++) {
4005 memcpy(&key->blend.rt[i], &key->blend.rt[0], sizeof(key->blend.rt[0]));
4006 }
4007 key->blend.independent_blend_enable = 1;
4008 }
4009
4010 for (i = 0; i < lp->framebuffer.nr_cbufs; i++) {
4011 struct pipe_rt_blend_state *blend_rt = &key->blend.rt[i];
4012
4013 if (lp->framebuffer.cbufs[i]) {
4014 enum pipe_format format = lp->framebuffer.cbufs[i]->format;
4015 const struct util_format_description *format_desc;
4016
4017 key->cbuf_format[i] = format;
4018 key->cbuf_nr_samples[i] = util_res_sample_count(lp->framebuffer.cbufs[i]->texture);
4019
4020 /*
4021 * Figure out if this is a 1d resource. Note that OpenGL allows crazy
4022 * mixing of 2d textures with height 1 and 1d textures, so make sure
4023 * we pick 1d if any cbuf or zsbuf is 1d.
4024 */
4025 if (llvmpipe_resource_is_1d(lp->framebuffer.cbufs[i]->texture)) {
4026 key->resource_1d = TRUE;
4027 }
4028
4029 format_desc = util_format_description(format);
4030 assert(format_desc->colorspace == UTIL_FORMAT_COLORSPACE_RGB ||
4031 format_desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB);
4032
4033 /*
4034 * Mask out color channels not present in the color buffer.
4035 */
4036 blend_rt->colormask &= util_format_colormask(format_desc);
4037
4038 /*
4039 * Disable blend for integer formats.
4040 */
4041 if (util_format_is_pure_integer(format)) {
4042 blend_rt->blend_enable = 0;
4043 }
4044
4045 /*
4046 * Our swizzled render tiles always have an alpha channel, but the
4047 * linear render target format often does not, so force here the dst
4048 * alpha to be one.
4049 *
4050 * This is not a mere optimization. Wrong results will be produced if
4051 * the dst alpha is used, the dst format does not have alpha, and the
4052 * previous rendering was not flushed from the swizzled to linear
4053 * buffer. For example, NonPowTwo DCT.
4054 *
4055 * TODO: This should be generalized to all channels for better
4056 * performance, but only alpha causes correctness issues.
4057 *
4058 * Also, force rgb/alpha func/factors match, to make AoS blending
4059 * easier.
4060 */
4061 if (format_desc->swizzle[3] > PIPE_SWIZZLE_W ||
4062 format_desc->swizzle[3] == format_desc->swizzle[0]) {
4063 /* Doesn't cover mixed snorm/unorm but can't render to them anyway */
4064 boolean clamped_zero = !util_format_is_float(format) &&
4065 !util_format_is_snorm(format);
4066 blend_rt->rgb_src_factor =
4067 force_dst_alpha_one(blend_rt->rgb_src_factor, clamped_zero);
4068 blend_rt->rgb_dst_factor =
4069 force_dst_alpha_one(blend_rt->rgb_dst_factor, clamped_zero);
4070 blend_rt->alpha_func = blend_rt->rgb_func;
4071 blend_rt->alpha_src_factor = blend_rt->rgb_src_factor;
4072 blend_rt->alpha_dst_factor = blend_rt->rgb_dst_factor;
4073 }
4074 }
4075 else {
4076 /* no color buffer for this fragment output */
4077 key->cbuf_format[i] = PIPE_FORMAT_NONE;
4078 key->cbuf_nr_samples[i] = 0;
4079 blend_rt->colormask = 0x0;
4080 blend_rt->blend_enable = 0;
4081 }
4082 }
4083
4084 /* This value will be the same for all the variants of a given shader:
4085 */
4086 key->nr_samplers = shader->info.base.file_max[TGSI_FILE_SAMPLER] + 1;
4087
4088 struct lp_sampler_static_state *fs_sampler;
4089
4090 fs_sampler = key->samplers;
4091
4092 memset(fs_sampler, 0, MAX2(key->nr_samplers, key->nr_sampler_views) * sizeof *fs_sampler);
4093
4094 for(i = 0; i < key->nr_samplers; ++i) {
4095 if(shader->info.base.file_mask[TGSI_FILE_SAMPLER] & (1 << i)) {
4096 lp_sampler_static_sampler_state(&fs_sampler[i].sampler_state,
4097 lp->samplers[PIPE_SHADER_FRAGMENT][i]);
4098 }
4099 }
4100
4101 /*
4102 * XXX If TGSI_FILE_SAMPLER_VIEW exists assume all texture opcodes
4103 * are dx10-style? Can't really have mixed opcodes, at least not
4104 * if we want to skip the holes here (without rescanning tgsi).
4105 */
4106 if (shader->info.base.file_max[TGSI_FILE_SAMPLER_VIEW] != -1) {
4107 key->nr_sampler_views = shader->info.base.file_max[TGSI_FILE_SAMPLER_VIEW] + 1;
4108 for(i = 0; i < key->nr_sampler_views; ++i) {
4109 /*
4110 * Note sview may exceed what's representable by file_mask.
4111 * This will still work, the only downside is that not actually
4112 * used views may be included in the shader key.
4113 */
4114 if(shader->info.base.file_mask[TGSI_FILE_SAMPLER_VIEW] & (1u << (i & 31))) {
4115 lp_sampler_static_texture_state(&fs_sampler[i].texture_state,
4116 lp->sampler_views[PIPE_SHADER_FRAGMENT][i]);
4117 }
4118 }
4119 }
4120 else {
4121 key->nr_sampler_views = key->nr_samplers;
4122 for(i = 0; i < key->nr_sampler_views; ++i) {
4123 if(shader->info.base.file_mask[TGSI_FILE_SAMPLER] & (1 << i)) {
4124 lp_sampler_static_texture_state(&fs_sampler[i].texture_state,
4125 lp->sampler_views[PIPE_SHADER_FRAGMENT][i]);
4126 }
4127 }
4128 }
4129
4130 struct lp_image_static_state *lp_image;
4131 lp_image = lp_fs_variant_key_images(key);
4132 key->nr_images = shader->info.base.file_max[TGSI_FILE_IMAGE] + 1;
4133 for (i = 0; i < key->nr_images; ++i) {
4134 if (shader->info.base.file_mask[TGSI_FILE_IMAGE] & (1 << i)) {
4135 lp_sampler_static_texture_state_image(&lp_image[i].image_state,
4136 &lp->images[PIPE_SHADER_FRAGMENT][i]);
4137 }
4138 }
4139 return key;
4140 }
4141
4142
4143
4144 /**
4145 * Update fragment shader state. This is called just prior to drawing
4146 * something when some fragment-related state has changed.
4147 */
4148 void
4149 llvmpipe_update_fs(struct llvmpipe_context *lp)
4150 {
4151 struct lp_fragment_shader *shader = lp->fs;
4152 struct lp_fragment_shader_variant_key *key;
4153 struct lp_fragment_shader_variant *variant = NULL;
4154 struct lp_fs_variant_list_item *li;
4155 char store[LP_FS_MAX_VARIANT_KEY_SIZE];
4156
4157 key = make_variant_key(lp, shader, store);
4158
4159 /* Search the variants for one which matches the key */
4160 li = first_elem(&shader->variants);
4161 while(!at_end(&shader->variants, li)) {
4162 if(memcmp(&li->base->key, key, shader->variant_key_size) == 0) {
4163 variant = li->base;
4164 break;
4165 }
4166 li = next_elem(li);
4167 }
4168
4169 if (variant) {
4170 /* Move this variant to the head of the list to implement LRU
4171 * deletion of shader's when we have too many.
4172 */
4173 move_to_head(&lp->fs_variants_list, &variant->list_item_global);
4174 }
4175 else {
4176 /* variant not found, create it now */
4177 int64_t t0, t1, dt;
4178 unsigned i;
4179 unsigned variants_to_cull;
4180
4181 if (LP_DEBUG & DEBUG_FS) {
4182 debug_printf("%u variants,\t%u instrs,\t%u instrs/variant\n",
4183 lp->nr_fs_variants,
4184 lp->nr_fs_instrs,
4185 lp->nr_fs_variants ? lp->nr_fs_instrs / lp->nr_fs_variants : 0);
4186 }
4187
4188 /* First, check if we've exceeded the max number of shader variants.
4189 * If so, free 6.25% of them (the least recently used ones).
4190 */
4191 variants_to_cull = lp->nr_fs_variants >= LP_MAX_SHADER_VARIANTS ? LP_MAX_SHADER_VARIANTS / 16 : 0;
4192
4193 if (variants_to_cull ||
4194 lp->nr_fs_instrs >= LP_MAX_SHADER_INSTRUCTIONS) {
4195 if (gallivm_debug & GALLIVM_DEBUG_PERF) {
4196 debug_printf("Evicting FS: %u fs variants,\t%u total variants,"
4197 "\t%u instrs,\t%u instrs/variant\n",
4198 shader->variants_cached,
4199 lp->nr_fs_variants, lp->nr_fs_instrs,
4200 lp->nr_fs_instrs / lp->nr_fs_variants);
4201 }
4202
4203 /*
4204 * We need to re-check lp->nr_fs_variants because an arbitrarliy large
4205 * number of shader variants (potentially all of them) could be
4206 * pending for destruction on flush.
4207 */
4208
4209 for (i = 0; i < variants_to_cull || lp->nr_fs_instrs >= LP_MAX_SHADER_INSTRUCTIONS; i++) {
4210 struct lp_fs_variant_list_item *item;
4211 if (is_empty_list(&lp->fs_variants_list)) {
4212 break;
4213 }
4214 item = last_elem(&lp->fs_variants_list);
4215 assert(item);
4216 assert(item->base);
4217 llvmpipe_remove_shader_variant(lp, item->base);
4218 lp_fs_variant_reference(lp, &item->base, NULL);
4219 }
4220 }
4221
4222 /*
4223 * Generate the new variant.
4224 */
4225 t0 = os_time_get();
4226 variant = generate_variant(lp, shader, key);
4227 t1 = os_time_get();
4228 dt = t1 - t0;
4229 LP_COUNT_ADD(llvm_compile_time, dt);
4230 LP_COUNT_ADD(nr_llvm_compiles, 2); /* emit vs. omit in/out test */
4231
4232 /* Put the new variant into the list */
4233 if (variant) {
4234 insert_at_head(&shader->variants, &variant->list_item_local);
4235 insert_at_head(&lp->fs_variants_list, &variant->list_item_global);
4236 lp->nr_fs_variants++;
4237 lp->nr_fs_instrs += variant->nr_instrs;
4238 shader->variants_cached++;
4239 }
4240 }
4241
4242 /* Bind this variant */
4243 lp_setup_set_fs_variant(lp->setup, variant);
4244 }
4245
4246
4247
4248
4249
4250 void
4251 llvmpipe_init_fs_funcs(struct llvmpipe_context *llvmpipe)
4252 {
4253 llvmpipe->pipe.create_fs_state = llvmpipe_create_fs_state;
4254 llvmpipe->pipe.bind_fs_state = llvmpipe_bind_fs_state;
4255 llvmpipe->pipe.delete_fs_state = llvmpipe_delete_fs_state;
4256
4257 llvmpipe->pipe.set_constant_buffer = llvmpipe_set_constant_buffer;
4258
4259 llvmpipe->pipe.set_shader_buffers = llvmpipe_set_shader_buffers;
4260 llvmpipe->pipe.set_shader_images = llvmpipe_set_shader_images;
4261 }
4262
4263