Merge branch 'master' into gallium-0.2
[mesa.git] / src / mesa / shader / slang / slang_link.c
1 /*
2 * Mesa 3-D graphics library
3 * Version: 7.2
4 *
5 * Copyright (C) 2008 Brian Paul All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
21 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 /**
26 * \file slang_link.c
27 * GLSL linker
28 * \author Brian Paul
29 */
30
31 #include "main/imports.h"
32 #include "main/context.h"
33 #include "main/hash.h"
34 #include "main/macros.h"
35 #include "shader/program.h"
36 #include "shader/prog_instruction.h"
37 #include "shader/prog_parameter.h"
38 #include "shader/prog_print.h"
39 #include "shader/prog_statevars.h"
40 #include "shader/prog_uniform.h"
41 #include "shader/shader_api.h"
42 #include "slang_link.h"
43
44
45 /** cast wrapper */
46 static struct gl_vertex_program *
47 vertex_program(struct gl_program *prog)
48 {
49 assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
50 return (struct gl_vertex_program *) prog;
51 }
52
53
54 /** cast wrapper */
55 static struct gl_fragment_program *
56 fragment_program(struct gl_program *prog)
57 {
58 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
59 return (struct gl_fragment_program *) prog;
60 }
61
62
63 /**
64 * Record a linking error.
65 */
66 static void
67 link_error(struct gl_shader_program *shProg, const char *msg)
68 {
69 if (shProg->InfoLog) {
70 _mesa_free(shProg->InfoLog);
71 }
72 shProg->InfoLog = _mesa_strdup(msg);
73 shProg->LinkStatus = GL_FALSE;
74 }
75
76
77
78 /**
79 * Linking varying vars involves rearranging varying vars so that the
80 * vertex program's output varyings matches the order of the fragment
81 * program's input varyings.
82 */
83 static GLboolean
84 link_varying_vars(struct gl_shader_program *shProg, struct gl_program *prog)
85 {
86 GLuint *map, i, firstVarying, newFile;
87
88 map = (GLuint *) malloc(prog->Varying->NumParameters * sizeof(GLuint));
89 if (!map)
90 return GL_FALSE;
91
92 for (i = 0; i < prog->Varying->NumParameters; i++) {
93 /* see if this varying is in the linked varying list */
94 const struct gl_program_parameter *var = prog->Varying->Parameters + i;
95 GLint j = _mesa_lookup_parameter_index(shProg->Varying, -1, var->Name);
96 if (j >= 0) {
97 /* already in list, check size */
98 if (var->Size != shProg->Varying->Parameters[j].Size) {
99 /* error */
100 link_error(shProg, "mismatched varying variable types");
101 return GL_FALSE;
102 }
103 }
104 else {
105 /* not already in linked list */
106 j = _mesa_add_varying(shProg->Varying, var->Name, var->Size);
107 }
108
109 /* map varying[i] to varying[j].
110 * Note: the loop here takes care of arrays or large (sz>4) vars.
111 */
112 {
113 GLint sz = var->Size;
114 while (sz > 0) {
115 /*printf("Link varying from %d to %d\n", i, j);*/
116 map[i++] = j++;
117 sz -= 4;
118 }
119 i--; /* go back one */
120 }
121 }
122
123
124 /* Varying variables are treated like other vertex program outputs
125 * (and like other fragment program inputs). The position of the
126 * first varying differs for vertex/fragment programs...
127 * Also, replace File=PROGRAM_VARYING with File=PROGRAM_INPUT/OUTPUT.
128 */
129 if (prog->Target == GL_VERTEX_PROGRAM_ARB) {
130 firstVarying = VERT_RESULT_VAR0;
131 newFile = PROGRAM_OUTPUT;
132 }
133 else {
134 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
135 firstVarying = FRAG_ATTRIB_VAR0;
136 newFile = PROGRAM_INPUT;
137 }
138
139 /* OK, now scan the program/shader instructions looking for varying vars,
140 * replacing the old index with the new index.
141 */
142 for (i = 0; i < prog->NumInstructions; i++) {
143 struct prog_instruction *inst = prog->Instructions + i;
144 GLuint j;
145
146 if (inst->DstReg.File == PROGRAM_VARYING) {
147 inst->DstReg.File = newFile;
148 inst->DstReg.Index = map[ inst->DstReg.Index ] + firstVarying;
149 }
150
151 for (j = 0; j < 3; j++) {
152 if (inst->SrcReg[j].File == PROGRAM_VARYING) {
153 inst->SrcReg[j].File = newFile;
154 inst->SrcReg[j].Index = map[ inst->SrcReg[j].Index ] + firstVarying;
155 }
156 }
157 }
158
159 free(map);
160
161 /* these will get recomputed before linking is completed */
162 prog->InputsRead = 0x0;
163 prog->OutputsWritten = 0x0;
164
165 return GL_TRUE;
166 }
167
168
169 /**
170 * Build the shProg->Uniforms list.
171 * This is basically a list/index of all uniforms found in either/both of
172 * the vertex and fragment shaders.
173 */
174 static void
175 link_uniform_vars(struct gl_shader_program *shProg,
176 struct gl_program *prog,
177 GLuint *numSamplers)
178 {
179 GLuint samplerMap[MAX_SAMPLERS];
180 GLuint i;
181
182 for (i = 0; i < prog->Parameters->NumParameters; i++) {
183 const struct gl_program_parameter *p = prog->Parameters->Parameters + i;
184
185 /*
186 * XXX FIX NEEDED HERE
187 * We should also be adding a uniform if p->Type == PROGRAM_STATE_VAR.
188 * For example, modelview matrix, light pos, etc.
189 * Also, we need to update the state-var name-generator code to
190 * generate GLSL-style names, like "gl_LightSource[0].position".
191 * Furthermore, we'll need to fix the state-var's size/datatype info.
192 */
193
194 if ((p->Type == PROGRAM_UNIFORM && p->Used) ||
195 p->Type == PROGRAM_SAMPLER) {
196 _mesa_append_uniform(shProg->Uniforms, p->Name, prog->Target, i);
197 }
198
199 if (p->Type == PROGRAM_SAMPLER) {
200 /* Allocate a new sampler index */
201 GLuint sampNum = *numSamplers;
202 GLuint oldSampNum = (GLuint) prog->Parameters->ParameterValues[i][0];
203 assert(oldSampNum < MAX_SAMPLERS);
204 samplerMap[oldSampNum] = sampNum;
205 (*numSamplers)++;
206 }
207 }
208
209
210 /* OK, now scan the program/shader instructions looking for sampler vars,
211 * replacing the old index with the new index.
212 */
213 prog->SamplersUsed = 0x0;
214 for (i = 0; i < prog->NumInstructions; i++) {
215 struct prog_instruction *inst = prog->Instructions + i;
216 if (_mesa_is_tex_instruction(inst->Opcode)) {
217 /*
218 printf("====== remap sampler from %d to %d\n",
219 inst->Sampler, map[ inst->Sampler ]);
220 */
221 /* here, texUnit is really samplerUnit */
222 inst->TexSrcUnit = samplerMap[inst->TexSrcUnit];
223 prog->SamplerTargets[inst->TexSrcUnit] = inst->TexSrcTarget;
224 prog->SamplersUsed |= (1 << inst->TexSrcUnit);
225 }
226 }
227
228 }
229
230
231 /**
232 * Resolve binding of generic vertex attributes.
233 * For example, if the vertex shader declared "attribute vec4 foobar" we'll
234 * allocate a generic vertex attribute for "foobar" and plug that value into
235 * the vertex program instructions.
236 * But if the user called glBindAttributeLocation(), those bindings will
237 * have priority.
238 */
239 static GLboolean
240 _slang_resolve_attributes(struct gl_shader_program *shProg,
241 const struct gl_program *origProg,
242 struct gl_program *linkedProg)
243 {
244 GLint attribMap[MAX_VERTEX_ATTRIBS];
245 GLuint i, j;
246 GLbitfield usedAttributes;
247
248 assert(origProg != linkedProg);
249 assert(origProg->Target == GL_VERTEX_PROGRAM_ARB);
250 assert(linkedProg->Target == GL_VERTEX_PROGRAM_ARB);
251
252 if (!shProg->Attributes)
253 shProg->Attributes = _mesa_new_parameter_list();
254
255 if (linkedProg->Attributes) {
256 _mesa_free_parameter_list(linkedProg->Attributes);
257 }
258 linkedProg->Attributes = _mesa_new_parameter_list();
259
260
261 /* Build a bitmask indicating which attribute indexes have been
262 * explicitly bound by the user with glBindAttributeLocation().
263 */
264 usedAttributes = 0x0;
265 for (i = 0; i < shProg->Attributes->NumParameters; i++) {
266 GLint attr = shProg->Attributes->Parameters[i].StateIndexes[0];
267 usedAttributes |= (1 << attr);
268 }
269
270 /* initialize the generic attribute map entries to -1 */
271 for (i = 0; i < MAX_VERTEX_ATTRIBS; i++) {
272 attribMap[i] = -1;
273 }
274
275 /*
276 * Scan program for generic attribute references
277 */
278 for (i = 0; i < linkedProg->NumInstructions; i++) {
279 struct prog_instruction *inst = linkedProg->Instructions + i;
280 for (j = 0; j < 3; j++) {
281 if (inst->SrcReg[j].File == PROGRAM_INPUT &&
282 inst->SrcReg[j].Index >= VERT_ATTRIB_GENERIC0) {
283 /*
284 * OK, we've found a generic vertex attribute reference.
285 */
286 const GLint k = inst->SrcReg[j].Index - VERT_ATTRIB_GENERIC0;
287
288 GLint attr = attribMap[k];
289
290 if (attr < 0) {
291 /* Need to figure out attribute mapping now.
292 */
293 const char *name = origProg->Attributes->Parameters[k].Name;
294 const GLint size = origProg->Attributes->Parameters[k].Size;
295 const GLenum type =origProg->Attributes->Parameters[k].DataType;
296 GLint index;
297
298 /* See if there's a user-defined attribute binding for
299 * this name.
300 */
301 index = _mesa_lookup_parameter_index(shProg->Attributes,
302 -1, name);
303 if (index >= 0) {
304 /* Found a user-defined binding */
305 attr = shProg->Attributes->Parameters[index].StateIndexes[0];
306 }
307 else {
308 /* No user-defined binding, choose our own attribute number.
309 * Start at 1 since generic attribute 0 always aliases
310 * glVertex/position.
311 */
312 for (attr = 1; attr < MAX_VERTEX_ATTRIBS; attr++) {
313 if (((1 << attr) & usedAttributes) == 0)
314 break;
315 }
316 if (attr == MAX_VERTEX_ATTRIBS) {
317 link_error(shProg, "Too many vertex attributes");
318 return GL_FALSE;
319 }
320
321 /* mark this attribute as used */
322 usedAttributes |= (1 << attr);
323 }
324
325 attribMap[k] = attr;
326
327 /* Save the final name->attrib binding so it can be queried
328 * with glGetAttributeLocation().
329 */
330 _mesa_add_attribute(linkedProg->Attributes, name,
331 size, type, attr);
332 }
333
334 assert(attr >= 0);
335
336 /* update the instruction's src reg */
337 inst->SrcReg[j].Index = VERT_ATTRIB_GENERIC0 + attr;
338 }
339 }
340 }
341
342 return GL_TRUE;
343 }
344
345
346 /**
347 * Scan program instructions to update the program's NumTemporaries field.
348 * Note: this implemenation relies on the code generator allocating
349 * temps in increasing order (0, 1, 2, ... ).
350 */
351 static void
352 _slang_count_temporaries(struct gl_program *prog)
353 {
354 GLuint i, j;
355 GLint maxIndex = -1;
356
357 for (i = 0; i < prog->NumInstructions; i++) {
358 const struct prog_instruction *inst = prog->Instructions + i;
359 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
360 for (j = 0; j < numSrc; j++) {
361 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
362 if (maxIndex < inst->SrcReg[j].Index)
363 maxIndex = inst->SrcReg[j].Index;
364 }
365 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
366 if (maxIndex < (GLint) inst->DstReg.Index)
367 maxIndex = inst->DstReg.Index;
368 }
369 }
370 }
371
372 prog->NumTemporaries = (GLuint) (maxIndex + 1);
373 }
374
375
376 /**
377 * Scan program instructions to update the program's InputsRead and
378 * OutputsWritten fields.
379 */
380 static void
381 _slang_update_inputs_outputs(struct gl_program *prog)
382 {
383 GLuint i, j;
384 GLuint maxAddrReg = 0;
385
386 prog->InputsRead = 0x0;
387 prog->OutputsWritten = 0x0;
388
389 for (i = 0; i < prog->NumInstructions; i++) {
390 const struct prog_instruction *inst = prog->Instructions + i;
391 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
392 for (j = 0; j < numSrc; j++) {
393 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
394 prog->InputsRead |= 1 << inst->SrcReg[j].Index;
395 if (prog->Target == GL_FRAGMENT_PROGRAM_ARB &&
396 inst->SrcReg[j].Index == FRAG_ATTRIB_FOGC) {
397 /* The fragment shader FOGC input is used for fog,
398 * front-facing and sprite/point coord.
399 */
400 struct gl_fragment_program *fp = fragment_program(prog);
401 const GLint swz = GET_SWZ(inst->SrcReg[j].Swizzle, 0);
402 if (swz == SWIZZLE_X)
403 fp->UsesFogFragCoord = GL_TRUE;
404 else if (swz == SWIZZLE_Y)
405 fp->UsesFrontFacing = GL_TRUE;
406 else if (swz == SWIZZLE_Z || swz == SWIZZLE_W)
407 fp->UsesPointCoord = GL_TRUE;
408 }
409 }
410 else if (inst->SrcReg[j].File == PROGRAM_ADDRESS) {
411 maxAddrReg = MAX2(maxAddrReg, inst->SrcReg[j].Index + 1);
412 }
413 }
414 if (inst->DstReg.File == PROGRAM_OUTPUT) {
415 prog->OutputsWritten |= 1 << inst->DstReg.Index;
416 }
417 else if (inst->DstReg.File == PROGRAM_ADDRESS) {
418 maxAddrReg = MAX2(maxAddrReg, inst->DstReg.Index + 1);
419 }
420 }
421 prog->NumAddressRegs = maxAddrReg;
422 }
423
424
425 /**
426 * Shader linker. Currently:
427 *
428 * 1. The last attached vertex shader and fragment shader are linked.
429 * 2. Varying vars in the two shaders are combined so their locations
430 * agree between the vertex and fragment stages. They're treated as
431 * vertex program output attribs and as fragment program input attribs.
432 * 3. The vertex and fragment programs are cloned and modified to update
433 * src/dst register references so they use the new, linked varying
434 * storage locations.
435 */
436 void
437 _slang_link(GLcontext *ctx,
438 GLhandleARB programObj,
439 struct gl_shader_program *shProg)
440 {
441 const struct gl_vertex_program *vertProg;
442 const struct gl_fragment_program *fragProg;
443 GLuint numSamplers = 0;
444 GLuint i;
445
446 _mesa_clear_shader_program_data(ctx, shProg);
447
448 /* check that all programs compiled successfully */
449 for (i = 0; i < shProg->NumShaders; i++) {
450 if (!shProg->Shaders[i]->CompileStatus) {
451 link_error(shProg, "linking with uncompiled shader\n");
452 return;
453 }
454 }
455
456 shProg->Uniforms = _mesa_new_uniform_list();
457 shProg->Varying = _mesa_new_parameter_list();
458
459 /**
460 * Find attached vertex, fragment shaders defining main()
461 */
462 vertProg = NULL;
463 fragProg = NULL;
464 for (i = 0; i < shProg->NumShaders; i++) {
465 struct gl_shader *shader = shProg->Shaders[i];
466 if (shader->Type == GL_VERTEX_SHADER && shader->Main)
467 vertProg = vertex_program(shader->Program);
468 else if (shader->Type == GL_FRAGMENT_SHADER && shader->Main)
469 fragProg = fragment_program(shader->Program);
470 else
471 _mesa_problem(ctx, "unexpected shader target in slang_link()");
472 }
473
474 #if FEATURE_es2_glsl
475 /* must have both a vertex and fragment program for ES2 */
476 if (!vertProg) {
477 link_error(shProg, "missing vertex shader\n");
478 return;
479 }
480 if (!fragProg) {
481 link_error(shProg, "missing fragment shader\n");
482 return;
483 }
484 #endif
485
486 /*
487 * Make copies of the vertex/fragment programs now since we'll be
488 * changing src/dst registers after merging the uniforms and varying vars.
489 */
490 _mesa_reference_vertprog(ctx, &shProg->VertexProgram, NULL);
491 if (vertProg) {
492 struct gl_vertex_program *linked_vprog =
493 vertex_program(_mesa_clone_program(ctx, &vertProg->Base));
494 shProg->VertexProgram = linked_vprog; /* refcount OK */
495 ASSERT(shProg->VertexProgram->Base.RefCount == 1);
496 }
497
498 _mesa_reference_fragprog(ctx, &shProg->FragmentProgram, NULL);
499 if (fragProg) {
500 struct gl_fragment_program *linked_fprog =
501 fragment_program(_mesa_clone_program(ctx, &fragProg->Base));
502 shProg->FragmentProgram = linked_fprog; /* refcount OK */
503 ASSERT(shProg->FragmentProgram->Base.RefCount == 1);
504 }
505
506 /* link varying vars */
507 if (shProg->VertexProgram) {
508 if (!link_varying_vars(shProg, &shProg->VertexProgram->Base))
509 return;
510 }
511 if (shProg->FragmentProgram) {
512 if (!link_varying_vars(shProg, &shProg->FragmentProgram->Base))
513 return;
514 }
515
516 /* link uniform vars */
517 if (shProg->VertexProgram)
518 link_uniform_vars(shProg, &shProg->VertexProgram->Base, &numSamplers);
519 if (shProg->FragmentProgram)
520 link_uniform_vars(shProg, &shProg->FragmentProgram->Base, &numSamplers);
521
522 /*_mesa_print_uniforms(shProg->Uniforms);*/
523
524 if (shProg->VertexProgram) {
525 if (!_slang_resolve_attributes(shProg, &vertProg->Base,
526 &shProg->VertexProgram->Base)) {
527 return;
528 }
529 }
530
531 if (shProg->VertexProgram) {
532 _slang_update_inputs_outputs(&shProg->VertexProgram->Base);
533 _slang_count_temporaries(&shProg->VertexProgram->Base);
534 if (!(shProg->VertexProgram->Base.OutputsWritten & (1 << VERT_RESULT_HPOS))) {
535 /* the vertex program did not compute a vertex position */
536 link_error(shProg,
537 "gl_Position was not written by vertex shader\n");
538 return;
539 }
540 }
541 if (shProg->FragmentProgram) {
542 _slang_count_temporaries(&shProg->FragmentProgram->Base);
543 _slang_update_inputs_outputs(&shProg->FragmentProgram->Base);
544 }
545
546 /* Check that all the varying vars needed by the fragment shader are
547 * actually produced by the vertex shader.
548 */
549 if (shProg->FragmentProgram) {
550 const GLbitfield varyingRead
551 = shProg->FragmentProgram->Base.InputsRead >> FRAG_ATTRIB_VAR0;
552 const GLbitfield varyingWritten = shProg->VertexProgram ?
553 shProg->VertexProgram->Base.OutputsWritten >> VERT_RESULT_VAR0 : 0x0;
554 if ((varyingRead & varyingWritten) != varyingRead) {
555 link_error(shProg,
556 "Fragment program using varying vars not written by vertex shader\n");
557 return;
558 }
559 }
560
561
562 if (fragProg && shProg->FragmentProgram) {
563 /* notify driver that a new fragment program has been compiled/linked */
564 ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
565 &shProg->FragmentProgram->Base);
566 #if 0
567 printf("************** original fragment program\n");
568 _mesa_print_program(&fragProg->Base);
569 _mesa_print_program_parameters(ctx, &fragProg->Base);
570 #endif
571 #if 0
572 printf("************** linked fragment prog\n");
573 _mesa_print_program(&shProg->FragmentProgram->Base);
574 _mesa_print_program_parameters(ctx, &shProg->FragmentProgram->Base);
575 #endif
576 }
577
578 if (vertProg && shProg->VertexProgram) {
579 /* notify driver that a new vertex program has been compiled/linked */
580 ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
581 &shProg->VertexProgram->Base);
582 #if 0
583 printf("************** original vertex program\n");
584 _mesa_print_program(&vertProg->Base);
585 _mesa_print_program_parameters(ctx, &vertProg->Base);
586 #endif
587 #if 0
588 printf("************** linked vertex prog\n");
589 _mesa_print_program(&shProg->VertexProgram->Base);
590 _mesa_print_program_parameters(ctx, &shProg->VertexProgram->Base);
591 #endif
592 }
593
594 shProg->LinkStatus = (shProg->VertexProgram || shProg->FragmentProgram);
595 }
596