linker.cpp 85.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Copyright © 2010 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file linker.cpp
 * GLSL linker implementation
 *
 * Given a set of shaders that are to be linked to generate a final program,
 * there are three distinct stages.
 *
 * In the first stage shaders are partitioned into groups based on the shader
 * type.  All shaders of a particular type (e.g., vertex shaders) are linked
 * together.
 *
 *   - Undefined references in each shader are resolve to definitions in
 *     another shader.
 *   - Types and qualifiers of uniforms, outputs, and global variables defined
 *     in multiple shaders with the same name are verified to be the same.
 *   - Initializers for uniforms and global variables defined
 *     in multiple shaders with the same name are verified to be the same.
 *
 * The result, in the terminology of the GLSL spec, is a set of shader
 * executables for each processing unit.
 *
 * After the first stage is complete, a series of semantic checks are performed
 * on each of the shader executables.
 *
 *   - Each shader executable must define a \c main function.
 *   - Each vertex shader executable must write to \c gl_Position.
 *   - Each fragment shader executable must write to either \c gl_FragData or
 *     \c gl_FragColor.
 *
 * In the final stage individual shader executables are linked to create a
 * complete exectuable.
 *
 *   - Types of uniforms defined in multiple shader stages with the same name
 *     are verified to be the same.
 *   - Initializers for uniforms defined in multiple shader stages with the
 *     same name are verified to be the same.
 *   - Types and qualifiers of outputs defined in one stage are verified to
 *     be the same as the types and qualifiers of inputs defined with the same
 *     name in a later stage.
 *
 * \author Ian Romanick <ian.d.romanick@intel.com>
 */
66

Chia-I Wu's avatar
Chia-I Wu committed
67
#include "main/core.h"
68
69
70
#include "glsl_symbol_table.h"
#include "ir.h"
#include "program.h"
71
#include "program/hash_table.h"
72
#include "linker.h"
73
#include "ir_optimization.h"
74

75
76
77
78
extern "C" {
#include "main/shaderobj.h"
}

79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
 * Visitor that determines whether or not a variable is ever written.
 */
class find_assignment_visitor : public ir_hierarchical_visitor {
public:
   find_assignment_visitor(const char *name)
      : name(name), found(false)
   {
      /* empty */
   }

   virtual ir_visitor_status visit_enter(ir_assignment *ir)
   {
      ir_variable *const var = ir->lhs->variable_referenced();

      if (strcmp(name, var->name) == 0) {
	 found = true;
	 return visit_stop;
      }

      return visit_continue_with_parent;
   }

102
103
   virtual ir_visitor_status visit_enter(ir_call *ir)
   {
104
      exec_list_iterator sig_iter = ir->callee->parameters.iterator();
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
      foreach_iter(exec_list_iterator, iter, *ir) {
	 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
	 ir_variable *sig_param = (ir_variable *)sig_iter.get();

	 if (sig_param->mode == ir_var_out ||
	     sig_param->mode == ir_var_inout) {
	    ir_variable *var = param_rval->variable_referenced();
	    if (var && strcmp(name, var->name) == 0) {
	       found = true;
	       return visit_stop;
	    }
	 }
	 sig_iter.next();
      }

120
121
122
123
124
125
126
127
128
      if (ir->return_deref != NULL) {
	 ir_variable *const var = ir->return_deref->variable_referenced();

	 if (strcmp(name, var->name) == 0) {
	    found = true;
	    return visit_stop;
	 }
      }

129
130
131
      return visit_continue_with_parent;
   }

132
133
134
135
136
137
138
139
140
141
   bool variable_found()
   {
      return found;
   }

private:
   const char *name;       /**< Find writes to a variable with this name. */
   bool found;             /**< Was a write to the variable found? */
};

142

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/**
 * Visitor that determines whether or not a variable is ever read.
 */
class find_deref_visitor : public ir_hierarchical_visitor {
public:
   find_deref_visitor(const char *name)
      : name(name), found(false)
   {
      /* empty */
   }

   virtual ir_visitor_status visit(ir_dereference_variable *ir)
   {
      if (strcmp(this->name, ir->var->name) == 0) {
	 this->found = true;
	 return visit_stop;
      }

      return visit_continue;
   }

   bool variable_found() const
   {
      return this->found;
   }

private:
   const char *name;       /**< Find writes to a variable with this name. */
   bool found;             /**< Was a write to the variable found? */
};


175
void
176
linker_error(gl_shader_program *prog, const char *fmt, ...)
177
178
179
{
   va_list ap;

180
   ralloc_strcat(&prog->InfoLog, "error: ");
181
   va_start(ap, fmt);
182
   ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
183
   va_end(ap);
184
185

   prog->LinkStatus = false;
186
187
188
}


189
190
191
192
193
194
195
196
197
198
199
200
201
void
linker_warning(gl_shader_program *prog, const char *fmt, ...)
{
   va_list ap;

   ralloc_strcat(&prog->InfoLog, "error: ");
   va_start(ap, fmt);
   ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
   va_end(ap);

}


202
void
203
204
link_invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
				   int generic_base)
205
{
206
   foreach_list(node, sh->ir) {
207
208
209
210
211
212
213
      ir_variable *const var = ((ir_instruction *) node)->as_variable();

      if ((var == NULL) || (var->mode != (unsigned) mode))
	 continue;

      /* Only assign locations for generic attributes / varyings / etc.
       */
214
      if ((var->location >= generic_base) && !var->explicit_location)
215
216
217
218
219
	  var->location = -1;
   }
}


220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/**
 * Determine the number of attribute slots required for a particular type
 *
 * This code is here because it implements the language rules of a specific
 * GLSL version.  Since it's a property of the language and not a property of
 * types in general, it doesn't really belong in glsl_type.
 */
unsigned
count_attribute_slots(const glsl_type *t)
{
   /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
    *
    *     "A scalar input counts the same amount against this limit as a vec4,
    *     so applications may want to consider packing groups of four
    *     unrelated float inputs together into a vector to better utilize the
    *     capabilities of the underlying hardware. A matrix input will use up
    *     multiple locations.  The number of locations used will equal the
    *     number of columns in the matrix."
    *
    * The spec does not explicitly say how arrays are counted.  However, it
    * should be safe to assume the total number of slots consumed by an array
    * is the number of entries in the array multiplied by the number of slots
    * consumed by a single element of the array.
    */

   if (t->is_array())
      return t->array_size() * count_attribute_slots(t->element_type());

   if (t->is_matrix())
      return t->matrix_columns;

   return 1;
}


255
/**
256
257
 * Verify that a vertex shader executable meets all semantic requirements.
 *
258
259
 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
 * as a side effect.
260
261
262
 *
 * \param shader  Vertex shader executable to be verified
 */
263
bool
264
validate_vertex_shader_executable(struct gl_shader_program *prog,
265
				  struct gl_shader *shader)
266
267
268
269
{
   if (shader == NULL)
      return true;

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
   /* From the GLSL 1.10 spec, page 48:
    *
    *     "The variable gl_Position is available only in the vertex
    *      language and is intended for writing the homogeneous vertex
    *      position. All executions of a well-formed vertex shader
    *      executable must write a value into this variable. [...] The
    *      variable gl_Position is available only in the vertex
    *      language and is intended for writing the homogeneous vertex
    *      position. All executions of a well-formed vertex shader
    *      executable must write a value into this variable."
    *
    * while in GLSL 1.40 this text is changed to:
    *
    *     "The variable gl_Position is available only in the vertex
    *      language and is intended for writing the homogeneous vertex
    *      position. It can be written at any time during shader
    *      execution. It may also be read back by a vertex shader
    *      after being written. This value will be used by primitive
    *      assembly, clipping, culling, and other fixed functionality
    *      operations, if present, that operate on primitives after
    *      vertex processing has occurred. Its value is undefined if
    *      the vertex shader executable does not write gl_Position."
    */
   if (prog->Version < 140) {
      find_assignment_visitor find("gl_Position");
      find.run(shader->ir);
      if (!find.variable_found()) {
	 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
	 return false;
      }
300
301
   }

302
303
   prog->Vert.ClipDistanceArraySize = 0;

304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
   if (prog->Version >= 130) {
      /* From section 7.1 (Vertex Shader Special Variables) of the
       * GLSL 1.30 spec:
       *
       *   "It is an error for a shader to statically write both
       *   gl_ClipVertex and gl_ClipDistance."
       */
      find_assignment_visitor clip_vertex("gl_ClipVertex");
      find_assignment_visitor clip_distance("gl_ClipDistance");

      clip_vertex.run(shader->ir);
      clip_distance.run(shader->ir);
      if (clip_vertex.variable_found() && clip_distance.variable_found()) {
         linker_error(prog, "vertex shader writes to both `gl_ClipVertex' "
                      "and `gl_ClipDistance'\n");
         return false;
      }
321
      prog->Vert.UsesClipDistance = clip_distance.variable_found();
322
323
324
325
      ir_variable *clip_distance_var =
         shader->symbols->get_variable("gl_ClipDistance");
      if (clip_distance_var)
         prog->Vert.ClipDistanceArraySize = clip_distance_var->type->length;
326
327
   }

328
329
330
331
   return true;
}


332
333
334
335
336
/**
 * Verify that a fragment shader executable meets all semantic requirements
 *
 * \param shader  Fragment shader executable to be verified
 */
337
bool
338
validate_fragment_shader_executable(struct gl_shader_program *prog,
339
				    struct gl_shader *shader)
340
341
342
343
344
345
346
{
   if (shader == NULL)
      return true;

   find_assignment_visitor frag_color("gl_FragColor");
   find_assignment_visitor frag_data("gl_FragData");

347
348
   frag_color.run(shader->ir);
   frag_data.run(shader->ir);
349
350

   if (frag_color.variable_found() && frag_data.variable_found()) {
351
352
      linker_error(prog,  "fragment shader writes to both "
		   "`gl_FragColor' and `gl_FragData'\n");
353
354
355
356
357
358
359
      return false;
   }

   return true;
}


360
/**
361
362
363
364
365
366
367
368
369
370
371
372
373
 * Generate a string describing the mode of a variable
 */
static const char *
mode_string(const ir_variable *var)
{
   switch (var->mode) {
   case ir_var_auto:
      return (var->read_only) ? "global constant" : "global variable";

   case ir_var_uniform: return "uniform";
   case ir_var_in:      return "shader input";
   case ir_var_out:     return "shader output";
   case ir_var_inout:   return "shader inout";
374

375
   case ir_var_const_in:
376
   case ir_var_temporary:
377
378
379
380
381
382
383
384
385
   default:
      assert(!"Should not get here.");
      return "invalid variable";
   }
}


/**
 * Perform validation of global variables used across multiple shaders
386
387
 */
bool
388
389
390
391
cross_validate_globals(struct gl_shader_program *prog,
		       struct gl_shader **shader_list,
		       unsigned num_shaders,
		       bool uniforms_only)
392
393
394
395
{
   /* Examine all of the uniforms in all of the shaders and cross validate
    * them.
    */
396
397
   glsl_symbol_table variables;
   for (unsigned i = 0; i < num_shaders; i++) {
398
399
400
      if (shader_list[i] == NULL)
	 continue;

401
      foreach_list(node, shader_list[i]->ir) {
402
403
	 ir_variable *const var = ((ir_instruction *) node)->as_variable();

404
405
406
407
	 if (var == NULL)
	    continue;

	 if (uniforms_only && (var->mode != ir_var_uniform))
408
409
	    continue;

410
411
412
413
414
415
	 /* Don't cross validate temporaries that are at global scope.  These
	  * will eventually get pulled into the shaders 'main'.
	  */
	 if (var->mode == ir_var_temporary)
	    continue;

416
417
	 /* If a global with this name has already been seen, verify that the
	  * new instance has the same type.  In addition, if the globals have
418
419
	  * initializers, the values of the initializers must be the same.
	  */
420
	 ir_variable *const existing = variables.get_variable(var->name);
421
422
	 if (existing != NULL) {
	    if (var->type != existing->type) {
423
424
425
426
427
428
429
430
431
432
	       /* Consider the types to be "the same" if both types are arrays
		* of the same type and one of the arrays is implicitly sized.
		* In addition, set the type of the linked variable to the
		* explicitly sized array.
		*/
	       if (var->type->is_array()
		   && existing->type->is_array()
		   && (var->type->fields.array == existing->type->fields.array)
		   && ((var->type->length == 0)
		       || (existing->type->length == 0))) {
433
		  if (var->type->length != 0) {
434
		     existing->type = var->type;
435
		  }
436
	       } else {
437
438
439
440
441
		  linker_error(prog, "%s `%s' declared as type "
			       "`%s' and type `%s'\n",
			       mode_string(var),
			       var->name, var->type->name,
			       existing->type->name);
442
443
		  return false;
	       }
444
445
	    }

446
447
448
	    if (var->explicit_location) {
	       if (existing->explicit_location
		   && (var->location != existing->location)) {
449
450
451
		     linker_error(prog, "explicit locations for %s "
				  "`%s' have differing values\n",
				  mode_string(var), var->name);
452
453
454
455
456
457
458
		     return false;
	       }

	       existing->location = var->location;
	       existing->explicit_location = true;
	    }

459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
	    /* Validate layout qualifiers for gl_FragDepth.
	     *
	     * From the AMD/ARB_conservative_depth specs:
	     *
	     *    "If gl_FragDepth is redeclared in any fragment shader in a
	     *    program, it must be redeclared in all fragment shaders in
	     *    that program that have static assignments to
	     *    gl_FragDepth. All redeclarations of gl_FragDepth in all
	     *    fragment shaders in a single program must have the same set
	     *    of qualifiers."
	     */
	    if (strcmp(var->name, "gl_FragDepth") == 0) {
	       bool layout_declared = var->depth_layout != ir_depth_layout_none;
	       bool layout_differs =
		  var->depth_layout != existing->depth_layout;

	       if (layout_declared && layout_differs) {
		  linker_error(prog,
			       "All redeclarations of gl_FragDepth in all "
			       "fragment shaders in a single program must have "
			       "the same set of qualifiers.");
	       }

	       if (var->used && layout_differs) {
		  linker_error(prog,
			       "If gl_FragDepth is redeclared with a layout "
			       "qualifier in any fragment shader, it must be "
			       "redeclared with the same layout qualifier in "
			       "all fragment shaders that have assignments to "
			       "gl_FragDepth");
	       }
	    }
491

492
493
494
495
496
497
498
499
500
501
502
503
504
505
	    /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
	     *
	     *     "If a shared global has multiple initializers, the
	     *     initializers must all be constant expressions, and they
	     *     must all have the same value. Otherwise, a link error will
	     *     result. (A shared global having only one initializer does
	     *     not require that initializer to be a constant expression.)"
	     *
	     * Previous to 4.20 the GLSL spec simply said that initializers
	     * must have the same value.  In this case of non-constant
	     * initializers, this was impossible to determine.  As a result,
	     * no vendor actually implemented that behavior.  The 4.20
	     * behavior matches the implemented behavior of at least one other
	     * vendor, so we'll implement that for all GLSL versions.
506
	     */
507
508
509
	    if (var->constant_initializer != NULL) {
	       if (existing->constant_initializer != NULL) {
		  if (!var->constant_initializer->has_value(existing->constant_initializer)) {
510
511
512
		     linker_error(prog, "initializers for %s "
				  "`%s' have differing values\n",
				  mode_string(var), var->name);
513
514
		     return false;
		  }
515
	       } else {
516
517
518
519
		  /* If the first-seen instance of a particular uniform did not
		   * have an initializer but a later instance does, copy the
		   * initializer to the version stored in the symbol table.
		   */
520
521
522
523
524
525
526
527
		  /* FINISHME: This is wrong.  The constant_value field should
		   * FINISHME: not be modified!  Imagine a case where a shader
		   * FINISHME: without an initializer is linked in two different
		   * FINISHME: programs with shaders that have differing
		   * FINISHME: initializers.  Linking with the first will
		   * FINISHME: modify the shader, and linking with the second
		   * FINISHME: will fail.
		   */
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
		  existing->constant_initializer =
		     var->constant_initializer->clone(ralloc_parent(existing),
						      NULL);
	       }
	    }

	    if (var->has_initializer) {
	       if (existing->has_initializer
		   && (var->constant_initializer == NULL
		       || existing->constant_initializer == NULL)) {
		  linker_error(prog,
			       "shared global variable `%s' has multiple "
			       "non-constant initializers.\n",
			       var->name);
		  return false;
	       }

	       /* Some instance had an initializer, so keep track of that.  In
		* this location, all sorts of initializers (constant or
		* otherwise) will propagate the existence to the variable
		* stored in the symbol table.
		*/
	       existing->has_initializer = true;
551
	    }
552
553

	    if (existing->invariant != var->invariant) {
554
555
556
	       linker_error(prog, "declarations for %s `%s' have "
			    "mismatching invariant qualifiers\n",
			    mode_string(var), var->name);
557
558
	       return false;
	    }
559
            if (existing->centroid != var->centroid) {
560
561
562
               linker_error(prog, "declarations for %s `%s' have "
			    "mismatching centroid qualifiers\n",
			    mode_string(var), var->name);
563
564
               return false;
            }
565
	 } else
566
	    variables.add_variable(var);
567
568
569
570
571
572
573
      }
   }

   return true;
}


574
575
576
577
578
579
580
/**
 * Perform validation of uniforms used across multiple shader stages
 */
bool
cross_validate_uniforms(struct gl_shader_program *prog)
{
   return cross_validate_globals(prog, prog->_LinkedShaders,
581
				 MESA_SHADER_TYPES, true);
582
583
}

584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/**
 * Accumulates the array of prog->UniformBlocks and checks that all
 * definitons of blocks agree on their contents.
 */
static bool
interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
{
   unsigned max_num_uniform_blocks = 0;
   for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
      if (prog->_LinkedShaders[i])
	 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
   }

   for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
      struct gl_shader *sh = prog->_LinkedShaders[i];

      prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
						     max_num_uniform_blocks);
      for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
	 prog->UniformBlockStageIndex[i][j] = -1;

      if (sh == NULL)
	 continue;

      for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
	 int index = link_cross_validate_uniform_block(prog,
						       &prog->UniformBlocks,
						       &prog->NumUniformBlocks,
						       &sh->UniformBlocks[j]);

	 if (index == -1) {
	    linker_error(prog, "uniform block `%s' has mismatching definitions",
			 sh->UniformBlocks[j].Name);
	    return false;
	 }

	 prog->UniformBlockStageIndex[i][index] = j;
      }
   }

   return true;
}
626

627
628
629
630
/**
 * Validate that outputs from one stage match inputs of another
 */
bool
631
cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
632
				 gl_shader *producer, gl_shader *consumer)
633
634
635
636
637
638
639
640
{
   glsl_symbol_table parameters;
   /* FINISHME: Figure these out dynamically. */
   const char *const producer_stage = "vertex";
   const char *const consumer_stage = "fragment";

   /* Find all shader outputs in the "producer" stage.
    */
641
   foreach_list(node, producer->ir) {
642
643
644
645
646
647
648
649
      ir_variable *const var = ((ir_instruction *) node)->as_variable();

      /* FINISHME: For geometry shaders, this should also look for inout
       * FINISHME: variables.
       */
      if ((var == NULL) || (var->mode != ir_var_out))
	 continue;

650
      parameters.add_variable(var);
651
652
653
654
655
656
657
   }


   /* Find all shader inputs in the "consumer" stage.  Any variables that have
    * matching outputs already in the symbol table must have the same type and
    * qualifiers.
    */
658
   foreach_list(node, consumer->ir) {
659
660
661
662
663
664
665
666
667
668
669
670
671
      ir_variable *const input = ((ir_instruction *) node)->as_variable();

      /* FINISHME: For geometry shaders, this should also look for inout
       * FINISHME: variables.
       */
      if ((input == NULL) || (input->mode != ir_var_in))
	 continue;

      ir_variable *const output = parameters.get_variable(input->name);
      if (output != NULL) {
	 /* Check that the types match between stages.
	  */
	 if (input->type != output->type) {
672
	    /* There is a bit of a special case for gl_TexCoord.  This
Bryan Cain's avatar
Bryan Cain committed
673
	     * built-in is unsized by default.  Applications that variable
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
	     * access it must redeclare it with a size.  There is some
	     * language in the GLSL spec that implies the fragment shader
	     * and vertex shader do not have to agree on this size.  Other
	     * driver behave this way, and one or two applications seem to
	     * rely on it.
	     *
	     * Neither declaration needs to be modified here because the array
	     * sizes are fixed later when update_array_sizes is called.
	     *
	     * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
	     *
	     *     "Unlike user-defined varying variables, the built-in
	     *     varying variables don't have a strict one-to-one
	     *     correspondence between the vertex language and the
	     *     fragment language."
	     */
	    if (!output->type->is_array()
		|| (strncmp("gl_", output->name, 3) != 0)) {
692
693
694
695
696
697
	       linker_error(prog,
			    "%s shader output `%s' declared as type `%s', "
			    "but %s shader input declared as type `%s'\n",
			    producer_stage, output->name,
			    output->type->name,
			    consumer_stage, input->type->name);
698
699
	       return false;
	    }
700
701
702
703
704
	 }

	 /* Check that all of the qualifiers match between stages.
	  */
	 if (input->centroid != output->centroid) {
705
706
707
708
709
710
711
712
	    linker_error(prog,
			 "%s shader output `%s' %s centroid qualifier, "
			 "but %s shader input %s centroid qualifier\n",
			 producer_stage,
			 output->name,
			 (output->centroid) ? "has" : "lacks",
			 consumer_stage,
			 (input->centroid) ? "has" : "lacks");
713
714
715
716
	    return false;
	 }

	 if (input->invariant != output->invariant) {
717
718
719
720
721
722
723
724
	    linker_error(prog,
			 "%s shader output `%s' %s invariant qualifier, "
			 "but %s shader input %s invariant qualifier\n",
			 producer_stage,
			 output->name,
			 (output->invariant) ? "has" : "lacks",
			 consumer_stage,
			 (input->invariant) ? "has" : "lacks");
725
726
727
728
	    return false;
	 }

	 if (input->interpolation != output->interpolation) {
729
730
731
732
733
734
735
736
737
738
	    linker_error(prog,
			 "%s shader output `%s' specifies %s "
			 "interpolation qualifier, "
			 "but %s shader input specifies %s "
			 "interpolation qualifier\n",
			 producer_stage,
			 output->name,
			 output->interpolation_string(),
			 consumer_stage,
			 input->interpolation_string());
739
740
741
742
743
744
745
746
747
	    return false;
	 }
      }
   }

   return true;
}


748
749
750
751
752
753
754
755
756
757
758
759
760
761
/**
 * Populates a shaders symbol table with all global declarations
 */
static void
populate_symbol_table(gl_shader *sh)
{
   sh->symbols = new(sh) glsl_symbol_table;

   foreach_list(node, sh->ir) {
      ir_instruction *const inst = (ir_instruction *) node;
      ir_variable *var;
      ir_function *func;

      if ((func = inst->as_function()) != NULL) {
762
	 sh->symbols->add_function(func);
763
      } else if ((var = inst->as_variable()) != NULL) {
764
	 sh->symbols->add_variable(var);
765
766
767
768
769
      }
   }
}


770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
/**
 * Remap variables referenced in an instruction tree
 *
 * This is used when instruction trees are cloned from one shader and placed in
 * another.  These trees will contain references to \c ir_variable nodes that
 * do not exist in the target shader.  This function finds these \c ir_variable
 * references and replaces the references with matching variables in the target
 * shader.
 *
 * If there is no matching variable in the target shader, a clone of the
 * \c ir_variable is made and added to the target shader.  The new variable is
 * added to \b both the instruction stream and the symbol table.
 *
 * \param inst         IR tree that is to be processed.
 * \param symbols      Symbol table containing global scope symbols in the
 *                     linked shader.
 * \param instructions Instruction stream where new variable declarations
 *                     should be added.
 */
void
790
791
remap_variables(ir_instruction *inst, struct gl_shader *target,
		hash_table *temps)
792
793
794
{
   class remap_visitor : public ir_hierarchical_visitor {
   public:
795
	 remap_visitor(struct gl_shader *target,
796
		    hash_table *temps)
797
      {
798
799
800
	 this->target = target;
	 this->symbols = target->symbols;
	 this->instructions = target->ir;
801
	 this->temps = temps;
802
803
804
805
      }

      virtual ir_visitor_status visit(ir_dereference_variable *ir)
      {
806
807
808
809
810
811
812
813
	 if (ir->var->mode == ir_var_temporary) {
	    ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);

	    assert(var != NULL);
	    ir->var = var;
	    return visit_continue;
	 }

814
815
816
817
818
	 ir_variable *const existing =
	    this->symbols->get_variable(ir->var->name);
	 if (existing != NULL)
	    ir->var = existing;
	 else {
819
	    ir_variable *copy = ir->var->clone(this->target, NULL);
820

821
	    this->symbols->add_variable(copy);
822
	    this->instructions->push_head(copy);
823
	    ir->var = copy;
824
825
826
827
828
829
	 }

	 return visit_continue;
      }

   private:
830
      struct gl_shader *target;
831
832
      glsl_symbol_table *symbols;
      exec_list *instructions;
833
      hash_table *temps;
834
835
   };

836
   remap_visitor v(target, temps);
837
838
839
840
841
842
843
844
845

   inst->accept(&v);
}


/**
 * Move non-declarations from one instruction stream to another
 *
 * The intended usage pattern of this function is to pass the pointer to the
846
 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
 * pointer) for \c last and \c false for \c make_copies on the first
 * call.  Successive calls pass the return value of the previous call for
 * \c last and \c true for \c make_copies.
 *
 * \param instructions Source instruction stream
 * \param last         Instruction after which new instructions should be
 *                     inserted in the target instruction stream
 * \param make_copies  Flag selecting whether instructions in \c instructions
 *                     should be copied (via \c ir_instruction::clone) into the
 *                     target list or moved.
 *
 * \return
 * The new "last" instruction in the target instruction stream.  This pointer
 * is suitable for use as the \c last parameter of a later call to this
 * function.
 */
exec_node *
move_non_declarations(exec_list *instructions, exec_node *last,
		      bool make_copies, gl_shader *target)
{
867
868
869
870
871
872
   hash_table *temps = NULL;

   if (make_copies)
      temps = hash_table_ctor(0, hash_table_pointer_hash,
			      hash_table_pointer_compare);

873
   foreach_list_safe(node, instructions) {
874
875
      ir_instruction *inst = (ir_instruction *) node;

876
877
878
879
880
      if (inst->as_function())
	 continue;

      ir_variable *var = inst->as_variable();
      if ((var != NULL) && (var->mode != ir_var_temporary))
881
882
	 continue;

883
      assert(inst->as_assignment()
884
             || inst->as_call()
885
             || inst->as_if() /* for initializers with the ?: operator */
886
	     || ((var != NULL) && (var->mode == ir_var_temporary)));
887
888

      if (make_copies) {
889
	 inst = inst->clone(target, NULL);
890
891
892
893

	 if (var != NULL)
	    hash_table_insert(temps, inst, var);
	 else
894
	    remap_variables(inst, target, temps);
895
896
897
898
899
900
901
902
      } else {
	 inst->remove();
      }

      last->insert_after(inst);
      last = inst;
   }

903
904
905
   if (make_copies)
      hash_table_dtor(temps);

906
907
908
   return last;
}

909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
/**
 * Get the function signature for main from a shader
 */
static ir_function_signature *
get_main_function_signature(gl_shader *sh)
{
   ir_function *const f = sh->symbols->get_function("main");
   if (f != NULL) {
      exec_list void_parameters;

      /* Look for the 'void main()' signature and ensure that it's defined.
       * This keeps the linker from accidentally pick a shader that just
       * contains a prototype for main.
       *
       * We don't have to check for multiple definitions of main (in multiple
       * shaders) because that would have already been caught above.
       */
      ir_function_signature *sig = f->matching_signature(&void_parameters);
      if ((sig != NULL) && sig->is_defined) {
	 return sig;
      }
   }

   return NULL;
}


936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
/**
 * This class is only used in link_intrastage_shaders() below but declaring
 * it inside that function leads to compiler warnings with some versions of
 * gcc.
 */
class array_sizing_visitor : public ir_hierarchical_visitor {
public:
   virtual ir_visitor_status visit(ir_variable *var)
   {
      if (var->type->is_array() && (var->type->length == 0)) {
         const glsl_type *type =
            glsl_type::get_array_instance(var->type->fields.array,
                                          var->max_array_access + 1);
         assert(type != NULL);
         var->type = type;
      }
      return visit_continue;
   }
};

956
957
958
959
960
961
962
963
/**
 * Combine a group of shaders for a single stage to generate a linked shader
 *
 * \note
 * If this function is supplied a single shader, it is cloned, and the new
 * shader is returned.
 */
static struct gl_shader *
964
965
link_intrastage_shaders(void *mem_ctx,
			struct gl_context *ctx,
966
			struct gl_shader_program *prog,
967
968
969
			struct gl_shader **shader_list,
			unsigned num_shaders)
{
970
971
972
   struct gl_uniform_block *uniform_blocks = NULL;
   unsigned num_uniform_blocks = 0;

973
974
975
976
977
   /* Check that global variables defined in multiple shaders are consistent.
    */
   if (!cross_validate_globals(prog, shader_list, num_shaders, false))
      return NULL;

978
979
980
981
982
   /* Check that uniform blocks between shaders for a stage agree. */
   for (unsigned i = 0; i < num_shaders; i++) {
      struct gl_shader *sh = shader_list[i];

      for (unsigned j = 0; j < shader_list[i]->NumUniformBlocks; j++) {
983
984
	 link_assign_uniform_block_offsets(shader_list[i]);

985
986
987
988
989
990
991
992
993
994
995
996
	 int index = link_cross_validate_uniform_block(mem_ctx,
						       &uniform_blocks,
						       &num_uniform_blocks,
						       &sh->UniformBlocks[j]);
	 if (index == -1) {
	    linker_error(prog, "uniform block `%s' has mismatching definitions",
			 sh->UniformBlocks[j].Name);
	    return NULL;
	 }
      }
   }

997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
   /* Check that there is only a single definition of each function signature
    * across all shaders.
    */
   for (unsigned i = 0; i < (num_shaders - 1); i++) {
      foreach_list(node, shader_list[i]->ir) {
	 ir_function *const f = ((ir_instruction *) node)->as_function();

	 if (f == NULL)
	    continue;

	 for (unsigned j = i + 1; j < num_shaders; j++) {
	    ir_function *const other =
	       shader_list[j]->symbols->get_function(f->name);

	    /* If the other shader has no function (and therefore no function
	     * signatures) with the same name, skip to the next shader.
	     */
	    if (other == NULL)
	       continue;

	    foreach_iter (exec_list_iterator, iter, *f) {
	       ir_function_signature *sig =
		  (ir_function_signature *) iter.get();

1021
	       if (!sig->is_defined || sig->is_builtin)
1022
1023
1024
1025
1026
1027
		  continue;

	       ir_function_signature *other_sig =
		  other->exact_matching_signature(& sig->parameters);

	       if ((other_sig != NULL) && other_sig->is_defined
1028
		   && !other_sig->is_builtin) {
1029
1030
		  linker_error(prog, "function `%s' is multiply defined",
			       f->name);
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
		  return NULL;
	       }
	    }
	 }
      }
   }

   /* Find the shader that defines main, and make a clone of it.
    *
    * Starting with the clone, search for undefined references.  If one is
    * found, find the shader that defines it.  Clone the reference and add
    * it to the shader.  Repeat until there are no undefined references or
    * until a reference cannot be resolved.
    */
1045
1046
1047
1048
1049
1050
1051
   gl_shader *main = NULL;
   for (unsigned i = 0; i < num_shaders; i++) {
      if (get_main_function_signature(shader_list[i]) != NULL) {
	 main = shader_list[i];
	 break;
      }
   }
1052

1053
   if (main == NULL) {
1054
1055
1056
      linker_error(prog, "%s shader lacks `main'\n",
		   (shader_list[0]->Type == GL_VERTEX_SHADER)
		   ? "vertex" : "fragment");
1057
1058
      return NULL;
   }
1059

1060
   gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
1061
   linked->ir = new(linked) exec_list;
1062
   clone_ir_list(mem_ctx, linked->ir, main->ir);
1063

1064
1065
1066
1067
   linked->UniformBlocks = uniform_blocks;
   linked->NumUniformBlocks = num_uniform_blocks;
   ralloc_steal(linked, linked->UniformBlocks);

1068
1069
   populate_symbol_table(linked);

1070
1071
1072
1073
1074
1075
1076
1077
   /* The a pointer to the main function in the final linked shader (i.e., the
    * copy of the original shader that contained the main function).
    */
   ir_function_signature *const main_sig = get_main_function_signature(linked);

   /* Move any instructions other than variable declarations or function
    * declarations into main.
    */
1078
1079
1080
1081
   exec_node *insertion_point =
      move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
			    linked);

1082
   for (unsigned i = 0; i < num_shaders; i++) {
1083
1084
1085
      if (shader_list[i] == main)
	 continue;

1086
      insertion_point = move_non_declarations(shader_list[i]->ir,
1087
					      insertion_point, true, linked);
1088
1089
   }

1090
1091
   /* Resolve initializers for global variables in the linked shader.
    */
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
   unsigned num_linking_shaders = num_shaders;
   for (unsigned i = 0; i < num_shaders; i++)
      num_linking_shaders += shader_list[i]->num_builtins_to_link;

   gl_shader **linking_shaders =
      (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));

   memcpy(linking_shaders, shader_list,
	  sizeof(linking_shaders[0]) * num_shaders);

   unsigned idx = num_shaders;
   for (unsigned i = 0; i < num_shaders; i++) {
      memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
	     sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
      idx += shader_list[i]->num_builtins_to_link;
   }

   assert(idx == num_linking_shaders);

1111
1112
1113
1114
1115
   if (!link_function_calls(prog, linked, linking_shaders,
			    num_linking_shaders)) {
      ctx->Driver.DeleteShader(ctx, linked);
      linked = NULL;
   }
1116
1117

   free(linking_shaders);
1118

1119
1120
1121
1122
1123
1124
1125
1126
#ifdef DEBUG
   /* At this point linked should contain all of the linked IR, so
    * validate it to make sure nothing went wrong.
    */
   if (linked)
      validate_ir_tree(linked->ir);
#endif

1127
   /* Make a pass over all variable declarations to ensure that arrays with
1128
1129
1130
    * unspecified sizes have a size specified.  The size is inferred from the
    * max_array_access field.
    */
1131
   if (linked != NULL) {
1132
      array_sizing_visitor v;
1133

1134
      v.run(linked->ir);
1135
   }
1136

1137
1138
1139
   return linked;
}

1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
/**
 * Update the sizes of linked shader uniform arrays to the maximum
 * array index used.
 *
 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
 *
 *     If one or more elements of an array are active,
 *     GetActiveUniform will return the name of the array in name,
 *     subject to the restrictions listed above. The type of the array
 *     is returned in type. The size parameter contains the highest
 *     array element index used, plus one. The compiler or linker
 *     determines the highest index used.  There will be only one
 *     active uniform reported by the GL per uniform array.

 */
static void
1156
update_array_sizes(struct gl_shader_program *prog)
1157
{
1158
1159
1160
1161
   for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
	 if (prog->_LinkedShaders[i] == NULL)
	    continue;

1162
1163
1164
      foreach_list(node, prog->_LinkedShaders[i]->ir) {
	 ir_variable *const var = ((ir_instruction *) node)->as_variable();

1165
1166
1167
	 if ((var == NULL) || (var->mode != ir_var_uniform &&
			       var->mode != ir_var_in &&
			       var->mode != ir_var_out) ||
1168
1169
1170
	     !var->type->is_array())
	    continue;

1171
1172
1173
1174
1175
1176
1177
	 /* GL_ARB_uniform_buffer_object says that std140 uniforms
	  * will not be eliminated.  Since we always do std140, just
	  * don't resize arrays in UBOs.
	  */
	 if (var->uniform_block != -1)
	    continue;

1178
	 unsigned int size = var->max_array_access;
1179
1180
1181
1182
	 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
	       if (prog->_LinkedShaders[j] == NULL)
		  continue;

1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
	    foreach_list(node2, prog->_LinkedShaders[j]->ir) {
	       ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
	       if (!other_var)
		  continue;

	       if (strcmp(var->name, other_var->name) == 0 &&
		   other_var->max_array_access > size) {
		  size = other_var->max_array_access;
	       }
	    }
	 }
1194

1195
	 if (size + 1 != var->type->fields.array->length) {
1196
1197
1198
	    /* If this is a built-in uniform (i.e., it's backed by some
	     * fixed-function state), adjust the number of state slots to
	     * match the new array size.  The number of slots per array entry
Bryan Cain's avatar
Bryan Cain committed
1199
	     * is not known.  It seems safe to assume that the total number of
1200
1201
1202
1203
1204
1205
1206
1207
1208
	     * slots is an integer multiple of the number of array elements.
	     * Determine the number of slots per array element by dividing by
	     * the old (total) size.
	     */
	    if (var->num_state_slots > 0) {
	       var->num_state_slots = (size + 1)
		  * (var->num_state_slots / var->type->length);
	    }

1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
	    var->type = glsl_type::get_array_instance(var->type->fields.array,
						      size + 1);
	    /* FINISHME: We should update the types of array
	     * dereferences of this variable now.
	     */
	 }
      }
   }
}

1219
/**
Bryan Cain's avatar
Bryan Cain committed
1220
 * Find a contiguous set of available bits in a bitmask.
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
 *
 * \param used_mask     Bits representing used (1) and unused (0) locations
 * \param needed_count  Number of contiguous bits needed.
 *
 * \return
 * Base location of the available bits on success or -1 on failure.
 */
int
find_available_slots(unsigned used_mask, unsigned needed_count)
{
   unsigned needed_mask = (1 << needed_count) - 1;
   const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;

   /* The comparison to 32 is redundant, but without it GCC emits "warning:
    * cannot optimize possibly infinite loops" for the loop below.
    */
   if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
      return -1;

   for (int i = 0; i <= max_bit_to_test; i++) {
      if ((needed_mask & ~used_mask) == needed_mask)
	 return i;

      needed_mask <<= 1;
   }

   return -1;
}


1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
/**
 * Assign locations for either VS inputs for FS outputs
 *
 * \param prog          Shader program whose variables need locations assigned
 * \param target_index  Selector for the program target to receive location
 *                      assignmnets.  Must be either \c MESA_SHADER_VERTEX or
 *                      \c MESA_SHADER_FRAGMENT.
 * \param max_index     Maximum number of generic locations.  This corresponds
 *                      to either the maximum number of draw buffers or the
 *                      maximum number of generic attributes.
 *
 * \return
 * If locations are successfully assigned, true is returned.  Otherwise an
 * error is emitted to the shader link log and false is returned.
 */
1266
bool
1267
1268
1269
assign_attribute_or_color_locations(gl_shader_program *prog,
				    unsigned target_index,
				    unsigned max_index)
1270
{
1271
   /* Mark invalid locations as being used.
1272
    */
1273
1274
   unsigned used_locations = (max_index >= 32)
      ? ~0 : ~((1 << max_index) - 1);
1275

1276
1277
1278
1279
1280
1281
   assert((target_index == MESA_SHADER_VERTEX)
	  || (target_index == MESA_SHADER_FRAGMENT));

   gl_shader *const sh = prog->_LinkedShaders[target_index];
   if (sh == NULL)
      return true;
1282

1283
   /* Operate in a total of four passes.
1284
1285
1286
1287
    *
    * 1. Invalidate the location assignments for all vertex shader inputs.
    *
    * 2. Assign locations for inputs that have user-defined (via
1288
1289
    *    glBindVertexAttribLocation) locations and outputs that have
    *    user-defined locations (via glBindFragDataLocation).
1290
    *
1291
1292
1293
1294
1295
1296
    * 3. Sort the attributes without assigned locations by number of slots
    *    required in decreasing order.  Fragmentation caused by attribute
    *    locations assigned by the application may prevent large attributes
    *    from having enough contiguous space.
    *
    * 4. Assign locations to any inputs without assigned locations.
1297
1298
    */

1299
   const int generic_base = (target_index == MESA_SHADER_VERTEX)
1300
      ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1301
1302
1303

   const enum ir_variable_mode direction =
      (target_index == MESA_SHADER_VERTEX) ? ir_var_in : ir_var_out;
1304

1305

1306
   link_invalidate_variable_locations(sh, direction, generic_base);
1307

1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
   /* Temporary storage for the set of attributes that need locations assigned.
    */
   struct temp_attr {
      unsigned slots;
      ir_variable *var;

      /* Used below in the call to qsort. */
      static int compare(const void *a, const void *b)
      {
	 const temp_attr *const l = (const temp_attr *) a;
	 const temp_attr *const r = (const temp_attr *) b;

	 /* Reversed because we want a descending order sort below. */
	 return r->slots - l->slots;
      }
   } to_assign[16];

   unsigned num_attr = 0;

1327
   foreach_list(node, sh->ir) {
1328
1329
      ir_variable *const var = ((ir_instruction *) node)->as_variable();

1330
      if ((var == NULL) || (var->mode != (unsigned) direction))
1331
1332
	 continue;

1333
      if (var->explicit_location) {
1334
	 if ((var->location >= (int)(max_index + generic_base))
1335
	     || (var->location < 0)) {
1336
1337
	    linker_error(prog,
			 "invalid explicit location %d specified for `%s'\n",
1338
1339
			 (var->location < 0)
			 ? var->location : var->location - generic_base,
1340
			 var->name);
1341
	    return false;
1342
1343
1344
1345
1346
1347
1348
	 }
      } else if (target_index == MESA_SHADER_VERTEX) {
	 unsigned binding;

	 if (prog->AttributeBindings->get(binding, var->name)) {
	    assert(binding >= VERT_ATTRIB_GENERIC0);
	    var->location = binding;
1349
	 }
1350
1351
      } else if (target_index == MESA_SHADER_FRAGMENT) {
	 unsigned binding;
1352
	 unsigned index;
1353
1354
1355
1356

	 if (prog->FragDataBindings->get(binding, var->name)) {
	    assert(binding >= FRAG_RESULT_DATA0);
	    var->location = binding;
1357
1358
1359
1360

	    if (prog->FragDataIndexBindings->get(index, var->name)) {
	       var->index = index;
	    }
1361
	 }
1362
1363
      }

1364
1365
1366
1367
      /* If the variable is not a built-in and has a location statically
       * assigned in the shader (presumably via a layout qualifier), make sure
       * that it doesn't collide with other assigned locations.  Otherwise,
       * add it to the list of variables that need linker-assigned locations.
1368
       */
1369
1370
      const unsigned slots = count_attribute_slots(var->type);
      if (var->location != -1) {
1371
	 if (var->location >= generic_base && var->index < 1) {
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
	    /* From page 61 of the OpenGL 4.0 spec:
	     *
	     *     "LinkProgram will fail if the attribute bindings assigned
	     *     by BindAttribLocation do not leave not enough space to
	     *     assign a location for an active matrix attribute or an
	     *     active attribute array, both of which require multiple
	     *     contiguous generic attributes."
	     *
	     * Previous versions of the spec contain similar language but omit
	     * the bit about attribute arrays.
	     *
	     * Page 61 of the OpenGL 4.0 spec also says:
	     *
	     *     "It is possible for an application to bind more than one
	     *     attribute name to the same location. This is referred to as
	     *     aliasing. This will only work if only one of the aliased
	     *     attributes is active in the executable program, or if no
	     *     path through the shader consumes more than one attribute of
	     *     a set of attributes aliased to the same location. A link
	     *     error can occur if the linker determines that every path
	     *     through the shader consumes multiple aliased attributes,
	     *     but implementations are not required to generate an error
	     *     in this case."
	     *
	     * These two paragraphs are either somewhat contradictory, or I
	     * don't fully understand one or both of them.
	     */
	    /* FINISHME: The code as currently written does not support
	     * FINISHME: attribute location aliasing (see comment above).
	     */
	    /* Mask representing the contiguous slots that will be used by
	     * this attribute.
	     */
	    const unsigned attr = var->location - generic_base;
	    const unsigned use_mask = (1 << slots) - 1;

	    /* Generate a link error if the set of bits requested for this
	     * attribute overlaps any previously allocated bits.
	     */
	    if ((~(use_mask << attr) & used_locations) != used_locations) {
1412
1413
	       const char *const string = (target_index == MESA_SHADER_VERTEX)
		  ? "vertex shader input" : "fragment shader output";
1414
	       linker_error(prog,
1415
			    "insufficient contiguous locations "
1416
1417
			    "available for %s `%s' %d %d %d", string,
			    var->name, used_locations, use_mask, attr);
1418
1419
1420
1421
1422
1423
	       return false;
	    }

	    used_locations |= (use_mask << attr);
	 }

1424
	 continue;
1425
      }
1426

1427
      to_assign[num_attr].slots = slots;
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
      to_assign[num_attr].var = var;
      num_attr++;
   }

   /* If all of the attributes were assigned locations by the application (or
    * are built-in attributes with fixed locations), return early.  This should
    * be the common case.
    */
   if (num_attr == 0)
      return true;

   qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);

1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
   if (target_index == MESA_SHADER_VERTEX) {
      /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS.  It can
       * only be explicitly assigned by via glBindAttribLocation.  Mark it as
       * reserved to prevent it from being automatically allocated below.
       */
      find_deref_visitor find("gl_Vertex");
      find.run(sh->ir);
      if (find.variable_found())
	 used_locations |= (1 << 0);
   }
1451

1452
1453
1454
   for (unsigned i = 0; i < num_attr; i++) {
      /* Mask representing the contiguous slots that will be used by this
       * attribute.
1455
       */
1456
1457
1458
1459
1460
      const unsigned use_mask = (1 << to_assign[i].slots) - 1;

      int location = find_available_slots(used_locations, to_assign[i].slots);

      if (location < 0) {
1461
1462
1463
	 const char *const string = (target_index == MESA_SHADER_VERTEX)
	    ? "vertex shader input" : "fragment shader output";

1464
	 linker_error(prog,
1465
		      "insufficient contiguous locations "
1466
1467
		      "available for %s `%s'",
		      string, to_assign[i].var->name);
1468
	 return false;
1469
      }
1470

1471
      to_assign[i].var->location = generic_base + location;
1472
      used_locations |= (use_mask << location);
1473
   }
1474
1475

   return true;
1476
1477
1478
}


1479
/**
1480
 * Demote shader inputs and outputs that are not used in other stages
1481
1482
 */
void
1483
demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1484
1485
1486
1487
{
   foreach_list(node, sh->ir) {
      ir_variable *const var = ((ir_instruction *) node)->as_variable();

1488
      if ((var == NULL) || (var->mode != int(mode)))
1489
1490
	 continue;

1491
1492
1493
      /* A shader 'in' or 'out' variable is only really an input or output if
       * its value is used by other shader stages.  This will cause the variable
       * to have a location assigned.
1494
1495
1496
1497
1498
1499
1500
1501
       */
      if (var->location == -1) {
	 var->mode = ir_var_auto;
      }
   }
}


1502
1503
1504
1505
1506
1507
1508
/**
 * Data structure tracking information about a transform feedback declaration
 * during linking.
 */
class tfeedback_decl
{
public:
1509
1510
   bool init(struct gl_context *ctx, struct gl_shader_program *prog,
             const void *mem_ctx, const char