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