OSDN Git Service

mesa: add packed_varyings list to gl_shader
[android-x86/external-mesa.git] / src / glsl / lower_packed_varyings.cpp
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
153 using namespace ir_builder;
154
155 namespace {
156
157 /**
158  * Visitor that performs varying packing.  For each varying declared in the
159  * shader, this visitor determines whether it needs to be packed.  If so, it
160  * demotes it to an ordinary global, creates new packed varyings, and
161  * generates assignments to convert between the original varying and the
162  * packed varying.
163  */
164 class lower_packed_varyings_visitor
165 {
166 public:
167    lower_packed_varyings_visitor(void *mem_ctx, unsigned locations_used,
168                                  ir_variable_mode mode,
169                                  unsigned gs_input_vertices,
170                                  exec_list *out_instructions,
171                                  exec_list *out_variables);
172
173    void run(struct gl_shader *shader);
174
175 private:
176    void bitwise_assign_pack(ir_rvalue *lhs, ir_rvalue *rhs);
177    void bitwise_assign_unpack(ir_rvalue *lhs, ir_rvalue *rhs);
178    unsigned lower_rvalue(ir_rvalue *rvalue, unsigned fine_location,
179                          ir_variable *unpacked_var, const char *name,
180                          bool gs_input_toplevel, unsigned vertex_index);
181    unsigned lower_arraylike(ir_rvalue *rvalue, unsigned array_size,
182                             unsigned fine_location,
183                             ir_variable *unpacked_var, const char *name,
184                             bool gs_input_toplevel, unsigned vertex_index);
185    ir_dereference *get_packed_varying_deref(unsigned location,
186                                             ir_variable *unpacked_var,
187                                             const char *name,
188                                             unsigned vertex_index);
189    bool needs_lowering(ir_variable *var);
190
191    /**
192     * Memory context used to allocate new instructions for the shader.
193     */
194    void * const mem_ctx;
195
196    /**
197     * Number of generic varying slots which are used by this shader.  This is
198     * used to allocate temporary intermediate data structures.  If any varying
199     * used by this shader has a location greater than or equal to
200     * VARYING_SLOT_VAR0 + locations_used, an assertion will fire.
201     */
202    const unsigned locations_used;
203
204    /**
205     * Array of pointers to the packed varyings that have been created for each
206     * generic varying slot.  NULL entries in this array indicate varying slots
207     * for which a packed varying has not been created yet.
208     */
209    ir_variable **packed_varyings;
210
211    /**
212     * Type of varying which is being lowered in this pass (either
213     * ir_var_shader_in or ir_var_shader_out).
214     */
215    const ir_variable_mode mode;
216
217    /**
218     * If we are currently lowering geometry shader inputs, the number of input
219     * vertices the geometry shader accepts.  Otherwise zero.
220     */
221    const unsigned gs_input_vertices;
222
223    /**
224     * Exec list into which the visitor should insert the packing instructions.
225     * Caller provides this list; it should insert the instructions into the
226     * appropriate place in the shader once the visitor has finished running.
227     */
228    exec_list *out_instructions;
229
230    /**
231     * Exec list into which the visitor should insert any new variables.
232     */
233    exec_list *out_variables;
234 };
235
236 } /* anonymous namespace */
237
238 lower_packed_varyings_visitor::lower_packed_varyings_visitor(
239       void *mem_ctx, unsigned locations_used, ir_variable_mode mode,
240       unsigned gs_input_vertices, exec_list *out_instructions,
241       exec_list *out_variables)
242    : mem_ctx(mem_ctx),
243      locations_used(locations_used),
244      packed_varyings((ir_variable **)
245                      rzalloc_array_size(mem_ctx, sizeof(*packed_varyings),
246                                         locations_used)),
247      mode(mode),
248      gs_input_vertices(gs_input_vertices),
249      out_instructions(out_instructions),
250      out_variables(out_variables)
251 {
252 }
253
254 void
255 lower_packed_varyings_visitor::run(struct gl_shader *shader)
256 {
257    foreach_in_list(ir_instruction, node, shader->ir) {
258       ir_variable *var = node->as_variable();
259       if (var == NULL)
260          continue;
261
262       if (var->data.mode != this->mode ||
263           var->data.location < VARYING_SLOT_VAR0 ||
264           !this->needs_lowering(var))
265          continue;
266
267       /* This lowering pass is only capable of packing floats and ints
268        * together when their interpolation mode is "flat".  Therefore, to be
269        * safe, caller should ensure that integral varyings always use flat
270        * interpolation, even when this is not required by GLSL.
271        */
272       assert(var->data.interpolation == INTERP_QUALIFIER_FLAT ||
273              !var->type->contains_integer());
274
275       /* Clone the variable for program resource list before
276        * it gets modified and lost.
277        */
278       if (!shader->packed_varyings)
279          shader->packed_varyings = new (shader) exec_list;
280
281       shader->packed_varyings->push_tail(var->clone(shader, NULL));
282
283       /* Change the old varying into an ordinary global. */
284       assert(var->data.mode != ir_var_temporary);
285       var->data.mode = ir_var_auto;
286
287       /* Create a reference to the old varying. */
288       ir_dereference_variable *deref
289          = new(this->mem_ctx) ir_dereference_variable(var);
290
291       /* Recursively pack or unpack it. */
292       this->lower_rvalue(deref, var->data.location * 4 + var->data.location_frac, var,
293                          var->name, this->gs_input_vertices != 0, 0);
294    }
295 }
296
297 #define SWIZZLE_ZWZW MAKE_SWIZZLE4(SWIZZLE_Z, SWIZZLE_W, SWIZZLE_Z, SWIZZLE_W)
298
299 /**
300  * Make an ir_assignment from \c rhs to \c lhs, performing appropriate
301  * bitcasts if necessary to match up types.
302  *
303  * This function is called when packing varyings.
304  */
305 void
306 lower_packed_varyings_visitor::bitwise_assign_pack(ir_rvalue *lhs,
307                                                    ir_rvalue *rhs)
308 {
309    if (lhs->type->base_type != rhs->type->base_type) {
310       /* Since we only mix types in flat varyings, and we always store flat
311        * varyings as type ivec4, we need only produce conversions from (uint
312        * or float) to int.
313        */
314       assert(lhs->type->base_type == GLSL_TYPE_INT);
315       switch (rhs->type->base_type) {
316       case GLSL_TYPE_UINT:
317          rhs = new(this->mem_ctx)
318             ir_expression(ir_unop_u2i, lhs->type, rhs);
319          break;
320       case GLSL_TYPE_FLOAT:
321          rhs = new(this->mem_ctx)
322             ir_expression(ir_unop_bitcast_f2i, lhs->type, rhs);
323          break;
324       case GLSL_TYPE_DOUBLE:
325          assert(rhs->type->vector_elements <= 2);
326          if (rhs->type->vector_elements == 2) {
327             ir_variable *t = new(mem_ctx) ir_variable(lhs->type, "pack", ir_var_temporary);
328
329             assert(lhs->type->vector_elements == 4);
330             this->out_variables->push_tail(t);
331             this->out_instructions->push_tail(
332                   assign(t, u2i(expr(ir_unop_unpack_double_2x32, swizzle_x(rhs->clone(mem_ctx, NULL)))), 0x3));
333             this->out_instructions->push_tail(
334                   assign(t,  u2i(expr(ir_unop_unpack_double_2x32, swizzle_y(rhs))), 0xc));
335             rhs = deref(t).val;
336          } else {
337             rhs = u2i(expr(ir_unop_unpack_double_2x32, rhs));
338          }
339          break;
340       default:
341          assert(!"Unexpected type conversion while lowering varyings");
342          break;
343       }
344    }
345    this->out_instructions->push_tail(new (this->mem_ctx) ir_assignment(lhs, rhs));
346 }
347
348
349 /**
350  * Make an ir_assignment from \c rhs to \c lhs, performing appropriate
351  * bitcasts if necessary to match up types.
352  *
353  * This function is called when unpacking varyings.
354  */
355 void
356 lower_packed_varyings_visitor::bitwise_assign_unpack(ir_rvalue *lhs,
357                                                      ir_rvalue *rhs)
358 {
359    if (lhs->type->base_type != rhs->type->base_type) {
360       /* Since we only mix types in flat varyings, and we always store flat
361        * varyings as type ivec4, we need only produce conversions from int to
362        * (uint or float).
363        */
364       assert(rhs->type->base_type == GLSL_TYPE_INT);
365       switch (lhs->type->base_type) {
366       case GLSL_TYPE_UINT:
367          rhs = new(this->mem_ctx)
368             ir_expression(ir_unop_i2u, lhs->type, rhs);
369          break;
370       case GLSL_TYPE_FLOAT:
371          rhs = new(this->mem_ctx)
372             ir_expression(ir_unop_bitcast_i2f, lhs->type, rhs);
373          break;
374       case GLSL_TYPE_DOUBLE:
375          assert(lhs->type->vector_elements <= 2);
376          if (lhs->type->vector_elements == 2) {
377             ir_variable *t = new(mem_ctx) ir_variable(lhs->type, "unpack", ir_var_temporary);
378             assert(rhs->type->vector_elements == 4);
379             this->out_variables->push_tail(t);
380             this->out_instructions->push_tail(
381                   assign(t, expr(ir_unop_pack_double_2x32, i2u(swizzle_xy(rhs->clone(mem_ctx, NULL)))), 0x1));
382             this->out_instructions->push_tail(
383                   assign(t, expr(ir_unop_pack_double_2x32, i2u(swizzle(rhs->clone(mem_ctx, NULL), SWIZZLE_ZWZW, 2))), 0x2));
384             rhs = deref(t).val;
385          } else {
386             rhs = expr(ir_unop_pack_double_2x32, i2u(rhs));
387          }
388          break;
389       default:
390          assert(!"Unexpected type conversion while lowering varyings");
391          break;
392       }
393    }
394    this->out_instructions->push_tail(new(this->mem_ctx) ir_assignment(lhs, rhs));
395 }
396
397
398 /**
399  * Recursively pack or unpack the given varying (or portion of a varying) by
400  * traversing all of its constituent vectors.
401  *
402  * \param fine_location is the location where the first constituent vector
403  * should be packed--the word "fine" indicates that this location is expressed
404  * in multiples of a float, rather than multiples of a vec4 as is used
405  * elsewhere in Mesa.
406  *
407  * \param gs_input_toplevel should be set to true if we are lowering geometry
408  * shader inputs, and we are currently lowering the whole input variable
409  * (i.e. we are lowering the array whose index selects the vertex).
410  *
411  * \param vertex_index: if we are lowering geometry shader inputs, and the
412  * level of the array that we are currently lowering is *not* the top level,
413  * then this indicates which vertex we are currently lowering.  Otherwise it
414  * is ignored.
415  *
416  * \return the location where the next constituent vector (after this one)
417  * should be packed.
418  */
419 unsigned
420 lower_packed_varyings_visitor::lower_rvalue(ir_rvalue *rvalue,
421                                             unsigned fine_location,
422                                             ir_variable *unpacked_var,
423                                             const char *name,
424                                             bool gs_input_toplevel,
425                                             unsigned vertex_index)
426 {
427    unsigned dmul = rvalue->type->is_double() ? 2 : 1;
428    /* When gs_input_toplevel is set, we should be looking at a geometry shader
429     * input array.
430     */
431    assert(!gs_input_toplevel || rvalue->type->is_array());
432
433    if (rvalue->type->is_record()) {
434       for (unsigned i = 0; i < rvalue->type->length; i++) {
435          if (i != 0)
436             rvalue = rvalue->clone(this->mem_ctx, NULL);
437          const char *field_name = rvalue->type->fields.structure[i].name;
438          ir_dereference_record *dereference_record = new(this->mem_ctx)
439             ir_dereference_record(rvalue, field_name);
440          char *deref_name
441             = ralloc_asprintf(this->mem_ctx, "%s.%s", name, field_name);
442          fine_location = this->lower_rvalue(dereference_record, fine_location,
443                                             unpacked_var, deref_name, false,
444                                             vertex_index);
445       }
446       return fine_location;
447    } else if (rvalue->type->is_array()) {
448       /* Arrays are packed/unpacked by considering each array element in
449        * sequence.
450        */
451       return this->lower_arraylike(rvalue, rvalue->type->array_size(),
452                                    fine_location, unpacked_var, name,
453                                    gs_input_toplevel, vertex_index);
454    } else if (rvalue->type->is_matrix()) {
455       /* Matrices are packed/unpacked by considering each column vector in
456        * sequence.
457        */
458       return this->lower_arraylike(rvalue, rvalue->type->matrix_columns,
459                                    fine_location, unpacked_var, name,
460                                    false, vertex_index);
461    } else if (rvalue->type->vector_elements * dmul +
462               fine_location % 4 > 4) {
463       /* This vector is going to be "double parked" across two varying slots,
464        * so handle it as two separate assignments. For doubles, a dvec3/dvec4
465        * can end up being spread over 3 slots. However the second splitting
466        * will happen later, here we just always want to split into 2.
467        */
468       unsigned left_components, right_components;
469       unsigned left_swizzle_values[4] = { 0, 0, 0, 0 };
470       unsigned right_swizzle_values[4] = { 0, 0, 0, 0 };
471       char left_swizzle_name[4] = { 0, 0, 0, 0 };
472       char right_swizzle_name[4] = { 0, 0, 0, 0 };
473
474       left_components = 4 - fine_location % 4;
475       if (rvalue->type->is_double()) {
476          /* We might actually end up with 0 left components! */
477          left_components /= 2;
478       }
479       right_components = rvalue->type->vector_elements - left_components;
480
481       for (unsigned i = 0; i < left_components; i++) {
482          left_swizzle_values[i] = i;
483          left_swizzle_name[i] = "xyzw"[i];
484       }
485       for (unsigned i = 0; i < right_components; i++) {
486          right_swizzle_values[i] = i + left_components;
487          right_swizzle_name[i] = "xyzw"[i + left_components];
488       }
489       ir_swizzle *left_swizzle = new(this->mem_ctx)
490          ir_swizzle(rvalue, left_swizzle_values, left_components);
491       ir_swizzle *right_swizzle = new(this->mem_ctx)
492          ir_swizzle(rvalue->clone(this->mem_ctx, NULL), right_swizzle_values,
493                     right_components);
494       char *left_name
495          = ralloc_asprintf(this->mem_ctx, "%s.%s", name, left_swizzle_name);
496       char *right_name
497          = ralloc_asprintf(this->mem_ctx, "%s.%s", name, right_swizzle_name);
498       if (left_components)
499          fine_location = this->lower_rvalue(left_swizzle, fine_location,
500                                             unpacked_var, left_name, false,
501                                             vertex_index);
502       else
503          /* Top up the fine location to the next slot */
504          fine_location++;
505       return this->lower_rvalue(right_swizzle, fine_location, unpacked_var,
506                                 right_name, false, vertex_index);
507    } else {
508       /* No special handling is necessary; pack the rvalue into the
509        * varying.
510        */
511       unsigned swizzle_values[4] = { 0, 0, 0, 0 };
512       unsigned components = rvalue->type->vector_elements * dmul;
513       unsigned location = fine_location / 4;
514       unsigned location_frac = fine_location % 4;
515       for (unsigned i = 0; i < components; ++i)
516          swizzle_values[i] = i + location_frac;
517       ir_dereference *packed_deref =
518          this->get_packed_varying_deref(location, unpacked_var, name,
519                                         vertex_index);
520       ir_swizzle *swizzle = new(this->mem_ctx)
521          ir_swizzle(packed_deref, swizzle_values, components);
522       if (this->mode == ir_var_shader_out) {
523          this->bitwise_assign_pack(swizzle, rvalue);
524       } else {
525          this->bitwise_assign_unpack(rvalue, swizzle);
526       }
527       return fine_location + components;
528    }
529 }
530
531 /**
532  * Recursively pack or unpack a varying for which we need to iterate over its
533  * constituent elements, accessing each one using an ir_dereference_array.
534  * This takes care of both arrays and matrices, since ir_dereference_array
535  * treats a matrix like an array of its column vectors.
536  *
537  * \param gs_input_toplevel should be set to true if we are lowering geometry
538  * shader inputs, and we are currently lowering the whole input variable
539  * (i.e. we are lowering the array whose index selects the vertex).
540  *
541  * \param vertex_index: if we are lowering geometry shader inputs, and the
542  * level of the array that we are currently lowering is *not* the top level,
543  * then this indicates which vertex we are currently lowering.  Otherwise it
544  * is ignored.
545  */
546 unsigned
547 lower_packed_varyings_visitor::lower_arraylike(ir_rvalue *rvalue,
548                                                unsigned array_size,
549                                                unsigned fine_location,
550                                                ir_variable *unpacked_var,
551                                                const char *name,
552                                                bool gs_input_toplevel,
553                                                unsigned vertex_index)
554 {
555    for (unsigned i = 0; i < array_size; i++) {
556       if (i != 0)
557          rvalue = rvalue->clone(this->mem_ctx, NULL);
558       ir_constant *constant = new(this->mem_ctx) ir_constant(i);
559       ir_dereference_array *dereference_array = new(this->mem_ctx)
560          ir_dereference_array(rvalue, constant);
561       if (gs_input_toplevel) {
562          /* Geometry shader inputs are a special case.  Instead of storing
563           * each element of the array at a different location, all elements
564           * are at the same location, but with a different vertex index.
565           */
566          (void) this->lower_rvalue(dereference_array, fine_location,
567                                    unpacked_var, name, false, i);
568       } else {
569          char *subscripted_name
570             = ralloc_asprintf(this->mem_ctx, "%s[%d]", name, i);
571          fine_location =
572             this->lower_rvalue(dereference_array, fine_location,
573                                unpacked_var, subscripted_name,
574                                false, vertex_index);
575       }
576    }
577    return fine_location;
578 }
579
580 /**
581  * Retrieve the packed varying corresponding to the given varying location.
582  * If no packed varying has been created for the given varying location yet,
583  * create it and add it to the shader before returning it.
584  *
585  * The newly created varying inherits its interpolation parameters from \c
586  * unpacked_var.  Its base type is ivec4 if we are lowering a flat varying,
587  * vec4 otherwise.
588  *
589  * \param vertex_index: if we are lowering geometry shader inputs, then this
590  * indicates which vertex we are currently lowering.  Otherwise it is ignored.
591  */
592 ir_dereference *
593 lower_packed_varyings_visitor::get_packed_varying_deref(
594       unsigned location, ir_variable *unpacked_var, const char *name,
595       unsigned vertex_index)
596 {
597    unsigned slot = location - VARYING_SLOT_VAR0;
598    assert(slot < locations_used);
599    if (this->packed_varyings[slot] == NULL) {
600       char *packed_name = ralloc_asprintf(this->mem_ctx, "packed:%s", name);
601       const glsl_type *packed_type;
602       if (unpacked_var->data.interpolation == INTERP_QUALIFIER_FLAT)
603          packed_type = glsl_type::ivec4_type;
604       else
605          packed_type = glsl_type::vec4_type;
606       if (this->gs_input_vertices != 0) {
607          packed_type =
608             glsl_type::get_array_instance(packed_type,
609                                           this->gs_input_vertices);
610       }
611       ir_variable *packed_var = new(this->mem_ctx)
612          ir_variable(packed_type, packed_name, this->mode);
613       if (this->gs_input_vertices != 0) {
614          /* Prevent update_array_sizes() from messing with the size of the
615           * array.
616           */
617          packed_var->data.max_array_access = this->gs_input_vertices - 1;
618       }
619       packed_var->data.centroid = unpacked_var->data.centroid;
620       packed_var->data.sample = unpacked_var->data.sample;
621       packed_var->data.patch = unpacked_var->data.patch;
622       packed_var->data.interpolation = unpacked_var->data.interpolation;
623       packed_var->data.location = location;
624       unpacked_var->insert_before(packed_var);
625       this->packed_varyings[slot] = packed_var;
626    } else {
627       /* For geometry shader inputs, only update the packed variable name the
628        * first time we visit each component.
629        */
630       if (this->gs_input_vertices == 0 || vertex_index == 0) {
631          ralloc_asprintf_append((char **) &this->packed_varyings[slot]->name,
632                                 ",%s", name);
633       }
634    }
635
636    ir_dereference *deref = new(this->mem_ctx)
637       ir_dereference_variable(this->packed_varyings[slot]);
638    if (this->gs_input_vertices != 0) {
639       /* When lowering GS inputs, the packed variable is an array, so we need
640        * to dereference it using vertex_index.
641        */
642       ir_constant *constant = new(this->mem_ctx) ir_constant(vertex_index);
643       deref = new(this->mem_ctx) ir_dereference_array(deref, constant);
644    }
645    return deref;
646 }
647
648 bool
649 lower_packed_varyings_visitor::needs_lowering(ir_variable *var)
650 {
651    /* Things composed of vec4's and varyings with explicitly assigned
652     * locations don't need lowering.  Everything else does.
653     */
654    if (var->data.explicit_location)
655       return false;
656
657    const glsl_type *type = var->type->without_array();
658    if (type->vector_elements == 4 && !type->is_double())
659       return false;
660    return true;
661 }
662
663
664 /**
665  * Visitor that splices varying packing code before every use of EmitVertex()
666  * in a geometry shader.
667  */
668 class lower_packed_varyings_gs_splicer : public ir_hierarchical_visitor
669 {
670 public:
671    explicit lower_packed_varyings_gs_splicer(void *mem_ctx,
672                                              const exec_list *instructions);
673
674    virtual ir_visitor_status visit_leave(ir_emit_vertex *ev);
675
676 private:
677    /**
678     * Memory context used to allocate new instructions for the shader.
679     */
680    void * const mem_ctx;
681
682    /**
683     * Instructions that should be spliced into place before each EmitVertex()
684     * call.
685     */
686    const exec_list *instructions;
687 };
688
689
690 lower_packed_varyings_gs_splicer::lower_packed_varyings_gs_splicer(
691       void *mem_ctx, const exec_list *instructions)
692    : mem_ctx(mem_ctx), instructions(instructions)
693 {
694 }
695
696
697 ir_visitor_status
698 lower_packed_varyings_gs_splicer::visit_leave(ir_emit_vertex *ev)
699 {
700    foreach_in_list(ir_instruction, ir, this->instructions) {
701       ev->insert_before(ir->clone(this->mem_ctx, NULL));
702    }
703    return visit_continue;
704 }
705
706
707 void
708 lower_packed_varyings(void *mem_ctx, unsigned locations_used,
709                       ir_variable_mode mode, unsigned gs_input_vertices,
710                       gl_shader *shader)
711 {
712    exec_list *instructions = shader->ir;
713    ir_function *main_func = shader->symbols->get_function("main");
714    exec_list void_parameters;
715    ir_function_signature *main_func_sig
716       = main_func->matching_signature(NULL, &void_parameters, false);
717    exec_list new_instructions, new_variables;
718    lower_packed_varyings_visitor visitor(mem_ctx, locations_used, mode,
719                                          gs_input_vertices,
720                                          &new_instructions,
721                                          &new_variables);
722    visitor.run(shader);
723    if (mode == ir_var_shader_out) {
724       if (shader->Stage == MESA_SHADER_GEOMETRY) {
725          /* For geometry shaders, outputs need to be lowered before each call
726           * to EmitVertex()
727           */
728          lower_packed_varyings_gs_splicer splicer(mem_ctx, &new_instructions);
729
730          /* Add all the variables in first. */
731          main_func_sig->body.head->insert_before(&new_variables);
732
733          /* Now update all the EmitVertex instances */
734          splicer.run(instructions);
735       } else {
736          /* For other shader types, outputs need to be lowered at the end of
737           * main()
738           */
739          main_func_sig->body.append_list(&new_variables);
740          main_func_sig->body.append_list(&new_instructions);
741       }
742    } else {
743       /* Shader inputs need to be lowered at the beginning of main() */
744       main_func_sig->body.head->insert_before(&new_instructions);
745       main_func_sig->body.head->insert_before(&new_variables);
746    }
747 }