1/*
2 * Copyright © 2011 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
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24/**
25 * \file lower_varyings_to_packed.cpp
26 *
27 * This lowering pass generates GLSL code that manually packs varyings into
28 * vec4 slots, for the benefit of back-ends that don't support packed varyings
29 * natively.
30 *
31 * For example, the following shader:
32 *
33 *   out mat3x2 foo;  // location=4, location_frac=0
34 *   out vec3 bar[2]; // location=5, location_frac=2
35 *
36 *   main()
37 *   {
38 *     ...
39 *   }
40 *
41 * Is rewritten to:
42 *
43 *   mat3x2 foo;
44 *   vec3 bar[2];
45 *   out vec4 packed4; // location=4, location_frac=0
46 *   out vec4 packed5; // location=5, location_frac=0
47 *   out vec4 packed6; // location=6, location_frac=0
48 *
49 *   main()
50 *   {
51 *     ...
52 *     packed4.xy = foo[0];
53 *     packed4.zw = foo[1];
54 *     packed5.xy = foo[2];
55 *     packed5.zw = bar[0].xy;
56 *     packed6.x = bar[0].z;
57 *     packed6.yzw = bar[1];
58 *   }
59 *
60 * This lowering pass properly handles "double parking" of a varying vector
61 * across two varying slots.  For example, in the code above, two of the
62 * components of bar[0] are stored in packed5, and the remaining component is
63 * stored in packed6.
64 *
65 * Note that in theory, the extra instructions may cause some loss of
66 * performance.  However, hopefully in most cases the performance loss will
67 * either be absorbed by a later optimization pass, or it will be offset by
68 * memory bandwidth savings (because fewer varyings are used).
69 *
70 * This lowering pass also packs flat floats, ints, and uints together, by
71 * using ivec4 as the base type of flat "varyings", and using appropriate
72 * casts to convert floats and uints into ints.
73 *
74 * This lowering pass also handles varyings whose type is a struct or an array
75 * of struct.  Structs are packed in order and with no gaps, so there may be a
76 * performance penalty due to structure elements being double-parked.
77 *
78 * Lowering of geometry shader inputs is slightly more complex, since geometry
79 * inputs are always arrays, so we need to lower arrays to arrays.  For
80 * example, the following input:
81 *
82 *   in struct Foo {
83 *     float f;
84 *     vec3 v;
85 *     vec2 a[2];
86 *   } arr[3];         // location=4, location_frac=0
87 *
88 * Would get lowered like this if it occurred in a fragment shader:
89 *
90 *   struct Foo {
91 *     float f;
92 *     vec3 v;
93 *     vec2 a[2];
94 *   } arr[3];
95 *   in vec4 packed4;  // location=4, location_frac=0
96 *   in vec4 packed5;  // location=5, location_frac=0
97 *   in vec4 packed6;  // location=6, location_frac=0
98 *   in vec4 packed7;  // location=7, location_frac=0
99 *   in vec4 packed8;  // location=8, location_frac=0
100 *   in vec4 packed9;  // location=9, location_frac=0
101 *
102 *   main()
103 *   {
104 *     arr[0].f = packed4.x;
105 *     arr[0].v = packed4.yzw;
106 *     arr[0].a[0] = packed5.xy;
107 *     arr[0].a[1] = packed5.zw;
108 *     arr[1].f = packed6.x;
109 *     arr[1].v = packed6.yzw;
110 *     arr[1].a[0] = packed7.xy;
111 *     arr[1].a[1] = packed7.zw;
112 *     arr[2].f = packed8.x;
113 *     arr[2].v = packed8.yzw;
114 *     arr[2].a[0] = packed9.xy;
115 *     arr[2].a[1] = packed9.zw;
116 *     ...
117 *   }
118 *
119 * But it would get lowered like this if it occurred in a geometry shader:
120 *
121 *   struct Foo {
122 *     float f;
123 *     vec3 v;
124 *     vec2 a[2];
125 *   } arr[3];
126 *   in vec4 packed4[3];  // location=4, location_frac=0
127 *   in vec4 packed5[3];  // location=5, location_frac=0
128 *
129 *   main()
130 *   {
131 *     arr[0].f = packed4[0].x;
132 *     arr[0].v = packed4[0].yzw;
133 *     arr[0].a[0] = packed5[0].xy;
134 *     arr[0].a[1] = packed5[0].zw;
135 *     arr[1].f = packed4[1].x;
136 *     arr[1].v = packed4[1].yzw;
137 *     arr[1].a[0] = packed5[1].xy;
138 *     arr[1].a[1] = packed5[1].zw;
139 *     arr[2].f = packed4[2].x;
140 *     arr[2].v = packed4[2].yzw;
141 *     arr[2].a[0] = packed5[2].xy;
142 *     arr[2].a[1] = packed5[2].zw;
143 *     ...
144 *   }
145 */
146
147#include "glsl_symbol_table.h"
148#include "ir.h"
149#include "ir_builder.h"
150#include "ir_optimization.h"
151#include "program/prog_instruction.h"
152#include "main/mtypes.h"
153
154using namespace ir_builder;
155
156namespace {
157
158/**
159 * Visitor that performs varying packing.  For each varying declared in the
160 * shader, this visitor determines whether it needs to be packed.  If so, it
161 * demotes it to an ordinary global, creates new packed varyings, and
162 * generates assignments to convert between the original varying and the
163 * packed varying.
164 */
165class lower_packed_varyings_visitor
166{
167public:
168   lower_packed_varyings_visitor(void *mem_ctx,
169                                 unsigned locations_used,
170                                 const uint8_t *components,
171                                 ir_variable_mode mode,
172                                 unsigned gs_input_vertices,
173                                 exec_list *out_instructions,
174                                 exec_list *out_variables,
175                                 bool disable_varying_packing,
176                                 bool xfb_enabled);
177
178   void run(struct gl_linked_shader *shader);
179
180private:
181   void bitwise_assign_pack(ir_rvalue *lhs, ir_rvalue *rhs);
182   void bitwise_assign_unpack(ir_rvalue *lhs, ir_rvalue *rhs);
183   unsigned lower_rvalue(ir_rvalue *rvalue, unsigned fine_location,
184                         ir_variable *unpacked_var, const char *name,
185                         bool gs_input_toplevel, unsigned vertex_index);
186   unsigned lower_arraylike(ir_rvalue *rvalue, unsigned array_size,
187                            unsigned fine_location,
188                            ir_variable *unpacked_var, const char *name,
189                            bool gs_input_toplevel, unsigned vertex_index);
190   ir_dereference *get_packed_varying_deref(unsigned location,
191                                            ir_variable *unpacked_var,
192                                            const char *name,
193                                            unsigned vertex_index);
194   bool needs_lowering(ir_variable *var);
195
196   /**
197    * Memory context used to allocate new instructions for the shader.
198    */
199   void * const mem_ctx;
200
201   /**
202    * Number of generic varying slots which are used by this shader.  This is
203    * used to allocate temporary intermediate data structures.  If any varying
204    * used by this shader has a location greater than or equal to
205    * VARYING_SLOT_VAR0 + locations_used, an assertion will fire.
206    */
207   const unsigned locations_used;
208
209   const uint8_t* components;
210
211   /**
212    * Array of pointers to the packed varyings that have been created for each
213    * generic varying slot.  NULL entries in this array indicate varying slots
214    * for which a packed varying has not been created yet.
215    */
216   ir_variable **packed_varyings;
217
218   /**
219    * Type of varying which is being lowered in this pass (either
220    * ir_var_shader_in or ir_var_shader_out).
221    */
222   const ir_variable_mode mode;
223
224   /**
225    * If we are currently lowering geometry shader inputs, the number of input
226    * vertices the geometry shader accepts.  Otherwise zero.
227    */
228   const unsigned gs_input_vertices;
229
230   /**
231    * Exec list into which the visitor should insert the packing instructions.
232    * Caller provides this list; it should insert the instructions into the
233    * appropriate place in the shader once the visitor has finished running.
234    */
235   exec_list *out_instructions;
236
237   /**
238    * Exec list into which the visitor should insert any new variables.
239    */
240   exec_list *out_variables;
241
242   bool disable_varying_packing;
243   bool xfb_enabled;
244};
245
246} /* anonymous namespace */
247
248lower_packed_varyings_visitor::lower_packed_varyings_visitor(
249      void *mem_ctx, unsigned locations_used, const uint8_t *components,
250      ir_variable_mode mode,
251      unsigned gs_input_vertices, exec_list *out_instructions,
252      exec_list *out_variables, bool disable_varying_packing,
253      bool xfb_enabled)
254   : mem_ctx(mem_ctx),
255     locations_used(locations_used),
256     components(components),
257     packed_varyings((ir_variable **)
258                     rzalloc_array_size(mem_ctx, sizeof(*packed_varyings),
259                                        locations_used)),
260     mode(mode),
261     gs_input_vertices(gs_input_vertices),
262     out_instructions(out_instructions),
263     out_variables(out_variables),
264     disable_varying_packing(disable_varying_packing),
265     xfb_enabled(xfb_enabled)
266{
267}
268
269void
270lower_packed_varyings_visitor::run(struct gl_linked_shader *shader)
271{
272   foreach_in_list(ir_instruction, node, shader->ir) {
273      ir_variable *var = node->as_variable();
274      if (var == NULL)
275         continue;
276
277      if (var->data.mode != this->mode ||
278          var->data.location < VARYING_SLOT_VAR0 ||
279          !this->needs_lowering(var))
280         continue;
281
282      /* This lowering pass is only capable of packing floats and ints
283       * together when their interpolation mode is "flat".  Treat integers as
284       * being flat when the interpolation mode is none.
285       */
286      assert(var->data.interpolation == INTERP_MODE_FLAT ||
287             var->data.interpolation == INTERP_MODE_NONE ||
288             !var->type->contains_integer());
289
290      /* Clone the variable for program resource list before
291       * it gets modified and lost.
292       */
293      if (!shader->packed_varyings)
294         shader->packed_varyings = new (shader) exec_list;
295
296      shader->packed_varyings->push_tail(var->clone(shader, NULL));
297
298      /* Change the old varying into an ordinary global. */
299      assert(var->data.mode != ir_var_temporary);
300      var->data.mode = ir_var_auto;
301
302      /* Create a reference to the old varying. */
303      ir_dereference_variable *deref
304         = new(this->mem_ctx) ir_dereference_variable(var);
305
306      /* Recursively pack or unpack it. */
307      this->lower_rvalue(deref, var->data.location * 4 + var->data.location_frac, var,
308                         var->name, this->gs_input_vertices != 0, 0);
309   }
310}
311
312#define SWIZZLE_ZWZW MAKE_SWIZZLE4(SWIZZLE_Z, SWIZZLE_W, SWIZZLE_Z, SWIZZLE_W)
313
314/**
315 * Make an ir_assignment from \c rhs to \c lhs, performing appropriate
316 * bitcasts if necessary to match up types.
317 *
318 * This function is called when packing varyings.
319 */
320void
321lower_packed_varyings_visitor::bitwise_assign_pack(ir_rvalue *lhs,
322                                                   ir_rvalue *rhs)
323{
324   if (lhs->type->base_type != rhs->type->base_type) {
325      /* Since we only mix types in flat varyings, and we always store flat
326       * varyings as type ivec4, we need only produce conversions from (uint
327       * or float) to int.
328       */
329      assert(lhs->type->base_type == GLSL_TYPE_INT);
330      switch (rhs->type->base_type) {
331      case GLSL_TYPE_UINT:
332         rhs = new(this->mem_ctx)
333            ir_expression(ir_unop_u2i, lhs->type, rhs);
334         break;
335      case GLSL_TYPE_FLOAT:
336         rhs = new(this->mem_ctx)
337            ir_expression(ir_unop_bitcast_f2i, lhs->type, rhs);
338         break;
339      case GLSL_TYPE_DOUBLE:
340         assert(rhs->type->vector_elements <= 2);
341         if (rhs->type->vector_elements == 2) {
342            ir_variable *t = new(mem_ctx) ir_variable(lhs->type, "pack", ir_var_temporary);
343
344            assert(lhs->type->vector_elements == 4);
345            this->out_variables->push_tail(t);
346            this->out_instructions->push_tail(
347                  assign(t, u2i(expr(ir_unop_unpack_double_2x32, swizzle_x(rhs->clone(mem_ctx, NULL)))), 0x3));
348            this->out_instructions->push_tail(
349                  assign(t,  u2i(expr(ir_unop_unpack_double_2x32, swizzle_y(rhs))), 0xc));
350            rhs = deref(t).val;
351         } else {
352            rhs = u2i(expr(ir_unop_unpack_double_2x32, rhs));
353         }
354         break;
355      case GLSL_TYPE_INT64:
356         assert(rhs->type->vector_elements <= 2);
357         if (rhs->type->vector_elements == 2) {
358            ir_variable *t = new(mem_ctx) ir_variable(lhs->type, "pack", ir_var_temporary);
359
360            assert(lhs->type->vector_elements == 4);
361            this->out_variables->push_tail(t);
362            this->out_instructions->push_tail(
363               assign(t, expr(ir_unop_unpack_int_2x32, swizzle_x(rhs->clone(mem_ctx, NULL))), 0x3));
364            this->out_instructions->push_tail(
365               assign(t,  expr(ir_unop_unpack_int_2x32, swizzle_y(rhs)), 0xc));
366            rhs = deref(t).val;
367         } else {
368            rhs = expr(ir_unop_unpack_int_2x32, rhs);
369         }
370         break;
371      case GLSL_TYPE_UINT64:
372         assert(rhs->type->vector_elements <= 2);
373         if (rhs->type->vector_elements == 2) {
374            ir_variable *t = new(mem_ctx) ir_variable(lhs->type, "pack", ir_var_temporary);
375
376            assert(lhs->type->vector_elements == 4);
377            this->out_variables->push_tail(t);
378            this->out_instructions->push_tail(
379                  assign(t, u2i(expr(ir_unop_unpack_uint_2x32, swizzle_x(rhs->clone(mem_ctx, NULL)))), 0x3));
380            this->out_instructions->push_tail(
381                  assign(t,  u2i(expr(ir_unop_unpack_uint_2x32, swizzle_y(rhs))), 0xc));
382            rhs = deref(t).val;
383         } else {
384            rhs = u2i(expr(ir_unop_unpack_uint_2x32, rhs));
385         }
386         break;
387      case GLSL_TYPE_SAMPLER:
388         rhs = u2i(expr(ir_unop_unpack_sampler_2x32, rhs));
389         break;
390      case GLSL_TYPE_IMAGE:
391         rhs = u2i(expr(ir_unop_unpack_image_2x32, rhs));
392         break;
393      default:
394         assert(!"Unexpected type conversion while lowering varyings");
395         break;
396      }
397   }
398   this->out_instructions->push_tail(new (this->mem_ctx) ir_assignment(lhs, rhs));
399}
400
401
402/**
403 * Make an ir_assignment from \c rhs to \c lhs, performing appropriate
404 * bitcasts if necessary to match up types.
405 *
406 * This function is called when unpacking varyings.
407 */
408void
409lower_packed_varyings_visitor::bitwise_assign_unpack(ir_rvalue *lhs,
410                                                     ir_rvalue *rhs)
411{
412   if (lhs->type->base_type != rhs->type->base_type) {
413      /* Since we only mix types in flat varyings, and we always store flat
414       * varyings as type ivec4, we need only produce conversions from int to
415       * (uint or float).
416       */
417      assert(rhs->type->base_type == GLSL_TYPE_INT);
418      switch (lhs->type->base_type) {
419      case GLSL_TYPE_UINT:
420         rhs = new(this->mem_ctx)
421            ir_expression(ir_unop_i2u, lhs->type, rhs);
422         break;
423      case GLSL_TYPE_FLOAT:
424         rhs = new(this->mem_ctx)
425            ir_expression(ir_unop_bitcast_i2f, lhs->type, rhs);
426         break;
427      case GLSL_TYPE_DOUBLE:
428         assert(lhs->type->vector_elements <= 2);
429         if (lhs->type->vector_elements == 2) {
430            ir_variable *t = new(mem_ctx) ir_variable(lhs->type, "unpack", ir_var_temporary);
431            assert(rhs->type->vector_elements == 4);
432            this->out_variables->push_tail(t);
433            this->out_instructions->push_tail(
434                  assign(t, expr(ir_unop_pack_double_2x32, i2u(swizzle_xy(rhs->clone(mem_ctx, NULL)))), 0x1));
435            this->out_instructions->push_tail(
436                  assign(t, expr(ir_unop_pack_double_2x32, i2u(swizzle(rhs->clone(mem_ctx, NULL), SWIZZLE_ZWZW, 2))), 0x2));
437            rhs = deref(t).val;
438         } else {
439            rhs = expr(ir_unop_pack_double_2x32, i2u(rhs));
440         }
441         break;
442      case GLSL_TYPE_INT64:
443         assert(lhs->type->vector_elements <= 2);
444         if (lhs->type->vector_elements == 2) {
445            ir_variable *t = new(mem_ctx) ir_variable(lhs->type, "unpack", ir_var_temporary);
446            assert(rhs->type->vector_elements == 4);
447            this->out_variables->push_tail(t);
448            this->out_instructions->push_tail(
449                  assign(t, expr(ir_unop_pack_int_2x32, swizzle_xy(rhs->clone(mem_ctx, NULL))), 0x1));
450            this->out_instructions->push_tail(
451                  assign(t, expr(ir_unop_pack_int_2x32, swizzle(rhs->clone(mem_ctx, NULL), SWIZZLE_ZWZW, 2)), 0x2));
452            rhs = deref(t).val;
453         } else {
454            rhs = expr(ir_unop_pack_int_2x32, rhs);
455         }
456         break;
457      case GLSL_TYPE_UINT64:
458         assert(lhs->type->vector_elements <= 2);
459         if (lhs->type->vector_elements == 2) {
460            ir_variable *t = new(mem_ctx) ir_variable(lhs->type, "unpack", ir_var_temporary);
461            assert(rhs->type->vector_elements == 4);
462            this->out_variables->push_tail(t);
463            this->out_instructions->push_tail(
464                  assign(t, expr(ir_unop_pack_uint_2x32, i2u(swizzle_xy(rhs->clone(mem_ctx, NULL)))), 0x1));
465            this->out_instructions->push_tail(
466                  assign(t, expr(ir_unop_pack_uint_2x32, i2u(swizzle(rhs->clone(mem_ctx, NULL), SWIZZLE_ZWZW, 2))), 0x2));
467            rhs = deref(t).val;
468         } else {
469            rhs = expr(ir_unop_pack_uint_2x32, i2u(rhs));
470         }
471         break;
472      case GLSL_TYPE_SAMPLER:
473         rhs = new(mem_ctx)
474            ir_expression(ir_unop_pack_sampler_2x32, lhs->type, i2u(rhs));
475         break;
476      case GLSL_TYPE_IMAGE:
477         rhs = new(mem_ctx)
478            ir_expression(ir_unop_pack_image_2x32, lhs->type, i2u(rhs));
479         break;
480      default:
481         assert(!"Unexpected type conversion while lowering varyings");
482         break;
483      }
484   }
485   this->out_instructions->push_tail(new(this->mem_ctx) ir_assignment(lhs, rhs));
486}
487
488
489/**
490 * Recursively pack or unpack the given varying (or portion of a varying) by
491 * traversing all of its constituent vectors.
492 *
493 * \param fine_location is the location where the first constituent vector
494 * should be packed--the word "fine" indicates that this location is expressed
495 * in multiples of a float, rather than multiples of a vec4 as is used
496 * elsewhere in Mesa.
497 *
498 * \param gs_input_toplevel should be set to true if we are lowering geometry
499 * shader inputs, and we are currently lowering the whole input variable
500 * (i.e. we are lowering the array whose index selects the vertex).
501 *
502 * \param vertex_index: if we are lowering geometry shader inputs, and the
503 * level of the array that we are currently lowering is *not* the top level,
504 * then this indicates which vertex we are currently lowering.  Otherwise it
505 * is ignored.
506 *
507 * \return the location where the next constituent vector (after this one)
508 * should be packed.
509 */
510unsigned
511lower_packed_varyings_visitor::lower_rvalue(ir_rvalue *rvalue,
512                                            unsigned fine_location,
513                                            ir_variable *unpacked_var,
514                                            const char *name,
515                                            bool gs_input_toplevel,
516                                            unsigned vertex_index)
517{
518   unsigned dmul = rvalue->type->is_64bit() ? 2 : 1;
519   /* When gs_input_toplevel is set, we should be looking at a geometry shader
520    * input array.
521    */
522   assert(!gs_input_toplevel || rvalue->type->is_array());
523
524   if (rvalue->type->is_struct()) {
525      for (unsigned i = 0; i < rvalue->type->length; i++) {
526         if (i != 0)
527            rvalue = rvalue->clone(this->mem_ctx, NULL);
528         const char *field_name = rvalue->type->fields.structure[i].name;
529         ir_dereference_record *dereference_record = new(this->mem_ctx)
530            ir_dereference_record(rvalue, field_name);
531         char *deref_name
532            = ralloc_asprintf(this->mem_ctx, "%s.%s", name, field_name);
533         fine_location = this->lower_rvalue(dereference_record, fine_location,
534                                            unpacked_var, deref_name, false,
535                                            vertex_index);
536      }
537      return fine_location;
538   } else if (rvalue->type->is_array()) {
539      /* Arrays are packed/unpacked by considering each array element in
540       * sequence.
541       */
542      return this->lower_arraylike(rvalue, rvalue->type->array_size(),
543                                   fine_location, unpacked_var, name,
544                                   gs_input_toplevel, vertex_index);
545   } else if (rvalue->type->is_matrix()) {
546      /* Matrices are packed/unpacked by considering each column vector in
547       * sequence.
548       */
549      return this->lower_arraylike(rvalue, rvalue->type->matrix_columns,
550                                   fine_location, unpacked_var, name,
551                                   false, vertex_index);
552   } else if (rvalue->type->vector_elements * dmul +
553              fine_location % 4 > 4) {
554      /* This vector is going to be "double parked" across two varying slots,
555       * so handle it as two separate assignments. For doubles, a dvec3/dvec4
556       * can end up being spread over 3 slots. However the second splitting
557       * will happen later, here we just always want to split into 2.
558       */
559      unsigned left_components, right_components;
560      unsigned left_swizzle_values[4] = { 0, 0, 0, 0 };
561      unsigned right_swizzle_values[4] = { 0, 0, 0, 0 };
562      char left_swizzle_name[4] = { 0, 0, 0, 0 };
563      char right_swizzle_name[4] = { 0, 0, 0, 0 };
564
565      left_components = 4 - fine_location % 4;
566      if (rvalue->type->is_64bit()) {
567         /* We might actually end up with 0 left components! */
568         left_components /= 2;
569      }
570      right_components = rvalue->type->vector_elements - left_components;
571
572      for (unsigned i = 0; i < left_components; i++) {
573         left_swizzle_values[i] = i;
574         left_swizzle_name[i] = "xyzw"[i];
575      }
576      for (unsigned i = 0; i < right_components; i++) {
577         right_swizzle_values[i] = i + left_components;
578         right_swizzle_name[i] = "xyzw"[i + left_components];
579      }
580      ir_swizzle *left_swizzle = new(this->mem_ctx)
581         ir_swizzle(rvalue, left_swizzle_values, left_components);
582      ir_swizzle *right_swizzle = new(this->mem_ctx)
583         ir_swizzle(rvalue->clone(this->mem_ctx, NULL), right_swizzle_values,
584                    right_components);
585      char *left_name
586         = ralloc_asprintf(this->mem_ctx, "%s.%s", name, left_swizzle_name);
587      char *right_name
588         = ralloc_asprintf(this->mem_ctx, "%s.%s", name, right_swizzle_name);
589      if (left_components)
590         fine_location = this->lower_rvalue(left_swizzle, fine_location,
591                                            unpacked_var, left_name, false,
592                                            vertex_index);
593      else
594         /* Top up the fine location to the next slot */
595         fine_location++;
596      return this->lower_rvalue(right_swizzle, fine_location, unpacked_var,
597                                right_name, false, vertex_index);
598   } else {
599      /* No special handling is necessary; pack the rvalue into the
600       * varying.
601       */
602      unsigned swizzle_values[4] = { 0, 0, 0, 0 };
603      unsigned components = rvalue->type->vector_elements * dmul;
604      unsigned location = fine_location / 4;
605      unsigned location_frac = fine_location % 4;
606      for (unsigned i = 0; i < components; ++i)
607         swizzle_values[i] = i + location_frac;
608      ir_dereference *packed_deref =
609         this->get_packed_varying_deref(location, unpacked_var, name,
610                                        vertex_index);
611      if (unpacked_var->data.stream != 0) {
612         assert(unpacked_var->data.stream < 4);
613         ir_variable *packed_var = packed_deref->variable_referenced();
614         for (unsigned i = 0; i < components; ++i) {
615            packed_var->data.stream |=
616               unpacked_var->data.stream << (2 * (location_frac + i));
617         }
618      }
619      ir_swizzle *swizzle = new(this->mem_ctx)
620         ir_swizzle(packed_deref, swizzle_values, components);
621      if (this->mode == ir_var_shader_out) {
622         this->bitwise_assign_pack(swizzle, rvalue);
623      } else {
624         this->bitwise_assign_unpack(rvalue, swizzle);
625      }
626      return fine_location + components;
627   }
628}
629
630/**
631 * Recursively pack or unpack a varying for which we need to iterate over its
632 * constituent elements, accessing each one using an ir_dereference_array.
633 * This takes care of both arrays and matrices, since ir_dereference_array
634 * treats a matrix like an array of its column vectors.
635 *
636 * \param gs_input_toplevel should be set to true if we are lowering geometry
637 * shader inputs, and we are currently lowering the whole input variable
638 * (i.e. we are lowering the array whose index selects the vertex).
639 *
640 * \param vertex_index: if we are lowering geometry shader inputs, and the
641 * level of the array that we are currently lowering is *not* the top level,
642 * then this indicates which vertex we are currently lowering.  Otherwise it
643 * is ignored.
644 */
645unsigned
646lower_packed_varyings_visitor::lower_arraylike(ir_rvalue *rvalue,
647                                               unsigned array_size,
648                                               unsigned fine_location,
649                                               ir_variable *unpacked_var,
650                                               const char *name,
651                                               bool gs_input_toplevel,
652                                               unsigned vertex_index)
653{
654   for (unsigned i = 0; i < array_size; i++) {
655      if (i != 0)
656         rvalue = rvalue->clone(this->mem_ctx, NULL);
657      ir_constant *constant = new(this->mem_ctx) ir_constant(i);
658      ir_dereference_array *dereference_array = new(this->mem_ctx)
659         ir_dereference_array(rvalue, constant);
660      if (gs_input_toplevel) {
661         /* Geometry shader inputs are a special case.  Instead of storing
662          * each element of the array at a different location, all elements
663          * are at the same location, but with a different vertex index.
664          */
665         (void) this->lower_rvalue(dereference_array, fine_location,
666                                   unpacked_var, name, false, i);
667      } else {
668         char *subscripted_name
669            = ralloc_asprintf(this->mem_ctx, "%s[%d]", name, i);
670         fine_location =
671            this->lower_rvalue(dereference_array, fine_location,
672                               unpacked_var, subscripted_name,
673                               false, vertex_index);
674      }
675   }
676   return fine_location;
677}
678
679/**
680 * Retrieve the packed varying corresponding to the given varying location.
681 * If no packed varying has been created for the given varying location yet,
682 * create it and add it to the shader before returning it.
683 *
684 * The newly created varying inherits its interpolation parameters from \c
685 * unpacked_var.  Its base type is ivec4 if we are lowering a flat varying,
686 * vec4 otherwise.
687 *
688 * \param vertex_index: if we are lowering geometry shader inputs, then this
689 * indicates which vertex we are currently lowering.  Otherwise it is ignored.
690 */
691ir_dereference *
692lower_packed_varyings_visitor::get_packed_varying_deref(
693      unsigned location, ir_variable *unpacked_var, const char *name,
694      unsigned vertex_index)
695{
696   unsigned slot = location - VARYING_SLOT_VAR0;
697   assert(slot < locations_used);
698   if (this->packed_varyings[slot] == NULL) {
699      char *packed_name = ralloc_asprintf(this->mem_ctx, "packed:%s", name);
700      const glsl_type *packed_type;
701      assert(components[slot] != 0);
702      if (unpacked_var->is_interpolation_flat())
703         packed_type = glsl_type::get_instance(GLSL_TYPE_INT, components[slot], 1);
704      else
705         packed_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, components[slot], 1);
706      if (this->gs_input_vertices != 0) {
707         packed_type =
708            glsl_type::get_array_instance(packed_type,
709                                          this->gs_input_vertices);
710      }
711      ir_variable *packed_var = new(this->mem_ctx)
712         ir_variable(packed_type, packed_name, this->mode);
713      if (this->gs_input_vertices != 0) {
714         /* Prevent update_array_sizes() from messing with the size of the
715          * array.
716          */
717         packed_var->data.max_array_access = this->gs_input_vertices - 1;
718      }
719      packed_var->data.centroid = unpacked_var->data.centroid;
720      packed_var->data.sample = unpacked_var->data.sample;
721      packed_var->data.patch = unpacked_var->data.patch;
722      packed_var->data.interpolation =
723         packed_type->without_array() == glsl_type::ivec4_type
724         ? unsigned(INTERP_MODE_FLAT) : unpacked_var->data.interpolation;
725      packed_var->data.location = location;
726      packed_var->data.precision = unpacked_var->data.precision;
727      packed_var->data.always_active_io = unpacked_var->data.always_active_io;
728      packed_var->data.stream = 1u << 31;
729      unpacked_var->insert_before(packed_var);
730      this->packed_varyings[slot] = packed_var;
731   } else {
732      ir_variable *var = this->packed_varyings[slot];
733
734      /* The slot needs to be marked as always active if any variable that got
735       * packed there was.
736       */
737      var->data.always_active_io |= unpacked_var->data.always_active_io;
738
739      /* For geometry shader inputs, only update the packed variable name the
740       * first time we visit each component.
741       */
742      if (this->gs_input_vertices == 0 || vertex_index == 0) {
743         if (var->is_name_ralloced())
744            ralloc_asprintf_append((char **) &var->name, ",%s", name);
745         else
746            var->name = ralloc_asprintf(var, "%s,%s", var->name, name);
747      }
748   }
749
750   ir_dereference *deref = new(this->mem_ctx)
751      ir_dereference_variable(this->packed_varyings[slot]);
752   if (this->gs_input_vertices != 0) {
753      /* When lowering GS inputs, the packed variable is an array, so we need
754       * to dereference it using vertex_index.
755       */
756      ir_constant *constant = new(this->mem_ctx) ir_constant(vertex_index);
757      deref = new(this->mem_ctx) ir_dereference_array(deref, constant);
758   }
759   return deref;
760}
761
762bool
763lower_packed_varyings_visitor::needs_lowering(ir_variable *var)
764{
765   /* Things composed of vec4's, varyings with explicitly assigned
766    * locations or varyings marked as must_be_shader_input (which might be used
767    * by interpolateAt* functions) shouldn't be lowered. Everything else can be.
768    */
769   if (var->data.explicit_location || var->data.must_be_shader_input)
770      return false;
771
772   /* Override disable_varying_packing if the var is only used by transform
773    * feedback. Also override it if transform feedback is enabled and the
774    * variable is an array, struct or matrix as the elements of these types
775    * will always have the same interpolation and therefore are safe to pack.
776    */
777   const glsl_type *type = var->type;
778   if (disable_varying_packing && !var->data.is_xfb_only &&
779       !((type->is_array() || type->is_struct() || type->is_matrix()) &&
780         xfb_enabled))
781      return false;
782
783   type = type->without_array();
784   if (type->vector_elements == 4 && !type->is_64bit())
785      return false;
786   return true;
787}
788
789
790/**
791 * Visitor that splices varying packing code before every use of EmitVertex()
792 * in a geometry shader.
793 */
794class lower_packed_varyings_gs_splicer : public ir_hierarchical_visitor
795{
796public:
797   explicit lower_packed_varyings_gs_splicer(void *mem_ctx,
798                                             const exec_list *instructions);
799
800   virtual ir_visitor_status visit_leave(ir_emit_vertex *ev);
801
802private:
803   /**
804    * Memory context used to allocate new instructions for the shader.
805    */
806   void * const mem_ctx;
807
808   /**
809    * Instructions that should be spliced into place before each EmitVertex()
810    * call.
811    */
812   const exec_list *instructions;
813};
814
815
816lower_packed_varyings_gs_splicer::lower_packed_varyings_gs_splicer(
817      void *mem_ctx, const exec_list *instructions)
818   : mem_ctx(mem_ctx), instructions(instructions)
819{
820}
821
822
823ir_visitor_status
824lower_packed_varyings_gs_splicer::visit_leave(ir_emit_vertex *ev)
825{
826   foreach_in_list(ir_instruction, ir, this->instructions) {
827      ev->insert_before(ir->clone(this->mem_ctx, NULL));
828   }
829   return visit_continue;
830}
831
832/**
833 * Visitor that splices varying packing code before every return.
834 */
835class lower_packed_varyings_return_splicer : public ir_hierarchical_visitor
836{
837public:
838   explicit lower_packed_varyings_return_splicer(void *mem_ctx,
839                                                 const exec_list *instructions);
840
841   virtual ir_visitor_status visit_leave(ir_return *ret);
842
843private:
844   /**
845    * Memory context used to allocate new instructions for the shader.
846    */
847   void * const mem_ctx;
848
849   /**
850    * Instructions that should be spliced into place before each return.
851    */
852   const exec_list *instructions;
853};
854
855
856lower_packed_varyings_return_splicer::lower_packed_varyings_return_splicer(
857      void *mem_ctx, const exec_list *instructions)
858   : mem_ctx(mem_ctx), instructions(instructions)
859{
860}
861
862
863ir_visitor_status
864lower_packed_varyings_return_splicer::visit_leave(ir_return *ret)
865{
866   foreach_in_list(ir_instruction, ir, this->instructions) {
867      ret->insert_before(ir->clone(this->mem_ctx, NULL));
868   }
869   return visit_continue;
870}
871
872void
873lower_packed_varyings(void *mem_ctx, unsigned locations_used,
874                      const uint8_t *components,
875                      ir_variable_mode mode, unsigned gs_input_vertices,
876                      gl_linked_shader *shader, bool disable_varying_packing,
877                      bool xfb_enabled)
878{
879   exec_list *instructions = shader->ir;
880   ir_function *main_func = shader->symbols->get_function("main");
881   exec_list void_parameters;
882   ir_function_signature *main_func_sig
883      = main_func->matching_signature(NULL, &void_parameters, false);
884   exec_list new_instructions, new_variables;
885   lower_packed_varyings_visitor visitor(mem_ctx,
886                                         locations_used,
887                                         components,
888                                         mode,
889                                         gs_input_vertices,
890                                         &new_instructions,
891                                         &new_variables,
892                                         disable_varying_packing,
893                                         xfb_enabled);
894   visitor.run(shader);
895   if (mode == ir_var_shader_out) {
896      if (shader->Stage == MESA_SHADER_GEOMETRY) {
897         /* For geometry shaders, outputs need to be lowered before each call
898          * to EmitVertex()
899          */
900         lower_packed_varyings_gs_splicer splicer(mem_ctx, &new_instructions);
901
902         /* Add all the variables in first. */
903         main_func_sig->body.get_head_raw()->insert_before(&new_variables);
904
905         /* Now update all the EmitVertex instances */
906         splicer.run(instructions);
907      } else {
908         /* For other shader types, outputs need to be lowered before each
909          * return statement and at the end of main()
910          */
911
912         lower_packed_varyings_return_splicer splicer(mem_ctx, &new_instructions);
913
914         main_func_sig->body.get_head_raw()->insert_before(&new_variables);
915
916         splicer.run(instructions);
917
918         /* Lower outputs at the end of main() if the last instruction is not
919          * a return statement
920          */
921         if (((ir_instruction*)instructions->get_tail())->ir_type != ir_type_return) {
922            main_func_sig->body.append_list(&new_instructions);
923         }
924      }
925   } else {
926      /* Shader inputs need to be lowered at the beginning of main() */
927      main_func_sig->body.get_head_raw()->insert_before(&new_instructions);
928      main_func_sig->body.get_head_raw()->insert_before(&new_variables);
929   }
930}
931