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