i965/blorp: allow all buffer formats provided src and dst match.
[profile/ivi/mesa.git] / src / mesa / drivers / dri / i965 / brw_blorp_blit.cpp
1 /*
2  * Copyright © 2012 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23
24 #include "main/teximage.h"
25
26 #include "glsl/ralloc.h"
27
28 #include "intel_fbo.h"
29
30 #include "brw_blorp.h"
31 #include "brw_context.h"
32 #include "brw_eu.h"
33 #include "brw_state.h"
34
35
36 /**
37  * Helper function for handling mirror image blits.
38  *
39  * If coord0 > coord1, swap them and invert the "mirror" boolean.
40  */
41 static inline void
42 fixup_mirroring(bool &mirror, GLint &coord0, GLint &coord1)
43 {
44    if (coord0 > coord1) {
45       mirror = !mirror;
46       GLint tmp = coord0;
47       coord0 = coord1;
48       coord1 = tmp;
49    }
50 }
51
52
53 /**
54  * Adjust {src,dst}_x{0,1} to account for clipping and scissoring of
55  * destination coordinates.
56  *
57  * Return true if there is still blitting to do, false if all pixels got
58  * rejected by the clip and/or scissor.
59  *
60  * For clarity, the nomenclature of this function assumes we are clipping and
61  * scissoring the X coordinate; the exact same logic applies for Y
62  * coordinates.
63  */
64 static inline bool
65 clip_or_scissor(bool mirror, GLint &src_x0, GLint &src_x1, GLint &dst_x0,
66                 GLint &dst_x1, GLint fb_xmin, GLint fb_xmax)
67 {
68    /* If we are going to scissor everything away, stop. */
69    if (!(fb_xmin < fb_xmax &&
70          dst_x0 < fb_xmax &&
71          fb_xmin < dst_x1 &&
72          dst_x0 < dst_x1)) {
73       return false;
74    }
75
76    /* Clip the destination rectangle, and keep track of how many pixels we
77     * clipped off of the left and right sides of it.
78     */
79    GLint pixels_clipped_left = 0;
80    GLint pixels_clipped_right = 0;
81    if (dst_x0 < fb_xmin) {
82       pixels_clipped_left = fb_xmin - dst_x0;
83       dst_x0 = fb_xmin;
84    }
85    if (fb_xmax < dst_x1) {
86       pixels_clipped_right = dst_x1 - fb_xmax;
87       dst_x1 = fb_xmax;
88    }
89
90    /* If we are mirrored, then before applying pixels_clipped_{left,right} to
91     * the source coordinates, we need to flip them to account for the
92     * mirroring.
93     */
94    if (mirror) {
95       GLint tmp = pixels_clipped_left;
96       pixels_clipped_left = pixels_clipped_right;
97       pixels_clipped_right = tmp;
98    }
99
100    /* Adjust the source rectangle to remove the pixels corresponding to those
101     * that were clipped/scissored out of the destination rectangle.
102     */
103    src_x0 += pixels_clipped_left;
104    src_x1 -= pixels_clipped_right;
105
106    return true;
107 }
108
109
110 static bool
111 try_blorp_blit(struct intel_context *intel,
112                GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
113                GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
114                GLenum filter, GLbitfield buffer_bit)
115 {
116    struct gl_context *ctx = &intel->ctx;
117
118    /* Sync up the state of window system buffers.  We need to do this before
119     * we go looking for the buffers.
120     */
121    intel_prepare_render(intel);
122
123    /* Find buffers */
124    const struct gl_framebuffer *read_fb = ctx->ReadBuffer;
125    const struct gl_framebuffer *draw_fb = ctx->DrawBuffer;
126    struct gl_renderbuffer *src_rb;
127    struct gl_renderbuffer *dst_rb;
128    switch (buffer_bit) {
129    case GL_COLOR_BUFFER_BIT:
130       src_rb = read_fb->_ColorReadBuffer;
131       dst_rb =
132          draw_fb->Attachment[
133             draw_fb->_ColorDrawBufferIndexes[0]].Renderbuffer;
134       break;
135    case GL_DEPTH_BUFFER_BIT:
136       src_rb = read_fb->Attachment[BUFFER_DEPTH].Renderbuffer;
137       dst_rb = draw_fb->Attachment[BUFFER_DEPTH].Renderbuffer;
138       break;
139    case GL_STENCIL_BUFFER_BIT:
140       src_rb = read_fb->Attachment[BUFFER_STENCIL].Renderbuffer;
141       dst_rb = draw_fb->Attachment[BUFFER_STENCIL].Renderbuffer;
142       break;
143    default:
144       assert(false);
145    }
146
147    /* Validate source */
148    if (!src_rb) return false;
149    struct intel_renderbuffer *src_irb = intel_renderbuffer(src_rb);
150    struct intel_mipmap_tree *src_mt = src_irb->mt;
151    if (!src_mt) return false;
152    if (buffer_bit == GL_STENCIL_BUFFER_BIT && src_mt->stencil_mt)
153       src_mt = src_mt->stencil_mt;
154
155    /* Validate destination */
156    if (!dst_rb) return false;
157    struct intel_renderbuffer *dst_irb = intel_renderbuffer(dst_rb);
158    struct intel_mipmap_tree *dst_mt = dst_irb->mt;
159    if (!dst_mt) return false;
160    if (buffer_bit == GL_STENCIL_BUFFER_BIT && dst_mt->stencil_mt)
161       dst_mt = dst_mt->stencil_mt;
162
163    /* Blorp blits can't translate from one format to another.  For that we'll
164     * have to fall back to the meta-op blit.  Note: the meta-op blit doesn't
165     * support multisampled blits, but fortunately this is ok because
166     * multisampled blits require identical source and destination formats.
167     */
168    if (src_mt->format != dst_mt->format)
169       return false;
170
171    /* Account for the fact that in the system framebuffer, the origin is at
172     * the lower left.
173     */
174    if (read_fb->Name == 0) {
175       srcY0 = read_fb->Height - srcY0;
176       srcY1 = read_fb->Height - srcY1;
177    }
178    if (draw_fb->Name == 0) {
179       dstY0 = draw_fb->Height - dstY0;
180       dstY1 = draw_fb->Height - dstY1;
181    }
182
183    /* Detect if the blit needs to be mirrored */
184    bool mirror_x = false, mirror_y = false;
185    fixup_mirroring(mirror_x, srcX0, srcX1);
186    fixup_mirroring(mirror_x, dstX0, dstX1);
187    fixup_mirroring(mirror_y, srcY0, srcY1);
188    fixup_mirroring(mirror_y, dstY0, dstY1);
189
190    /* Make sure width and height match */
191    GLsizei width = srcX1 - srcX0;
192    GLsizei height = srcY1 - srcY0;
193    if (width != dstX1 - dstX0) return false;
194    if (height != dstY1 - dstY0) return false;
195
196    /* If the destination rectangle needs to be clipped or scissored, do so.
197     */
198    if (!(clip_or_scissor(mirror_x, srcX0, srcX1, dstX0, dstX1,
199                          draw_fb->_Xmin, draw_fb->_Xmax) &&
200          clip_or_scissor(mirror_y, srcY0, srcY1, dstY0, dstY1,
201                          draw_fb->_Ymin, draw_fb->_Ymax))) {
202       /* Everything got clipped/scissored away, so the blit was successful. */
203       return true;
204    }
205
206    /* TODO: Clipping the source rectangle is not yet implemented. */
207    if (srcX0 < 0 || (GLuint) srcX1 > read_fb->Width) return false;
208    if (srcY0 < 0 || (GLuint) srcY1 > read_fb->Height) return false;
209
210    /* Get ready to blit.  This includes depth resolving the src and dst
211     * buffers if necessary.
212     */
213    intel_renderbuffer_resolve_depth(intel, src_irb);
214    intel_renderbuffer_resolve_depth(intel, dst_irb);
215
216    /* Do the blit */
217    brw_blorp_blit_params params(brw_context(ctx), src_mt, dst_mt,
218                                 srcX0, srcY0, dstX0, dstY0, dstX1, dstY1,
219                                 mirror_x, mirror_y);
220    brw_blorp_exec(intel, &params);
221
222    /* Mark the dst buffer as needing a HiZ resolve if necessary. */
223    intel_renderbuffer_set_needs_hiz_resolve(dst_irb);
224
225    return true;
226 }
227
228 GLbitfield
229 brw_blorp_framebuffer(struct intel_context *intel,
230                       GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
231                       GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
232                       GLbitfield mask, GLenum filter)
233 {
234    /* BLORP is not supported before Gen6. */
235    if (intel->gen < 6)
236       return mask;
237
238    static GLbitfield buffer_bits[] = {
239       GL_COLOR_BUFFER_BIT,
240       GL_DEPTH_BUFFER_BIT,
241       GL_STENCIL_BUFFER_BIT,
242    };
243
244    for (unsigned int i = 0; i < ARRAY_SIZE(buffer_bits); ++i) {
245       if ((mask & buffer_bits[i]) &&
246        try_blorp_blit(intel,
247                       srcX0, srcY0, srcX1, srcY1,
248                       dstX0, dstY0, dstX1, dstY1,
249                       filter, buffer_bits[i])) {
250          mask &= ~buffer_bits[i];
251       }
252    }
253
254    return mask;
255 }
256
257
258 /**
259  * Enum to specify the order of arguments in a sampler message
260  */
261 enum sampler_message_arg
262 {
263    SAMPLER_MESSAGE_ARG_U_FLOAT,
264    SAMPLER_MESSAGE_ARG_V_FLOAT,
265    SAMPLER_MESSAGE_ARG_U_INT,
266    SAMPLER_MESSAGE_ARG_V_INT,
267    SAMPLER_MESSAGE_ARG_SI_INT,
268    SAMPLER_MESSAGE_ARG_ZERO_INT,
269 };
270
271 /**
272  * Generator for WM programs used in BLORP blits.
273  *
274  * The bulk of the work done by the WM program is to wrap and unwrap the
275  * coordinate transformations used by the hardware to store surfaces in
276  * memory.  The hardware transforms a pixel location (X, Y, S) (where S is the
277  * sample index for a multisampled surface) to a memory offset by the
278  * following formulas:
279  *
280  *   offset = tile(tiling_format, encode_msaa(num_samples, layout, X, Y, S))
281  *   (X, Y, S) = decode_msaa(num_samples, layout, detile(tiling_format, offset))
282  *
283  * For a single-sampled surface, or for a multisampled surface that stores
284  * each sample in a different array slice, encode_msaa() and decode_msaa are
285  * the identity function:
286  *
287  *   encode_msaa(1, N/A, X, Y, 0) = (X, Y, 0)
288  *   decode_msaa(1, N/A, X, Y, 0) = (X, Y, 0)
289  *   encode_msaa(n, sliced, X, Y, S) = (X, Y, S)
290  *   decode_msaa(n, sliced, X, Y, S) = (X, Y, S)
291  *
292  * For a 4x interleaved multisampled surface, encode_msaa() embeds the sample
293  * number into bit 1 of the X and Y coordinates:
294  *
295  *   encode_msaa(4, interleaved, X, Y, S) = (X', Y', 0)
296  *     where X' = (X & ~0b1) << 1 | (S & 0b1) << 1 | (X & 0b1)
297  *           Y' = (Y & ~0b1 ) << 1 | (S & 0b10) | (Y & 0b1)
298  *   decode_msaa(4, interleaved, X, Y, 0) = (X', Y', S)
299  *     where X' = (X & ~0b11) >> 1 | (X & 0b1)
300  *           Y' = (Y & ~0b11) >> 1 | (Y & 0b1)
301  *           S = (Y & 0b10) | (X & 0b10) >> 1
302  *
303  * For X tiling, tile() combines together the low-order bits of the X and Y
304  * coordinates in the pattern 0byyyxxxxxxxxx, creating 4k tiles that are 512
305  * bytes wide and 8 rows high:
306  *
307  *   tile(x_tiled, X, Y, S) = A
308  *     where A = tile_num << 12 | offset
309  *           tile_num = (Y' >> 3) * tile_pitch + (X' >> 9)
310  *           offset = (Y' & 0b111) << 9
311  *                    | (X & 0b111111111)
312  *           X' = X * cpp
313  *           Y' = Y + S * qpitch
314  *   detile(x_tiled, A) = (X, Y, S)
315  *     where X = X' / cpp
316  *           Y = Y' % qpitch
317  *           S = Y' / qpitch
318  *           Y' = (tile_num / tile_pitch) << 3
319  *                | (A & 0b111000000000) >> 9
320  *           X' = (tile_num % tile_pitch) << 9
321  *                | (A & 0b111111111)
322  *
323  * (In all tiling formulas, cpp is the number of bytes occupied by a single
324  * sample ("chars per pixel"), tile_pitch is the number of 4k tiles required
325  * to fill the width of the surface, and qpitch is the spacing (in rows)
326  * between array slices).
327  *
328  * For Y tiling, tile() combines together the low-order bits of the X and Y
329  * coordinates in the pattern 0bxxxyyyyyxxxx, creating 4k tiles that are 128
330  * bytes wide and 32 rows high:
331  *
332  *   tile(y_tiled, X, Y, S) = A
333  *     where A = tile_num << 12 | offset
334  *           tile_num = (Y' >> 5) * tile_pitch + (X' >> 7)
335  *           offset = (X' & 0b1110000) << 5
336  *                    | (Y' & 0b11111) << 4
337  *                    | (X' & 0b1111)
338  *           X' = X * cpp
339  *           Y' = Y + S * qpitch
340  *   detile(y_tiled, A) = (X, Y, S)
341  *     where X = X' / cpp
342  *           Y = Y' % qpitch
343  *           S = Y' / qpitch
344  *           Y' = (tile_num / tile_pitch) << 5
345  *                | (A & 0b111110000) >> 4
346  *           X' = (tile_num % tile_pitch) << 7
347  *                | (A & 0b111000000000) >> 5
348  *                | (A & 0b1111)
349  *
350  * For W tiling, tile() combines together the low-order bits of the X and Y
351  * coordinates in the pattern 0bxxxyyyyxyxyx, creating 4k tiles that are 64
352  * bytes wide and 64 rows high (note that W tiling is only used for stencil
353  * buffers, which always have cpp = 1 and S=0):
354  *
355  *   tile(w_tiled, X, Y, S) = A
356  *     where A = tile_num << 12 | offset
357  *           tile_num = (Y' >> 6) * tile_pitch + (X' >> 6)
358  *           offset = (X' & 0b111000) << 6
359  *                    | (Y' & 0b111100) << 3
360  *                    | (X' & 0b100) << 2
361  *                    | (Y' & 0b10) << 2
362  *                    | (X' & 0b10) << 1
363  *                    | (Y' & 0b1) << 1
364  *                    | (X' & 0b1)
365  *           X' = X * cpp = X
366  *           Y' = Y + S * qpitch
367  *   detile(w_tiled, A) = (X, Y, S)
368  *     where X = X' / cpp = X'
369  *           Y = Y' % qpitch = Y'
370  *           S = Y / qpitch = 0
371  *           Y' = (tile_num / tile_pitch) << 6
372  *                | (A & 0b111100000) >> 3
373  *                | (A & 0b1000) >> 2
374  *                | (A & 0b10) >> 1
375  *           X' = (tile_num % tile_pitch) << 6
376  *                | (A & 0b111000000000) >> 6
377  *                | (A & 0b10000) >> 2
378  *                | (A & 0b100) >> 1
379  *                | (A & 0b1)
380  *
381  * Finally, for a non-tiled surface, tile() simply combines together the X and
382  * Y coordinates in the natural way:
383  *
384  *   tile(untiled, X, Y, S) = A
385  *     where A = Y * pitch + X'
386  *           X' = X * cpp
387  *           Y' = Y + S * qpitch
388  *   detile(untiled, A) = (X, Y, S)
389  *     where X = X' / cpp
390  *           Y = Y' % qpitch
391  *           S = Y' / qpitch
392  *           X' = A % pitch
393  *           Y' = A / pitch
394  *
395  * (In these formulas, pitch is the number of bytes occupied by a single row
396  * of samples).
397  */
398 class brw_blorp_blit_program
399 {
400 public:
401    brw_blorp_blit_program(struct brw_context *brw,
402                           const brw_blorp_blit_prog_key *key);
403    ~brw_blorp_blit_program();
404
405    const GLuint *compile(struct brw_context *brw, GLuint *program_size);
406
407    brw_blorp_prog_data prog_data;
408
409 private:
410    void alloc_regs();
411    void alloc_push_const_regs(int base_reg);
412    void compute_frag_coords();
413    void translate_tiling(bool old_tiled_w, bool new_tiled_w);
414    void encode_msaa(unsigned num_samples, bool interleaved);
415    void decode_msaa(unsigned num_samples, bool interleaved);
416    void kill_if_outside_dst_rect();
417    void translate_dst_to_src();
418    void single_to_blend();
419    void manual_blend();
420    void sample(struct brw_reg dst);
421    void texel_fetch(struct brw_reg dst);
422    void expand_to_32_bits(struct brw_reg src, struct brw_reg dst);
423    void texture_lookup(struct brw_reg dst, GLuint msg_type,
424                        const sampler_message_arg *args, int num_args);
425    void render_target_write();
426
427    void *mem_ctx;
428    struct brw_context *brw;
429    const brw_blorp_blit_prog_key *key;
430    struct brw_compile func;
431
432    /* Thread dispatch header */
433    struct brw_reg R0;
434
435    /* Pixel X/Y coordinates (always in R1). */
436    struct brw_reg R1;
437
438    /* Push constants */
439    struct brw_reg dst_x0;
440    struct brw_reg dst_x1;
441    struct brw_reg dst_y0;
442    struct brw_reg dst_y1;
443    struct {
444       struct brw_reg multiplier;
445       struct brw_reg offset;
446    } x_transform, y_transform;
447
448    /* Data to be written to render target (4 vec16's) */
449    struct brw_reg result;
450
451    /* Auxiliary storage for data returned by a sampling operation when
452     * blending (4 vec16's)
453     */
454    struct brw_reg texture_data;
455
456    /* X coordinates.  We have two of them so that we can perform coordinate
457     * transformations easily.
458     */
459    struct brw_reg x_coords[2];
460
461    /* Y coordinates.  We have two of them so that we can perform coordinate
462     * transformations easily.
463     */
464    struct brw_reg y_coords[2];
465
466    /* Which element of x_coords and y_coords is currently in use.
467     */
468    int xy_coord_index;
469
470    /* True if, at the point in the program currently being compiled, the
471     * sample index is known to be zero.
472     */
473    bool s_is_zero;
474
475    /* Register storing the sample index when s_is_zero is false. */
476    struct brw_reg sample_index;
477
478    /* Temporaries */
479    struct brw_reg t1;
480    struct brw_reg t2;
481
482    /* MRF used for sampling and render target writes */
483    GLuint base_mrf;
484 };
485
486 brw_blorp_blit_program::brw_blorp_blit_program(
487       struct brw_context *brw,
488       const brw_blorp_blit_prog_key *key)
489    : mem_ctx(ralloc_context(NULL)),
490      brw(brw),
491      key(key)
492 {
493    brw_init_compile(brw, &func, mem_ctx);
494 }
495
496 brw_blorp_blit_program::~brw_blorp_blit_program()
497 {
498    ralloc_free(mem_ctx);
499 }
500
501 const GLuint *
502 brw_blorp_blit_program::compile(struct brw_context *brw,
503                                 GLuint *program_size)
504 {
505    /* Since blorp uses color textures and render targets to do all its work
506     * (even when blitting stencil and depth data), we always have to configure
507     * the Gen7 GPU to use sliced layout on Gen7.  On Gen6, the MSAA layout is
508     * always interleaved.
509     */
510    const bool rt_interleaved = key->rt_samples > 0 && brw->intel.gen == 6;
511    const bool tex_interleaved = key->tex_samples > 0 && brw->intel.gen == 6;
512
513    /* Sanity checks */
514    if (key->dst_tiled_w && key->rt_samples > 0) {
515       /* If the destination image is W tiled and multisampled, then the thread
516        * must be dispatched once per sample, not once per pixel.  This is
517        * necessary because after conversion between W and Y tiling, there's no
518        * guarantee that all samples corresponding to a single pixel will still
519        * be together.
520        */
521       assert(key->persample_msaa_dispatch);
522    }
523
524    if (key->blend) {
525       /* We are blending, which means we won't have an opportunity to
526        * translate the tiling and sample count for the texture surface.  So
527        * the surface state for the texture must be configured with the correct
528        * tiling and sample count.
529        */
530       assert(!key->src_tiled_w);
531       assert(key->tex_samples == key->src_samples);
532       assert(tex_interleaved == key->src_interleaved);
533       assert(key->tex_samples > 0);
534    }
535
536    if (key->persample_msaa_dispatch) {
537       /* It only makes sense to do persample dispatch if the render target is
538        * configured as multisampled.
539        */
540       assert(key->rt_samples > 0);
541    }
542
543    /* Interleaved only makes sense on MSAA surfaces */
544    if (tex_interleaved) assert(key->tex_samples > 0);
545    if (key->src_interleaved) assert(key->src_samples > 0);
546    if (key->dst_interleaved) assert(key->dst_samples > 0);
547
548    /* Set up prog_data */
549    memset(&prog_data, 0, sizeof(prog_data));
550    prog_data.persample_msaa_dispatch = key->persample_msaa_dispatch;
551
552    brw_set_compression_control(&func, BRW_COMPRESSION_NONE);
553
554    alloc_regs();
555    compute_frag_coords();
556
557    /* Render target and texture hardware don't support W tiling. */
558    const bool rt_tiled_w = false;
559    const bool tex_tiled_w = false;
560
561    /* The address that data will be written to is determined by the
562     * coordinates supplied to the WM thread and the tiling and sample count of
563     * the render target, according to the formula:
564     *
565     * (X, Y, S) = decode_msaa(rt_samples, detile(rt_tiling, offset))
566     *
567     * If the actual tiling and sample count of the destination surface are not
568     * the same as the configuration of the render target, then these
569     * coordinates are wrong and we have to adjust them to compensate for the
570     * difference.
571     */
572    if (rt_tiled_w != key->dst_tiled_w ||
573        key->rt_samples != key->dst_samples ||
574        rt_interleaved != key->dst_interleaved) {
575       encode_msaa(key->rt_samples, rt_interleaved);
576       /* Now (X, Y, S) = detile(rt_tiling, offset) */
577       translate_tiling(rt_tiled_w, key->dst_tiled_w);
578       /* Now (X, Y, S) = detile(dst_tiling, offset) */
579       decode_msaa(key->dst_samples, key->dst_interleaved);
580    }
581
582    /* Now (X, Y, S) = decode_msaa(dst_samples, detile(dst_tiling, offset)).
583     *
584     * That is: X, Y and S now contain the true coordinates and sample index of
585     * the data that the WM thread should output.
586     *
587     * If we need to kill pixels that are outside the destination rectangle,
588     * now is the time to do it.
589     */
590
591    if (key->use_kill)
592       kill_if_outside_dst_rect();
593
594    /* Next, apply a translation to obtain coordinates in the source image. */
595    translate_dst_to_src();
596
597    /* If the source image is not multisampled, then we want to fetch sample
598     * number 0, because that's the only sample there is.
599     */
600    if (key->src_samples == 0)
601       s_is_zero = true;
602
603    /* X, Y, and S are now the coordinates of the pixel in the source image
604     * that we want to texture from.  Exception: if we are blending, then S is
605     * irrelevant, because we are going to fetch all samples.
606     */
607    if (key->blend) {
608       if (brw->intel.gen == 6) {
609          /* Gen6 hardware an automatically blend using the SAMPLE message */
610          single_to_blend();
611          sample(result);
612       } else {
613          /* Gen7+ hardware doesn't automaticaly blend. */
614          manual_blend();
615       }
616    } else {
617       /* We aren't blending, which means we just want to fetch a single sample
618        * from the source surface.  The address that we want to fetch from is
619        * related to the X, Y and S values according to the formula:
620        *
621        * (X, Y, S) = decode_msaa(src_samples, detile(src_tiling, offset)).
622        *
623        * If the actual tiling and sample count of the source surface are not
624        * the same as the configuration of the texture, then we need to adjust
625        * the coordinates to compensate for the difference.
626        */
627       if (tex_tiled_w != key->src_tiled_w ||
628           key->tex_samples != key->src_samples ||
629           tex_interleaved != key->src_interleaved) {
630          encode_msaa(key->src_samples, key->src_interleaved);
631          /* Now (X, Y, S) = detile(src_tiling, offset) */
632          translate_tiling(key->src_tiled_w, tex_tiled_w);
633          /* Now (X, Y, S) = detile(tex_tiling, offset) */
634          decode_msaa(key->tex_samples, tex_interleaved);
635       }
636
637       /* Now (X, Y, S) = decode_msaa(tex_samples, detile(tex_tiling, offset)).
638        *
639        * In other words: X, Y, and S now contain values which, when passed to
640        * the texturing unit, will cause data to be read from the correct
641        * memory location.  So we can fetch the texel now.
642        */
643       texel_fetch(result);
644    }
645
646    /* Finally, write the fetched (or blended) value to the render target and
647     * terminate the thread.
648     */
649    render_target_write();
650    return brw_get_program(&func, program_size);
651 }
652
653 void
654 brw_blorp_blit_program::alloc_push_const_regs(int base_reg)
655 {
656 #define CONST_LOC(name) offsetof(brw_blorp_wm_push_constants, name)
657 #define ALLOC_REG(name) \
658    this->name = \
659       brw_uw1_reg(BRW_GENERAL_REGISTER_FILE, base_reg, CONST_LOC(name) / 2)
660
661    ALLOC_REG(dst_x0);
662    ALLOC_REG(dst_x1);
663    ALLOC_REG(dst_y0);
664    ALLOC_REG(dst_y1);
665    ALLOC_REG(x_transform.multiplier);
666    ALLOC_REG(x_transform.offset);
667    ALLOC_REG(y_transform.multiplier);
668    ALLOC_REG(y_transform.offset);
669 #undef CONST_LOC
670 #undef ALLOC_REG
671 }
672
673 void
674 brw_blorp_blit_program::alloc_regs()
675 {
676    int reg = 0;
677    this->R0 = retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW);
678    this->R1 = retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW);
679    prog_data.first_curbe_grf = reg;
680    alloc_push_const_regs(reg);
681    reg += BRW_BLORP_NUM_PUSH_CONST_REGS;
682    this->result = vec16(brw_vec8_grf(reg, 0)); reg += 8;
683    this->texture_data = vec16(brw_vec8_grf(reg, 0)); reg += 8;
684    for (int i = 0; i < 2; ++i) {
685       this->x_coords[i]
686          = vec16(retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW));
687       this->y_coords[i]
688          = vec16(retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW));
689    }
690    this->xy_coord_index = 0;
691    this->sample_index
692       = vec16(retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW));
693    this->t1 = vec16(retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW));
694    this->t2 = vec16(retype(brw_vec8_grf(reg++, 0), BRW_REGISTER_TYPE_UW));
695
696    int mrf = 2;
697    this->base_mrf = mrf;
698 }
699
700 /* In the code that follows, X and Y can be used to quickly refer to the
701  * active elements of x_coords and y_coords, and Xp and Yp ("X prime" and "Y
702  * prime") to the inactive elements.
703  *
704  * S can be used to quickly refer to sample_index.
705  */
706 #define X x_coords[xy_coord_index]
707 #define Y y_coords[xy_coord_index]
708 #define Xp x_coords[!xy_coord_index]
709 #define Yp y_coords[!xy_coord_index]
710 #define S sample_index
711
712 /* Quickly swap the roles of (X, Y) and (Xp, Yp).  Saves us from having to do
713  * MOVs to transfor (Xp, Yp) to (X, Y) after a coordinate transformation.
714  */
715 #define SWAP_XY_AND_XPYP() xy_coord_index = !xy_coord_index;
716
717 /**
718  * Emit code to compute the X and Y coordinates of the pixels being rendered
719  * by this WM invocation.
720  *
721  * Assuming the render target is set up for Y tiling, these (X, Y) values are
722  * related to the address offset where outputs will be written by the formula:
723  *
724  *   (X, Y, S) = decode_msaa(detile(offset)).
725  *
726  * (See brw_blorp_blit_program).
727  */
728 void
729 brw_blorp_blit_program::compute_frag_coords()
730 {
731    /* R1.2[15:0] = X coordinate of upper left pixel of subspan 0 (pixel 0)
732     * R1.3[15:0] = X coordinate of upper left pixel of subspan 1 (pixel 4)
733     * R1.4[15:0] = X coordinate of upper left pixel of subspan 2 (pixel 8)
734     * R1.5[15:0] = X coordinate of upper left pixel of subspan 3 (pixel 12)
735     *
736     * Pixels within a subspan are laid out in this arrangement:
737     * 0 1
738     * 2 3
739     *
740     * So, to compute the coordinates of each pixel, we need to read every 2nd
741     * 16-bit value (vstride=2) from R1, starting at the 4th 16-bit value
742     * (suboffset=4), and duplicate each value 4 times (hstride=0, width=4).
743     * In other words, the data we want to access is R1.4<2;4,0>UW.
744     *
745     * Then, we need to add the repeating sequence (0, 1, 0, 1, ...) to the
746     * result, since pixels n+1 and n+3 are in the right half of the subspan.
747     */
748    brw_ADD(&func, X, stride(suboffset(R1, 4), 2, 4, 0), brw_imm_v(0x10101010));
749
750    /* Similarly, Y coordinates for subspans come from R1.2[31:16] through
751     * R1.5[31:16], so to get pixel Y coordinates we need to start at the 5th
752     * 16-bit value instead of the 4th (R1.5<2;4,0>UW instead of
753     * R1.4<2;4,0>UW).
754     *
755     * And we need to add the repeating sequence (0, 0, 1, 1, ...), since
756     * pixels n+2 and n+3 are in the bottom half of the subspan.
757     */
758    brw_ADD(&func, Y, stride(suboffset(R1, 5), 2, 4, 0), brw_imm_v(0x11001100));
759
760    if (key->persample_msaa_dispatch) {
761       /* The WM will be run in MSDISPMODE_PERSAMPLE with num_samples > 0.
762        * Therefore, subspan 0 will represent sample 0, subspan 1 will
763        * represent sample 1, and so on.
764        *
765        * So we need to populate S with the sequence (0, 0, 0, 0, 1, 1, 1, 1,
766        * 2, 2, 2, 2, 3, 3, 3, 3).  The easiest way to do this is to populate a
767        * temporary variable with the sequence (0, 1, 2, 3), and then copy from
768        * it using vstride=1, width=4, hstride=0.
769        *
770        * TODO: implement the necessary calculation for 8x multisampling.
771        */
772       brw_MOV(&func, t1, brw_imm_v(0x3210));
773       brw_MOV(&func, S, stride(t1, 1, 4, 0));
774       s_is_zero = false;
775    } else {
776       /* Either the destination surface is single-sampled, or the WM will be
777        * run in MSDISPMODE_PERPIXEL (which causes a single fragment dispatch
778        * per pixel).  In either case, it's not meaningful to compute a sample
779        * value.  Just set it to 0.
780        */
781       s_is_zero = true;
782    }
783 }
784
785 /**
786  * Emit code to compensate for the difference between Y and W tiling.
787  *
788  * This code modifies the X and Y coordinates according to the formula:
789  *
790  *   (X', Y', S') = detile(new_tiling, tile(old_tiling, X, Y, S))
791  *
792  * (See brw_blorp_blit_program).
793  *
794  * It can only translate between W and Y tiling, so new_tiling and old_tiling
795  * are booleans where true represents W tiling and false represents Y tiling.
796  */
797 void
798 brw_blorp_blit_program::translate_tiling(bool old_tiled_w, bool new_tiled_w)
799 {
800    if (old_tiled_w == new_tiled_w)
801       return;
802
803    /* In the code that follows, we can safely assume that S = 0, because W
804     * tiling formats always use interleaved encoding.
805     */
806    assert(s_is_zero);
807
808    if (new_tiled_w) {
809       /* Given X and Y coordinates that describe an address using Y tiling,
810        * translate to the X and Y coordinates that describe the same address
811        * using W tiling.
812        *
813        * If we break down the low order bits of X and Y, using a
814        * single letter to represent each low-order bit:
815        *
816        *   X = A << 7 | 0bBCDEFGH
817        *   Y = J << 5 | 0bKLMNP                                       (1)
818        *
819        * Then we can apply the Y tiling formula to see the memory offset being
820        * addressed:
821        *
822        *   offset = (J * tile_pitch + A) << 12 | 0bBCDKLMNPEFGH       (2)
823        *
824        * If we apply the W detiling formula to this memory location, that the
825        * corresponding X' and Y' coordinates are:
826        *
827        *   X' = A << 6 | 0bBCDPFH                                     (3)
828        *   Y' = J << 6 | 0bKLMNEG
829        *
830        * Combining (1) and (3), we see that to transform (X, Y) to (X', Y'),
831        * we need to make the following computation:
832        *
833        *   X' = (X & ~0b1011) >> 1 | (Y & 0b1) << 2 | X & 0b1         (4)
834        *   Y' = (Y & ~0b1) << 1 | (X & 0b1000) >> 2 | (X & 0b10) >> 1
835        */
836       brw_AND(&func, t1, X, brw_imm_uw(0xfff4)); /* X & ~0b1011 */
837       brw_SHR(&func, t1, t1, brw_imm_uw(1)); /* (X & ~0b1011) >> 1 */
838       brw_AND(&func, t2, Y, brw_imm_uw(1)); /* Y & 0b1 */
839       brw_SHL(&func, t2, t2, brw_imm_uw(2)); /* (Y & 0b1) << 2 */
840       brw_OR(&func, t1, t1, t2); /* (X & ~0b1011) >> 1 | (Y & 0b1) << 2 */
841       brw_AND(&func, t2, X, brw_imm_uw(1)); /* X & 0b1 */
842       brw_OR(&func, Xp, t1, t2);
843       brw_AND(&func, t1, Y, brw_imm_uw(0xfffe)); /* Y & ~0b1 */
844       brw_SHL(&func, t1, t1, brw_imm_uw(1)); /* (Y & ~0b1) << 1 */
845       brw_AND(&func, t2, X, brw_imm_uw(8)); /* X & 0b1000 */
846       brw_SHR(&func, t2, t2, brw_imm_uw(2)); /* (X & 0b1000) >> 2 */
847       brw_OR(&func, t1, t1, t2); /* (Y & ~0b1) << 1 | (X & 0b1000) >> 2 */
848       brw_AND(&func, t2, X, brw_imm_uw(2)); /* X & 0b10 */
849       brw_SHR(&func, t2, t2, brw_imm_uw(1)); /* (X & 0b10) >> 1 */
850       brw_OR(&func, Yp, t1, t2);
851       SWAP_XY_AND_XPYP();
852    } else {
853       /* Applying the same logic as above, but in reverse, we obtain the
854        * formulas:
855        *
856        * X' = (X & ~0b101) << 1 | (Y & 0b10) << 2 | (Y & 0b1) << 1 | X & 0b1
857        * Y' = (Y & ~0b11) >> 1 | (X & 0b100) >> 2
858        */
859       brw_AND(&func, t1, X, brw_imm_uw(0xfffa)); /* X & ~0b101 */
860       brw_SHL(&func, t1, t1, brw_imm_uw(1)); /* (X & ~0b101) << 1 */
861       brw_AND(&func, t2, Y, brw_imm_uw(2)); /* Y & 0b10 */
862       brw_SHL(&func, t2, t2, brw_imm_uw(2)); /* (Y & 0b10) << 2 */
863       brw_OR(&func, t1, t1, t2); /* (X & ~0b101) << 1 | (Y & 0b10) << 2 */
864       brw_AND(&func, t2, Y, brw_imm_uw(1)); /* Y & 0b1 */
865       brw_SHL(&func, t2, t2, brw_imm_uw(1)); /* (Y & 0b1) << 1 */
866       brw_OR(&func, t1, t1, t2); /* (X & ~0b101) << 1 | (Y & 0b10) << 2
867                                     | (Y & 0b1) << 1 */
868       brw_AND(&func, t2, X, brw_imm_uw(1)); /* X & 0b1 */
869       brw_OR(&func, Xp, t1, t2);
870       brw_AND(&func, t1, Y, brw_imm_uw(0xfffc)); /* Y & ~0b11 */
871       brw_SHR(&func, t1, t1, brw_imm_uw(1)); /* (Y & ~0b11) >> 1 */
872       brw_AND(&func, t2, X, brw_imm_uw(4)); /* X & 0b100 */
873       brw_SHR(&func, t2, t2, brw_imm_uw(2)); /* (X & 0b100) >> 2 */
874       brw_OR(&func, Yp, t1, t2);
875       SWAP_XY_AND_XPYP();
876    }
877 }
878
879 /**
880  * Emit code to compensate for the difference between MSAA and non-MSAA
881  * surfaces.
882  *
883  * This code modifies the X and Y coordinates according to the formula:
884  *
885  *   (X', Y', S') = encode_msaa_4x(X, Y, S)
886  *
887  * (See brw_blorp_blit_program).
888  */
889 void
890 brw_blorp_blit_program::encode_msaa(unsigned num_samples, bool interleaved)
891 {
892    if (num_samples == 0) {
893       /* No translation necessary, and S should already be zero. */
894       assert(s_is_zero);
895    } else if (!interleaved) {
896       /* No translation necessary. */
897    } else {
898       /* encode_msaa(4, interleaved, X, Y, S) = (X', Y', 0)
899        *   where X' = (X & ~0b1) << 1 | (S & 0b1) << 1 | (X & 0b1)
900        *         Y' = (Y & ~0b1 ) << 1 | (S & 0b10) | (Y & 0b1)
901        */
902       brw_AND(&func, t1, X, brw_imm_uw(0xfffe)); /* X & ~0b1 */
903       if (!s_is_zero) {
904          brw_AND(&func, t2, S, brw_imm_uw(1)); /* S & 0b1 */
905          brw_OR(&func, t1, t1, t2); /* (X & ~0b1) | (S & 0b1) */
906       }
907       brw_SHL(&func, t1, t1, brw_imm_uw(1)); /* (X & ~0b1) << 1
908                                                 | (S & 0b1) << 1 */
909       brw_AND(&func, t2, X, brw_imm_uw(1)); /* X & 0b1 */
910       brw_OR(&func, Xp, t1, t2);
911       brw_AND(&func, t1, Y, brw_imm_uw(0xfffe)); /* Y & ~0b1 */
912       brw_SHL(&func, t1, t1, brw_imm_uw(1)); /* (Y & ~0b1) << 1 */
913       if (!s_is_zero) {
914          brw_AND(&func, t2, S, brw_imm_uw(2)); /* S & 0b10 */
915          brw_OR(&func, t1, t1, t2); /* (Y & ~0b1) << 1 | (S & 0b10) */
916       }
917       brw_AND(&func, t2, Y, brw_imm_uw(1));
918       brw_OR(&func, Yp, t1, t2);
919       SWAP_XY_AND_XPYP();
920       s_is_zero = true;
921    }
922 }
923
924 /**
925  * Emit code to compensate for the difference between MSAA and non-MSAA
926  * surfaces.
927  *
928  * This code modifies the X and Y coordinates according to the formula:
929  *
930  *   (X', Y', S) = decode_msaa(num_samples, X, Y, S)
931  *
932  * (See brw_blorp_blit_program).
933  */
934 void
935 brw_blorp_blit_program::decode_msaa(unsigned num_samples, bool interleaved)
936 {
937    if (num_samples == 0) {
938       /* No translation necessary, and S should already be zero. */
939       assert(s_is_zero);
940    } else if (!interleaved) {
941       /* No translation necessary. */
942    } else {
943       /* decode_msaa(4, interleaved, X, Y, 0) = (X', Y', S)
944        *   where X' = (X & ~0b11) >> 1 | (X & 0b1)
945        *         Y' = (Y & ~0b11) >> 1 | (Y & 0b1)
946        *         S = (Y & 0b10) | (X & 0b10) >> 1
947        */
948       assert(s_is_zero);
949       brw_AND(&func, t1, X, brw_imm_uw(0xfffc)); /* X & ~0b11 */
950       brw_SHR(&func, t1, t1, brw_imm_uw(1)); /* (X & ~0b11) >> 1 */
951       brw_AND(&func, t2, X, brw_imm_uw(1)); /* X & 0b1 */
952       brw_OR(&func, Xp, t1, t2);
953       brw_AND(&func, t1, Y, brw_imm_uw(0xfffc)); /* Y & ~0b11 */
954       brw_SHR(&func, t1, t1, brw_imm_uw(1)); /* (Y & ~0b11) >> 1 */
955       brw_AND(&func, t2, Y, brw_imm_uw(1)); /* Y & 0b1 */
956       brw_OR(&func, Yp, t1, t2);
957       brw_AND(&func, t1, Y, brw_imm_uw(2)); /* Y & 0b10 */
958       brw_AND(&func, t2, X, brw_imm_uw(2)); /* X & 0b10 */
959       brw_SHR(&func, t2, t2, brw_imm_uw(1)); /* (X & 0b10) >> 1 */
960       brw_OR(&func, S, t1, t2);
961       s_is_zero = false;
962       SWAP_XY_AND_XPYP();
963    }
964 }
965
966 /**
967  * Emit code that kills pixels whose X and Y coordinates are outside the
968  * boundary of the rectangle defined by the push constants (dst_x0, dst_y0,
969  * dst_x1, dst_y1).
970  */
971 void
972 brw_blorp_blit_program::kill_if_outside_dst_rect()
973 {
974    struct brw_reg f0 = brw_flag_reg();
975    struct brw_reg g1 = retype(brw_vec1_grf(1, 7), BRW_REGISTER_TYPE_UW);
976    struct brw_reg null16 = vec16(retype(brw_null_reg(), BRW_REGISTER_TYPE_UW));
977
978    brw_CMP(&func, null16, BRW_CONDITIONAL_GE, X, dst_x0);
979    brw_CMP(&func, null16, BRW_CONDITIONAL_GE, Y, dst_y0);
980    brw_CMP(&func, null16, BRW_CONDITIONAL_L, X, dst_x1);
981    brw_CMP(&func, null16, BRW_CONDITIONAL_L, Y, dst_y1);
982
983    brw_set_predicate_control(&func, BRW_PREDICATE_NONE);
984    brw_push_insn_state(&func);
985    brw_set_mask_control(&func, BRW_MASK_DISABLE);
986    brw_AND(&func, g1, f0, g1);
987    brw_pop_insn_state(&func);
988 }
989
990 /**
991  * Emit code to translate from destination (X, Y) coordinates to source (X, Y)
992  * coordinates.
993  */
994 void
995 brw_blorp_blit_program::translate_dst_to_src()
996 {
997    brw_MUL(&func, Xp, X, x_transform.multiplier);
998    brw_MUL(&func, Yp, Y, y_transform.multiplier);
999    brw_ADD(&func, Xp, Xp, x_transform.offset);
1000    brw_ADD(&func, Yp, Yp, y_transform.offset);
1001    SWAP_XY_AND_XPYP();
1002 }
1003
1004 /**
1005  * Emit code to transform the X and Y coordinates as needed for blending
1006  * together the different samples in an MSAA texture.
1007  */
1008 void
1009 brw_blorp_blit_program::single_to_blend()
1010 {
1011    /* When looking up samples in an MSAA texture using the SAMPLE message,
1012     * Gen6 requires the texture coordinates to be odd integers (so that they
1013     * correspond to the center of a 2x2 block representing the four samples
1014     * that maxe up a pixel).  So we need to multiply our X and Y coordinates
1015     * each by 2 and then add 1.
1016     */
1017    brw_SHL(&func, t1, X, brw_imm_w(1));
1018    brw_SHL(&func, t2, Y, brw_imm_w(1));
1019    brw_ADD(&func, Xp, t1, brw_imm_w(1));
1020    brw_ADD(&func, Yp, t2, brw_imm_w(1));
1021    SWAP_XY_AND_XPYP();
1022 }
1023
1024 void
1025 brw_blorp_blit_program::manual_blend()
1026 {
1027    /* TODO: support num_samples != 4 */
1028    const int num_samples = 4;
1029
1030    /* Gather sample 0 data first */
1031    s_is_zero = true;
1032    texel_fetch(result);
1033
1034    /* Gather data for remaining samples and accumulate it into result. */
1035    s_is_zero = false;
1036    for (int i = 1; i < num_samples; ++i) {
1037       brw_MOV(&func, S, brw_imm_uw(i));
1038       texel_fetch(texture_data);
1039
1040       /* TODO: should use a smaller loop bound for non-RGBA formats */
1041       for (int j = 0; j < 4; ++j) {
1042          brw_ADD(&func, offset(result, 2*j), offset(vec8(result), 2*j),
1043                  offset(vec8(texture_data), 2*j));
1044       }
1045    }
1046
1047    /* Scale the result down by a factor of num_samples */
1048    /* TODO: should use a smaller loop bound for non-RGBA formats */
1049    for (int j = 0; j < 4; ++j) {
1050       brw_MUL(&func, offset(result, 2*j), offset(vec8(result), 2*j),
1051               brw_imm_f(1.0/num_samples));
1052    }
1053 }
1054
1055 /**
1056  * Emit code to look up a value in the texture using the SAMPLE message (which
1057  * does blending of MSAA surfaces).
1058  */
1059 void
1060 brw_blorp_blit_program::sample(struct brw_reg dst)
1061 {
1062    static const sampler_message_arg args[2] = {
1063       SAMPLER_MESSAGE_ARG_U_FLOAT,
1064       SAMPLER_MESSAGE_ARG_V_FLOAT
1065    };
1066
1067    texture_lookup(dst, GEN5_SAMPLER_MESSAGE_SAMPLE, args, ARRAY_SIZE(args));
1068 }
1069
1070 /**
1071  * Emit code to look up a value in the texture using the SAMPLE_LD message
1072  * (which does a simple texel fetch).
1073  */
1074 void
1075 brw_blorp_blit_program::texel_fetch(struct brw_reg dst)
1076 {
1077    static const sampler_message_arg gen6_args[5] = {
1078       SAMPLER_MESSAGE_ARG_U_INT,
1079       SAMPLER_MESSAGE_ARG_V_INT,
1080       SAMPLER_MESSAGE_ARG_ZERO_INT, /* R */
1081       SAMPLER_MESSAGE_ARG_ZERO_INT, /* LOD */
1082       SAMPLER_MESSAGE_ARG_SI_INT
1083    };
1084    static const sampler_message_arg gen7_ld_args[3] = {
1085       SAMPLER_MESSAGE_ARG_U_INT,
1086       SAMPLER_MESSAGE_ARG_ZERO_INT, /* LOD */
1087       SAMPLER_MESSAGE_ARG_V_INT
1088    };
1089    static const sampler_message_arg gen7_ld2dss_args[3] = {
1090       SAMPLER_MESSAGE_ARG_SI_INT,
1091       SAMPLER_MESSAGE_ARG_U_INT,
1092       SAMPLER_MESSAGE_ARG_V_INT
1093    };
1094
1095    switch (brw->intel.gen) {
1096    case 6:
1097       texture_lookup(dst, GEN5_SAMPLER_MESSAGE_SAMPLE_LD, gen6_args,
1098                      s_is_zero ? 2 : 5);
1099       break;
1100    case 7:
1101       if (key->tex_samples > 0) {
1102          texture_lookup(dst, GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DSS,
1103                         gen7_ld2dss_args, ARRAY_SIZE(gen7_ld2dss_args));
1104       } else {
1105          assert(s_is_zero);
1106          texture_lookup(dst, GEN5_SAMPLER_MESSAGE_SAMPLE_LD, gen7_ld_args,
1107                         ARRAY_SIZE(gen7_ld_args));
1108       }
1109       break;
1110    default:
1111       assert(!"Should not get here.");
1112       break;
1113    };
1114 }
1115
1116 void
1117 brw_blorp_blit_program::expand_to_32_bits(struct brw_reg src,
1118                                           struct brw_reg dst)
1119 {
1120    brw_MOV(&func, vec8(dst), vec8(src));
1121    brw_set_compression_control(&func, BRW_COMPRESSION_2NDHALF);
1122    brw_MOV(&func, offset(vec8(dst), 1), suboffset(vec8(src), 8));
1123    brw_set_compression_control(&func, BRW_COMPRESSION_NONE);
1124 }
1125
1126 void
1127 brw_blorp_blit_program::texture_lookup(struct brw_reg dst,
1128                                        GLuint msg_type,
1129                                        const sampler_message_arg *args,
1130                                        int num_args)
1131 {
1132    struct brw_reg mrf =
1133       retype(vec16(brw_message_reg(base_mrf)), BRW_REGISTER_TYPE_UD);
1134    for (int arg = 0; arg < num_args; ++arg) {
1135       switch (args[arg]) {
1136       case SAMPLER_MESSAGE_ARG_U_FLOAT:
1137          expand_to_32_bits(X, retype(mrf, BRW_REGISTER_TYPE_F));
1138          break;
1139       case SAMPLER_MESSAGE_ARG_V_FLOAT:
1140          expand_to_32_bits(Y, retype(mrf, BRW_REGISTER_TYPE_F));
1141          break;
1142       case SAMPLER_MESSAGE_ARG_U_INT:
1143          expand_to_32_bits(X, mrf);
1144          break;
1145       case SAMPLER_MESSAGE_ARG_V_INT:
1146          expand_to_32_bits(Y, mrf);
1147          break;
1148       case SAMPLER_MESSAGE_ARG_SI_INT:
1149          /* Note: on Gen7, this code may be reached with s_is_zero==true
1150           * because in Gen7's ld2dss message, the sample index is the first
1151           * argument.  When this happens, we need to move a 0 into the
1152           * appropriate message register.
1153           */
1154          if (s_is_zero)
1155             brw_MOV(&func, mrf, brw_imm_ud(0));
1156          else
1157             expand_to_32_bits(S, mrf);
1158          break;
1159       case SAMPLER_MESSAGE_ARG_ZERO_INT:
1160          brw_MOV(&func, mrf, brw_imm_ud(0));
1161          break;
1162       }
1163       mrf.nr += 2;
1164    }
1165
1166    brw_SAMPLE(&func,
1167               retype(dst, BRW_REGISTER_TYPE_UW) /* dest */,
1168               base_mrf /* msg_reg_nr */,
1169               brw_message_reg(base_mrf) /* src0 */,
1170               BRW_BLORP_TEXTURE_BINDING_TABLE_INDEX,
1171               0 /* sampler */,
1172               WRITEMASK_XYZW,
1173               msg_type,
1174               8 /* response_length.  TODO: should be smaller for non-RGBA formats? */,
1175               mrf.nr - base_mrf /* msg_length */,
1176               0 /* header_present */,
1177               BRW_SAMPLER_SIMD_MODE_SIMD16,
1178               BRW_SAMPLER_RETURN_FORMAT_FLOAT32);
1179 }
1180
1181 #undef X
1182 #undef Y
1183 #undef U
1184 #undef V
1185 #undef S
1186 #undef SWAP_XY_AND_XPYP
1187
1188 void
1189 brw_blorp_blit_program::render_target_write()
1190 {
1191    struct brw_reg mrf_rt_write = vec16(brw_message_reg(base_mrf));
1192    int mrf_offset = 0;
1193
1194    /* If we may have killed pixels, then we need to send R0 and R1 in a header
1195     * so that the render target knows which pixels we killed.
1196     */
1197    bool use_header = key->use_kill;
1198    if (use_header) {
1199       /* Copy R0/1 to MRF */
1200       brw_MOV(&func, retype(mrf_rt_write, BRW_REGISTER_TYPE_UD),
1201               retype(R0, BRW_REGISTER_TYPE_UD));
1202       mrf_offset += 2;
1203    }
1204
1205    /* Copy texture data to MRFs */
1206    for (int i = 0; i < 4; ++i) {
1207       /* E.g. mov(16) m2.0<1>:f r2.0<8;8,1>:f { Align1, H1 } */
1208       brw_MOV(&func, offset(mrf_rt_write, mrf_offset),
1209               offset(vec8(result), 2*i));
1210       mrf_offset += 2;
1211    }
1212
1213    /* Now write to the render target and terminate the thread */
1214    brw_fb_WRITE(&func,
1215                 16 /* dispatch_width */,
1216                 base_mrf /* msg_reg_nr */,
1217                 mrf_rt_write /* src0 */,
1218                 BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD16_SINGLE_SOURCE,
1219                 BRW_BLORP_RENDERBUFFER_BINDING_TABLE_INDEX,
1220                 mrf_offset /* msg_length.  TODO: Should be smaller for non-RGBA formats. */,
1221                 0 /* response_length */,
1222                 true /* eot */,
1223                 use_header);
1224 }
1225
1226
1227 void
1228 brw_blorp_coord_transform_params::setup(GLuint src0, GLuint dst0, GLuint dst1,
1229                                         bool mirror)
1230 {
1231    if (!mirror) {
1232       /* When not mirroring a coordinate (say, X), we need:
1233        *   x' - src_x0 = x - dst_x0
1234        * Therefore:
1235        *   x' = 1*x + (src_x0 - dst_x0)
1236        */
1237       multiplier = 1;
1238       offset = src0 - dst0;
1239    } else {
1240       /* When mirroring X we need:
1241        *   x' - src_x0 = dst_x1 - x - 1
1242        * Therefore:
1243        *   x' = -1*x + (src_x0 + dst_x1 - 1)
1244        */
1245       multiplier = -1;
1246       offset = src0 + dst1 - 1;
1247    }
1248 }
1249
1250
1251 brw_blorp_blit_params::brw_blorp_blit_params(struct brw_context *brw,
1252                                              struct intel_mipmap_tree *src_mt,
1253                                              struct intel_mipmap_tree *dst_mt,
1254                                              GLuint src_x0, GLuint src_y0,
1255                                              GLuint dst_x0, GLuint dst_y0,
1256                                              GLuint dst_x1, GLuint dst_y1,
1257                                              bool mirror_x, bool mirror_y)
1258 {
1259    src.set(brw, src_mt, 0, 0);
1260    dst.set(brw, dst_mt, 0, 0);
1261
1262    use_wm_prog = true;
1263    memset(&wm_prog_key, 0, sizeof(wm_prog_key));
1264
1265    if (brw->intel.gen > 6) {
1266       /* Gen7 only supports interleaved MSAA surfaces for texturing with the
1267        * ld2dms instruction (which blorp doesn't use).  So if the source is
1268        * interleaved MSAA, we'll have to map it as a single-sampled texture
1269        * and de-interleave the samples ourselves.
1270        */
1271       if (src.num_samples > 0 && src_mt->msaa_is_interleaved)
1272          src.num_samples = 0;
1273
1274       /* Similarly, Gen7 only supports interleaved MSAA surfaces for depth and
1275        * stencil render targets.  Blorp always maps its destination surface as
1276        * a color render target (even if it's actually a depth or stencil
1277        * buffer).  So if the destination is interleaved MSAA, we'll have to
1278        * map it as a single-sampled texture and interleave the samples
1279        * ourselves.
1280        */
1281       if (dst.num_samples > 0 && dst_mt->msaa_is_interleaved)
1282          dst.num_samples = 0;
1283    }
1284
1285    if (dst.map_stencil_as_y_tiled && dst.num_samples > 0) {
1286       /* If the destination surface is a W-tiled multisampled stencil buffer
1287        * that we're mapping as Y tiled, then we need to arrange for the WM
1288        * program to run once per sample rather than once per pixel, because
1289        * the memory layout of related samples doesn't match between W and Y
1290        * tiling.
1291        */
1292       wm_prog_key.persample_msaa_dispatch = true;
1293    }
1294
1295    if (src.num_samples > 0 && dst.num_samples > 0) {
1296       /* We are blitting from a multisample buffer to a multisample buffer, so
1297        * we must preserve samples within a pixel.  This means we have to
1298        * arrange for the WM program to run once per sample rather than once
1299        * per pixel.
1300        */
1301       wm_prog_key.persample_msaa_dispatch = true;
1302    }
1303
1304    /* The render path must be configured to use the same number of samples as
1305     * the destination buffer.
1306     */
1307    num_samples = dst.num_samples;
1308
1309    GLenum base_format = _mesa_get_format_base_format(src_mt->format);
1310    if (base_format != GL_DEPTH_COMPONENT && /* TODO: what about depth/stencil? */
1311        base_format != GL_STENCIL_INDEX &&
1312        src_mt->num_samples > 0 && dst_mt->num_samples == 0) {
1313       /* We are downsampling a color buffer, so blend. */
1314       wm_prog_key.blend = true;
1315    }
1316
1317    /* src_samples and dst_samples are the true sample counts */
1318    wm_prog_key.src_samples = src_mt->num_samples;
1319    wm_prog_key.dst_samples = dst_mt->num_samples;
1320
1321    /* tex_samples and rt_samples are the sample counts that are set up in
1322     * SURFACE_STATE.
1323     */
1324    wm_prog_key.tex_samples = src.num_samples;
1325    wm_prog_key.rt_samples  = dst.num_samples;
1326
1327    /* src_interleaved and dst_interleaved indicate whether src and dst are
1328     * truly interleaved.
1329     */
1330    wm_prog_key.src_interleaved = src_mt->msaa_is_interleaved;
1331    wm_prog_key.dst_interleaved = dst_mt->msaa_is_interleaved;
1332
1333    wm_prog_key.src_tiled_w = src.map_stencil_as_y_tiled;
1334    wm_prog_key.dst_tiled_w = dst.map_stencil_as_y_tiled;
1335    x0 = wm_push_consts.dst_x0 = dst_x0;
1336    y0 = wm_push_consts.dst_y0 = dst_y0;
1337    x1 = wm_push_consts.dst_x1 = dst_x1;
1338    y1 = wm_push_consts.dst_y1 = dst_y1;
1339    wm_push_consts.x_transform.setup(src_x0, dst_x0, dst_x1, mirror_x);
1340    wm_push_consts.y_transform.setup(src_y0, dst_y0, dst_y1, mirror_y);
1341
1342    if (dst.num_samples == 0 && dst_mt->num_samples > 0) {
1343       /* We must expand the rectangle we send through the rendering pipeline,
1344        * to account for the fact that we are mapping the destination region as
1345        * single-sampled when it is in fact multisampled.  We must also align
1346        * it to a multiple of the multisampling pattern, because the
1347        * differences between multisampled and single-sampled surface formats
1348        * will mean that pixels are scrambled within the multisampling pattern.
1349        * TODO: what if this makes the coordinates too large?
1350        *
1351        * Note: this only works if the destination surface's MSAA layout is
1352        * interleaved.  If it's sliced, then we have no choice but to set up
1353        * the rendering pipeline as multisampled.
1354        */
1355       assert(dst_mt->msaa_is_interleaved);
1356       x0 = (x0 * 2) & ~3;
1357       y0 = (y0 * 2) & ~3;
1358       x1 = ALIGN(x1 * 2, 4);
1359       y1 = ALIGN(y1 * 2, 4);
1360       wm_prog_key.use_kill = true;
1361    }
1362
1363    if (dst.map_stencil_as_y_tiled) {
1364       /* We must modify the rectangle we send through the rendering pipeline,
1365        * to account for the fact that we are mapping it as Y-tiled when it is
1366        * in fact W-tiled.  Y tiles have dimensions 128x32 whereas W tiles have
1367        * dimensions 64x64.  We must also align it to a multiple of the tile
1368        * size, because the differences between W and Y tiling formats will
1369        * mean that pixels are scrambled within the tile.
1370        *
1371        * Note: if the destination surface configured as an interleaved MSAA
1372        * surface, then the effective tile size we need to align it to is
1373        * smaller, because each pixel covers a 2x2 or a 4x2 block of samples.
1374        *
1375        * TODO: what if this makes the coordinates too large?
1376        */
1377       unsigned x_align = 64, y_align = 64;
1378       if (dst_mt->num_samples > 0 && dst_mt->msaa_is_interleaved) {
1379          x_align /= (dst_mt->num_samples == 4 ? 2 : 4);
1380          y_align /= 2;
1381       }
1382       x0 = (x0 & ~(x_align - 1)) * 2;
1383       y0 = (y0 & ~(y_align - 1)) / 2;
1384       x1 = ALIGN(x1, x_align) * 2;
1385       y1 = ALIGN(y1, y_align) / 2;
1386       wm_prog_key.use_kill = true;
1387    }
1388 }
1389
1390 uint32_t
1391 brw_blorp_blit_params::get_wm_prog(struct brw_context *brw,
1392                                    brw_blorp_prog_data **prog_data) const
1393 {
1394    uint32_t prog_offset;
1395    if (!brw_search_cache(&brw->cache, BRW_BLORP_BLIT_PROG,
1396                          &this->wm_prog_key, sizeof(this->wm_prog_key),
1397                          &prog_offset, prog_data)) {
1398       brw_blorp_blit_program prog(brw, &this->wm_prog_key);
1399       GLuint program_size;
1400       const GLuint *program = prog.compile(brw, &program_size);
1401       brw_upload_cache(&brw->cache, BRW_BLORP_BLIT_PROG,
1402                        &this->wm_prog_key, sizeof(this->wm_prog_key),
1403                        program, program_size,
1404                        &prog.prog_data, sizeof(prog.prog_data),
1405                        &prog_offset, prog_data);
1406    }
1407    return prog_offset;
1408 }