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/framebuffer.h"
35 #include "main/hash.h"
36 #include "main/macros.h"
37 #include "main/shaderobj.h"
38 #include "main/state.h"
39 #include "program.h"
40 #include "prog_cache.h"
41 #include "prog_parameter.h"
42 #include "prog_instruction.h"
43 #include "util/bitscan.h"
44 #include "util/ralloc.h"
45 #include "util/u_atomic.h"
46
47
48 /**
49 * A pointer to this dummy program is put into the hash table when
50 * glGenPrograms is called.
51 */
52 struct gl_program _mesa_DummyProgram;
53
54
55 /**
56 * Init context's vertex/fragment program state
57 */
58 void
_mesa_init_program(struct gl_context * ctx)59 _mesa_init_program(struct gl_context *ctx)
60 {
61 /*
62 * If this assertion fails, we need to increase the field
63 * size for register indexes (see INST_INDEX_BITS).
64 */
65 assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents / 4
66 <= (1 << INST_INDEX_BITS));
67 assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents / 4
68 <= (1 << INST_INDEX_BITS));
69
70 assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxTemps <= (1 << INST_INDEX_BITS));
71 assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxLocalParams <= (1 << INST_INDEX_BITS));
72 assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTemps <= (1 << INST_INDEX_BITS));
73 assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxLocalParams <= (1 << INST_INDEX_BITS));
74
75 assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents <= 4 * MAX_UNIFORMS);
76 assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents <= 4 * MAX_UNIFORMS);
77
78 assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxAddressOffset <= (1 << INST_INDEX_BITS));
79 assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxAddressOffset <= (1 << INST_INDEX_BITS));
80
81 /* If this fails, increase prog_instruction::TexSrcUnit size */
82 STATIC_ASSERT(MAX_TEXTURE_UNITS <= (1 << 5));
83
84 /* If this fails, increase prog_instruction::TexSrcTarget size */
85 STATIC_ASSERT(NUM_TEXTURE_TARGETS <= (1 << 4));
86
87 ctx->Program.ErrorPos = -1;
88 ctx->Program.ErrorString = strdup("");
89
90 ctx->VertexProgram.Enabled = GL_FALSE;
91 ctx->VertexProgram.PointSizeEnabled =
92 (ctx->API == API_OPENGLES2) ? GL_TRUE : GL_FALSE;
93 ctx->VertexProgram.TwoSideEnabled = GL_FALSE;
94 _mesa_reference_program(ctx, &ctx->VertexProgram.Current,
95 ctx->Shared->DefaultVertexProgram);
96 assert(ctx->VertexProgram.Current);
97 ctx->VertexProgram.Cache = _mesa_new_program_cache();
98
99 ctx->FragmentProgram.Enabled = GL_FALSE;
100 _mesa_reference_program(ctx, &ctx->FragmentProgram.Current,
101 ctx->Shared->DefaultFragmentProgram);
102 assert(ctx->FragmentProgram.Current);
103 ctx->FragmentProgram.Cache = _mesa_new_program_cache();
104 _mesa_reset_vertex_processing_mode(ctx);
105
106 /* XXX probably move this stuff */
107 ctx->ATIFragmentShader.Enabled = GL_FALSE;
108 ctx->ATIFragmentShader.Current = ctx->Shared->DefaultFragmentShader;
109 assert(ctx->ATIFragmentShader.Current);
110 ctx->ATIFragmentShader.Current->RefCount++;
111 }
112
113
114 /**
115 * Free a context's vertex/fragment program state
116 */
117 void
_mesa_free_program_data(struct gl_context * ctx)118 _mesa_free_program_data(struct gl_context *ctx)
119 {
120 _mesa_reference_program(ctx, &ctx->VertexProgram.Current, NULL);
121 _mesa_delete_program_cache(ctx, ctx->VertexProgram.Cache);
122 _mesa_reference_program(ctx, &ctx->FragmentProgram.Current, NULL);
123 _mesa_delete_shader_cache(ctx, ctx->FragmentProgram.Cache);
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
_mesa_update_default_objects_program(struct gl_context * ctx)143 _mesa_update_default_objects_program(struct gl_context *ctx)
144 {
145 _mesa_reference_program(ctx, &ctx->VertexProgram.Current,
146 ctx->Shared->DefaultVertexProgram);
147 assert(ctx->VertexProgram.Current);
148
149 _mesa_reference_program(ctx, &ctx->FragmentProgram.Current,
150 ctx->Shared->DefaultFragmentProgram);
151 assert(ctx->FragmentProgram.Current);
152
153 /* XXX probably move this stuff */
154 if (ctx->ATIFragmentShader.Current) {
155 ctx->ATIFragmentShader.Current->RefCount--;
156 if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
157 free(ctx->ATIFragmentShader.Current);
158 }
159 }
160 ctx->ATIFragmentShader.Current = (struct ati_fragment_shader *) ctx->Shared->DefaultFragmentShader;
161 assert(ctx->ATIFragmentShader.Current);
162 ctx->ATIFragmentShader.Current->RefCount++;
163 }
164
165
166 /**
167 * Set the vertex/fragment program error state (position and error string).
168 * This is generally called from within the parsers.
169 */
170 void
_mesa_set_program_error(struct gl_context * ctx,GLint pos,const char * string)171 _mesa_set_program_error(struct gl_context *ctx, GLint pos, const char *string)
172 {
173 ctx->Program.ErrorPos = pos;
174 free((void *) ctx->Program.ErrorString);
175 if (!string)
176 string = "";
177 ctx->Program.ErrorString = strdup(string);
178 }
179
180
181 /**
182 * Initialize a new gl_program object.
183 */
184 struct gl_program *
_mesa_init_gl_program(struct gl_program * prog,gl_shader_stage stage,GLuint id,bool is_arb_asm)185 _mesa_init_gl_program(struct gl_program *prog, gl_shader_stage stage,
186 GLuint id, bool is_arb_asm)
187 {
188 if (!prog)
189 return NULL;
190
191 memset(prog, 0, sizeof(*prog));
192 prog->Id = id;
193 prog->Target = _mesa_shader_stage_to_program(stage);
194 prog->RefCount = 1;
195 prog->Format = GL_PROGRAM_FORMAT_ASCII_ARB;
196 prog->info.stage = stage;
197 prog->info.is_arb_asm = is_arb_asm;
198
199 /* Uniforms that lack an initializer in the shader code have an initial
200 * value of zero. This includes sampler uniforms.
201 *
202 * Page 24 (page 30 of the PDF) of the GLSL 1.20 spec says:
203 *
204 * "The link time initial value is either the value of the variable's
205 * initializer, if present, or 0 if no initializer is present. Sampler
206 * types cannot have initializers."
207 *
208 * So we only initialise ARB assembly style programs.
209 */
210 if (is_arb_asm) {
211 /* default mapping from samplers to texture units */
212 for (unsigned i = 0; i < MAX_SAMPLERS; i++)
213 prog->SamplerUnits[i] = i;
214 }
215
216 return prog;
217 }
218
219
220 /**
221 * Allocate and initialize a new fragment/vertex program object but
222 * don't put it into the program hash table. Called via
223 * ctx->Driver.NewProgram. May be overridden (ie. replaced) by a
224 * device driver function to implement OO deriviation with additional
225 * types not understood by this function.
226 *
227 * \param ctx context
228 * \param id program id/number
229 * \param stage shader stage
230 * \return pointer to new program object
231 */
232 struct gl_program *
_mesa_new_program(struct gl_context * ctx,gl_shader_stage stage,GLuint id,bool is_arb_asm)233 _mesa_new_program(struct gl_context *ctx, gl_shader_stage stage, GLuint id,
234 bool is_arb_asm)
235 {
236 struct gl_program *prog = rzalloc(NULL, struct gl_program);
237
238 return _mesa_init_gl_program(prog, stage, id, is_arb_asm);
239 }
240
241
242 /**
243 * Delete a program and remove it from the hash table, ignoring the
244 * reference count.
245 * Called via ctx->Driver.DeleteProgram. May be wrapped (OO deriviation)
246 * by a device driver function.
247 */
248 void
_mesa_delete_program(struct gl_context * ctx,struct gl_program * prog)249 _mesa_delete_program(struct gl_context *ctx, struct gl_program *prog)
250 {
251 (void) ctx;
252 assert(prog);
253 assert(prog->RefCount==0);
254
255 if (prog == &_mesa_DummyProgram)
256 return;
257
258 if (prog->Parameters) {
259 _mesa_free_parameter_list(prog->Parameters);
260 }
261
262 if (prog->nir) {
263 ralloc_free(prog->nir);
264 }
265
266 if (prog->sh.BindlessSamplers) {
267 ralloc_free(prog->sh.BindlessSamplers);
268 }
269
270 if (prog->sh.BindlessImages) {
271 ralloc_free(prog->sh.BindlessImages);
272 }
273
274 if (prog->driver_cache_blob) {
275 ralloc_free(prog->driver_cache_blob);
276 }
277
278 ralloc_free(prog);
279 }
280
281
282 /**
283 * Return the gl_program object for a given ID.
284 * Basically just a wrapper for _mesa_HashLookup() to avoid a lot of
285 * casts elsewhere.
286 */
287 struct gl_program *
_mesa_lookup_program(struct gl_context * ctx,GLuint id)288 _mesa_lookup_program(struct gl_context *ctx, GLuint id)
289 {
290 if (id)
291 return (struct gl_program *) _mesa_HashLookup(ctx->Shared->Programs, id);
292 else
293 return NULL;
294 }
295
296
297 /**
298 * Reference counting for vertex/fragment programs
299 * This is normally only called from the _mesa_reference_program() macro
300 * when there's a real pointer change.
301 */
302 void
_mesa_reference_program_(struct gl_context * ctx,struct gl_program ** ptr,struct gl_program * prog)303 _mesa_reference_program_(struct gl_context *ctx,
304 struct gl_program **ptr,
305 struct gl_program *prog)
306 {
307 #ifndef NDEBUG
308 assert(ptr);
309 if (*ptr && prog) {
310 /* sanity check */
311 if ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB)
312 assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
313 else if ((*ptr)->Target == GL_FRAGMENT_PROGRAM_ARB)
314 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB ||
315 prog->Target == GL_FRAGMENT_PROGRAM_NV);
316 else if ((*ptr)->Target == GL_GEOMETRY_PROGRAM_NV)
317 assert(prog->Target == GL_GEOMETRY_PROGRAM_NV);
318 }
319 #endif
320
321 if (*ptr) {
322 struct gl_program *oldProg = *ptr;
323
324 assert(oldProg->RefCount > 0);
325
326 if (p_atomic_dec_zero(&oldProg->RefCount)) {
327 assert(ctx);
328 _mesa_reference_shader_program_data(ctx, &oldProg->sh.data, NULL);
329 ctx->Driver.DeleteProgram(ctx, oldProg);
330 }
331
332 *ptr = NULL;
333 }
334
335 assert(!*ptr);
336 if (prog) {
337 p_atomic_inc(&prog->RefCount);
338 }
339
340 *ptr = prog;
341 }
342
343
344 /**
345 * Insert 'count' NOP instructions at 'start' in the given program.
346 * Adjust branch targets accordingly.
347 */
348 GLboolean
_mesa_insert_instructions(struct gl_program * prog,GLuint start,GLuint count)349 _mesa_insert_instructions(struct gl_program *prog, GLuint start, GLuint count)
350 {
351 const GLuint origLen = prog->arb.NumInstructions;
352 const GLuint newLen = origLen + count;
353 struct prog_instruction *newInst;
354 GLuint i;
355
356 /* adjust branches */
357 for (i = 0; i < prog->arb.NumInstructions; i++) {
358 struct prog_instruction *inst = prog->arb.Instructions + i;
359 if (inst->BranchTarget > 0) {
360 if ((GLuint)inst->BranchTarget >= start) {
361 inst->BranchTarget += count;
362 }
363 }
364 }
365
366 /* Alloc storage for new instructions */
367 newInst = rzalloc_array(prog, struct prog_instruction, newLen);
368 if (!newInst) {
369 return GL_FALSE;
370 }
371
372 /* Copy 'start' instructions into new instruction buffer */
373 _mesa_copy_instructions(newInst, prog->arb.Instructions, start);
374
375 /* init the new instructions */
376 _mesa_init_instructions(newInst + start, count);
377
378 /* Copy the remaining/tail instructions to new inst buffer */
379 _mesa_copy_instructions(newInst + start + count,
380 prog->arb.Instructions + start,
381 origLen - start);
382
383 /* free old instructions */
384 ralloc_free(prog->arb.Instructions);
385
386 /* install new instructions */
387 prog->arb.Instructions = newInst;
388 prog->arb.NumInstructions = newLen;
389
390 return GL_TRUE;
391 }
392
393 /**
394 * Delete 'count' instructions at 'start' in the given program.
395 * Adjust branch targets accordingly.
396 */
397 GLboolean
_mesa_delete_instructions(struct gl_program * prog,GLuint start,GLuint count,void * mem_ctx)398 _mesa_delete_instructions(struct gl_program *prog, GLuint start, GLuint count,
399 void *mem_ctx)
400 {
401 const GLuint origLen = prog->arb.NumInstructions;
402 const GLuint newLen = origLen - count;
403 struct prog_instruction *newInst;
404 GLuint i;
405
406 /* adjust branches */
407 for (i = 0; i < prog->arb.NumInstructions; i++) {
408 struct prog_instruction *inst = prog->arb.Instructions + i;
409 if (inst->BranchTarget > 0) {
410 if (inst->BranchTarget > (GLint) start) {
411 inst->BranchTarget -= count;
412 }
413 }
414 }
415
416 /* Alloc storage for new instructions */
417 newInst = rzalloc_array(mem_ctx, struct prog_instruction, newLen);
418 if (!newInst) {
419 return GL_FALSE;
420 }
421
422 /* Copy 'start' instructions into new instruction buffer */
423 _mesa_copy_instructions(newInst, prog->arb.Instructions, start);
424
425 /* Copy the remaining/tail instructions to new inst buffer */
426 _mesa_copy_instructions(newInst + start,
427 prog->arb.Instructions + start + count,
428 newLen - start);
429
430 /* free old instructions */
431 ralloc_free(prog->arb.Instructions);
432
433 /* install new instructions */
434 prog->arb.Instructions = newInst;
435 prog->arb.NumInstructions = newLen;
436
437 return GL_TRUE;
438 }
439
440
441 /**
442 * Populate the 'used' array with flags indicating which registers (TEMPs,
443 * INPUTs, OUTPUTs, etc, are used by the given program.
444 * \param file type of register to scan for
445 * \param used returns true/false flags for in use / free
446 * \param usedSize size of the 'used' array
447 */
448 void
_mesa_find_used_registers(const struct gl_program * prog,gl_register_file file,GLboolean used[],GLuint usedSize)449 _mesa_find_used_registers(const struct gl_program *prog,
450 gl_register_file file,
451 GLboolean used[], GLuint usedSize)
452 {
453 GLuint i, j;
454
455 memset(used, 0, usedSize);
456
457 for (i = 0; i < prog->arb.NumInstructions; i++) {
458 const struct prog_instruction *inst = prog->arb.Instructions + i;
459 const GLuint n = _mesa_num_inst_src_regs(inst->Opcode);
460
461 if (inst->DstReg.File == file) {
462 assert(inst->DstReg.Index < usedSize);
463 if(inst->DstReg.Index < usedSize)
464 used[inst->DstReg.Index] = GL_TRUE;
465 }
466
467 for (j = 0; j < n; j++) {
468 if (inst->SrcReg[j].File == file) {
469 assert(inst->SrcReg[j].Index < (GLint) usedSize);
470 if (inst->SrcReg[j].Index < (GLint) usedSize)
471 used[inst->SrcReg[j].Index] = GL_TRUE;
472 }
473 }
474 }
475 }
476
477
478 /**
479 * Scan the given 'used' register flag array for the first entry
480 * that's >= firstReg.
481 * \param used vector of flags indicating registers in use (as returned
482 * by _mesa_find_used_registers())
483 * \param usedSize size of the 'used' array
484 * \param firstReg first register to start searching at
485 * \return index of unused register, or -1 if none.
486 */
487 GLint
_mesa_find_free_register(const GLboolean used[],GLuint usedSize,GLuint firstReg)488 _mesa_find_free_register(const GLboolean used[],
489 GLuint usedSize, GLuint firstReg)
490 {
491 GLuint i;
492
493 assert(firstReg < usedSize);
494
495 for (i = firstReg; i < usedSize; i++)
496 if (!used[i])
497 return i;
498
499 return -1;
500 }
501
502
503 /* Gets the minimum number of shader invocations per fragment.
504 * This function is useful to determine if we need to do per
505 * sample shading or per fragment shading.
506 */
507 GLint
_mesa_get_min_invocations_per_fragment(struct gl_context * ctx,const struct gl_program * prog)508 _mesa_get_min_invocations_per_fragment(struct gl_context *ctx,
509 const struct gl_program *prog)
510 {
511 /* From ARB_sample_shading specification:
512 * "Using gl_SampleID in a fragment shader causes the entire shader
513 * to be evaluated per-sample."
514 *
515 * "Using gl_SamplePosition in a fragment shader causes the entire
516 * shader to be evaluated per-sample."
517 *
518 * "If MULTISAMPLE or SAMPLE_SHADING_ARB is disabled, sample shading
519 * has no effect."
520 */
521 if (ctx->Multisample.Enabled) {
522 /* The ARB_gpu_shader5 specification says:
523 *
524 * "Use of the "sample" qualifier on a fragment shader input
525 * forces per-sample shading"
526 */
527 if (prog->info.fs.uses_sample_qualifier ||
528 BITSET_TEST(prog->info.system_values_read, SYSTEM_VALUE_SAMPLE_ID) ||
529 BITSET_TEST(prog->info.system_values_read, SYSTEM_VALUE_SAMPLE_POS))
530 return MAX2(_mesa_geometric_samples(ctx->DrawBuffer), 1);
531 else if (ctx->Multisample.SampleShading)
532 return MAX2(ceilf(ctx->Multisample.MinSampleShadingValue *
533 _mesa_geometric_samples(ctx->DrawBuffer)), 1);
534 else
535 return 1;
536 }
537 return 1;
538 }
539
540
541 GLbitfield
gl_external_samplers(const struct gl_program * prog)542 gl_external_samplers(const struct gl_program *prog)
543 {
544 GLbitfield external_samplers = 0;
545 GLbitfield mask = prog->SamplersUsed;
546
547 while (mask) {
548 int idx = u_bit_scan(&mask);
549 if (prog->sh.SamplerTargets[idx] == TEXTURE_EXTERNAL_INDEX)
550 external_samplers |= (1 << idx);
551 }
552
553 return external_samplers;
554 }
555
compare_state_var(const void * a1,const void * a2)556 static int compare_state_var(const void *a1, const void *a2)
557 {
558 const struct gl_program_parameter *p1 =
559 (const struct gl_program_parameter *)a1;
560 const struct gl_program_parameter *p2 =
561 (const struct gl_program_parameter *)a2;
562
563 for (unsigned i = 0; i < STATE_LENGTH; i++) {
564 if (p1->StateIndexes[i] != p2->StateIndexes[i])
565 return p1->StateIndexes[i] - p2->StateIndexes[i];
566 }
567 return 0;
568 }
569
570 void
_mesa_add_separate_state_parameters(struct gl_program * prog,struct gl_program_parameter_list * state_params)571 _mesa_add_separate_state_parameters(struct gl_program *prog,
572 struct gl_program_parameter_list *state_params)
573 {
574 unsigned num_state_params = state_params->NumParameters;
575
576 /* All state parameters should be vec4s. */
577 for (unsigned i = 0; i < num_state_params; i++) {
578 assert(state_params->Parameters[i].Type == PROGRAM_STATE_VAR);
579 assert(state_params->Parameters[i].Size == 4);
580 assert(state_params->Parameters[i].ValueOffset == i * 4);
581 }
582
583 /* Sort state parameters to facilitate better parameter merging. */
584 qsort(state_params->Parameters, num_state_params,
585 sizeof(state_params->Parameters[0]), compare_state_var);
586 unsigned *remap = malloc(num_state_params * sizeof(unsigned));
587
588 /* Add state parameters to the end of the parameter list. */
589 for (unsigned i = 0; i < num_state_params; i++) {
590 unsigned old_index = state_params->Parameters[i].ValueOffset / 4;
591
592 remap[old_index] =
593 _mesa_add_parameter(prog->Parameters, PROGRAM_STATE_VAR,
594 state_params->Parameters[i].Name,
595 state_params->Parameters[i].Size,
596 GL_NONE, NULL,
597 state_params->Parameters[i].StateIndexes,
598 state_params->Parameters[i].Padded);
599
600 prog->Parameters->StateFlags |=
601 _mesa_program_state_flags(state_params->Parameters[i].StateIndexes);
602 }
603
604 /* Fix up state parameter offsets in instructions. */
605 int num_instr = prog->arb.NumInstructions;
606 struct prog_instruction *instrs = prog->arb.Instructions;
607
608 /* Fix src indices after sorting. */
609 for (unsigned i = 0; i < num_instr; i++) {
610 struct prog_instruction *inst = instrs + i;
611 unsigned num_src = _mesa_num_inst_src_regs(inst->Opcode);
612
613 for (unsigned j = 0; j < num_src; j++) {
614 if (inst->SrcReg[j].File == PROGRAM_STATE_VAR)
615 inst->SrcReg[j].Index = remap[inst->SrcReg[j].Index];
616 }
617 }
618 free(remap);
619 }
620