Merge commit 'origin/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 struct gl_uniform *uniform =
197 _mesa_append_uniform(shProg->Uniforms, p->Name, prog->Target, i);
198 if (uniform)
199 uniform->Initialized = p->Initialized;
200 }
201
202 if (p->Type == PROGRAM_SAMPLER) {
203 /* Allocate a new sampler index */
204 GLuint sampNum = *numSamplers;
205 GLuint oldSampNum = (GLuint) prog->Parameters->ParameterValues[i][0];
206 assert(oldSampNum < MAX_SAMPLERS);
207 samplerMap[oldSampNum] = sampNum;
208 (*numSamplers)++;
209 }
210 }
211
212
213 /* OK, now scan the program/shader instructions looking for sampler vars,
214 * replacing the old index with the new index.
215 */
216 prog->SamplersUsed = 0x0;
217 for (i = 0; i < prog->NumInstructions; i++) {
218 struct prog_instruction *inst = prog->Instructions + i;
219 if (_mesa_is_tex_instruction(inst->Opcode)) {
220 /*
221 printf("====== remap sampler from %d to %d\n",
222 inst->Sampler, map[ inst->Sampler ]);
223 */
224 /* here, texUnit is really samplerUnit */
225 assert(inst->TexSrcUnit < MAX_SAMPLERS);
226 inst->TexSrcUnit = samplerMap[inst->TexSrcUnit];
227 prog->SamplerTargets[inst->TexSrcUnit] = inst->TexSrcTarget;
228 prog->SamplersUsed |= (1 << inst->TexSrcUnit);
229 }
230 }
231
232 }
233
234
235 /**
236 * Resolve binding of generic vertex attributes.
237 * For example, if the vertex shader declared "attribute vec4 foobar" we'll
238 * allocate a generic vertex attribute for "foobar" and plug that value into
239 * the vertex program instructions.
240 * But if the user called glBindAttributeLocation(), those bindings will
241 * have priority.
242 */
243 static GLboolean
244 _slang_resolve_attributes(struct gl_shader_program *shProg,
245 const struct gl_program *origProg,
246 struct gl_program *linkedProg)
247 {
248 GLint attribMap[MAX_VERTEX_ATTRIBS];
249 GLuint i, j;
250 GLbitfield usedAttributes;
251
252 assert(origProg != linkedProg);
253 assert(origProg->Target == GL_VERTEX_PROGRAM_ARB);
254 assert(linkedProg->Target == GL_VERTEX_PROGRAM_ARB);
255
256 if (!shProg->Attributes)
257 shProg->Attributes = _mesa_new_parameter_list();
258
259 if (linkedProg->Attributes) {
260 _mesa_free_parameter_list(linkedProg->Attributes);
261 }
262 linkedProg->Attributes = _mesa_new_parameter_list();
263
264
265 /* Build a bitmask indicating which attribute indexes have been
266 * explicitly bound by the user with glBindAttributeLocation().
267 */
268 usedAttributes = 0x0;
269 for (i = 0; i < shProg->Attributes->NumParameters; i++) {
270 GLint attr = shProg->Attributes->Parameters[i].StateIndexes[0];
271 usedAttributes |= (1 << attr);
272 }
273
274 /* initialize the generic attribute map entries to -1 */
275 for (i = 0; i < MAX_VERTEX_ATTRIBS; i++) {
276 attribMap[i] = -1;
277 }
278
279 /*
280 * Scan program for generic attribute references
281 */
282 for (i = 0; i < linkedProg->NumInstructions; i++) {
283 struct prog_instruction *inst = linkedProg->Instructions + i;
284 for (j = 0; j < 3; j++) {
285 if (inst->SrcReg[j].File == PROGRAM_INPUT &&
286 inst->SrcReg[j].Index >= VERT_ATTRIB_GENERIC0) {
287 /*
288 * OK, we've found a generic vertex attribute reference.
289 */
290 const GLint k = inst->SrcReg[j].Index - VERT_ATTRIB_GENERIC0;
291
292 GLint attr = attribMap[k];
293
294 if (attr < 0) {
295 /* Need to figure out attribute mapping now.
296 */
297 const char *name = origProg->Attributes->Parameters[k].Name;
298 const GLint size = origProg->Attributes->Parameters[k].Size;
299 const GLenum type =origProg->Attributes->Parameters[k].DataType;
300 GLint index;
301
302 /* See if there's a user-defined attribute binding for
303 * this name.
304 */
305 index = _mesa_lookup_parameter_index(shProg->Attributes,
306 -1, name);
307 if (index >= 0) {
308 /* Found a user-defined binding */
309 attr = shProg->Attributes->Parameters[index].StateIndexes[0];
310 }
311 else {
312 /* No user-defined binding, choose our own attribute number.
313 * Start at 1 since generic attribute 0 always aliases
314 * glVertex/position.
315 */
316 for (attr = 1; attr < MAX_VERTEX_ATTRIBS; attr++) {
317 if (((1 << attr) & usedAttributes) == 0)
318 break;
319 }
320 if (attr == MAX_VERTEX_ATTRIBS) {
321 link_error(shProg, "Too many vertex attributes");
322 return GL_FALSE;
323 }
324
325 /* mark this attribute as used */
326 usedAttributes |= (1 << attr);
327 }
328
329 attribMap[k] = attr;
330
331 /* Save the final name->attrib binding so it can be queried
332 * with glGetAttributeLocation().
333 */
334 _mesa_add_attribute(linkedProg->Attributes, name,
335 size, type, attr);
336 }
337
338 assert(attr >= 0);
339
340 /* update the instruction's src reg */
341 inst->SrcReg[j].Index = VERT_ATTRIB_GENERIC0 + attr;
342 }
343 }
344 }
345
346 return GL_TRUE;
347 }
348
349
350 /**
351 * Scan program instructions to update the program's NumTemporaries field.
352 * Note: this implemenation relies on the code generator allocating
353 * temps in increasing order (0, 1, 2, ... ).
354 */
355 static void
356 _slang_count_temporaries(struct gl_program *prog)
357 {
358 GLuint i, j;
359 GLint maxIndex = -1;
360
361 for (i = 0; i < prog->NumInstructions; i++) {
362 const struct prog_instruction *inst = prog->Instructions + i;
363 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
364 for (j = 0; j < numSrc; j++) {
365 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
366 if (maxIndex < inst->SrcReg[j].Index)
367 maxIndex = inst->SrcReg[j].Index;
368 }
369 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
370 if (maxIndex < (GLint) inst->DstReg.Index)
371 maxIndex = inst->DstReg.Index;
372 }
373 }
374 }
375
376 prog->NumTemporaries = (GLuint) (maxIndex + 1);
377 }
378
379
380 /**
381 * Scan program instructions to update the program's InputsRead and
382 * OutputsWritten fields.
383 */
384 static void
385 _slang_update_inputs_outputs(struct gl_program *prog)
386 {
387 GLuint i, j;
388 GLuint maxAddrReg = 0;
389
390 prog->InputsRead = 0x0;
391 prog->OutputsWritten = 0x0;
392
393 for (i = 0; i < prog->NumInstructions; i++) {
394 const struct prog_instruction *inst = prog->Instructions + i;
395 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
396 for (j = 0; j < numSrc; j++) {
397 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
398 prog->InputsRead |= 1 << inst->SrcReg[j].Index;
399 if (prog->Target == GL_FRAGMENT_PROGRAM_ARB &&
400 inst->SrcReg[j].Index == FRAG_ATTRIB_FOGC) {
401 /* The fragment shader FOGC input is used for fog,
402 * front-facing and sprite/point coord.
403 */
404 struct gl_fragment_program *fp = fragment_program(prog);
405 const GLint swz = GET_SWZ(inst->SrcReg[j].Swizzle, 0);
406 if (swz == SWIZZLE_X)
407 fp->UsesFogFragCoord = GL_TRUE;
408 else if (swz == SWIZZLE_Y)
409 fp->UsesFrontFacing = GL_TRUE;
410 else if (swz == SWIZZLE_Z || swz == SWIZZLE_W)
411 fp->UsesPointCoord = GL_TRUE;
412 }
413 }
414 else if (inst->SrcReg[j].File == PROGRAM_ADDRESS) {
415 maxAddrReg = MAX2(maxAddrReg, (GLuint) (inst->SrcReg[j].Index + 1));
416 }
417 }
418 if (inst->DstReg.File == PROGRAM_OUTPUT) {
419 prog->OutputsWritten |= 1 << inst->DstReg.Index;
420 }
421 else if (inst->DstReg.File == PROGRAM_ADDRESS) {
422 maxAddrReg = MAX2(maxAddrReg, inst->DstReg.Index + 1);
423 }
424 }
425 prog->NumAddressRegs = maxAddrReg;
426 }
427
428
429 /**
430 * Shader linker. Currently:
431 *
432 * 1. The last attached vertex shader and fragment shader are linked.
433 * 2. Varying vars in the two shaders are combined so their locations
434 * agree between the vertex and fragment stages. They're treated as
435 * vertex program output attribs and as fragment program input attribs.
436 * 3. The vertex and fragment programs are cloned and modified to update
437 * src/dst register references so they use the new, linked varying
438 * storage locations.
439 */
440 void
441 _slang_link(GLcontext *ctx,
442 GLhandleARB programObj,
443 struct gl_shader_program *shProg)
444 {
445 const struct gl_vertex_program *vertProg;
446 const struct gl_fragment_program *fragProg;
447 GLuint numSamplers = 0;
448 GLuint i;
449
450 _mesa_clear_shader_program_data(ctx, shProg);
451
452 /* check that all programs compiled successfully */
453 for (i = 0; i < shProg->NumShaders; i++) {
454 if (!shProg->Shaders[i]->CompileStatus) {
455 link_error(shProg, "linking with uncompiled shader\n");
456 return;
457 }
458 }
459
460 shProg->Uniforms = _mesa_new_uniform_list();
461 shProg->Varying = _mesa_new_parameter_list();
462
463 /**
464 * Find attached vertex, fragment shaders defining main()
465 */
466 vertProg = NULL;
467 fragProg = NULL;
468 for (i = 0; i < shProg->NumShaders; i++) {
469 struct gl_shader *shader = shProg->Shaders[i];
470 if (shader->Type == GL_VERTEX_SHADER) {
471 if (shader->Main)
472 vertProg = vertex_program(shader->Program);
473 }
474 else if (shader->Type == GL_FRAGMENT_SHADER) {
475 if (shader->Main)
476 fragProg = fragment_program(shader->Program);
477 }
478 else {
479 _mesa_problem(ctx, "unexpected shader target in slang_link()");
480 }
481 }
482
483 #if FEATURE_es2_glsl
484 /* must have both a vertex and fragment program for ES2 */
485 if (!vertProg) {
486 link_error(shProg, "missing vertex shader\n");
487 return;
488 }
489 if (!fragProg) {
490 link_error(shProg, "missing fragment shader\n");
491 return;
492 }
493 #endif
494
495 /*
496 * Make copies of the vertex/fragment programs now since we'll be
497 * changing src/dst registers after merging the uniforms and varying vars.
498 */
499 _mesa_reference_vertprog(ctx, &shProg->VertexProgram, NULL);
500 if (vertProg) {
501 struct gl_vertex_program *linked_vprog =
502 vertex_program(_mesa_clone_program(ctx, &vertProg->Base));
503 shProg->VertexProgram = linked_vprog; /* refcount OK */
504 ASSERT(shProg->VertexProgram->Base.RefCount == 1);
505 }
506
507 _mesa_reference_fragprog(ctx, &shProg->FragmentProgram, NULL);
508 if (fragProg) {
509 struct gl_fragment_program *linked_fprog =
510 fragment_program(_mesa_clone_program(ctx, &fragProg->Base));
511 shProg->FragmentProgram = linked_fprog; /* refcount OK */
512 ASSERT(shProg->FragmentProgram->Base.RefCount == 1);
513 }
514
515 /* link varying vars */
516 if (shProg->VertexProgram) {
517 if (!link_varying_vars(shProg, &shProg->VertexProgram->Base))
518 return;
519 }
520 if (shProg->FragmentProgram) {
521 if (!link_varying_vars(shProg, &shProg->FragmentProgram->Base))
522 return;
523 }
524
525 /* link uniform vars */
526 if (shProg->VertexProgram)
527 link_uniform_vars(shProg, &shProg->VertexProgram->Base, &numSamplers);
528 if (shProg->FragmentProgram)
529 link_uniform_vars(shProg, &shProg->FragmentProgram->Base, &numSamplers);
530
531 /*_mesa_print_uniforms(shProg->Uniforms);*/
532
533 if (shProg->VertexProgram) {
534 if (!_slang_resolve_attributes(shProg, &vertProg->Base,
535 &shProg->VertexProgram->Base)) {
536 return;
537 }
538 }
539
540 if (shProg->VertexProgram) {
541 _slang_update_inputs_outputs(&shProg->VertexProgram->Base);
542 _slang_count_temporaries(&shProg->VertexProgram->Base);
543 if (!(shProg->VertexProgram->Base.OutputsWritten & (1 << VERT_RESULT_HPOS))) {
544 /* the vertex program did not compute a vertex position */
545 link_error(shProg,
546 "gl_Position was not written by vertex shader\n");
547 return;
548 }
549 }
550 if (shProg->FragmentProgram) {
551 _slang_count_temporaries(&shProg->FragmentProgram->Base);
552 _slang_update_inputs_outputs(&shProg->FragmentProgram->Base);
553 }
554
555 /* Check that all the varying vars needed by the fragment shader are
556 * actually produced by the vertex shader.
557 */
558 if (shProg->FragmentProgram) {
559 const GLbitfield varyingRead
560 = shProg->FragmentProgram->Base.InputsRead >> FRAG_ATTRIB_VAR0;
561 const GLbitfield varyingWritten = shProg->VertexProgram ?
562 shProg->VertexProgram->Base.OutputsWritten >> VERT_RESULT_VAR0 : 0x0;
563 if ((varyingRead & varyingWritten) != varyingRead) {
564 link_error(shProg,
565 "Fragment program using varying vars not written by vertex shader\n");
566 return;
567 }
568 }
569
570
571 if (fragProg && shProg->FragmentProgram) {
572 /* Compute initial program's TexturesUsed info */
573 _mesa_update_shader_textures_used(&shProg->FragmentProgram->Base);
574
575 /* notify driver that a new fragment program has been compiled/linked */
576 ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
577 &shProg->FragmentProgram->Base);
578 if (MESA_VERBOSE & VERBOSE_GLSL_DUMP) {
579 printf("Mesa original fragment program:\n");
580 _mesa_print_program(&fragProg->Base);
581 _mesa_print_program_parameters(ctx, &fragProg->Base);
582
583 printf("Mesa post-link fragment program:\n");
584 _mesa_print_program(&shProg->FragmentProgram->Base);
585 _mesa_print_program_parameters(ctx, &shProg->FragmentProgram->Base);
586 }
587 }
588
589 if (vertProg && shProg->VertexProgram) {
590 /* Compute initial program's TexturesUsed info */
591 _mesa_update_shader_textures_used(&shProg->VertexProgram->Base);
592
593 /* notify driver that a new vertex program has been compiled/linked */
594 ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
595 &shProg->VertexProgram->Base);
596 if (MESA_VERBOSE & VERBOSE_GLSL_DUMP) {
597 printf("Mesa original vertex program:\n");
598 _mesa_print_program(&vertProg->Base);
599 _mesa_print_program_parameters(ctx, &vertProg->Base);
600
601 printf("Mesa post-link vertex program:\n");
602 _mesa_print_program(&shProg->VertexProgram->Base);
603 _mesa_print_program_parameters(ctx, &shProg->VertexProgram->Base);
604 }
605 }
606
607 shProg->LinkStatus = (shProg->VertexProgram || shProg->FragmentProgram);
608 }
609