Merge branch 'mesa_7_7_branch'
[mesa.git] / src / mesa / shader / slang / slang_link.c
1 /*
2 * Mesa 3-D graphics library
3 * Version: 7.3
4 *
5 * Copyright (C) 2008 Brian Paul All Rights Reserved.
6 * Copyright (C) 2009 VMware, Inc. All Rights Reserved.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included
16 * in all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
22 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26 /**
27 * \file slang_link.c
28 * GLSL linker
29 * \author Brian Paul
30 */
31
32 #include "main/imports.h"
33 #include "main/context.h"
34 #include "main/hash.h"
35 #include "main/macros.h"
36 #include "shader/program.h"
37 #include "shader/prog_instruction.h"
38 #include "shader/prog_parameter.h"
39 #include "shader/prog_print.h"
40 #include "shader/prog_statevars.h"
41 #include "shader/prog_uniform.h"
42 #include "shader/shader_api.h"
43 #include "slang_builtin.h"
44 #include "slang_link.h"
45
46
47 /** cast wrapper */
48 static struct gl_vertex_program *
49 vertex_program(struct gl_program *prog)
50 {
51 assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
52 return (struct gl_vertex_program *) prog;
53 }
54
55
56 /** cast wrapper */
57 static struct gl_fragment_program *
58 fragment_program(struct gl_program *prog)
59 {
60 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
61 return (struct gl_fragment_program *) prog;
62 }
63
64
65 /**
66 * Record a linking error.
67 */
68 static void
69 link_error(struct gl_shader_program *shProg, const char *msg)
70 {
71 if (shProg->InfoLog) {
72 _mesa_free(shProg->InfoLog);
73 }
74 shProg->InfoLog = _mesa_strdup(msg);
75 shProg->LinkStatus = GL_FALSE;
76 }
77
78
79
80 /**
81 * Check if the given bit is either set or clear in both bitfields.
82 */
83 static GLboolean
84 bits_agree(GLbitfield flags1, GLbitfield flags2, GLbitfield bit)
85 {
86 return (flags1 & bit) == (flags2 & bit);
87 }
88
89
90 /**
91 * Linking varying vars involves rearranging varying vars so that the
92 * vertex program's output varyings matches the order of the fragment
93 * program's input varyings.
94 * We'll then rewrite instructions to replace PROGRAM_VARYING with either
95 * PROGRAM_INPUT or PROGRAM_OUTPUT depending on whether it's a vertex or
96 * fragment shader.
97 * This is also where we set program Input/OutputFlags to indicate
98 * which inputs are centroid-sampled, invariant, etc.
99 */
100 static GLboolean
101 link_varying_vars(GLcontext *ctx,
102 struct gl_shader_program *shProg, struct gl_program *prog)
103 {
104 GLuint *map, i, firstVarying, newFile;
105 GLbitfield *inOutFlags;
106
107 map = (GLuint *) _mesa_malloc(prog->Varying->NumParameters * sizeof(GLuint));
108 if (!map)
109 return GL_FALSE;
110
111 /* Varying variables are treated like other vertex program outputs
112 * (and like other fragment program inputs). The position of the
113 * first varying differs for vertex/fragment programs...
114 * Also, replace File=PROGRAM_VARYING with File=PROGRAM_INPUT/OUTPUT.
115 */
116 if (prog->Target == GL_VERTEX_PROGRAM_ARB) {
117 firstVarying = VERT_RESULT_VAR0;
118 newFile = PROGRAM_OUTPUT;
119 inOutFlags = prog->OutputFlags;
120 }
121 else {
122 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
123 firstVarying = FRAG_ATTRIB_VAR0;
124 newFile = PROGRAM_INPUT;
125 inOutFlags = prog->InputFlags;
126 }
127
128 for (i = 0; i < prog->Varying->NumParameters; i++) {
129 /* see if this varying is in the linked varying list */
130 const struct gl_program_parameter *var = prog->Varying->Parameters + i;
131 GLint j = _mesa_lookup_parameter_index(shProg->Varying, -1, var->Name);
132 if (j >= 0) {
133 /* varying is already in list, do some error checking */
134 const struct gl_program_parameter *v =
135 &shProg->Varying->Parameters[j];
136 if (var->Size != v->Size) {
137 link_error(shProg, "mismatched varying variable types");
138 _mesa_free(map);
139 return GL_FALSE;
140 }
141 if (!bits_agree(var->Flags, v->Flags, PROG_PARAM_BIT_CENTROID)) {
142 char msg[100];
143 _mesa_snprintf(msg, sizeof(msg),
144 "centroid modifier mismatch for '%s'", var->Name);
145 link_error(shProg, msg);
146 _mesa_free(map);
147 return GL_FALSE;
148 }
149 if (!bits_agree(var->Flags, v->Flags, PROG_PARAM_BIT_INVARIANT)) {
150 char msg[100];
151 _mesa_snprintf(msg, sizeof(msg),
152 "invariant modifier mismatch for '%s'", var->Name);
153 link_error(shProg, msg);
154 _mesa_free(map);
155 return GL_FALSE;
156 }
157 }
158 else {
159 /* not already in linked list */
160 j = _mesa_add_varying(shProg->Varying, var->Name, var->Size,
161 var->Flags);
162 }
163
164 if (shProg->Varying->NumParameters > ctx->Const.MaxVarying) {
165 link_error(shProg, "Too many varying variables");
166 _mesa_free(map);
167 return GL_FALSE;
168 }
169
170 /* Map varying[i] to varying[j].
171 * Note: the loop here takes care of arrays or large (sz>4) vars.
172 */
173 {
174 GLint sz = var->Size;
175 while (sz > 0) {
176 inOutFlags[firstVarying + j] = var->Flags;
177 /*printf("Link varying from %d to %d\n", i, j);*/
178 map[i++] = j++;
179 sz -= 4;
180 }
181 i--; /* go back one */
182 }
183 }
184
185
186 /* OK, now scan the program/shader instructions looking for varying vars,
187 * replacing the old index with the new index.
188 */
189 for (i = 0; i < prog->NumInstructions; i++) {
190 struct prog_instruction *inst = prog->Instructions + i;
191 GLuint j;
192
193 if (inst->DstReg.File == PROGRAM_VARYING) {
194 inst->DstReg.File = newFile;
195 inst->DstReg.Index = map[ inst->DstReg.Index ] + firstVarying;
196 }
197
198 for (j = 0; j < 3; j++) {
199 if (inst->SrcReg[j].File == PROGRAM_VARYING) {
200 inst->SrcReg[j].File = newFile;
201 inst->SrcReg[j].Index = map[ inst->SrcReg[j].Index ] + firstVarying;
202 }
203 }
204 }
205
206 _mesa_free(map);
207
208 /* these will get recomputed before linking is completed */
209 prog->InputsRead = 0x0;
210 prog->OutputsWritten = 0x0;
211
212 return GL_TRUE;
213 }
214
215
216 /**
217 * Build the shProg->Uniforms list.
218 * This is basically a list/index of all uniforms found in either/both of
219 * the vertex and fragment shaders.
220 *
221 * About uniforms:
222 * Each uniform has two indexes, one that points into the vertex
223 * program's parameter array and another that points into the fragment
224 * program's parameter array. When the user changes a uniform's value
225 * we have to change the value in the vertex and/or fragment program's
226 * parameter array.
227 *
228 * This function will be called twice to set up the two uniform->parameter
229 * mappings.
230 *
231 * If a uniform is only present in the vertex program OR fragment program
232 * then the fragment/vertex parameter index, respectively, will be -1.
233 */
234 static GLboolean
235 link_uniform_vars(GLcontext *ctx,
236 struct gl_shader_program *shProg,
237 struct gl_program *prog,
238 GLuint *numSamplers)
239 {
240 GLuint samplerMap[200]; /* max number of samplers declared, not used */
241 GLuint i;
242
243 for (i = 0; i < prog->Parameters->NumParameters; i++) {
244 const struct gl_program_parameter *p = prog->Parameters->Parameters + i;
245
246 /*
247 * XXX FIX NEEDED HERE
248 * We should also be adding a uniform if p->Type == PROGRAM_STATE_VAR.
249 * For example, modelview matrix, light pos, etc.
250 * Also, we need to update the state-var name-generator code to
251 * generate GLSL-style names, like "gl_LightSource[0].position".
252 * Furthermore, we'll need to fix the state-var's size/datatype info.
253 */
254
255 if ((p->Type == PROGRAM_UNIFORM || p->Type == PROGRAM_SAMPLER)
256 && p->Used) {
257 /* add this uniform, indexing into the target's Parameters list */
258 struct gl_uniform *uniform =
259 _mesa_append_uniform(shProg->Uniforms, p->Name, prog->Target, i);
260 if (uniform)
261 uniform->Initialized = p->Initialized;
262 }
263
264 /* The samplerMap[] table we build here is used to remap/re-index
265 * sampler references by TEX instructions.
266 */
267 if (p->Type == PROGRAM_SAMPLER && p->Used) {
268 /* Allocate a new sampler index */
269 GLuint oldSampNum = (GLuint) prog->Parameters->ParameterValues[i][0];
270 GLuint newSampNum = *numSamplers;
271 if (newSampNum >= ctx->Const.MaxTextureImageUnits) {
272 char s[100];
273 _mesa_sprintf(s, "Too many texture samplers (%u, max is %u)",
274 newSampNum, ctx->Const.MaxTextureImageUnits);
275 link_error(shProg, s);
276 return GL_FALSE;
277 }
278 /* save old->new mapping in the table */
279 if (oldSampNum < Elements(samplerMap))
280 samplerMap[oldSampNum] = newSampNum;
281 /* update parameter's sampler index */
282 prog->Parameters->ParameterValues[i][0] = (GLfloat) newSampNum;
283 (*numSamplers)++;
284 }
285 }
286
287 /* OK, now scan the program/shader instructions looking for texture
288 * instructions using sampler vars. Replace old sampler indexes with
289 * new ones.
290 */
291 prog->SamplersUsed = 0x0;
292 for (i = 0; i < prog->NumInstructions; i++) {
293 struct prog_instruction *inst = prog->Instructions + i;
294 if (_mesa_is_tex_instruction(inst->Opcode)) {
295 /* here, inst->TexSrcUnit is really the sampler unit */
296 const GLint oldSampNum = inst->TexSrcUnit;
297
298 #if 0
299 printf("====== remap sampler from %d to %d\n",
300 inst->TexSrcUnit, samplerMap[ inst->TexSrcUnit ]);
301 #endif
302
303 if (oldSampNum < Elements(samplerMap)) {
304 const GLuint newSampNum = samplerMap[oldSampNum];
305 inst->TexSrcUnit = newSampNum;
306 prog->SamplerTargets[newSampNum] = inst->TexSrcTarget;
307 prog->SamplersUsed |= (1 << newSampNum);
308 if (inst->TexShadow) {
309 prog->ShadowSamplers |= (1 << newSampNum);
310 }
311 }
312 }
313 }
314
315 return GL_TRUE;
316 }
317
318
319 /**
320 * Resolve binding of generic vertex attributes.
321 * For example, if the vertex shader declared "attribute vec4 foobar" we'll
322 * allocate a generic vertex attribute for "foobar" and plug that value into
323 * the vertex program instructions.
324 * But if the user called glBindAttributeLocation(), those bindings will
325 * have priority.
326 */
327 static GLboolean
328 _slang_resolve_attributes(struct gl_shader_program *shProg,
329 const struct gl_program *origProg,
330 struct gl_program *linkedProg)
331 {
332 GLint attribMap[MAX_VERTEX_GENERIC_ATTRIBS];
333 GLuint i, j;
334 GLbitfield usedAttributes; /* generics only, not legacy attributes */
335 GLbitfield inputsRead = 0x0;
336
337 assert(origProg != linkedProg);
338 assert(origProg->Target == GL_VERTEX_PROGRAM_ARB);
339 assert(linkedProg->Target == GL_VERTEX_PROGRAM_ARB);
340
341 if (!shProg->Attributes)
342 shProg->Attributes = _mesa_new_parameter_list();
343
344 if (linkedProg->Attributes) {
345 _mesa_free_parameter_list(linkedProg->Attributes);
346 }
347 linkedProg->Attributes = _mesa_new_parameter_list();
348
349
350 /* Build a bitmask indicating which attribute indexes have been
351 * explicitly bound by the user with glBindAttributeLocation().
352 */
353 usedAttributes = 0x0;
354 for (i = 0; i < shProg->Attributes->NumParameters; i++) {
355 GLint attr = shProg->Attributes->Parameters[i].StateIndexes[0];
356 usedAttributes |= (1 << attr);
357 }
358
359 /* If gl_Vertex is used, that actually counts against the limit
360 * on generic vertex attributes. This avoids the ambiguity of
361 * whether glVertexAttrib4fv(0, v) sets legacy attribute 0 (vert pos)
362 * or generic attribute[0]. If gl_Vertex is used, we want the former.
363 */
364 if (origProg->InputsRead & VERT_BIT_POS) {
365 usedAttributes |= 0x1;
366 }
367
368 /* initialize the generic attribute map entries to -1 */
369 for (i = 0; i < MAX_VERTEX_GENERIC_ATTRIBS; i++) {
370 attribMap[i] = -1;
371 }
372
373 /*
374 * Scan program for generic attribute references
375 */
376 for (i = 0; i < linkedProg->NumInstructions; i++) {
377 struct prog_instruction *inst = linkedProg->Instructions + i;
378 for (j = 0; j < 3; j++) {
379 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
380 inputsRead |= (1 << inst->SrcReg[j].Index);
381 }
382
383 if (inst->SrcReg[j].File == PROGRAM_INPUT &&
384 inst->SrcReg[j].Index >= VERT_ATTRIB_GENERIC0) {
385 /*
386 * OK, we've found a generic vertex attribute reference.
387 */
388 const GLint k = inst->SrcReg[j].Index - VERT_ATTRIB_GENERIC0;
389
390 GLint attr = attribMap[k];
391
392 if (attr < 0) {
393 /* Need to figure out attribute mapping now.
394 */
395 const char *name = origProg->Attributes->Parameters[k].Name;
396 const GLint size = origProg->Attributes->Parameters[k].Size;
397 const GLenum type =origProg->Attributes->Parameters[k].DataType;
398 GLint index;
399
400 /* See if there's a user-defined attribute binding for
401 * this name.
402 */
403 index = _mesa_lookup_parameter_index(shProg->Attributes,
404 -1, name);
405 if (index >= 0) {
406 /* Found a user-defined binding */
407 attr = shProg->Attributes->Parameters[index].StateIndexes[0];
408 }
409 else {
410 /* No user-defined binding, choose our own attribute number.
411 * Start at 1 since generic attribute 0 always aliases
412 * glVertex/position.
413 */
414 for (attr = 0; attr < MAX_VERTEX_GENERIC_ATTRIBS; attr++) {
415 if (((1 << attr) & usedAttributes) == 0)
416 break;
417 }
418 if (attr == MAX_VERTEX_GENERIC_ATTRIBS) {
419 link_error(shProg, "Too many vertex attributes");
420 return GL_FALSE;
421 }
422
423 /* mark this attribute as used */
424 usedAttributes |= (1 << attr);
425 }
426
427 attribMap[k] = attr;
428
429 /* Save the final name->attrib binding so it can be queried
430 * with glGetAttributeLocation().
431 */
432 _mesa_add_attribute(linkedProg->Attributes, name,
433 size, type, attr);
434 }
435
436 assert(attr >= 0);
437
438 /* update the instruction's src reg */
439 inst->SrcReg[j].Index = VERT_ATTRIB_GENERIC0 + attr;
440 }
441 }
442 }
443
444 /* Handle pre-defined attributes here (gl_Vertex, gl_Normal, etc).
445 * When the user queries the active attributes we need to include both
446 * the user-defined attributes and the built-in ones.
447 */
448 for (i = VERT_ATTRIB_POS; i < VERT_ATTRIB_GENERIC0; i++) {
449 if (inputsRead & (1 << i)) {
450 _mesa_add_attribute(linkedProg->Attributes,
451 _slang_vert_attrib_name(i),
452 4, /* size in floats */
453 _slang_vert_attrib_type(i),
454 -1 /* attrib/input */);
455 }
456 }
457
458 return GL_TRUE;
459 }
460
461
462 /**
463 * Scan program instructions to update the program's NumTemporaries field.
464 * Note: this implemenation relies on the code generator allocating
465 * temps in increasing order (0, 1, 2, ... ).
466 */
467 static void
468 _slang_count_temporaries(struct gl_program *prog)
469 {
470 GLuint i, j;
471 GLint maxIndex = -1;
472
473 for (i = 0; i < prog->NumInstructions; i++) {
474 const struct prog_instruction *inst = prog->Instructions + i;
475 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
476 for (j = 0; j < numSrc; j++) {
477 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
478 if (maxIndex < inst->SrcReg[j].Index)
479 maxIndex = inst->SrcReg[j].Index;
480 }
481 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
482 if (maxIndex < (GLint) inst->DstReg.Index)
483 maxIndex = inst->DstReg.Index;
484 }
485 }
486 }
487
488 prog->NumTemporaries = (GLuint) (maxIndex + 1);
489 }
490
491
492 /**
493 * Scan program instructions to update the program's InputsRead and
494 * OutputsWritten fields.
495 */
496 static void
497 _slang_update_inputs_outputs(struct gl_program *prog)
498 {
499 GLuint i, j;
500 GLuint maxAddrReg = 0;
501
502 prog->InputsRead = 0x0;
503 prog->OutputsWritten = 0x0;
504
505 for (i = 0; i < prog->NumInstructions; i++) {
506 const struct prog_instruction *inst = prog->Instructions + i;
507 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
508 for (j = 0; j < numSrc; j++) {
509 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
510 prog->InputsRead |= 1 << inst->SrcReg[j].Index;
511 }
512 else if (inst->SrcReg[j].File == PROGRAM_ADDRESS) {
513 maxAddrReg = MAX2(maxAddrReg, (GLuint) (inst->SrcReg[j].Index + 1));
514 }
515 }
516
517 if (inst->DstReg.File == PROGRAM_OUTPUT) {
518 prog->OutputsWritten |= BITFIELD64_BIT(inst->DstReg.Index);
519 if (inst->DstReg.RelAddr) {
520 /* If the output attribute is indexed with relative addressing
521 * we know that it must be a varying or texcoord such as
522 * gl_TexCoord[i] = v; In this case, mark all the texcoords
523 * or varying outputs as being written. It's not an error if
524 * a vertex shader writes varying vars that aren't used by the
525 * fragment shader. But it is an error for a fragment shader
526 * to use varyings that are not written by the vertex shader.
527 */
528 if (prog->Target == GL_VERTEX_PROGRAM_ARB) {
529 if (inst->DstReg.Index == VERT_RESULT_TEX0) {
530 /* mark all texcoord outputs as written */
531 const GLbitfield64 mask =
532 BITFIELD64_RANGE(VERT_RESULT_TEX0,
533 (VERT_RESULT_TEX0
534 + MAX_TEXTURE_COORD_UNITS - 1));
535 prog->OutputsWritten |= mask;
536 }
537 else if (inst->DstReg.Index == VERT_RESULT_VAR0) {
538 /* mark all generic varying outputs as written */
539 const GLbitfield64 mask =
540 BITFIELD64_RANGE(VERT_RESULT_VAR0,
541 (VERT_RESULT_VAR0 + MAX_VARYING - 1));
542 prog->OutputsWritten |= mask;
543 }
544 }
545 }
546 }
547 else if (inst->DstReg.File == PROGRAM_ADDRESS) {
548 maxAddrReg = MAX2(maxAddrReg, inst->DstReg.Index + 1);
549 }
550 }
551 prog->NumAddressRegs = maxAddrReg;
552 }
553
554
555
556 /**
557 * Remove extra #version directives from the concatenated source string.
558 * Disable the extra ones by converting first two chars to //, a comment.
559 * This is a bit of hack to work around a preprocessor bug that only
560 * allows one #version directive per source.
561 */
562 static void
563 remove_extra_version_directives(GLchar *source)
564 {
565 GLuint verCount = 0;
566 while (1) {
567 char *ver = _mesa_strstr(source, "#version");
568 if (ver) {
569 verCount++;
570 if (verCount > 1) {
571 ver[0] = '/';
572 ver[1] = '/';
573 }
574 source += 8;
575 }
576 else {
577 break;
578 }
579 }
580 }
581
582
583
584 /**
585 * Return a new shader whose source code is the concatenation of
586 * all the shader sources of the given type.
587 */
588 static struct gl_shader *
589 concat_shaders(struct gl_shader_program *shProg, GLenum shaderType)
590 {
591 struct gl_shader *newShader;
592 const struct gl_shader *firstShader = NULL;
593 GLuint *shaderLengths;
594 GLchar *source;
595 GLuint totalLen = 0, len = 0;
596 GLuint i;
597
598 shaderLengths = (GLuint *)_mesa_malloc(shProg->NumShaders * sizeof(GLuint));
599 if (!shaderLengths) {
600 return NULL;
601 }
602
603 /* compute total size of new shader source code */
604 for (i = 0; i < shProg->NumShaders; i++) {
605 const struct gl_shader *shader = shProg->Shaders[i];
606 if (shader->Type == shaderType) {
607 shaderLengths[i] = _mesa_strlen(shader->Source);
608 totalLen += shaderLengths[i];
609 if (!firstShader)
610 firstShader = shader;
611 }
612 }
613
614 if (totalLen == 0) {
615 _mesa_free(shaderLengths);
616 return NULL;
617 }
618
619 source = (GLchar *) _mesa_malloc(totalLen + 1);
620 if (!source) {
621 _mesa_free(shaderLengths);
622 return NULL;
623 }
624
625 /* concatenate shaders */
626 for (i = 0; i < shProg->NumShaders; i++) {
627 const struct gl_shader *shader = shProg->Shaders[i];
628 if (shader->Type == shaderType) {
629 _mesa_memcpy(source + len, shader->Source, shaderLengths[i]);
630 len += shaderLengths[i];
631 }
632 }
633 source[len] = '\0';
634 /*
635 _mesa_printf("---NEW CONCATENATED SHADER---:\n%s\n------------\n", source);
636 */
637
638 _mesa_free(shaderLengths);
639
640 remove_extra_version_directives(source);
641
642 newShader = CALLOC_STRUCT(gl_shader);
643 if (!newShader) {
644 _mesa_free(source);
645 return NULL;
646 }
647
648 newShader->Type = shaderType;
649 newShader->Source = source;
650 newShader->Pragmas = firstShader->Pragmas;
651
652 return newShader;
653 }
654
655
656 /**
657 * Search the shader program's list of shaders to find the one that
658 * defines main().
659 * This will involve shader concatenation and recompilation if needed.
660 */
661 static struct gl_shader *
662 get_main_shader(GLcontext *ctx,
663 struct gl_shader_program *shProg, GLenum type)
664 {
665 struct gl_shader *shader = NULL;
666 GLuint i;
667
668 /*
669 * Look for a shader that defines main() and has no unresolved references.
670 */
671 for (i = 0; i < shProg->NumShaders; i++) {
672 shader = shProg->Shaders[i];
673 if (shader->Type == type &&
674 shader->Main &&
675 !shader->UnresolvedRefs) {
676 /* All set! */
677 return shader;
678 }
679 }
680
681 /*
682 * There must have been unresolved references during the original
683 * compilation. Try concatenating all the shaders of the given type
684 * and recompile that.
685 */
686 shader = concat_shaders(shProg, type);
687
688 if (shader) {
689 _slang_compile(ctx, shader);
690
691 /* Finally, check if recompiling failed */
692 if (!shader->CompileStatus ||
693 !shader->Main ||
694 shader->UnresolvedRefs) {
695 link_error(shProg, "Unresolved symbols");
696 _mesa_free_shader(ctx, shader);
697 return NULL;
698 }
699 }
700
701 return shader;
702 }
703
704
705 /**
706 * Shader linker. Currently:
707 *
708 * 1. The last attached vertex shader and fragment shader are linked.
709 * 2. Varying vars in the two shaders are combined so their locations
710 * agree between the vertex and fragment stages. They're treated as
711 * vertex program output attribs and as fragment program input attribs.
712 * 3. The vertex and fragment programs are cloned and modified to update
713 * src/dst register references so they use the new, linked varying
714 * storage locations.
715 */
716 void
717 _slang_link(GLcontext *ctx,
718 GLhandleARB programObj,
719 struct gl_shader_program *shProg)
720 {
721 const struct gl_vertex_program *vertProg = NULL;
722 const struct gl_fragment_program *fragProg = NULL;
723 GLuint numSamplers = 0;
724 GLuint i;
725
726 _mesa_clear_shader_program_data(ctx, shProg);
727
728 /* Initialize LinkStatus to "success". Will be cleared if error. */
729 shProg->LinkStatus = GL_TRUE;
730
731 /* check that all programs compiled successfully */
732 for (i = 0; i < shProg->NumShaders; i++) {
733 if (!shProg->Shaders[i]->CompileStatus) {
734 link_error(shProg, "linking with uncompiled shader\n");
735 return;
736 }
737 }
738
739 shProg->Uniforms = _mesa_new_uniform_list();
740 shProg->Varying = _mesa_new_parameter_list();
741
742 /*
743 * Find the vertex and fragment shaders which define main()
744 */
745 {
746 struct gl_shader *vertShader, *fragShader;
747 vertShader = get_main_shader(ctx, shProg, GL_VERTEX_SHADER);
748 fragShader = get_main_shader(ctx, shProg, GL_FRAGMENT_SHADER);
749 if (vertShader)
750 vertProg = vertex_program(vertShader->Program);
751 if (fragShader)
752 fragProg = fragment_program(fragShader->Program);
753 if (!shProg->LinkStatus)
754 return;
755 }
756
757 #if FEATURE_es2_glsl
758 /* must have both a vertex and fragment program for ES2 */
759 if (!vertProg) {
760 link_error(shProg, "missing vertex shader\n");
761 return;
762 }
763 if (!fragProg) {
764 link_error(shProg, "missing fragment shader\n");
765 return;
766 }
767 #endif
768
769 /*
770 * Make copies of the vertex/fragment programs now since we'll be
771 * changing src/dst registers after merging the uniforms and varying vars.
772 */
773 _mesa_reference_vertprog(ctx, &shProg->VertexProgram, NULL);
774 if (vertProg) {
775 struct gl_vertex_program *linked_vprog =
776 vertex_program(_mesa_clone_program(ctx, &vertProg->Base));
777 shProg->VertexProgram = linked_vprog; /* refcount OK */
778 /* vertex program ID not significant; just set Id for debugging purposes */
779 shProg->VertexProgram->Base.Id = shProg->Name;
780 ASSERT(shProg->VertexProgram->Base.RefCount == 1);
781 }
782
783 _mesa_reference_fragprog(ctx, &shProg->FragmentProgram, NULL);
784 if (fragProg) {
785 struct gl_fragment_program *linked_fprog =
786 fragment_program(_mesa_clone_program(ctx, &fragProg->Base));
787 shProg->FragmentProgram = linked_fprog; /* refcount OK */
788 /* vertex program ID not significant; just set Id for debugging purposes */
789 shProg->FragmentProgram->Base.Id = shProg->Name;
790 ASSERT(shProg->FragmentProgram->Base.RefCount == 1);
791 }
792
793 /* link varying vars */
794 if (shProg->VertexProgram) {
795 if (!link_varying_vars(ctx, shProg, &shProg->VertexProgram->Base))
796 return;
797 }
798 if (shProg->FragmentProgram) {
799 if (!link_varying_vars(ctx, shProg, &shProg->FragmentProgram->Base))
800 return;
801 }
802
803 /* link uniform vars */
804 if (shProg->VertexProgram) {
805 if (!link_uniform_vars(ctx, shProg, &shProg->VertexProgram->Base,
806 &numSamplers)) {
807 return;
808 }
809 }
810 if (shProg->FragmentProgram) {
811 if (!link_uniform_vars(ctx, shProg, &shProg->FragmentProgram->Base,
812 &numSamplers)) {
813 return;
814 }
815 }
816
817 /*_mesa_print_uniforms(shProg->Uniforms);*/
818
819 if (shProg->VertexProgram) {
820 if (!_slang_resolve_attributes(shProg, &vertProg->Base,
821 &shProg->VertexProgram->Base)) {
822 return;
823 }
824 }
825
826 if (shProg->VertexProgram) {
827 _slang_update_inputs_outputs(&shProg->VertexProgram->Base);
828 _slang_count_temporaries(&shProg->VertexProgram->Base);
829 if (!(shProg->VertexProgram->Base.OutputsWritten
830 & BITFIELD64_BIT(VERT_RESULT_HPOS))) {
831 /* the vertex program did not compute a vertex position */
832 link_error(shProg,
833 "gl_Position was not written by vertex shader\n");
834 return;
835 }
836 }
837 if (shProg->FragmentProgram) {
838 _slang_count_temporaries(&shProg->FragmentProgram->Base);
839 _slang_update_inputs_outputs(&shProg->FragmentProgram->Base);
840 }
841
842 /* Check that all the varying vars needed by the fragment shader are
843 * actually produced by the vertex shader.
844 */
845 if (shProg->FragmentProgram) {
846 const GLbitfield varyingRead
847 = shProg->FragmentProgram->Base.InputsRead >> FRAG_ATTRIB_VAR0;
848 const GLbitfield64 varyingWritten = shProg->VertexProgram ?
849 shProg->VertexProgram->Base.OutputsWritten >> VERT_RESULT_VAR0 : 0x0;
850 if ((varyingRead & varyingWritten) != varyingRead) {
851 link_error(shProg,
852 "Fragment program using varying vars not written by vertex shader\n");
853 return;
854 }
855 }
856
857 /* check that gl_FragColor and gl_FragData are not both written to */
858 if (shProg->FragmentProgram) {
859 const GLbitfield64 outputsWritten =
860 shProg->FragmentProgram->Base.OutputsWritten;
861 if ((outputsWritten & BITFIELD64_BIT(FRAG_RESULT_COLOR)) &&
862 (outputsWritten >= BITFIELD64_BIT(FRAG_RESULT_DATA0))) {
863 link_error(shProg, "Fragment program cannot write both gl_FragColor"
864 " and gl_FragData[].\n");
865 return;
866 }
867 }
868
869
870 if (fragProg && shProg->FragmentProgram) {
871 /* Compute initial program's TexturesUsed info */
872 _mesa_update_shader_textures_used(&shProg->FragmentProgram->Base);
873
874 /* notify driver that a new fragment program has been compiled/linked */
875 ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
876 &shProg->FragmentProgram->Base);
877 if (ctx->Shader.Flags & GLSL_DUMP) {
878 _mesa_printf("Mesa pre-link fragment program:\n");
879 _mesa_print_program(&fragProg->Base);
880 _mesa_print_program_parameters(ctx, &fragProg->Base);
881
882 _mesa_printf("Mesa post-link fragment program:\n");
883 _mesa_print_program(&shProg->FragmentProgram->Base);
884 _mesa_print_program_parameters(ctx, &shProg->FragmentProgram->Base);
885 }
886 }
887
888 if (vertProg && shProg->VertexProgram) {
889 /* Compute initial program's TexturesUsed info */
890 _mesa_update_shader_textures_used(&shProg->VertexProgram->Base);
891
892 /* notify driver that a new vertex program has been compiled/linked */
893 ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
894 &shProg->VertexProgram->Base);
895 if (ctx->Shader.Flags & GLSL_DUMP) {
896 _mesa_printf("Mesa pre-link vertex program:\n");
897 _mesa_print_program(&vertProg->Base);
898 _mesa_print_program_parameters(ctx, &vertProg->Base);
899
900 _mesa_printf("Mesa post-link vertex program:\n");
901 _mesa_print_program(&shProg->VertexProgram->Base);
902 _mesa_print_program_parameters(ctx, &shProg->VertexProgram->Base);
903 }
904 }
905
906 /* Debug: */
907 if (0) {
908 if (shProg->VertexProgram)
909 _mesa_postprocess_program(ctx, &shProg->VertexProgram->Base);
910 if (shProg->FragmentProgram)
911 _mesa_postprocess_program(ctx, &shProg->FragmentProgram->Base);
912 }
913
914 if (ctx->Shader.Flags & GLSL_DUMP) {
915 _mesa_printf("Varying vars:\n");
916 _mesa_print_parameter_list(shProg->Varying);
917 if (shProg->InfoLog) {
918 _mesa_printf("Info Log: %s\n", shProg->InfoLog);
919 }
920 }
921
922 shProg->LinkStatus = (shProg->VertexProgram || shProg->FragmentProgram);
923 }
924