mesa: remove FEATURE_ATI_fragment_shader define.
[mesa.git] / src / mesa / program / program.c
1 /*
2 * Mesa 3-D graphics library
3 * Version: 6.5.3
4 *
5 * Copyright (C) 1999-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 program.c
27 * Vertex and fragment program support functions.
28 * \author Brian Paul
29 */
30
31
32 #include "main/glheader.h"
33 #include "main/context.h"
34 #include "main/hash.h"
35 #include "main/mfeatures.h"
36 #include "program.h"
37 #include "prog_cache.h"
38 #include "prog_parameter.h"
39 #include "prog_instruction.h"
40
41
42 /**
43 * A pointer to this dummy program is put into the hash table when
44 * glGenPrograms is called.
45 */
46 struct gl_program _mesa_DummyProgram;
47
48
49 /**
50 * Init context's vertex/fragment program state
51 */
52 void
53 _mesa_init_program(struct gl_context *ctx)
54 {
55 GLuint i;
56
57 /*
58 * If this assertion fails, we need to increase the field
59 * size for register indexes (see INST_INDEX_BITS).
60 */
61 ASSERT(ctx->Const.VertexProgram.MaxUniformComponents / 4
62 <= (1 << INST_INDEX_BITS));
63 ASSERT(ctx->Const.FragmentProgram.MaxUniformComponents / 4
64 <= (1 << INST_INDEX_BITS));
65
66 ASSERT(ctx->Const.VertexProgram.MaxTemps <= (1 << INST_INDEX_BITS));
67 ASSERT(ctx->Const.VertexProgram.MaxLocalParams <= (1 << INST_INDEX_BITS));
68 ASSERT(ctx->Const.FragmentProgram.MaxTemps <= (1 << INST_INDEX_BITS));
69 ASSERT(ctx->Const.FragmentProgram.MaxLocalParams <= (1 << INST_INDEX_BITS));
70
71 ASSERT(ctx->Const.VertexProgram.MaxUniformComponents <= 4 * MAX_UNIFORMS);
72 ASSERT(ctx->Const.FragmentProgram.MaxUniformComponents <= 4 * MAX_UNIFORMS);
73
74 ASSERT(ctx->Const.VertexProgram.MaxAddressOffset <= (1 << INST_INDEX_BITS));
75 ASSERT(ctx->Const.FragmentProgram.MaxAddressOffset <= (1 << INST_INDEX_BITS));
76
77 /* If this fails, increase prog_instruction::TexSrcUnit size */
78 ASSERT(MAX_TEXTURE_UNITS <= (1 << 5));
79
80 /* If this fails, increase prog_instruction::TexSrcTarget size */
81 ASSERT(NUM_TEXTURE_TARGETS <= (1 << 4));
82
83 ctx->Program.ErrorPos = -1;
84 ctx->Program.ErrorString = _mesa_strdup("");
85
86 ctx->VertexProgram.Enabled = GL_FALSE;
87 ctx->VertexProgram.PointSizeEnabled =
88 (ctx->API == API_OPENGLES2) ? GL_TRUE : GL_FALSE;
89 ctx->VertexProgram.TwoSideEnabled = GL_FALSE;
90 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current,
91 ctx->Shared->DefaultVertexProgram);
92 assert(ctx->VertexProgram.Current);
93 for (i = 0; i < MAX_NV_VERTEX_PROGRAM_PARAMS / 4; i++) {
94 ctx->VertexProgram.TrackMatrix[i] = GL_NONE;
95 ctx->VertexProgram.TrackMatrixTransform[i] = GL_IDENTITY_NV;
96 }
97 ctx->VertexProgram.Cache = _mesa_new_program_cache();
98
99 ctx->FragmentProgram.Enabled = GL_FALSE;
100 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
101 ctx->Shared->DefaultFragmentProgram);
102 assert(ctx->FragmentProgram.Current);
103 ctx->FragmentProgram.Cache = _mesa_new_program_cache();
104
105 ctx->GeometryProgram.Enabled = GL_FALSE;
106 /* right now by default we don't have a geometry program */
107 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current,
108 NULL);
109 ctx->GeometryProgram.Cache = _mesa_new_program_cache();
110
111 /* XXX probably move this stuff */
112 ctx->ATIFragmentShader.Enabled = GL_FALSE;
113 ctx->ATIFragmentShader.Current = ctx->Shared->DefaultFragmentShader;
114 assert(ctx->ATIFragmentShader.Current);
115 ctx->ATIFragmentShader.Current->RefCount++;
116 }
117
118
119 /**
120 * Free a context's vertex/fragment program state
121 */
122 void
123 _mesa_free_program_data(struct gl_context *ctx)
124 {
125 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
126 _mesa_delete_program_cache(ctx, ctx->VertexProgram.Cache);
127 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
128 _mesa_delete_shader_cache(ctx, ctx->FragmentProgram.Cache);
129 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current, NULL);
130 _mesa_delete_program_cache(ctx, ctx->GeometryProgram.Cache);
131
132 /* XXX probably move this stuff */
133 if (ctx->ATIFragmentShader.Current) {
134 ctx->ATIFragmentShader.Current->RefCount--;
135 if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
136 free(ctx->ATIFragmentShader.Current);
137 }
138 }
139
140 free((void *) ctx->Program.ErrorString);
141 }
142
143
144 /**
145 * Update the default program objects in the given context to reference those
146 * specified in the shared state and release those referencing the old
147 * shared state.
148 */
149 void
150 _mesa_update_default_objects_program(struct gl_context *ctx)
151 {
152 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current,
153 ctx->Shared->DefaultVertexProgram);
154 assert(ctx->VertexProgram.Current);
155
156 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
157 ctx->Shared->DefaultFragmentProgram);
158 assert(ctx->FragmentProgram.Current);
159
160 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current,
161 ctx->Shared->DefaultGeometryProgram);
162
163 /* XXX probably move this stuff */
164 if (ctx->ATIFragmentShader.Current) {
165 ctx->ATIFragmentShader.Current->RefCount--;
166 if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
167 free(ctx->ATIFragmentShader.Current);
168 }
169 }
170 ctx->ATIFragmentShader.Current = (struct ati_fragment_shader *) ctx->Shared->DefaultFragmentShader;
171 assert(ctx->ATIFragmentShader.Current);
172 ctx->ATIFragmentShader.Current->RefCount++;
173 }
174
175
176 /**
177 * Set the vertex/fragment program error state (position and error string).
178 * This is generally called from within the parsers.
179 */
180 void
181 _mesa_set_program_error(struct gl_context *ctx, GLint pos, const char *string)
182 {
183 ctx->Program.ErrorPos = pos;
184 free((void *) ctx->Program.ErrorString);
185 if (!string)
186 string = "";
187 ctx->Program.ErrorString = _mesa_strdup(string);
188 }
189
190
191 /**
192 * Find the line number and column for 'pos' within 'string'.
193 * Return a copy of the line which contains 'pos'. Free the line with
194 * free().
195 * \param string the program string
196 * \param pos the position within the string
197 * \param line returns the line number corresponding to 'pos'.
198 * \param col returns the column number corresponding to 'pos'.
199 * \return copy of the line containing 'pos'.
200 */
201 const GLubyte *
202 _mesa_find_line_column(const GLubyte *string, const GLubyte *pos,
203 GLint *line, GLint *col)
204 {
205 const GLubyte *lineStart = string;
206 const GLubyte *p = string;
207 GLubyte *s;
208 int len;
209
210 *line = 1;
211
212 while (p != pos) {
213 if (*p == (GLubyte) '\n') {
214 (*line)++;
215 lineStart = p + 1;
216 }
217 p++;
218 }
219
220 *col = (pos - lineStart) + 1;
221
222 /* return copy of this line */
223 while (*p != 0 && *p != '\n')
224 p++;
225 len = p - lineStart;
226 s = malloc(len + 1);
227 memcpy(s, lineStart, len);
228 s[len] = 0;
229
230 return s;
231 }
232
233
234 /**
235 * Initialize a new vertex/fragment program object.
236 */
237 static struct gl_program *
238 _mesa_init_program_struct( struct gl_context *ctx, struct gl_program *prog,
239 GLenum target, GLuint id)
240 {
241 (void) ctx;
242 if (prog) {
243 GLuint i;
244 memset(prog, 0, sizeof(*prog));
245 prog->Id = id;
246 prog->Target = target;
247 prog->Resident = GL_TRUE;
248 prog->RefCount = 1;
249 prog->Format = GL_PROGRAM_FORMAT_ASCII_ARB;
250
251 /* default mapping from samplers to texture units */
252 for (i = 0; i < MAX_SAMPLERS; i++)
253 prog->SamplerUnits[i] = i;
254 }
255
256 return prog;
257 }
258
259
260 /**
261 * Initialize a new fragment program object.
262 */
263 struct gl_program *
264 _mesa_init_fragment_program( struct gl_context *ctx, struct gl_fragment_program *prog,
265 GLenum target, GLuint id)
266 {
267 if (prog)
268 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
269 else
270 return NULL;
271 }
272
273
274 /**
275 * Initialize a new vertex program object.
276 */
277 struct gl_program *
278 _mesa_init_vertex_program( struct gl_context *ctx, struct gl_vertex_program *prog,
279 GLenum target, GLuint id)
280 {
281 if (prog)
282 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
283 else
284 return NULL;
285 }
286
287
288 /**
289 * Initialize a new geometry program object.
290 */
291 struct gl_program *
292 _mesa_init_geometry_program( struct gl_context *ctx, struct gl_geometry_program *prog,
293 GLenum target, GLuint id)
294 {
295 if (prog)
296 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
297 else
298 return NULL;
299 }
300
301
302 /**
303 * Allocate and initialize a new fragment/vertex program object but
304 * don't put it into the program hash table. Called via
305 * ctx->Driver.NewProgram. May be overridden (ie. replaced) by a
306 * device driver function to implement OO deriviation with additional
307 * types not understood by this function.
308 *
309 * \param ctx context
310 * \param id program id/number
311 * \param target program target/type
312 * \return pointer to new program object
313 */
314 struct gl_program *
315 _mesa_new_program(struct gl_context *ctx, GLenum target, GLuint id)
316 {
317 struct gl_program *prog;
318 switch (target) {
319 case GL_VERTEX_PROGRAM_ARB: /* == GL_VERTEX_PROGRAM_NV */
320 case GL_VERTEX_STATE_PROGRAM_NV:
321 prog = _mesa_init_vertex_program(ctx, CALLOC_STRUCT(gl_vertex_program),
322 target, id );
323 break;
324 case GL_FRAGMENT_PROGRAM_NV:
325 case GL_FRAGMENT_PROGRAM_ARB:
326 prog =_mesa_init_fragment_program(ctx,
327 CALLOC_STRUCT(gl_fragment_program),
328 target, id );
329 break;
330 case MESA_GEOMETRY_PROGRAM:
331 prog = _mesa_init_geometry_program(ctx,
332 CALLOC_STRUCT(gl_geometry_program),
333 target, id);
334 break;
335 default:
336 _mesa_problem(ctx, "bad target in _mesa_new_program");
337 prog = NULL;
338 }
339 return prog;
340 }
341
342
343 /**
344 * Delete a program and remove it from the hash table, ignoring the
345 * reference count.
346 * Called via ctx->Driver.DeleteProgram. May be wrapped (OO deriviation)
347 * by a device driver function.
348 */
349 void
350 _mesa_delete_program(struct gl_context *ctx, struct gl_program *prog)
351 {
352 (void) ctx;
353 ASSERT(prog);
354 ASSERT(prog->RefCount==0);
355
356 if (prog == &_mesa_DummyProgram)
357 return;
358
359 free(prog->String);
360
361 if (prog->Instructions) {
362 _mesa_free_instructions(prog->Instructions, prog->NumInstructions);
363 }
364 if (prog->Parameters) {
365 _mesa_free_parameter_list(prog->Parameters);
366 }
367
368 free(prog);
369 }
370
371
372 /**
373 * Return the gl_program object for a given ID.
374 * Basically just a wrapper for _mesa_HashLookup() to avoid a lot of
375 * casts elsewhere.
376 */
377 struct gl_program *
378 _mesa_lookup_program(struct gl_context *ctx, GLuint id)
379 {
380 if (id)
381 return (struct gl_program *) _mesa_HashLookup(ctx->Shared->Programs, id);
382 else
383 return NULL;
384 }
385
386
387 /**
388 * Reference counting for vertex/fragment programs
389 * This is normally only called from the _mesa_reference_program() macro
390 * when there's a real pointer change.
391 */
392 void
393 _mesa_reference_program_(struct gl_context *ctx,
394 struct gl_program **ptr,
395 struct gl_program *prog)
396 {
397 #ifndef NDEBUG
398 assert(ptr);
399 if (*ptr && prog) {
400 /* sanity check */
401 if ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB)
402 ASSERT(prog->Target == GL_VERTEX_PROGRAM_ARB);
403 else if ((*ptr)->Target == GL_FRAGMENT_PROGRAM_ARB)
404 ASSERT(prog->Target == GL_FRAGMENT_PROGRAM_ARB ||
405 prog->Target == GL_FRAGMENT_PROGRAM_NV);
406 else if ((*ptr)->Target == MESA_GEOMETRY_PROGRAM)
407 ASSERT(prog->Target == MESA_GEOMETRY_PROGRAM);
408 }
409 #endif
410
411 if (*ptr) {
412 GLboolean deleteFlag;
413
414 /*_glthread_LOCK_MUTEX((*ptr)->Mutex);*/
415 #if 0
416 printf("Program %p ID=%u Target=%s Refcount-- to %d\n",
417 *ptr, (*ptr)->Id,
418 ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB ? "VP" :
419 ((*ptr)->Target == MESA_GEOMETRY_PROGRAM ? "GP" : "FP")),
420 (*ptr)->RefCount - 1);
421 #endif
422 ASSERT((*ptr)->RefCount > 0);
423 (*ptr)->RefCount--;
424
425 deleteFlag = ((*ptr)->RefCount == 0);
426 /*_glthread_UNLOCK_MUTEX((*ptr)->Mutex);*/
427
428 if (deleteFlag) {
429 ASSERT(ctx);
430 ctx->Driver.DeleteProgram(ctx, *ptr);
431 }
432
433 *ptr = NULL;
434 }
435
436 assert(!*ptr);
437 if (prog) {
438 /*_glthread_LOCK_MUTEX(prog->Mutex);*/
439 prog->RefCount++;
440 #if 0
441 printf("Program %p ID=%u Target=%s Refcount++ to %d\n",
442 prog, prog->Id,
443 (prog->Target == GL_VERTEX_PROGRAM_ARB ? "VP" :
444 (prog->Target == MESA_GEOMETRY_PROGRAM ? "GP" : "FP")),
445 prog->RefCount);
446 #endif
447 /*_glthread_UNLOCK_MUTEX(prog->Mutex);*/
448 }
449
450 *ptr = prog;
451 }
452
453
454 /**
455 * Return a copy of a program.
456 * XXX Problem here if the program object is actually OO-derivation
457 * made by a device driver.
458 */
459 struct gl_program *
460 _mesa_clone_program(struct gl_context *ctx, const struct gl_program *prog)
461 {
462 struct gl_program *clone;
463
464 clone = ctx->Driver.NewProgram(ctx, prog->Target, prog->Id);
465 if (!clone)
466 return NULL;
467
468 assert(clone->Target == prog->Target);
469 assert(clone->RefCount == 1);
470
471 clone->String = (GLubyte *) _mesa_strdup((char *) prog->String);
472 clone->Format = prog->Format;
473 clone->Instructions = _mesa_alloc_instructions(prog->NumInstructions);
474 if (!clone->Instructions) {
475 _mesa_reference_program(ctx, &clone, NULL);
476 return NULL;
477 }
478 _mesa_copy_instructions(clone->Instructions, prog->Instructions,
479 prog->NumInstructions);
480 clone->InputsRead = prog->InputsRead;
481 clone->OutputsWritten = prog->OutputsWritten;
482 clone->SamplersUsed = prog->SamplersUsed;
483 clone->ShadowSamplers = prog->ShadowSamplers;
484 memcpy(clone->TexturesUsed, prog->TexturesUsed, sizeof(prog->TexturesUsed));
485
486 if (prog->Parameters)
487 clone->Parameters = _mesa_clone_parameter_list(prog->Parameters);
488 memcpy(clone->LocalParams, prog->LocalParams, sizeof(clone->LocalParams));
489 memcpy(clone->LocalParams, prog->LocalParams, sizeof(clone->LocalParams));
490 clone->IndirectRegisterFiles = prog->IndirectRegisterFiles;
491 clone->NumInstructions = prog->NumInstructions;
492 clone->NumTemporaries = prog->NumTemporaries;
493 clone->NumParameters = prog->NumParameters;
494 clone->NumAttributes = prog->NumAttributes;
495 clone->NumAddressRegs = prog->NumAddressRegs;
496 clone->NumNativeInstructions = prog->NumNativeInstructions;
497 clone->NumNativeTemporaries = prog->NumNativeTemporaries;
498 clone->NumNativeParameters = prog->NumNativeParameters;
499 clone->NumNativeAttributes = prog->NumNativeAttributes;
500 clone->NumNativeAddressRegs = prog->NumNativeAddressRegs;
501 clone->NumAluInstructions = prog->NumAluInstructions;
502 clone->NumTexInstructions = prog->NumTexInstructions;
503 clone->NumTexIndirections = prog->NumTexIndirections;
504 clone->NumNativeAluInstructions = prog->NumNativeAluInstructions;
505 clone->NumNativeTexInstructions = prog->NumNativeTexInstructions;
506 clone->NumNativeTexIndirections = prog->NumNativeTexIndirections;
507
508 switch (prog->Target) {
509 case GL_VERTEX_PROGRAM_ARB:
510 {
511 const struct gl_vertex_program *vp = gl_vertex_program_const(prog);
512 struct gl_vertex_program *vpc = gl_vertex_program(clone);
513 vpc->IsPositionInvariant = vp->IsPositionInvariant;
514 vpc->IsNVProgram = vp->IsNVProgram;
515 }
516 break;
517 case GL_FRAGMENT_PROGRAM_ARB:
518 {
519 const struct gl_fragment_program *fp = gl_fragment_program_const(prog);
520 struct gl_fragment_program *fpc = gl_fragment_program(clone);
521 fpc->UsesKill = fp->UsesKill;
522 fpc->UsesDFdy = fp->UsesDFdy;
523 fpc->OriginUpperLeft = fp->OriginUpperLeft;
524 fpc->PixelCenterInteger = fp->PixelCenterInteger;
525 }
526 break;
527 case MESA_GEOMETRY_PROGRAM:
528 {
529 const struct gl_geometry_program *gp = gl_geometry_program_const(prog);
530 struct gl_geometry_program *gpc = gl_geometry_program(clone);
531 gpc->VerticesOut = gp->VerticesOut;
532 gpc->InputType = gp->InputType;
533 gpc->OutputType = gp->OutputType;
534 }
535 break;
536 default:
537 _mesa_problem(NULL, "Unexpected target in _mesa_clone_program");
538 }
539
540 return clone;
541 }
542
543
544 /**
545 * Insert 'count' NOP instructions at 'start' in the given program.
546 * Adjust branch targets accordingly.
547 */
548 GLboolean
549 _mesa_insert_instructions(struct gl_program *prog, GLuint start, GLuint count)
550 {
551 const GLuint origLen = prog->NumInstructions;
552 const GLuint newLen = origLen + count;
553 struct prog_instruction *newInst;
554 GLuint i;
555
556 /* adjust branches */
557 for (i = 0; i < prog->NumInstructions; i++) {
558 struct prog_instruction *inst = prog->Instructions + i;
559 if (inst->BranchTarget > 0) {
560 if ((GLuint)inst->BranchTarget >= start) {
561 inst->BranchTarget += count;
562 }
563 }
564 }
565
566 /* Alloc storage for new instructions */
567 newInst = _mesa_alloc_instructions(newLen);
568 if (!newInst) {
569 return GL_FALSE;
570 }
571
572 /* Copy 'start' instructions into new instruction buffer */
573 _mesa_copy_instructions(newInst, prog->Instructions, start);
574
575 /* init the new instructions */
576 _mesa_init_instructions(newInst + start, count);
577
578 /* Copy the remaining/tail instructions to new inst buffer */
579 _mesa_copy_instructions(newInst + start + count,
580 prog->Instructions + start,
581 origLen - start);
582
583 /* free old instructions */
584 _mesa_free_instructions(prog->Instructions, origLen);
585
586 /* install new instructions */
587 prog->Instructions = newInst;
588 prog->NumInstructions = newLen;
589
590 return GL_TRUE;
591 }
592
593 /**
594 * Delete 'count' instructions at 'start' in the given program.
595 * Adjust branch targets accordingly.
596 */
597 GLboolean
598 _mesa_delete_instructions(struct gl_program *prog, GLuint start, GLuint count)
599 {
600 const GLuint origLen = prog->NumInstructions;
601 const GLuint newLen = origLen - count;
602 struct prog_instruction *newInst;
603 GLuint i;
604
605 /* adjust branches */
606 for (i = 0; i < prog->NumInstructions; i++) {
607 struct prog_instruction *inst = prog->Instructions + i;
608 if (inst->BranchTarget > 0) {
609 if (inst->BranchTarget > (GLint) start) {
610 inst->BranchTarget -= count;
611 }
612 }
613 }
614
615 /* Alloc storage for new instructions */
616 newInst = _mesa_alloc_instructions(newLen);
617 if (!newInst) {
618 return GL_FALSE;
619 }
620
621 /* Copy 'start' instructions into new instruction buffer */
622 _mesa_copy_instructions(newInst, prog->Instructions, start);
623
624 /* Copy the remaining/tail instructions to new inst buffer */
625 _mesa_copy_instructions(newInst + start,
626 prog->Instructions + start + count,
627 newLen - start);
628
629 /* free old instructions */
630 _mesa_free_instructions(prog->Instructions, origLen);
631
632 /* install new instructions */
633 prog->Instructions = newInst;
634 prog->NumInstructions = newLen;
635
636 return GL_TRUE;
637 }
638
639
640 /**
641 * Search instructions for registers that match (oldFile, oldIndex),
642 * replacing them with (newFile, newIndex).
643 */
644 static void
645 replace_registers(struct prog_instruction *inst, GLuint numInst,
646 GLuint oldFile, GLuint oldIndex,
647 GLuint newFile, GLuint newIndex)
648 {
649 GLuint i, j;
650 for (i = 0; i < numInst; i++) {
651 /* src regs */
652 for (j = 0; j < _mesa_num_inst_src_regs(inst[i].Opcode); j++) {
653 if (inst[i].SrcReg[j].File == oldFile &&
654 inst[i].SrcReg[j].Index == oldIndex) {
655 inst[i].SrcReg[j].File = newFile;
656 inst[i].SrcReg[j].Index = newIndex;
657 }
658 }
659 /* dst reg */
660 if (inst[i].DstReg.File == oldFile && inst[i].DstReg.Index == oldIndex) {
661 inst[i].DstReg.File = newFile;
662 inst[i].DstReg.Index = newIndex;
663 }
664 }
665 }
666
667
668 /**
669 * Search instructions for references to program parameters. When found,
670 * increment the parameter index by 'offset'.
671 * Used when combining programs.
672 */
673 static void
674 adjust_param_indexes(struct prog_instruction *inst, GLuint numInst,
675 GLuint offset)
676 {
677 GLuint i, j;
678 for (i = 0; i < numInst; i++) {
679 for (j = 0; j < _mesa_num_inst_src_regs(inst[i].Opcode); j++) {
680 GLuint f = inst[i].SrcReg[j].File;
681 if (f == PROGRAM_CONSTANT ||
682 f == PROGRAM_UNIFORM ||
683 f == PROGRAM_STATE_VAR) {
684 inst[i].SrcReg[j].Index += offset;
685 }
686 }
687 }
688 }
689
690
691 /**
692 * Combine two programs into one. Fix instructions so the outputs of
693 * the first program go to the inputs of the second program.
694 */
695 struct gl_program *
696 _mesa_combine_programs(struct gl_context *ctx,
697 const struct gl_program *progA,
698 const struct gl_program *progB)
699 {
700 struct prog_instruction *newInst;
701 struct gl_program *newProg;
702 const GLuint lenA = progA->NumInstructions - 1; /* omit END instr */
703 const GLuint lenB = progB->NumInstructions;
704 const GLuint numParamsA = _mesa_num_parameters(progA->Parameters);
705 const GLuint newLength = lenA + lenB;
706 GLboolean usedTemps[MAX_PROGRAM_TEMPS];
707 GLuint firstTemp = 0;
708 GLbitfield inputsB;
709 GLuint i;
710
711 ASSERT(progA->Target == progB->Target);
712
713 newInst = _mesa_alloc_instructions(newLength);
714 if (!newInst)
715 return GL_FALSE;
716
717 _mesa_copy_instructions(newInst, progA->Instructions, lenA);
718 _mesa_copy_instructions(newInst + lenA, progB->Instructions, lenB);
719
720 /* adjust branch / instruction addresses for B's instructions */
721 for (i = 0; i < lenB; i++) {
722 newInst[lenA + i].BranchTarget += lenA;
723 }
724
725 newProg = ctx->Driver.NewProgram(ctx, progA->Target, 0);
726 newProg->Instructions = newInst;
727 newProg->NumInstructions = newLength;
728
729 /* find used temp regs (we may need new temps below) */
730 _mesa_find_used_registers(newProg, PROGRAM_TEMPORARY,
731 usedTemps, MAX_PROGRAM_TEMPS);
732
733 if (newProg->Target == GL_FRAGMENT_PROGRAM_ARB) {
734 const struct gl_fragment_program *fprogA, *fprogB;
735 struct gl_fragment_program *newFprog;
736 GLbitfield progB_inputsRead = progB->InputsRead;
737 GLint progB_colorFile, progB_colorIndex;
738
739 fprogA = gl_fragment_program_const(progA);
740 fprogB = gl_fragment_program_const(progB);
741 newFprog = gl_fragment_program(newProg);
742
743 newFprog->UsesKill = fprogA->UsesKill || fprogB->UsesKill;
744 newFprog->UsesDFdy = fprogA->UsesDFdy || fprogB->UsesDFdy;
745
746 /* We'll do a search and replace for instances
747 * of progB_colorFile/progB_colorIndex below...
748 */
749 progB_colorFile = PROGRAM_INPUT;
750 progB_colorIndex = FRAG_ATTRIB_COL0;
751
752 /*
753 * The fragment program may get color from a state var rather than
754 * a fragment input (vertex output) if it's constant.
755 * See the texenvprogram.c code.
756 * So, search the program's parameter list now to see if the program
757 * gets color from a state var instead of a conventional fragment
758 * input register.
759 */
760 for (i = 0; i < progB->Parameters->NumParameters; i++) {
761 struct gl_program_parameter *p = &progB->Parameters->Parameters[i];
762 if (p->Type == PROGRAM_STATE_VAR &&
763 p->StateIndexes[0] == STATE_INTERNAL &&
764 p->StateIndexes[1] == STATE_CURRENT_ATTRIB &&
765 (int) p->StateIndexes[2] == (int) VERT_ATTRIB_COLOR0) {
766 progB_inputsRead |= FRAG_BIT_COL0;
767 progB_colorFile = PROGRAM_STATE_VAR;
768 progB_colorIndex = i;
769 break;
770 }
771 }
772
773 /* Connect color outputs of fprogA to color inputs of fprogB, via a
774 * new temporary register.
775 */
776 if ((progA->OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_COLOR)) &&
777 (progB_inputsRead & FRAG_BIT_COL0)) {
778 GLint tempReg = _mesa_find_free_register(usedTemps, MAX_PROGRAM_TEMPS,
779 firstTemp);
780 if (tempReg < 0) {
781 _mesa_problem(ctx, "No free temp regs found in "
782 "_mesa_combine_programs(), using 31");
783 tempReg = 31;
784 }
785 firstTemp = tempReg + 1;
786
787 /* replace writes to result.color[0] with tempReg */
788 replace_registers(newInst, lenA,
789 PROGRAM_OUTPUT, FRAG_RESULT_COLOR,
790 PROGRAM_TEMPORARY, tempReg);
791 /* replace reads from the input color with tempReg */
792 replace_registers(newInst + lenA, lenB,
793 progB_colorFile, progB_colorIndex, /* search for */
794 PROGRAM_TEMPORARY, tempReg /* replace with */ );
795 }
796
797 /* compute combined program's InputsRead */
798 inputsB = progB_inputsRead;
799 if (progA->OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_COLOR)) {
800 inputsB &= ~(1 << FRAG_ATTRIB_COL0);
801 }
802 newProg->InputsRead = progA->InputsRead | inputsB;
803 newProg->OutputsWritten = progB->OutputsWritten;
804 newProg->SamplersUsed = progA->SamplersUsed | progB->SamplersUsed;
805 }
806 else {
807 /* vertex program */
808 assert(0); /* XXX todo */
809 }
810
811 /*
812 * Merge parameters (uniforms, constants, etc)
813 */
814 newProg->Parameters = _mesa_combine_parameter_lists(progA->Parameters,
815 progB->Parameters);
816
817 adjust_param_indexes(newInst + lenA, lenB, numParamsA);
818
819
820 return newProg;
821 }
822
823
824 /**
825 * Populate the 'used' array with flags indicating which registers (TEMPs,
826 * INPUTs, OUTPUTs, etc, are used by the given program.
827 * \param file type of register to scan for
828 * \param used returns true/false flags for in use / free
829 * \param usedSize size of the 'used' array
830 */
831 void
832 _mesa_find_used_registers(const struct gl_program *prog,
833 gl_register_file file,
834 GLboolean used[], GLuint usedSize)
835 {
836 GLuint i, j;
837
838 memset(used, 0, usedSize);
839
840 for (i = 0; i < prog->NumInstructions; i++) {
841 const struct prog_instruction *inst = prog->Instructions + i;
842 const GLuint n = _mesa_num_inst_src_regs(inst->Opcode);
843
844 if (inst->DstReg.File == file) {
845 ASSERT(inst->DstReg.Index < usedSize);
846 if(inst->DstReg.Index < usedSize)
847 used[inst->DstReg.Index] = GL_TRUE;
848 }
849
850 for (j = 0; j < n; j++) {
851 if (inst->SrcReg[j].File == file) {
852 ASSERT(inst->SrcReg[j].Index < usedSize);
853 if(inst->SrcReg[j].Index < usedSize)
854 used[inst->SrcReg[j].Index] = GL_TRUE;
855 }
856 }
857 }
858 }
859
860
861 /**
862 * Scan the given 'used' register flag array for the first entry
863 * that's >= firstReg.
864 * \param used vector of flags indicating registers in use (as returned
865 * by _mesa_find_used_registers())
866 * \param usedSize size of the 'used' array
867 * \param firstReg first register to start searching at
868 * \return index of unused register, or -1 if none.
869 */
870 GLint
871 _mesa_find_free_register(const GLboolean used[],
872 GLuint usedSize, GLuint firstReg)
873 {
874 GLuint i;
875
876 assert(firstReg < usedSize);
877
878 for (i = firstReg; i < usedSize; i++)
879 if (!used[i])
880 return i;
881
882 return -1;
883 }
884
885
886
887 /**
888 * Check if the given register index is valid (doesn't exceed implementation-
889 * dependent limits).
890 * \return GL_TRUE if OK, GL_FALSE if bad index
891 */
892 GLboolean
893 _mesa_valid_register_index(const struct gl_context *ctx,
894 gl_shader_type shaderType,
895 gl_register_file file, GLint index)
896 {
897 const struct gl_program_constants *c;
898
899 switch (shaderType) {
900 case MESA_SHADER_VERTEX:
901 c = &ctx->Const.VertexProgram;
902 break;
903 case MESA_SHADER_FRAGMENT:
904 c = &ctx->Const.FragmentProgram;
905 break;
906 case MESA_SHADER_GEOMETRY:
907 c = &ctx->Const.GeometryProgram;
908 break;
909 default:
910 _mesa_problem(ctx,
911 "unexpected shader type in _mesa_valid_register_index()");
912 return GL_FALSE;
913 }
914
915 switch (file) {
916 case PROGRAM_UNDEFINED:
917 return GL_TRUE; /* XXX or maybe false? */
918
919 case PROGRAM_TEMPORARY:
920 return index >= 0 && index < c->MaxTemps;
921
922 case PROGRAM_ENV_PARAM:
923 return index >= 0 && index < c->MaxEnvParams;
924
925 case PROGRAM_LOCAL_PARAM:
926 return index >= 0 && index < c->MaxLocalParams;
927
928 case PROGRAM_NAMED_PARAM:
929 return index >= 0 && index < c->MaxParameters;
930
931 case PROGRAM_UNIFORM:
932 case PROGRAM_STATE_VAR:
933 /* aka constant buffer */
934 return index >= 0 && index < c->MaxUniformComponents / 4;
935
936 case PROGRAM_CONSTANT:
937 /* constant buffer w/ possible relative negative addressing */
938 return (index > (int) c->MaxUniformComponents / -4 &&
939 index < c->MaxUniformComponents / 4);
940
941 case PROGRAM_INPUT:
942 if (index < 0)
943 return GL_FALSE;
944
945 switch (shaderType) {
946 case MESA_SHADER_VERTEX:
947 return index < VERT_ATTRIB_GENERIC0 + c->MaxAttribs;
948 case MESA_SHADER_FRAGMENT:
949 return index < FRAG_ATTRIB_VAR0 + ctx->Const.MaxVarying;
950 case MESA_SHADER_GEOMETRY:
951 return index < GEOM_ATTRIB_VAR0 + ctx->Const.MaxVarying;
952 default:
953 return GL_FALSE;
954 }
955
956 case PROGRAM_OUTPUT:
957 if (index < 0)
958 return GL_FALSE;
959
960 switch (shaderType) {
961 case MESA_SHADER_VERTEX:
962 return index < VERT_RESULT_VAR0 + ctx->Const.MaxVarying;
963 case MESA_SHADER_FRAGMENT:
964 return index < FRAG_RESULT_DATA0 + ctx->Const.MaxDrawBuffers;
965 case MESA_SHADER_GEOMETRY:
966 return index < GEOM_RESULT_VAR0 + ctx->Const.MaxVarying;
967 default:
968 return GL_FALSE;
969 }
970
971 case PROGRAM_ADDRESS:
972 return index >= 0 && index < c->MaxAddressRegs;
973
974 default:
975 _mesa_problem(ctx,
976 "unexpected register file in _mesa_valid_register_index()");
977 return GL_FALSE;
978 }
979 }
980
981
982
983 /**
984 * "Post-process" a GPU program. This is intended to be used for debugging.
985 * Example actions include no-op'ing instructions or changing instruction
986 * behaviour.
987 */
988 void
989 _mesa_postprocess_program(struct gl_context *ctx, struct gl_program *prog)
990 {
991 static const GLfloat white[4] = { 0.5, 0.5, 0.5, 0.5 };
992 GLuint i;
993 GLuint whiteSwizzle;
994 GLint whiteIndex = _mesa_add_unnamed_constant(prog->Parameters,
995 (gl_constant_value *) white,
996 4, &whiteSwizzle);
997
998 (void) whiteIndex;
999
1000 for (i = 0; i < prog->NumInstructions; i++) {
1001 struct prog_instruction *inst = prog->Instructions + i;
1002 const GLuint n = _mesa_num_inst_src_regs(inst->Opcode);
1003
1004 (void) n;
1005
1006 if (_mesa_is_tex_instruction(inst->Opcode)) {
1007 #if 0
1008 /* replace TEX/TXP/TXB with MOV */
1009 inst->Opcode = OPCODE_MOV;
1010 inst->DstReg.WriteMask = WRITEMASK_XYZW;
1011 inst->SrcReg[0].Swizzle = SWIZZLE_XYZW;
1012 inst->SrcReg[0].Negate = NEGATE_NONE;
1013 #endif
1014
1015 #if 0
1016 /* disable shadow texture mode */
1017 inst->TexShadow = 0;
1018 #endif
1019 }
1020
1021 if (inst->Opcode == OPCODE_TXP) {
1022 #if 0
1023 inst->Opcode = OPCODE_MOV;
1024 inst->DstReg.WriteMask = WRITEMASK_XYZW;
1025 inst->SrcReg[0].File = PROGRAM_CONSTANT;
1026 inst->SrcReg[0].Index = whiteIndex;
1027 inst->SrcReg[0].Swizzle = SWIZZLE_XYZW;
1028 inst->SrcReg[0].Negate = NEGATE_NONE;
1029 #endif
1030 #if 0
1031 inst->TexShadow = 0;
1032 #endif
1033 #if 0
1034 inst->Opcode = OPCODE_TEX;
1035 inst->TexShadow = 0;
1036 #endif
1037 }
1038
1039 }
1040 }