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