mesa: Clean up nomenclature for pipeline stages.
[mesa.git] / src / mesa / program / program.c
1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 * 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/macros.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 /*
56 * If this assertion fails, we need to increase the field
57 * size for register indexes (see INST_INDEX_BITS).
58 */
59 ASSERT(ctx->Const.VertexProgram.MaxUniformComponents / 4
60 <= (1 << INST_INDEX_BITS));
61 ASSERT(ctx->Const.FragmentProgram.MaxUniformComponents / 4
62 <= (1 << INST_INDEX_BITS));
63
64 ASSERT(ctx->Const.VertexProgram.MaxTemps <= (1 << INST_INDEX_BITS));
65 ASSERT(ctx->Const.VertexProgram.MaxLocalParams <= (1 << INST_INDEX_BITS));
66 ASSERT(ctx->Const.FragmentProgram.MaxTemps <= (1 << INST_INDEX_BITS));
67 ASSERT(ctx->Const.FragmentProgram.MaxLocalParams <= (1 << INST_INDEX_BITS));
68
69 ASSERT(ctx->Const.VertexProgram.MaxUniformComponents <= 4 * MAX_UNIFORMS);
70 ASSERT(ctx->Const.FragmentProgram.MaxUniformComponents <= 4 * MAX_UNIFORMS);
71
72 ASSERT(ctx->Const.VertexProgram.MaxAddressOffset <= (1 << INST_INDEX_BITS));
73 ASSERT(ctx->Const.FragmentProgram.MaxAddressOffset <= (1 << INST_INDEX_BITS));
74
75 /* If this fails, increase prog_instruction::TexSrcUnit size */
76 STATIC_ASSERT(MAX_TEXTURE_UNITS <= (1 << 5));
77
78 /* If this fails, increase prog_instruction::TexSrcTarget size */
79 STATIC_ASSERT(NUM_TEXTURE_TARGETS <= (1 << 4));
80
81 ctx->Program.ErrorPos = -1;
82 ctx->Program.ErrorString = _mesa_strdup("");
83
84 ctx->VertexProgram.Enabled = GL_FALSE;
85 ctx->VertexProgram.PointSizeEnabled =
86 (ctx->API == API_OPENGLES2) ? GL_TRUE : GL_FALSE;
87 ctx->VertexProgram.TwoSideEnabled = GL_FALSE;
88 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current,
89 ctx->Shared->DefaultVertexProgram);
90 assert(ctx->VertexProgram.Current);
91 ctx->VertexProgram.Cache = _mesa_new_program_cache();
92
93 ctx->FragmentProgram.Enabled = GL_FALSE;
94 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
95 ctx->Shared->DefaultFragmentProgram);
96 assert(ctx->FragmentProgram.Current);
97 ctx->FragmentProgram.Cache = _mesa_new_program_cache();
98
99 ctx->GeometryProgram.Enabled = GL_FALSE;
100 /* right now by default we don't have a geometry program */
101 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current,
102 NULL);
103 ctx->GeometryProgram.Cache = _mesa_new_program_cache();
104
105 /* XXX probably move this stuff */
106 ctx->ATIFragmentShader.Enabled = GL_FALSE;
107 ctx->ATIFragmentShader.Current = ctx->Shared->DefaultFragmentShader;
108 assert(ctx->ATIFragmentShader.Current);
109 ctx->ATIFragmentShader.Current->RefCount++;
110 }
111
112
113 /**
114 * Free a context's vertex/fragment program state
115 */
116 void
117 _mesa_free_program_data(struct gl_context *ctx)
118 {
119 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
120 _mesa_delete_program_cache(ctx, ctx->VertexProgram.Cache);
121 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
122 _mesa_delete_shader_cache(ctx, ctx->FragmentProgram.Cache);
123 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current, NULL);
124 _mesa_delete_program_cache(ctx, ctx->GeometryProgram.Cache);
125
126 /* XXX probably move this stuff */
127 if (ctx->ATIFragmentShader.Current) {
128 ctx->ATIFragmentShader.Current->RefCount--;
129 if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
130 free(ctx->ATIFragmentShader.Current);
131 }
132 }
133
134 free((void *) ctx->Program.ErrorString);
135 }
136
137
138 /**
139 * Update the default program objects in the given context to reference those
140 * specified in the shared state and release those referencing the old
141 * shared state.
142 */
143 void
144 _mesa_update_default_objects_program(struct gl_context *ctx)
145 {
146 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current,
147 ctx->Shared->DefaultVertexProgram);
148 assert(ctx->VertexProgram.Current);
149
150 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
151 ctx->Shared->DefaultFragmentProgram);
152 assert(ctx->FragmentProgram.Current);
153
154 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current,
155 ctx->Shared->DefaultGeometryProgram);
156
157 /* XXX probably move this stuff */
158 if (ctx->ATIFragmentShader.Current) {
159 ctx->ATIFragmentShader.Current->RefCount--;
160 if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
161 free(ctx->ATIFragmentShader.Current);
162 }
163 }
164 ctx->ATIFragmentShader.Current = (struct ati_fragment_shader *) ctx->Shared->DefaultFragmentShader;
165 assert(ctx->ATIFragmentShader.Current);
166 ctx->ATIFragmentShader.Current->RefCount++;
167 }
168
169
170 /**
171 * Set the vertex/fragment program error state (position and error string).
172 * This is generally called from within the parsers.
173 */
174 void
175 _mesa_set_program_error(struct gl_context *ctx, GLint pos, const char *string)
176 {
177 ctx->Program.ErrorPos = pos;
178 free((void *) ctx->Program.ErrorString);
179 if (!string)
180 string = "";
181 ctx->Program.ErrorString = _mesa_strdup(string);
182 }
183
184
185 /**
186 * Find the line number and column for 'pos' within 'string'.
187 * Return a copy of the line which contains 'pos'. Free the line with
188 * free().
189 * \param string the program string
190 * \param pos the position within the string
191 * \param line returns the line number corresponding to 'pos'.
192 * \param col returns the column number corresponding to 'pos'.
193 * \return copy of the line containing 'pos'.
194 */
195 const GLubyte *
196 _mesa_find_line_column(const GLubyte *string, const GLubyte *pos,
197 GLint *line, GLint *col)
198 {
199 const GLubyte *lineStart = string;
200 const GLubyte *p = string;
201 GLubyte *s;
202 int len;
203
204 *line = 1;
205
206 while (p != pos) {
207 if (*p == (GLubyte) '\n') {
208 (*line)++;
209 lineStart = p + 1;
210 }
211 p++;
212 }
213
214 *col = (pos - lineStart) + 1;
215
216 /* return copy of this line */
217 while (*p != 0 && *p != '\n')
218 p++;
219 len = p - lineStart;
220 s = malloc(len + 1);
221 memcpy(s, lineStart, len);
222 s[len] = 0;
223
224 return s;
225 }
226
227
228 /**
229 * Initialize a new vertex/fragment program object.
230 */
231 static struct gl_program *
232 _mesa_init_program_struct( struct gl_context *ctx, struct gl_program *prog,
233 GLenum target, GLuint id)
234 {
235 (void) ctx;
236 if (prog) {
237 GLuint i;
238 memset(prog, 0, sizeof(*prog));
239 prog->Id = id;
240 prog->Target = target;
241 prog->RefCount = 1;
242 prog->Format = GL_PROGRAM_FORMAT_ASCII_ARB;
243
244 /* default mapping from samplers to texture units */
245 for (i = 0; i < MAX_SAMPLERS; i++)
246 prog->SamplerUnits[i] = i;
247 }
248
249 return prog;
250 }
251
252
253 /**
254 * Initialize a new fragment program object.
255 */
256 struct gl_program *
257 _mesa_init_fragment_program( struct gl_context *ctx, struct gl_fragment_program *prog,
258 GLenum target, GLuint id)
259 {
260 if (prog)
261 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
262 else
263 return NULL;
264 }
265
266
267 /**
268 * Initialize a new vertex program object.
269 */
270 struct gl_program *
271 _mesa_init_vertex_program( struct gl_context *ctx, struct gl_vertex_program *prog,
272 GLenum target, GLuint id)
273 {
274 if (prog)
275 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
276 else
277 return NULL;
278 }
279
280
281 /**
282 * Initialize a new geometry program object.
283 */
284 struct gl_program *
285 _mesa_init_geometry_program( struct gl_context *ctx, struct gl_geometry_program *prog,
286 GLenum target, GLuint id)
287 {
288 if (prog)
289 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
290 else
291 return NULL;
292 }
293
294
295 /**
296 * Allocate and initialize a new fragment/vertex program object but
297 * don't put it into the program hash table. Called via
298 * ctx->Driver.NewProgram. May be overridden (ie. replaced) by a
299 * device driver function to implement OO deriviation with additional
300 * types not understood by this function.
301 *
302 * \param ctx context
303 * \param id program id/number
304 * \param target program target/type
305 * \return pointer to new program object
306 */
307 struct gl_program *
308 _mesa_new_program(struct gl_context *ctx, GLenum target, GLuint id)
309 {
310 struct gl_program *prog;
311 switch (target) {
312 case GL_VERTEX_PROGRAM_ARB: /* == GL_VERTEX_PROGRAM_NV */
313 prog = _mesa_init_vertex_program(ctx, CALLOC_STRUCT(gl_vertex_program),
314 target, id );
315 break;
316 case GL_FRAGMENT_PROGRAM_NV:
317 case GL_FRAGMENT_PROGRAM_ARB:
318 prog =_mesa_init_fragment_program(ctx,
319 CALLOC_STRUCT(gl_fragment_program),
320 target, id );
321 break;
322 case MESA_GEOMETRY_PROGRAM:
323 prog = _mesa_init_geometry_program(ctx,
324 CALLOC_STRUCT(gl_geometry_program),
325 target, id);
326 break;
327 default:
328 _mesa_problem(ctx, "bad target in _mesa_new_program");
329 prog = NULL;
330 }
331 return prog;
332 }
333
334
335 /**
336 * Delete a program and remove it from the hash table, ignoring the
337 * reference count.
338 * Called via ctx->Driver.DeleteProgram. May be wrapped (OO deriviation)
339 * by a device driver function.
340 */
341 void
342 _mesa_delete_program(struct gl_context *ctx, struct gl_program *prog)
343 {
344 (void) ctx;
345 ASSERT(prog);
346 ASSERT(prog->RefCount==0);
347
348 if (prog == &_mesa_DummyProgram)
349 return;
350
351 free(prog->String);
352 free(prog->LocalParams);
353
354 if (prog->Instructions) {
355 _mesa_free_instructions(prog->Instructions, prog->NumInstructions);
356 }
357 if (prog->Parameters) {
358 _mesa_free_parameter_list(prog->Parameters);
359 }
360
361 free(prog);
362 }
363
364
365 /**
366 * Return the gl_program object for a given ID.
367 * Basically just a wrapper for _mesa_HashLookup() to avoid a lot of
368 * casts elsewhere.
369 */
370 struct gl_program *
371 _mesa_lookup_program(struct gl_context *ctx, GLuint id)
372 {
373 if (id)
374 return (struct gl_program *) _mesa_HashLookup(ctx->Shared->Programs, id);
375 else
376 return NULL;
377 }
378
379
380 /**
381 * Reference counting for vertex/fragment programs
382 * This is normally only called from the _mesa_reference_program() macro
383 * when there's a real pointer change.
384 */
385 void
386 _mesa_reference_program_(struct gl_context *ctx,
387 struct gl_program **ptr,
388 struct gl_program *prog)
389 {
390 #ifndef NDEBUG
391 assert(ptr);
392 if (*ptr && prog) {
393 /* sanity check */
394 if ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB)
395 ASSERT(prog->Target == GL_VERTEX_PROGRAM_ARB);
396 else if ((*ptr)->Target == GL_FRAGMENT_PROGRAM_ARB)
397 ASSERT(prog->Target == GL_FRAGMENT_PROGRAM_ARB ||
398 prog->Target == GL_FRAGMENT_PROGRAM_NV);
399 else if ((*ptr)->Target == MESA_GEOMETRY_PROGRAM)
400 ASSERT(prog->Target == MESA_GEOMETRY_PROGRAM);
401 }
402 #endif
403
404 if (*ptr) {
405 GLboolean deleteFlag;
406
407 /*_glthread_LOCK_MUTEX((*ptr)->Mutex);*/
408 #if 0
409 printf("Program %p ID=%u Target=%s Refcount-- to %d\n",
410 *ptr, (*ptr)->Id,
411 ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB ? "VP" :
412 ((*ptr)->Target == MESA_GEOMETRY_PROGRAM ? "GP" : "FP")),
413 (*ptr)->RefCount - 1);
414 #endif
415 ASSERT((*ptr)->RefCount > 0);
416 (*ptr)->RefCount--;
417
418 deleteFlag = ((*ptr)->RefCount == 0);
419 /*_glthread_UNLOCK_MUTEX((*ptr)->Mutex);*/
420
421 if (deleteFlag) {
422 ASSERT(ctx);
423 ctx->Driver.DeleteProgram(ctx, *ptr);
424 }
425
426 *ptr = NULL;
427 }
428
429 assert(!*ptr);
430 if (prog) {
431 /*_glthread_LOCK_MUTEX(prog->Mutex);*/
432 prog->RefCount++;
433 #if 0
434 printf("Program %p ID=%u Target=%s Refcount++ to %d\n",
435 prog, prog->Id,
436 (prog->Target == GL_VERTEX_PROGRAM_ARB ? "VP" :
437 (prog->Target == MESA_GEOMETRY_PROGRAM ? "GP" : "FP")),
438 prog->RefCount);
439 #endif
440 /*_glthread_UNLOCK_MUTEX(prog->Mutex);*/
441 }
442
443 *ptr = prog;
444 }
445
446
447 /**
448 * Return a copy of a program.
449 * XXX Problem here if the program object is actually OO-derivation
450 * made by a device driver.
451 */
452 struct gl_program *
453 _mesa_clone_program(struct gl_context *ctx, const struct gl_program *prog)
454 {
455 struct gl_program *clone;
456
457 clone = ctx->Driver.NewProgram(ctx, prog->Target, prog->Id);
458 if (!clone)
459 return NULL;
460
461 assert(clone->Target == prog->Target);
462 assert(clone->RefCount == 1);
463
464 clone->String = (GLubyte *) _mesa_strdup((char *) prog->String);
465 clone->Format = prog->Format;
466 clone->Instructions = _mesa_alloc_instructions(prog->NumInstructions);
467 if (!clone->Instructions) {
468 _mesa_reference_program(ctx, &clone, NULL);
469 return NULL;
470 }
471 _mesa_copy_instructions(clone->Instructions, prog->Instructions,
472 prog->NumInstructions);
473 clone->InputsRead = prog->InputsRead;
474 clone->OutputsWritten = prog->OutputsWritten;
475 clone->SamplersUsed = prog->SamplersUsed;
476 clone->ShadowSamplers = prog->ShadowSamplers;
477 memcpy(clone->TexturesUsed, prog->TexturesUsed, sizeof(prog->TexturesUsed));
478
479 if (prog->Parameters)
480 clone->Parameters = _mesa_clone_parameter_list(prog->Parameters);
481 if (prog->LocalParams) {
482 clone->LocalParams = malloc(MAX_PROGRAM_LOCAL_PARAMS *
483 sizeof(float[4]));
484 if (!clone->LocalParams) {
485 _mesa_reference_program(ctx, &clone, NULL);
486 return NULL;
487 }
488 memcpy(clone->LocalParams, prog->LocalParams,
489 MAX_PROGRAM_LOCAL_PARAMS * sizeof(float[4]));
490 }
491 clone->IndirectRegisterFiles = prog->IndirectRegisterFiles;
492 clone->NumInstructions = prog->NumInstructions;
493 clone->NumTemporaries = prog->NumTemporaries;
494 clone->NumParameters = prog->NumParameters;
495 clone->NumAttributes = prog->NumAttributes;
496 clone->NumAddressRegs = prog->NumAddressRegs;
497 clone->NumNativeInstructions = prog->NumNativeInstructions;
498 clone->NumNativeTemporaries = prog->NumNativeTemporaries;
499 clone->NumNativeParameters = prog->NumNativeParameters;
500 clone->NumNativeAttributes = prog->NumNativeAttributes;
501 clone->NumNativeAddressRegs = prog->NumNativeAddressRegs;
502 clone->NumAluInstructions = prog->NumAluInstructions;
503 clone->NumTexInstructions = prog->NumTexInstructions;
504 clone->NumTexIndirections = prog->NumTexIndirections;
505 clone->NumNativeAluInstructions = prog->NumNativeAluInstructions;
506 clone->NumNativeTexInstructions = prog->NumNativeTexInstructions;
507 clone->NumNativeTexIndirections = prog->NumNativeTexIndirections;
508
509 switch (prog->Target) {
510 case GL_VERTEX_PROGRAM_ARB:
511 {
512 const struct gl_vertex_program *vp = gl_vertex_program_const(prog);
513 struct gl_vertex_program *vpc = gl_vertex_program(clone);
514 vpc->IsPositionInvariant = vp->IsPositionInvariant;
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 GLbitfield64 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 GLbitfield64 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 = VARYING_SLOT_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 |= VARYING_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 & VARYING_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 << VARYING_SLOT_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 < (GLint) usedSize);
853 if (inst->SrcReg[j].Index < (GLint) 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_stage 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 < (GLint) c->MaxTemps;
921
922 case PROGRAM_UNIFORM:
923 case PROGRAM_STATE_VAR:
924 /* aka constant buffer */
925 return index >= 0 && index < (GLint) c->MaxUniformComponents / 4;
926
927 case PROGRAM_CONSTANT:
928 /* constant buffer w/ possible relative negative addressing */
929 return (index > (int) c->MaxUniformComponents / -4 &&
930 index < (int) c->MaxUniformComponents / 4);
931
932 case PROGRAM_INPUT:
933 if (index < 0)
934 return GL_FALSE;
935
936 switch (shaderType) {
937 case MESA_SHADER_VERTEX:
938 return index < VERT_ATTRIB_GENERIC0 + (GLint) c->MaxAttribs;
939 case MESA_SHADER_FRAGMENT:
940 return index < VARYING_SLOT_VAR0 + (GLint) ctx->Const.MaxVarying;
941 case MESA_SHADER_GEOMETRY:
942 return index < VARYING_SLOT_VAR0 + (GLint) ctx->Const.MaxVarying;
943 default:
944 return GL_FALSE;
945 }
946
947 case PROGRAM_OUTPUT:
948 if (index < 0)
949 return GL_FALSE;
950
951 switch (shaderType) {
952 case MESA_SHADER_VERTEX:
953 return index < VARYING_SLOT_VAR0 + (GLint) ctx->Const.MaxVarying;
954 case MESA_SHADER_FRAGMENT:
955 return index < FRAG_RESULT_DATA0 + (GLint) ctx->Const.MaxDrawBuffers;
956 case MESA_SHADER_GEOMETRY:
957 return index < VARYING_SLOT_VAR0 + (GLint) ctx->Const.MaxVarying;
958 default:
959 return GL_FALSE;
960 }
961
962 case PROGRAM_ADDRESS:
963 return index >= 0 && index < (GLint) c->MaxAddressRegs;
964
965 default:
966 _mesa_problem(ctx,
967 "unexpected register file in _mesa_valid_register_index()");
968 return GL_FALSE;
969 }
970 }
971
972
973
974 /**
975 * "Post-process" a GPU program. This is intended to be used for debugging.
976 * Example actions include no-op'ing instructions or changing instruction
977 * behaviour.
978 */
979 void
980 _mesa_postprocess_program(struct gl_context *ctx, struct gl_program *prog)
981 {
982 static const GLfloat white[4] = { 0.5, 0.5, 0.5, 0.5 };
983 GLuint i;
984 GLuint whiteSwizzle;
985 GLint whiteIndex = _mesa_add_unnamed_constant(prog->Parameters,
986 (gl_constant_value *) white,
987 4, &whiteSwizzle);
988
989 (void) whiteIndex;
990
991 for (i = 0; i < prog->NumInstructions; i++) {
992 struct prog_instruction *inst = prog->Instructions + i;
993 const GLuint n = _mesa_num_inst_src_regs(inst->Opcode);
994
995 (void) n;
996
997 if (_mesa_is_tex_instruction(inst->Opcode)) {
998 #if 0
999 /* replace TEX/TXP/TXB with MOV */
1000 inst->Opcode = OPCODE_MOV;
1001 inst->DstReg.WriteMask = WRITEMASK_XYZW;
1002 inst->SrcReg[0].Swizzle = SWIZZLE_XYZW;
1003 inst->SrcReg[0].Negate = NEGATE_NONE;
1004 #endif
1005
1006 #if 0
1007 /* disable shadow texture mode */
1008 inst->TexShadow = 0;
1009 #endif
1010 }
1011
1012 if (inst->Opcode == OPCODE_TXP) {
1013 #if 0
1014 inst->Opcode = OPCODE_MOV;
1015 inst->DstReg.WriteMask = WRITEMASK_XYZW;
1016 inst->SrcReg[0].File = PROGRAM_CONSTANT;
1017 inst->SrcReg[0].Index = whiteIndex;
1018 inst->SrcReg[0].Swizzle = SWIZZLE_XYZW;
1019 inst->SrcReg[0].Negate = NEGATE_NONE;
1020 #endif
1021 #if 0
1022 inst->TexShadow = 0;
1023 #endif
1024 #if 0
1025 inst->Opcode = OPCODE_TEX;
1026 inst->TexShadow = 0;
1027 #endif
1028 }
1029
1030 }
1031 }
1032
1033 /* Gets the minimum number of shader invocations per fragment.
1034 * This function is useful to determine if we need to do per
1035 * sample shading or per fragment shading.
1036 */
1037 GLint
1038 _mesa_get_min_invocations_per_fragment(struct gl_context *ctx,
1039 const struct gl_fragment_program *prog)
1040 {
1041 /* From ARB_sample_shading specification:
1042 * "Using gl_SampleID in a fragment shader causes the entire shader
1043 * to be evaluated per-sample."
1044 *
1045 * "Using gl_SamplePosition in a fragment shader causes the entire
1046 * shader to be evaluated per-sample."
1047 *
1048 * "If MULTISAMPLE or SAMPLE_SHADING_ARB is disabled, sample shading
1049 * has no effect."
1050 */
1051 if (ctx->Multisample.Enabled) {
1052 /* The ARB_gpu_shader5 specification says:
1053 *
1054 * "Use of the "sample" qualifier on a fragment shader input
1055 * forces per-sample shading"
1056 */
1057 if (prog->IsSample)
1058 return MAX2(ctx->DrawBuffer->Visual.samples, 1);
1059
1060 if (prog->Base.SystemValuesRead & (SYSTEM_BIT_SAMPLE_ID |
1061 SYSTEM_BIT_SAMPLE_POS))
1062 return MAX2(ctx->DrawBuffer->Visual.samples, 1);
1063 else if (ctx->Multisample.SampleShading)
1064 return MAX2(ceil(ctx->Multisample.MinSampleShadingValue *
1065 ctx->DrawBuffer->Visual.samples), 1);
1066 else
1067 return 1;
1068 }
1069 return 1;
1070 }