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