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