mesa: glsl: count number of temp regs used
[mesa.git] / src / mesa / shader / slang / slang_link.c
1 /*
2 * Mesa 3-D graphics library
3 * Version: 6.5.3
4 *
5 * Copyright (C) 2007 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
46 /**
47 * Linking varying vars involves rearranging varying vars so that the
48 * vertex program's output varyings matches the order of the fragment
49 * program's input varyings.
50 */
51 static GLboolean
52 link_varying_vars(struct gl_shader_program *shProg, struct gl_program *prog)
53 {
54 GLuint *map, i, firstVarying, newFile;
55 GLbitfield varsWritten, varsRead;
56
57 map = (GLuint *) malloc(prog->Varying->NumParameters * sizeof(GLuint));
58 if (!map)
59 return GL_FALSE;
60
61 for (i = 0; i < prog->Varying->NumParameters; i++) {
62 /* see if this varying is in the linked varying list */
63 const struct gl_program_parameter *var
64 = prog->Varying->Parameters + i;
65
66 GLint j = _mesa_lookup_parameter_index(shProg->Varying, -1, var->Name);
67 if (j >= 0) {
68 /* already in list, check size */
69 if (var->Size != shProg->Varying->Parameters[j].Size) {
70 /* error */
71 return GL_FALSE;
72 }
73 }
74 else {
75 /* not already in linked list */
76 j = _mesa_add_varying(shProg->Varying, var->Name, var->Size);
77 }
78 ASSERT(j >= 0);
79
80 map[i] = j;
81 }
82
83
84 /* Varying variables are treated like other vertex program outputs
85 * (and like other fragment program inputs). The position of the
86 * first varying differs for vertex/fragment programs...
87 * Also, replace File=PROGRAM_VARYING with File=PROGRAM_INPUT/OUTPUT.
88 */
89 if (prog->Target == GL_VERTEX_PROGRAM_ARB) {
90 firstVarying = VERT_RESULT_VAR0;
91 newFile = PROGRAM_OUTPUT;
92 }
93 else {
94 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
95 firstVarying = FRAG_ATTRIB_VAR0;
96 newFile = PROGRAM_INPUT;
97 }
98
99 /* keep track of which varying vars we read and write */
100 varsWritten = varsRead = 0x0;
101
102 /* OK, now scan the program/shader instructions looking for varying vars,
103 * replacing the old index with the new index.
104 */
105 for (i = 0; i < prog->NumInstructions; i++) {
106 struct prog_instruction *inst = prog->Instructions + i;
107 GLuint j;
108
109 if (inst->DstReg.File == PROGRAM_VARYING) {
110 inst->DstReg.File = newFile;
111 inst->DstReg.Index = map[ inst->DstReg.Index ] + firstVarying;
112 varsWritten |= (1 << inst->DstReg.Index);
113 }
114
115 for (j = 0; j < 3; j++) {
116 if (inst->SrcReg[j].File == PROGRAM_VARYING) {
117 inst->SrcReg[j].File = newFile;
118 inst->SrcReg[j].Index = map[ inst->SrcReg[j].Index ] + firstVarying;
119 varsRead |= (1 << inst->SrcReg[j].Index);
120 }
121 }
122 }
123
124 if (prog->Target == GL_VERTEX_PROGRAM_ARB) {
125 prog->OutputsWritten |= varsWritten;
126 /*printf("VERT OUTPUTS: 0x%x \n", varsWritten);*/
127 }
128 else {
129 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
130 prog->InputsRead |= varsRead;
131 /*printf("FRAG INPUTS: 0x%x\n", varsRead);*/
132 }
133
134 free(map);
135
136 return GL_TRUE;
137 }
138
139
140 /**
141 * Build the shProg->Uniforms list.
142 * This is basically a list/index of all uniforms found in either/both of
143 * the vertex and fragment shaders.
144 */
145 static void
146 link_uniform_vars(struct gl_shader_program *shProg,
147 struct gl_program *prog,
148 GLuint *numSamplers)
149 {
150 GLuint samplerMap[MAX_SAMPLERS];
151 GLuint i;
152
153 for (i = 0; i < prog->Parameters->NumParameters; i++) {
154 const struct gl_program_parameter *p = prog->Parameters->Parameters + i;
155
156 /*
157 * XXX FIX NEEDED HERE
158 * We should also be adding a uniform if p->Type == PROGRAM_STATE_VAR.
159 * For example, modelview matrix, light pos, etc.
160 * Also, we need to update the state-var name-generator code to
161 * generate GLSL-style names, like "gl_LightSource[0].position".
162 * Furthermore, we'll need to fix the state-var's size/datatype info.
163 */
164
165 if (p->Type == PROGRAM_UNIFORM ||
166 p->Type == PROGRAM_SAMPLER) {
167 _mesa_append_uniform(shProg->Uniforms, p->Name, prog->Target, i);
168 }
169
170 if (p->Type == PROGRAM_SAMPLER) {
171 /* Allocate a new sampler index */
172 GLuint sampNum = *numSamplers;
173 GLuint oldSampNum = (GLuint) prog->Parameters->ParameterValues[i][0];
174 assert(oldSampNum < MAX_SAMPLERS);
175 samplerMap[oldSampNum] = sampNum;
176 (*numSamplers)++;
177 }
178 }
179
180
181 /* OK, now scan the program/shader instructions looking for sampler vars,
182 * replacing the old index with the new index.
183 */
184 prog->SamplersUsed = 0x0;
185 for (i = 0; i < prog->NumInstructions; i++) {
186 struct prog_instruction *inst = prog->Instructions + i;
187 if (_mesa_is_tex_instruction(inst->Opcode)) {
188 /*
189 printf("====== remap sampler from %d to %d\n",
190 inst->Sampler, map[ inst->Sampler ]);
191 */
192 /* here, texUnit is really samplerUnit */
193 inst->TexSrcUnit = samplerMap[inst->TexSrcUnit];
194 prog->SamplerTargets[inst->TexSrcUnit] = inst->TexSrcTarget;
195 prog->SamplersUsed |= (1 << inst->TexSrcUnit);
196 }
197 }
198
199 }
200
201
202 /**
203 * Resolve binding of generic vertex attributes.
204 * For example, if the vertex shader declared "attribute vec4 foobar" we'll
205 * allocate a generic vertex attribute for "foobar" and plug that value into
206 * the vertex program instructions.
207 */
208 static GLboolean
209 _slang_resolve_attributes(struct gl_shader_program *shProg,
210 struct gl_program *prog)
211 {
212 GLuint i, j;
213 GLbitfield usedAttributes;
214
215 assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
216
217 if (!shProg->Attributes)
218 shProg->Attributes = _mesa_new_parameter_list();
219
220 /* Build a bitmask indicating which attribute indexes have been
221 * explicitly bound by the user with glBindAttributeLocation().
222 */
223 usedAttributes = 0x0;
224 for (i = 0; i < shProg->Attributes->NumParameters; i++) {
225 GLint attr = shProg->Attributes->Parameters[i].StateIndexes[0];
226 usedAttributes |= attr;
227 }
228
229 /*
230 * Scan program for generic attribute references
231 */
232 for (i = 0; i < prog->NumInstructions; i++) {
233 struct prog_instruction *inst = prog->Instructions + i;
234 for (j = 0; j < 3; j++) {
235 if (inst->SrcReg[j].File == PROGRAM_INPUT &&
236 inst->SrcReg[j].Index >= VERT_ATTRIB_GENERIC0) {
237 /* this is a generic attrib */
238 const GLint k = inst->SrcReg[j].Index - VERT_ATTRIB_GENERIC0;
239 const char *name = prog->Attributes->Parameters[k].Name;
240 /* See if this attrib name is in the program's attribute list
241 * (i.e. was bound by the user).
242 */
243 GLint index = _mesa_lookup_parameter_index(shProg->Attributes,
244 -1, name);
245 GLint attr;
246 if (index >= 0) {
247 /* found, user must have specified a binding */
248 attr = shProg->Attributes->Parameters[index].StateIndexes[0];
249 }
250 else {
251 /* Not found, choose our own attribute number.
252 * Start at 1 since generic attribute 0 always aliases
253 * glVertex/position.
254 */
255 GLint size = prog->Attributes->Parameters[k].Size;
256 GLenum datatype = prog->Attributes->Parameters[k].DataType;
257 for (attr = 1; attr < MAX_VERTEX_ATTRIBS; attr++) {
258 if (((1 << attr) & usedAttributes) == 0)
259 break;
260 }
261 if (attr == MAX_VERTEX_ATTRIBS) {
262 /* too many! XXX record error log */
263 return GL_FALSE;
264 }
265 _mesa_add_attribute(shProg->Attributes, name, size, datatype,attr);
266
267 /* set the attribute as used */
268 usedAttributes |= 1<<attr;
269 }
270
271 inst->SrcReg[j].Index = VERT_ATTRIB_GENERIC0 + attr;
272 }
273 }
274 }
275 return GL_TRUE;
276 }
277
278
279 /**
280 * Scan program instructions to update the program's NumTemporaries field.
281 * Note: this implemenation relies on the code generator allocating
282 * temps in increasing order (0, 1, 2, ... ).
283 */
284 static void
285 _slang_count_temporaries(struct gl_program *prog)
286 {
287 GLuint i, j;
288 GLint maxIndex = -1;
289
290 for (i = 0; i < prog->NumInstructions; i++) {
291 const struct prog_instruction *inst = prog->Instructions + i;
292 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
293 for (j = 0; j < numSrc; j++) {
294 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
295 if (maxIndex < inst->SrcReg[j].Index)
296 maxIndex = inst->SrcReg[j].Index;
297 }
298 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
299 if (maxIndex < inst->DstReg.Index)
300 maxIndex = inst->DstReg.Index;
301 }
302 }
303 }
304
305 prog->NumTemporaries = (GLuint) (maxIndex + 1);
306 }
307
308
309 /**
310 * Scan program instructions to update the program's InputsRead and
311 * OutputsWritten fields.
312 */
313 static void
314 _slang_update_inputs_outputs(struct gl_program *prog)
315 {
316 GLuint i, j;
317
318 prog->InputsRead = 0x0;
319 prog->OutputsWritten = 0x0;
320
321 for (i = 0; i < prog->NumInstructions; i++) {
322 const struct prog_instruction *inst = prog->Instructions + i;
323 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
324 for (j = 0; j < numSrc; j++) {
325 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
326 prog->InputsRead |= 1 << inst->SrcReg[j].Index;
327 }
328 }
329 if (inst->DstReg.File == PROGRAM_OUTPUT) {
330 prog->OutputsWritten |= 1 << inst->DstReg.Index;
331 }
332 }
333 }
334
335
336 /**
337 * Scan a vertex program looking for instances of
338 * (PROGRAM_INPUT, VERT_ATTRIB_GENERIC0 + oldAttrib) and replace with
339 * (PROGRAM_INPUT, VERT_ATTRIB_GENERIC0 + newAttrib).
340 * This is used when the user calls glBindAttribLocation on an already linked
341 * shader program.
342 */
343 void
344 _slang_remap_attribute(struct gl_program *prog, GLuint oldAttrib, GLuint newAttrib)
345 {
346 GLuint i, j;
347
348 assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
349
350 for (i = 0; i < prog->NumInstructions; i++) {
351 struct prog_instruction *inst = prog->Instructions + i;
352 for (j = 0; j < 3; j++) {
353 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
354 if (inst->SrcReg[j].Index == VERT_ATTRIB_GENERIC0 + oldAttrib) {
355 inst->SrcReg[j].Index = VERT_ATTRIB_GENERIC0 + newAttrib;
356 }
357 }
358 }
359 }
360
361 _slang_update_inputs_outputs(prog);
362 }
363
364
365
366 /** cast wrapper */
367 static struct gl_vertex_program *
368 vertex_program(struct gl_program *prog)
369 {
370 assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
371 return (struct gl_vertex_program *) prog;
372 }
373
374
375 /** cast wrapper */
376 static struct gl_fragment_program *
377 fragment_program(struct gl_program *prog)
378 {
379 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
380 return (struct gl_fragment_program *) prog;
381 }
382
383
384 /**
385 * Record a linking error.
386 */
387 static void
388 link_error(struct gl_shader_program *shProg, const char *msg)
389 {
390 if (shProg->InfoLog) {
391 _mesa_free(shProg->InfoLog);
392 }
393 shProg->InfoLog = _mesa_strdup(msg);
394 shProg->LinkStatus = GL_FALSE;
395 }
396
397
398
399 /**
400 * Shader linker. Currently:
401 *
402 * 1. The last attached vertex shader and fragment shader are linked.
403 * 2. Varying vars in the two shaders are combined so their locations
404 * agree between the vertex and fragment stages. They're treated as
405 * vertex program output attribs and as fragment program input attribs.
406 * 3. The vertex and fragment programs are cloned and modified to update
407 * src/dst register references so they use the new, linked varying
408 * storage locations.
409 */
410 void
411 _slang_link(GLcontext *ctx,
412 GLhandleARB programObj,
413 struct gl_shader_program *shProg)
414 {
415 const struct gl_vertex_program *vertProg;
416 const struct gl_fragment_program *fragProg;
417 GLuint numSamplers = 0;
418 GLuint i;
419
420 _mesa_clear_shader_program_data(ctx, shProg);
421
422 /* check that all programs compiled successfully */
423 for (i = 0; i < shProg->NumShaders; i++) {
424 if (!shProg->Shaders[i]->CompileStatus) {
425 link_error(shProg, "linking with uncompiled shader\n");
426 return;
427 }
428 }
429
430 shProg->Uniforms = _mesa_new_uniform_list();
431 shProg->Varying = _mesa_new_parameter_list();
432
433 /**
434 * Find attached vertex, fragment shaders defining main()
435 */
436 vertProg = NULL;
437 fragProg = NULL;
438 for (i = 0; i < shProg->NumShaders; i++) {
439 struct gl_shader *shader = shProg->Shaders[i];
440 if (shader->Type == GL_VERTEX_SHADER && shader->Main)
441 vertProg = vertex_program(shader->Program);
442 else if (shader->Type == GL_FRAGMENT_SHADER && shader->Main)
443 fragProg = fragment_program(shader->Program);
444 else
445 _mesa_problem(ctx, "unexpected shader target in slang_link()");
446 }
447
448 /*
449 * Make copies of the vertex/fragment programs now since we'll be
450 * changing src/dst registers after merging the uniforms and varying vars.
451 */
452 _mesa_reference_vertprog(ctx, &shProg->VertexProgram, NULL);
453 if (vertProg) {
454 struct gl_vertex_program *linked_vprog =
455 vertex_program(_mesa_clone_program(ctx, &vertProg->Base));
456 shProg->VertexProgram = linked_vprog; /* refcount OK */
457 ASSERT(shProg->VertexProgram->Base.RefCount == 1);
458 }
459
460 _mesa_reference_fragprog(ctx, &shProg->FragmentProgram, NULL);
461 if (fragProg) {
462 struct gl_fragment_program *linked_fprog =
463 fragment_program(_mesa_clone_program(ctx, &fragProg->Base));
464 shProg->FragmentProgram = linked_fprog; /* refcount OK */
465 ASSERT(shProg->FragmentProgram->Base.RefCount == 1);
466 }
467
468 /* link varying vars */
469 if (shProg->VertexProgram)
470 link_varying_vars(shProg, &shProg->VertexProgram->Base);
471 if (shProg->FragmentProgram)
472 link_varying_vars(shProg, &shProg->FragmentProgram->Base);
473
474 /* link uniform vars */
475 if (shProg->VertexProgram)
476 link_uniform_vars(shProg, &shProg->VertexProgram->Base, &numSamplers);
477 if (shProg->FragmentProgram)
478 link_uniform_vars(shProg, &shProg->FragmentProgram->Base, &numSamplers);
479
480 /*_mesa_print_uniforms(shProg->Uniforms);*/
481
482 if (shProg->VertexProgram) {
483 if (!_slang_resolve_attributes(shProg, &shProg->VertexProgram->Base)) {
484 /*goto cleanup;*/
485 _mesa_problem(ctx, "_slang_resolve_attributes() failed");
486 return;
487 }
488 }
489
490 if (shProg->VertexProgram) {
491 _slang_update_inputs_outputs(&shProg->VertexProgram->Base);
492 _slang_count_temporaries(&shProg->VertexProgram->Base);
493 if (!(shProg->VertexProgram->Base.OutputsWritten & (1 << VERT_RESULT_HPOS))) {
494 /* the vertex program did not compute a vertex position */
495 link_error(shProg,
496 "gl_Position was not written by vertex shader\n");
497 return;
498 }
499 }
500 if (shProg->FragmentProgram) {
501 _slang_count_temporaries(&shProg->FragmentProgram->Base);
502 _slang_update_inputs_outputs(&shProg->FragmentProgram->Base);
503 }
504
505 /* Check that all the varying vars needed by the fragment shader are
506 * actually produced by the vertex shader.
507 */
508 if (shProg->FragmentProgram) {
509 const GLbitfield varyingRead
510 = shProg->FragmentProgram->Base.InputsRead >> FRAG_ATTRIB_VAR0;
511 const GLbitfield varyingWritten = shProg->VertexProgram ?
512 shProg->VertexProgram->Base.OutputsWritten >> VERT_RESULT_VAR0 : 0x0;
513 if ((varyingRead & varyingWritten) != varyingRead) {
514 link_error(shProg,
515 "Fragment program using varying vars not written by vertex shader\n");
516 return;
517 }
518 }
519
520 /* Check that the vertex program doesn't use too many sampler units */
521 if (shProg->VertexProgram &&
522 _mesa_bitcount(shProg->VertexProgram->Base.SamplersUsed) > ctx->Const.MaxVertexTextureImageUnits) {
523 link_error(shProg, "Vertex program uses too many samplers.\n");
524 return;
525 }
526
527 if (fragProg && shProg->FragmentProgram) {
528 /* notify driver that a new fragment program has been compiled/linked */
529 ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
530 &shProg->FragmentProgram->Base);
531 #if 0
532 printf("************** original fragment program\n");
533 _mesa_print_program(&fragProg->Base);
534 _mesa_print_program_parameters(ctx, &fragProg->Base);
535 #endif
536 #if 01
537 printf("************** linked fragment prog\n");
538 _mesa_print_program(&shProg->FragmentProgram->Base);
539 _mesa_print_program_parameters(ctx, &shProg->FragmentProgram->Base);
540 #endif
541 }
542
543 if (vertProg && shProg->VertexProgram) {
544 /* notify driver that a new vertex program has been compiled/linked */
545 ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
546 &shProg->VertexProgram->Base);
547 #if 0
548 printf("************** original vertex program\n");
549 _mesa_print_program(&vertProg->Base);
550 _mesa_print_program_parameters(ctx, &vertProg->Base);
551 #endif
552 #if 01
553 printf("************** linked vertex prog\n");
554 _mesa_print_program(&shProg->VertexProgram->Base);
555 _mesa_print_program_parameters(ctx, &shProg->VertexProgram->Base);
556 #endif
557 }
558
559 shProg->LinkStatus = (shProg->VertexProgram || shProg->FragmentProgram);
560 }
561