aboutsummaryrefslogtreecommitdiff
path: root/mesalib/src
diff options
context:
space:
mode:
Diffstat (limited to 'mesalib/src')
-rw-r--r--mesalib/src/glsl/ir_reader.cpp1995
-rw-r--r--mesalib/src/glsl/link_functions.cpp528
-rw-r--r--mesalib/src/glsl/linker.cpp3348
-rw-r--r--mesalib/src/mesa/main/teximage.c33
-rw-r--r--mesalib/src/mesa/main/texparam.c137
-rw-r--r--mesalib/src/mesa/program/ir_to_mesa.cpp6424
-rw-r--r--mesalib/src/mesa/state_tracker/st_cb_texture.c4043
-rw-r--r--mesalib/src/mesa/state_tracker/st_extensions.c6
-rw-r--r--mesalib/src/mesa/state_tracker/st_mesa_to_tgsi.c2496
9 files changed, 9514 insertions, 9496 deletions
diff --git a/mesalib/src/glsl/ir_reader.cpp b/mesalib/src/glsl/ir_reader.cpp
index 5b1eccb46..b78aa051b 100644
--- a/mesalib/src/glsl/ir_reader.cpp
+++ b/mesalib/src/glsl/ir_reader.cpp
@@ -1,996 +1,999 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice (including the next
- * paragraph) shall be included in all copies or substantial portions of the
- * Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-#include "ir_reader.h"
-#include "glsl_parser_extras.h"
-#include "glsl_types.h"
-#include "s_expression.h"
-
-const static bool debug = false;
-
-class ir_reader {
-public:
- ir_reader(_mesa_glsl_parse_state *);
-
- void read(exec_list *instructions, const char *src, bool scan_for_protos);
-
-private:
- void *mem_ctx;
- _mesa_glsl_parse_state *state;
-
- void ir_read_error(s_expression *, const char *fmt, ...);
-
- const glsl_type *read_type(s_expression *);
-
- void scan_for_prototypes(exec_list *, s_expression *);
- ir_function *read_function(s_expression *, bool skip_body);
- void read_function_sig(ir_function *, s_expression *, bool skip_body);
-
- void read_instructions(exec_list *, s_expression *, ir_loop *);
- ir_instruction *read_instruction(s_expression *, ir_loop *);
- ir_variable *read_declaration(s_expression *);
- ir_if *read_if(s_expression *, ir_loop *);
- ir_loop *read_loop(s_expression *);
- ir_return *read_return(s_expression *);
- ir_rvalue *read_rvalue(s_expression *);
- ir_assignment *read_assignment(s_expression *);
- ir_expression *read_expression(s_expression *);
- ir_call *read_call(s_expression *);
- ir_swizzle *read_swizzle(s_expression *);
- ir_constant *read_constant(s_expression *);
- ir_texture *read_texture(s_expression *);
-
- ir_dereference *read_dereference(s_expression *);
-};
-
-ir_reader::ir_reader(_mesa_glsl_parse_state *state) : state(state)
-{
- this->mem_ctx = state;
-}
-
-void
-_mesa_glsl_read_ir(_mesa_glsl_parse_state *state, exec_list *instructions,
- const char *src, bool scan_for_protos)
-{
- ir_reader r(state);
- r.read(instructions, src, scan_for_protos);
-}
-
-void
-ir_reader::read(exec_list *instructions, const char *src, bool scan_for_protos)
-{
- s_expression *expr = s_expression::read_expression(mem_ctx, src);
- if (expr == NULL) {
- ir_read_error(NULL, "couldn't parse S-Expression.");
- return;
- }
-
- if (scan_for_protos) {
- scan_for_prototypes(instructions, expr);
- if (state->error)
- return;
- }
-
- read_instructions(instructions, expr, NULL);
- talloc_free(expr);
-
- if (debug)
- validate_ir_tree(instructions);
-}
-
-void
-ir_reader::ir_read_error(s_expression *expr, const char *fmt, ...)
-{
- va_list ap;
-
- state->error = true;
-
- if (state->current_function != NULL)
- state->info_log = talloc_asprintf_append(state->info_log,
- "In function %s:\n",
- state->current_function->function_name());
- state->info_log = talloc_strdup_append(state->info_log, "error: ");
-
- va_start(ap, fmt);
- state->info_log = talloc_vasprintf_append(state->info_log, fmt, ap);
- va_end(ap);
- state->info_log = talloc_strdup_append(state->info_log, "\n");
-
- if (expr != NULL) {
- state->info_log = talloc_strdup_append(state->info_log,
- "...in this context:\n ");
- expr->print();
- state->info_log = talloc_strdup_append(state->info_log, "\n\n");
- }
-}
-
-const glsl_type *
-ir_reader::read_type(s_expression *expr)
-{
- s_expression *s_base_type;
- s_int *s_size;
-
- s_pattern pat[] = { "array", s_base_type, s_size };
- if (MATCH(expr, pat)) {
- const glsl_type *base_type = read_type(s_base_type);
- if (base_type == NULL) {
- ir_read_error(NULL, "when reading base type of array type");
- return NULL;
- }
-
- return glsl_type::get_array_instance(base_type, s_size->value());
- }
-
- s_symbol *type_sym = SX_AS_SYMBOL(expr);
- if (type_sym == NULL) {
- ir_read_error(expr, "expected <type>");
- return NULL;
- }
-
- const glsl_type *type = state->symbols->get_type(type_sym->value());
- if (type == NULL)
- ir_read_error(expr, "invalid type: %s", type_sym->value());
-
- return type;
-}
-
-
-void
-ir_reader::scan_for_prototypes(exec_list *instructions, s_expression *expr)
-{
- s_list *list = SX_AS_LIST(expr);
- if (list == NULL) {
- ir_read_error(expr, "Expected (<instruction> ...); found an atom.");
- return;
- }
-
- foreach_iter(exec_list_iterator, it, list->subexpressions) {
- s_list *sub = SX_AS_LIST(it.get());
- if (sub == NULL)
- continue; // not a (function ...); ignore it.
-
- s_symbol *tag = SX_AS_SYMBOL(sub->subexpressions.get_head());
- if (tag == NULL || strcmp(tag->value(), "function") != 0)
- continue; // not a (function ...); ignore it.
-
- ir_function *f = read_function(sub, true);
- if (f == NULL)
- return;
- instructions->push_tail(f);
- }
-}
-
-ir_function *
-ir_reader::read_function(s_expression *expr, bool skip_body)
-{
- bool added = false;
- s_symbol *name;
-
- s_pattern pat[] = { "function", name };
- if (!PARTIAL_MATCH(expr, pat)) {
- ir_read_error(expr, "Expected (function <name> (signature ...) ...)");
- return NULL;
- }
-
- ir_function *f = state->symbols->get_function(name->value());
- if (f == NULL) {
- f = new(mem_ctx) ir_function(name->value());
- added = state->symbols->add_function(f);
- assert(added);
- }
-
- exec_list_iterator it = ((s_list *) expr)->subexpressions.iterator();
- it.next(); // skip "function" tag
- it.next(); // skip function name
- for (/* nothing */; it.has_next(); it.next()) {
- s_expression *s_sig = (s_expression *) it.get();
- read_function_sig(f, s_sig, skip_body);
- }
- return added ? f : NULL;
-}
-
-void
-ir_reader::read_function_sig(ir_function *f, s_expression *expr, bool skip_body)
-{
- s_expression *type_expr;
- s_list *paramlist;
- s_list *body_list;
-
- s_pattern pat[] = { "signature", type_expr, paramlist, body_list };
- if (!MATCH(expr, pat)) {
- ir_read_error(expr, "Expected (signature <type> (parameters ...) "
- "(<instruction> ...))");
- return;
- }
-
- const glsl_type *return_type = read_type(type_expr);
- if (return_type == NULL)
- return;
-
- s_symbol *paramtag = SX_AS_SYMBOL(paramlist->subexpressions.get_head());
- if (paramtag == NULL || strcmp(paramtag->value(), "parameters") != 0) {
- ir_read_error(paramlist, "Expected (parameters ...)");
- return;
- }
-
- // Read the parameters list into a temporary place.
- exec_list hir_parameters;
- state->symbols->push_scope();
-
- exec_list_iterator it = paramlist->subexpressions.iterator();
- for (it.next() /* skip "parameters" */; it.has_next(); it.next()) {
- ir_variable *var = read_declaration((s_expression *) it.get());
- if (var == NULL)
- return;
-
- hir_parameters.push_tail(var);
- }
-
- ir_function_signature *sig = f->exact_matching_signature(&hir_parameters);
- if (sig == NULL && skip_body) {
- /* If scanning for prototypes, generate a new signature. */
- sig = new(mem_ctx) ir_function_signature(return_type);
- sig->is_builtin = true;
- f->add_signature(sig);
- } else if (sig != NULL) {
- const char *badvar = sig->qualifiers_match(&hir_parameters);
- if (badvar != NULL) {
- ir_read_error(expr, "function `%s' parameter `%s' qualifiers "
- "don't match prototype", f->name, badvar);
- return;
- }
-
- if (sig->return_type != return_type) {
- ir_read_error(expr, "function `%s' return type doesn't "
- "match prototype", f->name);
- return;
- }
- } else {
- /* No prototype for this body exists - skip it. */
- state->symbols->pop_scope();
- return;
- }
- assert(sig != NULL);
-
- sig->replace_parameters(&hir_parameters);
-
- if (!skip_body && !body_list->subexpressions.is_empty()) {
- if (sig->is_defined) {
- ir_read_error(expr, "function %s redefined", f->name);
- return;
- }
- state->current_function = sig;
- read_instructions(&sig->body, body_list, NULL);
- state->current_function = NULL;
- sig->is_defined = true;
- }
-
- state->symbols->pop_scope();
-}
-
-void
-ir_reader::read_instructions(exec_list *instructions, s_expression *expr,
- ir_loop *loop_ctx)
-{
- // Read in a list of instructions
- s_list *list = SX_AS_LIST(expr);
- if (list == NULL) {
- ir_read_error(expr, "Expected (<instruction> ...); found an atom.");
- return;
- }
-
- foreach_iter(exec_list_iterator, it, list->subexpressions) {
- s_expression *sub = (s_expression*) it.get();
- ir_instruction *ir = read_instruction(sub, loop_ctx);
- if (ir != NULL) {
- /* Global variable declarations should be moved to the top, before
- * any functions that might use them. Functions are added to the
- * instruction stream when scanning for prototypes, so without this
- * hack, they always appear before variable declarations.
- */
- if (state->current_function == NULL && ir->as_variable() != NULL)
- instructions->push_head(ir);
- else
- instructions->push_tail(ir);
- }
- }
-}
-
-
-ir_instruction *
-ir_reader::read_instruction(s_expression *expr, ir_loop *loop_ctx)
-{
- s_symbol *symbol = SX_AS_SYMBOL(expr);
- if (symbol != NULL) {
- if (strcmp(symbol->value(), "break") == 0 && loop_ctx != NULL)
- return new(mem_ctx) ir_loop_jump(ir_loop_jump::jump_break);
- if (strcmp(symbol->value(), "continue") == 0 && loop_ctx != NULL)
- return new(mem_ctx) ir_loop_jump(ir_loop_jump::jump_continue);
- }
-
- s_list *list = SX_AS_LIST(expr);
- if (list == NULL || list->subexpressions.is_empty()) {
- ir_read_error(expr, "Invalid instruction.\n");
- return NULL;
- }
-
- s_symbol *tag = SX_AS_SYMBOL(list->subexpressions.get_head());
- if (tag == NULL) {
- ir_read_error(expr, "expected instruction tag");
- return NULL;
- }
-
- ir_instruction *inst = NULL;
- if (strcmp(tag->value(), "declare") == 0) {
- inst = read_declaration(list);
- } else if (strcmp(tag->value(), "assign") == 0) {
- inst = read_assignment(list);
- } else if (strcmp(tag->value(), "if") == 0) {
- inst = read_if(list, loop_ctx);
- } else if (strcmp(tag->value(), "loop") == 0) {
- inst = read_loop(list);
- } else if (strcmp(tag->value(), "return") == 0) {
- inst = read_return(list);
- } else if (strcmp(tag->value(), "function") == 0) {
- inst = read_function(list, false);
- } else {
- inst = read_rvalue(list);
- if (inst == NULL)
- ir_read_error(NULL, "when reading instruction");
- }
- return inst;
-}
-
-ir_variable *
-ir_reader::read_declaration(s_expression *expr)
-{
- s_list *s_quals;
- s_expression *s_type;
- s_symbol *s_name;
-
- s_pattern pat[] = { "declare", s_quals, s_type, s_name };
- if (!MATCH(expr, pat)) {
- ir_read_error(expr, "expected (declare (<qualifiers>) <type> <name>)");
- return NULL;
- }
-
- const glsl_type *type = read_type(s_type);
- if (type == NULL)
- return NULL;
-
- ir_variable *var = new(mem_ctx) ir_variable(type, s_name->value(),
- ir_var_auto);
-
- foreach_iter(exec_list_iterator, it, s_quals->subexpressions) {
- s_symbol *qualifier = SX_AS_SYMBOL(it.get());
- if (qualifier == NULL) {
- ir_read_error(expr, "qualifier list must contain only symbols");
- return NULL;
- }
-
- // FINISHME: Check for duplicate/conflicting qualifiers.
- if (strcmp(qualifier->value(), "centroid") == 0) {
- var->centroid = 1;
- } else if (strcmp(qualifier->value(), "invariant") == 0) {
- var->invariant = 1;
- } else if (strcmp(qualifier->value(), "uniform") == 0) {
- var->mode = ir_var_uniform;
- } else if (strcmp(qualifier->value(), "auto") == 0) {
- var->mode = ir_var_auto;
- } else if (strcmp(qualifier->value(), "in") == 0) {
- var->mode = ir_var_in;
- } else if (strcmp(qualifier->value(), "out") == 0) {
- var->mode = ir_var_out;
- } else if (strcmp(qualifier->value(), "inout") == 0) {
- var->mode = ir_var_inout;
- } else if (strcmp(qualifier->value(), "smooth") == 0) {
- var->interpolation = ir_var_smooth;
- } else if (strcmp(qualifier->value(), "flat") == 0) {
- var->interpolation = ir_var_flat;
- } else if (strcmp(qualifier->value(), "noperspective") == 0) {
- var->interpolation = ir_var_noperspective;
- } else {
- ir_read_error(expr, "unknown qualifier: %s", qualifier->value());
- return NULL;
- }
- }
-
- // Add the variable to the symbol table
- state->symbols->add_variable(var);
-
- return var;
-}
-
-
-ir_if *
-ir_reader::read_if(s_expression *expr, ir_loop *loop_ctx)
-{
- s_expression *s_cond;
- s_expression *s_then;
- s_expression *s_else;
-
- s_pattern pat[] = { "if", s_cond, s_then, s_else };
- if (!MATCH(expr, pat)) {
- ir_read_error(expr, "expected (if <condition> (<then>...) (<else>...))");
- return NULL;
- }
-
- ir_rvalue *condition = read_rvalue(s_cond);
- if (condition == NULL) {
- ir_read_error(NULL, "when reading condition of (if ...)");
- return NULL;
- }
-
- ir_if *iff = new(mem_ctx) ir_if(condition);
-
- read_instructions(&iff->then_instructions, s_then, loop_ctx);
- read_instructions(&iff->else_instructions, s_else, loop_ctx);
- if (state->error) {
- delete iff;
- iff = NULL;
- }
- return iff;
-}
-
-
-ir_loop *
-ir_reader::read_loop(s_expression *expr)
-{
- s_expression *s_counter, *s_from, *s_to, *s_inc, *s_body;
-
- s_pattern pat[] = { "loop", s_counter, s_from, s_to, s_inc, s_body };
- if (!MATCH(expr, pat)) {
- ir_read_error(expr, "expected (loop <counter> <from> <to> "
- "<increment> <body>)");
- return NULL;
- }
-
- // FINISHME: actually read the count/from/to fields.
-
- ir_loop *loop = new(mem_ctx) ir_loop;
- read_instructions(&loop->body_instructions, s_body, loop);
- if (state->error) {
- delete loop;
- loop = NULL;
- }
- return loop;
-}
-
-
-ir_return *
-ir_reader::read_return(s_expression *expr)
-{
- s_expression *s_retval;
-
- s_pattern pat[] = { "return", s_retval};
- if (!MATCH(expr, pat)) {
- ir_read_error(expr, "expected (return <rvalue>)");
- return NULL;
- }
-
- ir_rvalue *retval = read_rvalue(s_retval);
- if (retval == NULL) {
- ir_read_error(NULL, "when reading return value");
- return NULL;
- }
-
- return new(mem_ctx) ir_return(retval);
-}
-
-
-ir_rvalue *
-ir_reader::read_rvalue(s_expression *expr)
-{
- s_list *list = SX_AS_LIST(expr);
- if (list == NULL || list->subexpressions.is_empty())
- return NULL;
-
- s_symbol *tag = SX_AS_SYMBOL(list->subexpressions.get_head());
- if (tag == NULL) {
- ir_read_error(expr, "expected rvalue tag");
- return NULL;
- }
-
- ir_rvalue *rvalue = read_dereference(list);
- if (rvalue != NULL || state->error)
- return rvalue;
- else if (strcmp(tag->value(), "swiz") == 0) {
- rvalue = read_swizzle(list);
- } else if (strcmp(tag->value(), "expression") == 0) {
- rvalue = read_expression(list);
- } else if (strcmp(tag->value(), "call") == 0) {
- rvalue = read_call(list);
- } else if (strcmp(tag->value(), "constant") == 0) {
- rvalue = read_constant(list);
- } else {
- rvalue = read_texture(list);
- if (rvalue == NULL && !state->error)
- ir_read_error(expr, "unrecognized rvalue tag: %s", tag->value());
- }
-
- return rvalue;
-}
-
-ir_assignment *
-ir_reader::read_assignment(s_expression *expr)
-{
- s_expression *cond_expr = NULL;
- s_expression *lhs_expr, *rhs_expr;
- s_list *mask_list;
-
- s_pattern pat4[] = { "assign", mask_list, lhs_expr, rhs_expr };
- s_pattern pat5[] = { "assign", cond_expr, mask_list, lhs_expr, rhs_expr };
- if (!MATCH(expr, pat4) && !MATCH(expr, pat5)) {
- ir_read_error(expr, "expected (assign [<condition>] (<write mask>) "
- "<lhs> <rhs>)");
- return NULL;
- }
-
- ir_rvalue *condition = NULL;
- if (cond_expr != NULL) {
- condition = read_rvalue(cond_expr);
- if (condition == NULL) {
- ir_read_error(NULL, "when reading condition of assignment");
- return NULL;
- }
- }
-
- unsigned mask = 0;
-
- s_symbol *mask_symbol;
- s_pattern mask_pat[] = { mask_symbol };
- if (MATCH(mask_list, mask_pat)) {
- const char *mask_str = mask_symbol->value();
- unsigned mask_length = strlen(mask_str);
- if (mask_length > 4) {
- ir_read_error(expr, "invalid write mask: %s", mask_str);
- return NULL;
- }
-
- const unsigned idx_map[] = { 3, 0, 1, 2 }; /* w=bit 3, x=0, y=1, z=2 */
-
- for (unsigned i = 0; i < mask_length; i++) {
- if (mask_str[i] < 'w' || mask_str[i] > 'z') {
- ir_read_error(expr, "write mask contains invalid character: %c",
- mask_str[i]);
- return NULL;
- }
- mask |= 1 << idx_map[mask_str[i] - 'w'];
- }
- } else if (!mask_list->subexpressions.is_empty()) {
- ir_read_error(mask_list, "expected () or (<write mask>)");
- return NULL;
- }
-
- ir_dereference *lhs = read_dereference(lhs_expr);
- if (lhs == NULL) {
- ir_read_error(NULL, "when reading left-hand side of assignment");
- return NULL;
- }
-
- ir_rvalue *rhs = read_rvalue(rhs_expr);
- if (rhs == NULL) {
- ir_read_error(NULL, "when reading right-hand side of assignment");
- return NULL;
- }
-
- if (mask == 0 && (lhs->type->is_vector() || lhs->type->is_scalar())) {
- ir_read_error(expr, "non-zero write mask required.");
- return NULL;
- }
-
- return new(mem_ctx) ir_assignment(lhs, rhs, condition, mask);
-}
-
-ir_call *
-ir_reader::read_call(s_expression *expr)
-{
- s_symbol *name;
- s_list *params;
-
- s_pattern pat[] = { "call", name, params };
- if (!MATCH(expr, pat)) {
- ir_read_error(expr, "expected (call <name> (<param> ...))");
- return NULL;
- }
-
- exec_list parameters;
-
- foreach_iter(exec_list_iterator, it, params->subexpressions) {
- s_expression *expr = (s_expression*) it.get();
- ir_rvalue *param = read_rvalue(expr);
- if (param == NULL) {
- ir_read_error(expr, "when reading parameter to function call");
- return NULL;
- }
- parameters.push_tail(param);
- }
-
- ir_function *f = state->symbols->get_function(name->value());
- if (f == NULL) {
- ir_read_error(expr, "found call to undefined function %s",
- name->value());
- return NULL;
- }
-
- ir_function_signature *callee = f->matching_signature(&parameters);
- if (callee == NULL) {
- ir_read_error(expr, "couldn't find matching signature for function "
- "%s", name->value());
- return NULL;
- }
-
- return new(mem_ctx) ir_call(callee, &parameters);
-}
-
-ir_expression *
-ir_reader::read_expression(s_expression *expr)
-{
- s_expression *s_type;
- s_symbol *s_op;
- s_expression *s_arg1;
-
- s_pattern pat[] = { "expression", s_type, s_op, s_arg1 };
- if (!PARTIAL_MATCH(expr, pat)) {
- ir_read_error(expr, "expected (expression <type> <operator> "
- "<operand> [<operand>])");
- return NULL;
- }
- s_expression *s_arg2 = (s_expression *) s_arg1->next; // may be tail sentinel
-
- const glsl_type *type = read_type(s_type);
- if (type == NULL)
- return NULL;
-
- /* Read the operator */
- ir_expression_operation op = ir_expression::get_operator(s_op->value());
- if (op == (ir_expression_operation) -1) {
- ir_read_error(expr, "invalid operator: %s", s_op->value());
- return NULL;
- }
-
- unsigned num_operands = ir_expression::get_num_operands(op);
- if (num_operands == 1 && !s_arg1->next->is_tail_sentinel()) {
- ir_read_error(expr, "expected (expression <type> %s <operand>)",
- s_op->value());
- return NULL;
- }
-
- ir_rvalue *arg1 = read_rvalue(s_arg1);
- ir_rvalue *arg2 = NULL;
- if (arg1 == NULL) {
- ir_read_error(NULL, "when reading first operand of %s", s_op->value());
- return NULL;
- }
-
- if (num_operands == 2) {
- if (s_arg2->is_tail_sentinel() || !s_arg2->next->is_tail_sentinel()) {
- ir_read_error(expr, "expected (expression <type> %s <operand> "
- "<operand>)", s_op->value());
- return NULL;
- }
- arg2 = read_rvalue(s_arg2);
- if (arg2 == NULL) {
- ir_read_error(NULL, "when reading second operand of %s",
- s_op->value());
- return NULL;
- }
- }
-
- return new(mem_ctx) ir_expression(op, type, arg1, arg2);
-}
-
-ir_swizzle *
-ir_reader::read_swizzle(s_expression *expr)
-{
- s_symbol *swiz;
- s_expression *sub;
-
- s_pattern pat[] = { "swiz", swiz, sub };
- if (!MATCH(expr, pat)) {
- ir_read_error(expr, "expected (swiz <swizzle> <rvalue>)");
- return NULL;
- }
-
- if (strlen(swiz->value()) > 4) {
- ir_read_error(expr, "expected a valid swizzle; found %s", swiz->value());
- return NULL;
- }
-
- ir_rvalue *rvalue = read_rvalue(sub);
- if (rvalue == NULL)
- return NULL;
-
- ir_swizzle *ir = ir_swizzle::create(rvalue, swiz->value(),
- rvalue->type->vector_elements);
- if (ir == NULL)
- ir_read_error(expr, "invalid swizzle");
-
- return ir;
-}
-
-ir_constant *
-ir_reader::read_constant(s_expression *expr)
-{
- s_expression *type_expr;
- s_list *values;
-
- s_pattern pat[] = { "constant", type_expr, values };
- if (!MATCH(expr, pat)) {
- ir_read_error(expr, "expected (constant <type> (...))");
- return NULL;
- }
-
- const glsl_type *type = read_type(type_expr);
- if (type == NULL)
- return NULL;
-
- if (values == NULL) {
- ir_read_error(expr, "expected (constant <type> (...))");
- return NULL;
- }
-
- if (type->is_array()) {
- unsigned elements_supplied = 0;
- exec_list elements;
- foreach_iter(exec_list_iterator, it, values->subexpressions) {
- s_expression *elt = (s_expression *) it.get();
- ir_constant *ir_elt = read_constant(elt);
- if (ir_elt == NULL)
- return NULL;
- elements.push_tail(ir_elt);
- elements_supplied++;
- }
-
- if (elements_supplied != type->length) {
- ir_read_error(values, "expected exactly %u array elements, "
- "given %u", type->length, elements_supplied);
- return NULL;
- }
- return new(mem_ctx) ir_constant(type, &elements);
- }
-
- const glsl_type *const base_type = type->get_base_type();
-
- ir_constant_data data = { { 0 } };
-
- // Read in list of values (at most 16).
- int k = 0;
- foreach_iter(exec_list_iterator, it, values->subexpressions) {
- if (k >= 16) {
- ir_read_error(values, "expected at most 16 numbers");
- return NULL;
- }
-
- s_expression *expr = (s_expression*) it.get();
-
- if (base_type->base_type == GLSL_TYPE_FLOAT) {
- s_number *value = SX_AS_NUMBER(expr);
- if (value == NULL) {
- ir_read_error(values, "expected numbers");
- return NULL;
- }
- data.f[k] = value->fvalue();
- } else {
- s_int *value = SX_AS_INT(expr);
- if (value == NULL) {
- ir_read_error(values, "expected integers");
- return NULL;
- }
-
- switch (base_type->base_type) {
- case GLSL_TYPE_UINT: {
- data.u[k] = value->value();
- break;
- }
- case GLSL_TYPE_INT: {
- data.i[k] = value->value();
- break;
- }
- case GLSL_TYPE_BOOL: {
- data.b[k] = value->value();
- break;
- }
- default:
- ir_read_error(values, "unsupported constant type");
- return NULL;
- }
- }
- ++k;
- }
-
- return new(mem_ctx) ir_constant(type, &data);
-}
-
-ir_dereference *
-ir_reader::read_dereference(s_expression *expr)
-{
- s_symbol *s_var;
- s_expression *s_subject;
- s_expression *s_index;
- s_symbol *s_field;
-
- s_pattern var_pat[] = { "var_ref", s_var };
- s_pattern array_pat[] = { "array_ref", s_subject, s_index };
- s_pattern record_pat[] = { "record_ref", s_subject, s_field };
-
- if (MATCH(expr, var_pat)) {
- ir_variable *var = state->symbols->get_variable(s_var->value());
- if (var == NULL) {
- ir_read_error(expr, "undeclared variable: %s", s_var->value());
- return NULL;
- }
- return new(mem_ctx) ir_dereference_variable(var);
- } else if (MATCH(expr, array_pat)) {
- ir_rvalue *subject = read_rvalue(s_subject);
- if (subject == NULL) {
- ir_read_error(NULL, "when reading the subject of an array_ref");
- return NULL;
- }
-
- ir_rvalue *idx = read_rvalue(s_index);
- if (subject == NULL) {
- ir_read_error(NULL, "when reading the index of an array_ref");
- return NULL;
- }
- return new(mem_ctx) ir_dereference_array(subject, idx);
- } else if (MATCH(expr, record_pat)) {
- ir_rvalue *subject = read_rvalue(s_subject);
- if (subject == NULL) {
- ir_read_error(NULL, "when reading the subject of a record_ref");
- return NULL;
- }
- return new(mem_ctx) ir_dereference_record(subject, s_field->value());
- }
- return NULL;
-}
-
-ir_texture *
-ir_reader::read_texture(s_expression *expr)
-{
- s_symbol *tag = NULL;
- s_expression *s_sampler = NULL;
- s_expression *s_coord = NULL;
- s_list *s_offset = NULL;
- s_expression *s_proj = NULL;
- s_list *s_shadow = NULL;
- s_expression *s_lod = NULL;
-
- ir_texture_opcode op;
-
- s_pattern tex_pattern[] =
- { "tex", s_sampler, s_coord, s_offset, s_proj, s_shadow };
- s_pattern txf_pattern[] =
- { "txf", s_sampler, s_coord, s_offset, s_lod };
- s_pattern other_pattern[] =
- { tag, s_sampler, s_coord, s_offset, s_proj, s_shadow, s_lod };
-
- if (MATCH(expr, tex_pattern)) {
- op = ir_tex;
- } else if (MATCH(expr, txf_pattern)) {
- op = ir_txf;
- } else if (MATCH(expr, other_pattern)) {
- op = ir_texture::get_opcode(tag->value());
- if (op == -1)
- return NULL;
- }
-
- ir_texture *tex = new(mem_ctx) ir_texture(op);
-
- // Read sampler (must be a deref)
- ir_dereference *sampler = read_dereference(s_sampler);
- if (sampler == NULL) {
- ir_read_error(NULL, "when reading sampler in (%s ...)",
- tex->opcode_string());
- return NULL;
- }
- tex->set_sampler(sampler);
-
- // Read coordinate (any rvalue)
- tex->coordinate = read_rvalue(s_coord);
- if (tex->coordinate == NULL) {
- ir_read_error(NULL, "when reading coordinate in (%s ...)",
- tex->opcode_string());
- return NULL;
- }
-
- // Read texel offset, i.e. (0 0 0)
- s_int *offset_x;
- s_int *offset_y;
- s_int *offset_z;
- s_pattern offset_pat[] = { offset_x, offset_y, offset_z };
- if (!MATCH(s_offset, offset_pat)) {
- ir_read_error(s_offset, "expected (<int> <int> <int>)");
- return NULL;
- }
- tex->offsets[0] = offset_x->value();
- tex->offsets[1] = offset_y->value();
- tex->offsets[2] = offset_z->value();
-
- if (op != ir_txf) {
- s_int *proj_as_int = SX_AS_INT(s_proj);
- if (proj_as_int && proj_as_int->value() == 1) {
- tex->projector = NULL;
- } else {
- tex->projector = read_rvalue(s_proj);
- if (tex->projector == NULL) {
- ir_read_error(NULL, "when reading projective divide in (%s ..)",
- tex->opcode_string());
- return NULL;
- }
- }
-
- if (s_shadow->subexpressions.is_empty()) {
- tex->shadow_comparitor = NULL;
- } else {
- tex->shadow_comparitor = read_rvalue(s_shadow);
- if (tex->shadow_comparitor == NULL) {
- ir_read_error(NULL, "when reading shadow comparitor in (%s ..)",
- tex->opcode_string());
- return NULL;
- }
- }
- }
-
- switch (op) {
- case ir_txb:
- tex->lod_info.bias = read_rvalue(s_lod);
- if (tex->lod_info.bias == NULL) {
- ir_read_error(NULL, "when reading LOD bias in (txb ...)");
- return NULL;
- }
- break;
- case ir_txl:
- case ir_txf:
- tex->lod_info.lod = read_rvalue(s_lod);
- if (tex->lod_info.lod == NULL) {
- ir_read_error(NULL, "when reading LOD in (%s ...)",
- tex->opcode_string());
- return NULL;
- }
- break;
- case ir_txd: {
- s_expression *s_dx, *s_dy;
- s_pattern dxdy_pat[] = { s_dx, s_dy };
- if (!MATCH(s_lod, dxdy_pat)) {
- ir_read_error(s_lod, "expected (dPdx dPdy) in (txd ...)");
- return NULL;
- }
- tex->lod_info.grad.dPdx = read_rvalue(s_dx);
- if (tex->lod_info.grad.dPdx == NULL) {
- ir_read_error(NULL, "when reading dPdx in (txd ...)");
- return NULL;
- }
- tex->lod_info.grad.dPdy = read_rvalue(s_dy);
- if (tex->lod_info.grad.dPdy == NULL) {
- ir_read_error(NULL, "when reading dPdy in (txd ...)");
- return NULL;
- }
- break;
- }
- default:
- // tex doesn't have any extra parameters.
- break;
- };
- return tex;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#include "ir_reader.h"
+#include "glsl_parser_extras.h"
+#include "glsl_types.h"
+#include "s_expression.h"
+
+const static bool debug = false;
+
+class ir_reader {
+public:
+ ir_reader(_mesa_glsl_parse_state *);
+
+ void read(exec_list *instructions, const char *src, bool scan_for_protos);
+
+private:
+ void *mem_ctx;
+ _mesa_glsl_parse_state *state;
+
+ void ir_read_error(s_expression *, const char *fmt, ...);
+
+ const glsl_type *read_type(s_expression *);
+
+ void scan_for_prototypes(exec_list *, s_expression *);
+ ir_function *read_function(s_expression *, bool skip_body);
+ void read_function_sig(ir_function *, s_expression *, bool skip_body);
+
+ void read_instructions(exec_list *, s_expression *, ir_loop *);
+ ir_instruction *read_instruction(s_expression *, ir_loop *);
+ ir_variable *read_declaration(s_expression *);
+ ir_if *read_if(s_expression *, ir_loop *);
+ ir_loop *read_loop(s_expression *);
+ ir_return *read_return(s_expression *);
+ ir_rvalue *read_rvalue(s_expression *);
+ ir_assignment *read_assignment(s_expression *);
+ ir_expression *read_expression(s_expression *);
+ ir_call *read_call(s_expression *);
+ ir_swizzle *read_swizzle(s_expression *);
+ ir_constant *read_constant(s_expression *);
+ ir_texture *read_texture(s_expression *);
+
+ ir_dereference *read_dereference(s_expression *);
+};
+
+ir_reader::ir_reader(_mesa_glsl_parse_state *state) : state(state)
+{
+ this->mem_ctx = state;
+}
+
+void
+_mesa_glsl_read_ir(_mesa_glsl_parse_state *state, exec_list *instructions,
+ const char *src, bool scan_for_protos)
+{
+ ir_reader r(state);
+ r.read(instructions, src, scan_for_protos);
+}
+
+void
+ir_reader::read(exec_list *instructions, const char *src, bool scan_for_protos)
+{
+ s_expression *expr = s_expression::read_expression(mem_ctx, src);
+ if (expr == NULL) {
+ ir_read_error(NULL, "couldn't parse S-Expression.");
+ return;
+ }
+
+ if (scan_for_protos) {
+ scan_for_prototypes(instructions, expr);
+ if (state->error)
+ return;
+ }
+
+ read_instructions(instructions, expr, NULL);
+ talloc_free(expr);
+
+ if (debug)
+ validate_ir_tree(instructions);
+}
+
+void
+ir_reader::ir_read_error(s_expression *expr, const char *fmt, ...)
+{
+ va_list ap;
+
+ state->error = true;
+
+ if (state->current_function != NULL)
+ state->info_log = talloc_asprintf_append(state->info_log,
+ "In function %s:\n",
+ state->current_function->function_name());
+ state->info_log = talloc_strdup_append(state->info_log, "error: ");
+
+ va_start(ap, fmt);
+ state->info_log = talloc_vasprintf_append(state->info_log, fmt, ap);
+ va_end(ap);
+ state->info_log = talloc_strdup_append(state->info_log, "\n");
+
+ if (expr != NULL) {
+ state->info_log = talloc_strdup_append(state->info_log,
+ "...in this context:\n ");
+ expr->print();
+ state->info_log = talloc_strdup_append(state->info_log, "\n\n");
+ }
+}
+
+const glsl_type *
+ir_reader::read_type(s_expression *expr)
+{
+ s_expression *s_base_type;
+ s_int *s_size;
+
+ s_pattern pat[] = { "array", s_base_type, s_size };
+ if (MATCH(expr, pat)) {
+ const glsl_type *base_type = read_type(s_base_type);
+ if (base_type == NULL) {
+ ir_read_error(NULL, "when reading base type of array type");
+ return NULL;
+ }
+
+ return glsl_type::get_array_instance(base_type, s_size->value());
+ }
+
+ s_symbol *type_sym = SX_AS_SYMBOL(expr);
+ if (type_sym == NULL) {
+ ir_read_error(expr, "expected <type>");
+ return NULL;
+ }
+
+ const glsl_type *type = state->symbols->get_type(type_sym->value());
+ if (type == NULL)
+ ir_read_error(expr, "invalid type: %s", type_sym->value());
+
+ return type;
+}
+
+
+void
+ir_reader::scan_for_prototypes(exec_list *instructions, s_expression *expr)
+{
+ s_list *list = SX_AS_LIST(expr);
+ if (list == NULL) {
+ ir_read_error(expr, "Expected (<instruction> ...); found an atom.");
+ return;
+ }
+
+ foreach_iter(exec_list_iterator, it, list->subexpressions) {
+ s_list *sub = SX_AS_LIST(it.get());
+ if (sub == NULL)
+ continue; // not a (function ...); ignore it.
+
+ s_symbol *tag = SX_AS_SYMBOL(sub->subexpressions.get_head());
+ if (tag == NULL || strcmp(tag->value(), "function") != 0)
+ continue; // not a (function ...); ignore it.
+
+ ir_function *f = read_function(sub, true);
+ if (f == NULL)
+ return;
+ instructions->push_tail(f);
+ }
+}
+
+ir_function *
+ir_reader::read_function(s_expression *expr, bool skip_body)
+{
+ bool added = false;
+ s_symbol *name;
+
+ s_pattern pat[] = { "function", name };
+ if (!PARTIAL_MATCH(expr, pat)) {
+ ir_read_error(expr, "Expected (function <name> (signature ...) ...)");
+ return NULL;
+ }
+
+ ir_function *f = state->symbols->get_function(name->value());
+ if (f == NULL) {
+ f = new(mem_ctx) ir_function(name->value());
+ added = state->symbols->add_function(f);
+ assert(added);
+ }
+
+ exec_list_iterator it = ((s_list *) expr)->subexpressions.iterator();
+ it.next(); // skip "function" tag
+ it.next(); // skip function name
+ for (/* nothing */; it.has_next(); it.next()) {
+ s_expression *s_sig = (s_expression *) it.get();
+ read_function_sig(f, s_sig, skip_body);
+ }
+ return added ? f : NULL;
+}
+
+void
+ir_reader::read_function_sig(ir_function *f, s_expression *expr, bool skip_body)
+{
+ s_expression *type_expr;
+ s_list *paramlist;
+ s_list *body_list;
+
+ s_pattern pat[] = { "signature", type_expr, paramlist, body_list };
+ if (!MATCH(expr, pat)) {
+ ir_read_error(expr, "Expected (signature <type> (parameters ...) "
+ "(<instruction> ...))");
+ return;
+ }
+
+ const glsl_type *return_type = read_type(type_expr);
+ if (return_type == NULL)
+ return;
+
+ s_symbol *paramtag = SX_AS_SYMBOL(paramlist->subexpressions.get_head());
+ if (paramtag == NULL || strcmp(paramtag->value(), "parameters") != 0) {
+ ir_read_error(paramlist, "Expected (parameters ...)");
+ return;
+ }
+
+ // Read the parameters list into a temporary place.
+ exec_list hir_parameters;
+ state->symbols->push_scope();
+
+ exec_list_iterator it = paramlist->subexpressions.iterator();
+ for (it.next() /* skip "parameters" */; it.has_next(); it.next()) {
+ ir_variable *var = read_declaration((s_expression *) it.get());
+ if (var == NULL)
+ return;
+
+ hir_parameters.push_tail(var);
+ }
+
+ ir_function_signature *sig = f->exact_matching_signature(&hir_parameters);
+ if (sig == NULL && skip_body) {
+ /* If scanning for prototypes, generate a new signature. */
+ sig = new(mem_ctx) ir_function_signature(return_type);
+ sig->is_builtin = true;
+ f->add_signature(sig);
+ } else if (sig != NULL) {
+ const char *badvar = sig->qualifiers_match(&hir_parameters);
+ if (badvar != NULL) {
+ ir_read_error(expr, "function `%s' parameter `%s' qualifiers "
+ "don't match prototype", f->name, badvar);
+ return;
+ }
+
+ if (sig->return_type != return_type) {
+ ir_read_error(expr, "function `%s' return type doesn't "
+ "match prototype", f->name);
+ return;
+ }
+ } else {
+ /* No prototype for this body exists - skip it. */
+ state->symbols->pop_scope();
+ return;
+ }
+ assert(sig != NULL);
+
+ sig->replace_parameters(&hir_parameters);
+
+ if (!skip_body && !body_list->subexpressions.is_empty()) {
+ if (sig->is_defined) {
+ ir_read_error(expr, "function %s redefined", f->name);
+ return;
+ }
+ state->current_function = sig;
+ read_instructions(&sig->body, body_list, NULL);
+ state->current_function = NULL;
+ sig->is_defined = true;
+ }
+
+ state->symbols->pop_scope();
+}
+
+void
+ir_reader::read_instructions(exec_list *instructions, s_expression *expr,
+ ir_loop *loop_ctx)
+{
+ // Read in a list of instructions
+ s_list *list = SX_AS_LIST(expr);
+ if (list == NULL) {
+ ir_read_error(expr, "Expected (<instruction> ...); found an atom.");
+ return;
+ }
+
+ foreach_iter(exec_list_iterator, it, list->subexpressions) {
+ s_expression *sub = (s_expression*) it.get();
+ ir_instruction *ir = read_instruction(sub, loop_ctx);
+ if (ir != NULL) {
+ /* Global variable declarations should be moved to the top, before
+ * any functions that might use them. Functions are added to the
+ * instruction stream when scanning for prototypes, so without this
+ * hack, they always appear before variable declarations.
+ */
+ if (state->current_function == NULL && ir->as_variable() != NULL)
+ instructions->push_head(ir);
+ else
+ instructions->push_tail(ir);
+ }
+ }
+}
+
+
+ir_instruction *
+ir_reader::read_instruction(s_expression *expr, ir_loop *loop_ctx)
+{
+ s_symbol *symbol = SX_AS_SYMBOL(expr);
+ if (symbol != NULL) {
+ if (strcmp(symbol->value(), "break") == 0 && loop_ctx != NULL)
+ return new(mem_ctx) ir_loop_jump(ir_loop_jump::jump_break);
+ if (strcmp(symbol->value(), "continue") == 0 && loop_ctx != NULL)
+ return new(mem_ctx) ir_loop_jump(ir_loop_jump::jump_continue);
+ }
+
+ s_list *list = SX_AS_LIST(expr);
+ if (list == NULL || list->subexpressions.is_empty()) {
+ ir_read_error(expr, "Invalid instruction.\n");
+ return NULL;
+ }
+
+ s_symbol *tag = SX_AS_SYMBOL(list->subexpressions.get_head());
+ if (tag == NULL) {
+ ir_read_error(expr, "expected instruction tag");
+ return NULL;
+ }
+
+ ir_instruction *inst = NULL;
+ if (strcmp(tag->value(), "declare") == 0) {
+ inst = read_declaration(list);
+ } else if (strcmp(tag->value(), "assign") == 0) {
+ inst = read_assignment(list);
+ } else if (strcmp(tag->value(), "if") == 0) {
+ inst = read_if(list, loop_ctx);
+ } else if (strcmp(tag->value(), "loop") == 0) {
+ inst = read_loop(list);
+ } else if (strcmp(tag->value(), "return") == 0) {
+ inst = read_return(list);
+ } else if (strcmp(tag->value(), "function") == 0) {
+ inst = read_function(list, false);
+ } else {
+ inst = read_rvalue(list);
+ if (inst == NULL)
+ ir_read_error(NULL, "when reading instruction");
+ }
+ return inst;
+}
+
+ir_variable *
+ir_reader::read_declaration(s_expression *expr)
+{
+ s_list *s_quals;
+ s_expression *s_type;
+ s_symbol *s_name;
+
+ s_pattern pat[] = { "declare", s_quals, s_type, s_name };
+ if (!MATCH(expr, pat)) {
+ ir_read_error(expr, "expected (declare (<qualifiers>) <type> <name>)");
+ return NULL;
+ }
+
+ const glsl_type *type = read_type(s_type);
+ if (type == NULL)
+ return NULL;
+
+ ir_variable *var = new(mem_ctx) ir_variable(type, s_name->value(),
+ ir_var_auto);
+
+ foreach_iter(exec_list_iterator, it, s_quals->subexpressions) {
+ s_symbol *qualifier = SX_AS_SYMBOL(it.get());
+ if (qualifier == NULL) {
+ ir_read_error(expr, "qualifier list must contain only symbols");
+ return NULL;
+ }
+
+ // FINISHME: Check for duplicate/conflicting qualifiers.
+ if (strcmp(qualifier->value(), "centroid") == 0) {
+ var->centroid = 1;
+ } else if (strcmp(qualifier->value(), "invariant") == 0) {
+ var->invariant = 1;
+ } else if (strcmp(qualifier->value(), "uniform") == 0) {
+ var->mode = ir_var_uniform;
+ } else if (strcmp(qualifier->value(), "auto") == 0) {
+ var->mode = ir_var_auto;
+ } else if (strcmp(qualifier->value(), "in") == 0) {
+ var->mode = ir_var_in;
+ } else if (strcmp(qualifier->value(), "out") == 0) {
+ var->mode = ir_var_out;
+ } else if (strcmp(qualifier->value(), "inout") == 0) {
+ var->mode = ir_var_inout;
+ } else if (strcmp(qualifier->value(), "smooth") == 0) {
+ var->interpolation = ir_var_smooth;
+ } else if (strcmp(qualifier->value(), "flat") == 0) {
+ var->interpolation = ir_var_flat;
+ } else if (strcmp(qualifier->value(), "noperspective") == 0) {
+ var->interpolation = ir_var_noperspective;
+ } else {
+ ir_read_error(expr, "unknown qualifier: %s", qualifier->value());
+ return NULL;
+ }
+ }
+
+ // Add the variable to the symbol table
+ state->symbols->add_variable(var);
+
+ return var;
+}
+
+
+ir_if *
+ir_reader::read_if(s_expression *expr, ir_loop *loop_ctx)
+{
+ s_expression *s_cond;
+ s_expression *s_then;
+ s_expression *s_else;
+
+ s_pattern pat[] = { "if", s_cond, s_then, s_else };
+ if (!MATCH(expr, pat)) {
+ ir_read_error(expr, "expected (if <condition> (<then>...) (<else>...))");
+ return NULL;
+ }
+
+ ir_rvalue *condition = read_rvalue(s_cond);
+ if (condition == NULL) {
+ ir_read_error(NULL, "when reading condition of (if ...)");
+ return NULL;
+ }
+
+ ir_if *iff = new(mem_ctx) ir_if(condition);
+
+ read_instructions(&iff->then_instructions, s_then, loop_ctx);
+ read_instructions(&iff->else_instructions, s_else, loop_ctx);
+ if (state->error) {
+ delete iff;
+ iff = NULL;
+ }
+ return iff;
+}
+
+
+ir_loop *
+ir_reader::read_loop(s_expression *expr)
+{
+ s_expression *s_counter, *s_from, *s_to, *s_inc, *s_body;
+
+ s_pattern pat[] = { "loop", s_counter, s_from, s_to, s_inc, s_body };
+ if (!MATCH(expr, pat)) {
+ ir_read_error(expr, "expected (loop <counter> <from> <to> "
+ "<increment> <body>)");
+ return NULL;
+ }
+
+ // FINISHME: actually read the count/from/to fields.
+
+ ir_loop *loop = new(mem_ctx) ir_loop;
+ read_instructions(&loop->body_instructions, s_body, loop);
+ if (state->error) {
+ delete loop;
+ loop = NULL;
+ }
+ return loop;
+}
+
+
+ir_return *
+ir_reader::read_return(s_expression *expr)
+{
+ s_expression *s_retval;
+
+ s_pattern pat[] = { "return", s_retval};
+ if (!MATCH(expr, pat)) {
+ ir_read_error(expr, "expected (return <rvalue>)");
+ return NULL;
+ }
+
+ ir_rvalue *retval = read_rvalue(s_retval);
+ if (retval == NULL) {
+ ir_read_error(NULL, "when reading return value");
+ return NULL;
+ }
+
+ return new(mem_ctx) ir_return(retval);
+}
+
+
+ir_rvalue *
+ir_reader::read_rvalue(s_expression *expr)
+{
+ s_list *list = SX_AS_LIST(expr);
+ if (list == NULL || list->subexpressions.is_empty())
+ return NULL;
+
+ s_symbol *tag = SX_AS_SYMBOL(list->subexpressions.get_head());
+ if (tag == NULL) {
+ ir_read_error(expr, "expected rvalue tag");
+ return NULL;
+ }
+
+ ir_rvalue *rvalue = read_dereference(list);
+ if (rvalue != NULL || state->error)
+ return rvalue;
+ else if (strcmp(tag->value(), "swiz") == 0) {
+ rvalue = read_swizzle(list);
+ } else if (strcmp(tag->value(), "expression") == 0) {
+ rvalue = read_expression(list);
+ } else if (strcmp(tag->value(), "call") == 0) {
+ rvalue = read_call(list);
+ } else if (strcmp(tag->value(), "constant") == 0) {
+ rvalue = read_constant(list);
+ } else {
+ rvalue = read_texture(list);
+ if (rvalue == NULL && !state->error)
+ ir_read_error(expr, "unrecognized rvalue tag: %s", tag->value());
+ }
+
+ return rvalue;
+}
+
+ir_assignment *
+ir_reader::read_assignment(s_expression *expr)
+{
+ s_expression *cond_expr = NULL;
+ s_expression *lhs_expr, *rhs_expr;
+ s_list *mask_list;
+
+ s_pattern pat4[] = { "assign", mask_list, lhs_expr, rhs_expr };
+ s_pattern pat5[] = { "assign", cond_expr, mask_list, lhs_expr, rhs_expr };
+ if (!MATCH(expr, pat4) && !MATCH(expr, pat5)) {
+ ir_read_error(expr, "expected (assign [<condition>] (<write mask>) "
+ "<lhs> <rhs>)");
+ return NULL;
+ }
+
+ ir_rvalue *condition = NULL;
+ if (cond_expr != NULL) {
+ condition = read_rvalue(cond_expr);
+ if (condition == NULL) {
+ ir_read_error(NULL, "when reading condition of assignment");
+ return NULL;
+ }
+ }
+
+ unsigned mask = 0;
+
+ s_symbol *mask_symbol;
+ s_pattern mask_pat[] = { mask_symbol };
+ if (MATCH(mask_list, mask_pat)) {
+ const char *mask_str = mask_symbol->value();
+ unsigned mask_length = strlen(mask_str);
+ if (mask_length > 4) {
+ ir_read_error(expr, "invalid write mask: %s", mask_str);
+ return NULL;
+ }
+
+ const unsigned idx_map[] = { 3, 0, 1, 2 }; /* w=bit 3, x=0, y=1, z=2 */
+
+ for (unsigned i = 0; i < mask_length; i++) {
+ if (mask_str[i] < 'w' || mask_str[i] > 'z') {
+ ir_read_error(expr, "write mask contains invalid character: %c",
+ mask_str[i]);
+ return NULL;
+ }
+ mask |= 1 << idx_map[mask_str[i] - 'w'];
+ }
+ } else if (!mask_list->subexpressions.is_empty()) {
+ ir_read_error(mask_list, "expected () or (<write mask>)");
+ return NULL;
+ }
+
+ ir_dereference *lhs = read_dereference(lhs_expr);
+ if (lhs == NULL) {
+ ir_read_error(NULL, "when reading left-hand side of assignment");
+ return NULL;
+ }
+
+ ir_rvalue *rhs = read_rvalue(rhs_expr);
+ if (rhs == NULL) {
+ ir_read_error(NULL, "when reading right-hand side of assignment");
+ return NULL;
+ }
+
+ if (mask == 0 && (lhs->type->is_vector() || lhs->type->is_scalar())) {
+ ir_read_error(expr, "non-zero write mask required.");
+ return NULL;
+ }
+
+ return new(mem_ctx) ir_assignment(lhs, rhs, condition, mask);
+}
+
+ir_call *
+ir_reader::read_call(s_expression *expr)
+{
+ s_symbol *name;
+ s_list *params;
+
+ s_pattern pat[] = { "call", name, params };
+ if (!MATCH(expr, pat)) {
+ ir_read_error(expr, "expected (call <name> (<param> ...))");
+ return NULL;
+ }
+
+ exec_list parameters;
+
+ foreach_iter(exec_list_iterator, it, params->subexpressions) {
+ s_expression *expr = (s_expression*) it.get();
+ ir_rvalue *param = read_rvalue(expr);
+ if (param == NULL) {
+ ir_read_error(expr, "when reading parameter to function call");
+ return NULL;
+ }
+ parameters.push_tail(param);
+ }
+
+ ir_function *f = state->symbols->get_function(name->value());
+ if (f == NULL) {
+ ir_read_error(expr, "found call to undefined function %s",
+ name->value());
+ return NULL;
+ }
+
+ ir_function_signature *callee = f->matching_signature(&parameters);
+ if (callee == NULL) {
+ ir_read_error(expr, "couldn't find matching signature for function "
+ "%s", name->value());
+ return NULL;
+ }
+
+ return new(mem_ctx) ir_call(callee, &parameters);
+}
+
+ir_expression *
+ir_reader::read_expression(s_expression *expr)
+{
+ s_expression *s_type;
+ s_symbol *s_op;
+ s_expression *s_arg1;
+
+ s_pattern pat[] = { "expression", s_type, s_op, s_arg1 };
+ if (!PARTIAL_MATCH(expr, pat)) {
+ ir_read_error(expr, "expected (expression <type> <operator> "
+ "<operand> [<operand>])");
+ return NULL;
+ }
+ s_expression *s_arg2 = (s_expression *) s_arg1->next; // may be tail sentinel
+
+ const glsl_type *type = read_type(s_type);
+ if (type == NULL)
+ return NULL;
+
+ /* Read the operator */
+ ir_expression_operation op = ir_expression::get_operator(s_op->value());
+ if (op == (ir_expression_operation) -1) {
+ ir_read_error(expr, "invalid operator: %s", s_op->value());
+ return NULL;
+ }
+
+ unsigned num_operands = ir_expression::get_num_operands(op);
+ if (num_operands == 1 && !s_arg1->next->is_tail_sentinel()) {
+ ir_read_error(expr, "expected (expression <type> %s <operand>)",
+ s_op->value());
+ return NULL;
+ }
+
+ ir_rvalue *arg1 = read_rvalue(s_arg1);
+ ir_rvalue *arg2 = NULL;
+ if (arg1 == NULL) {
+ ir_read_error(NULL, "when reading first operand of %s", s_op->value());
+ return NULL;
+ }
+
+ if (num_operands == 2) {
+ if (s_arg2->is_tail_sentinel() || !s_arg2->next->is_tail_sentinel()) {
+ ir_read_error(expr, "expected (expression <type> %s <operand> "
+ "<operand>)", s_op->value());
+ return NULL;
+ }
+ arg2 = read_rvalue(s_arg2);
+ if (arg2 == NULL) {
+ ir_read_error(NULL, "when reading second operand of %s",
+ s_op->value());
+ return NULL;
+ }
+ }
+
+ return new(mem_ctx) ir_expression(op, type, arg1, arg2);
+}
+
+ir_swizzle *
+ir_reader::read_swizzle(s_expression *expr)
+{
+ s_symbol *swiz;
+ s_expression *sub;
+
+ s_pattern pat[] = { "swiz", swiz, sub };
+ if (!MATCH(expr, pat)) {
+ ir_read_error(expr, "expected (swiz <swizzle> <rvalue>)");
+ return NULL;
+ }
+
+ if (strlen(swiz->value()) > 4) {
+ ir_read_error(expr, "expected a valid swizzle; found %s", swiz->value());
+ return NULL;
+ }
+
+ ir_rvalue *rvalue = read_rvalue(sub);
+ if (rvalue == NULL)
+ return NULL;
+
+ ir_swizzle *ir = ir_swizzle::create(rvalue, swiz->value(),
+ rvalue->type->vector_elements);
+ if (ir == NULL)
+ ir_read_error(expr, "invalid swizzle");
+
+ return ir;
+}
+
+ir_constant *
+ir_reader::read_constant(s_expression *expr)
+{
+ s_expression *type_expr;
+ s_list *values;
+
+ s_pattern pat[] = { "constant", type_expr, values };
+ if (!MATCH(expr, pat)) {
+ ir_read_error(expr, "expected (constant <type> (...))");
+ return NULL;
+ }
+
+ const glsl_type *type = read_type(type_expr);
+ if (type == NULL)
+ return NULL;
+
+ if (values == NULL) {
+ ir_read_error(expr, "expected (constant <type> (...))");
+ return NULL;
+ }
+
+ if (type->is_array()) {
+ unsigned elements_supplied = 0;
+ exec_list elements;
+ foreach_iter(exec_list_iterator, it, values->subexpressions) {
+ s_expression *elt = (s_expression *) it.get();
+ ir_constant *ir_elt = read_constant(elt);
+ if (ir_elt == NULL)
+ return NULL;
+ elements.push_tail(ir_elt);
+ elements_supplied++;
+ }
+
+ if (elements_supplied != type->length) {
+ ir_read_error(values, "expected exactly %u array elements, "
+ "given %u", type->length, elements_supplied);
+ return NULL;
+ }
+ return new(mem_ctx) ir_constant(type, &elements);
+ }
+
+ const glsl_type *const base_type = type->get_base_type();
+
+ ir_constant_data data = { { 0 } };
+
+ // Read in list of values (at most 16).
+ int k = 0;
+ foreach_iter(exec_list_iterator, it, values->subexpressions) {
+ if (k >= 16) {
+ ir_read_error(values, "expected at most 16 numbers");
+ return NULL;
+ }
+
+ s_expression *expr = (s_expression*) it.get();
+
+ if (base_type->base_type == GLSL_TYPE_FLOAT) {
+ s_number *value = SX_AS_NUMBER(expr);
+ if (value == NULL) {
+ ir_read_error(values, "expected numbers");
+ return NULL;
+ }
+ data.f[k] = value->fvalue();
+ } else {
+ s_int *value = SX_AS_INT(expr);
+ if (value == NULL) {
+ ir_read_error(values, "expected integers");
+ return NULL;
+ }
+
+ switch (base_type->base_type) {
+ case GLSL_TYPE_UINT: {
+ data.u[k] = value->value();
+ break;
+ }
+ case GLSL_TYPE_INT: {
+ data.i[k] = value->value();
+ break;
+ }
+ case GLSL_TYPE_BOOL: {
+ data.b[k] = value->value();
+ break;
+ }
+ default:
+ ir_read_error(values, "unsupported constant type");
+ return NULL;
+ }
+ }
+ ++k;
+ }
+
+ return new(mem_ctx) ir_constant(type, &data);
+}
+
+ir_dereference *
+ir_reader::read_dereference(s_expression *expr)
+{
+ s_symbol *s_var;
+ s_expression *s_subject;
+ s_expression *s_index;
+ s_symbol *s_field;
+
+ s_pattern var_pat[] = { "var_ref", s_var };
+ s_pattern array_pat[] = { "array_ref", s_subject, s_index };
+ s_pattern record_pat[] = { "record_ref", s_subject, s_field };
+
+ if (MATCH(expr, var_pat)) {
+ ir_variable *var = state->symbols->get_variable(s_var->value());
+ if (var == NULL) {
+ ir_read_error(expr, "undeclared variable: %s", s_var->value());
+ return NULL;
+ }
+ return new(mem_ctx) ir_dereference_variable(var);
+ } else if (MATCH(expr, array_pat)) {
+ ir_rvalue *subject = read_rvalue(s_subject);
+ if (subject == NULL) {
+ ir_read_error(NULL, "when reading the subject of an array_ref");
+ return NULL;
+ }
+
+ ir_rvalue *idx = read_rvalue(s_index);
+ if (subject == NULL) {
+ ir_read_error(NULL, "when reading the index of an array_ref");
+ return NULL;
+ }
+ return new(mem_ctx) ir_dereference_array(subject, idx);
+ } else if (MATCH(expr, record_pat)) {
+ ir_rvalue *subject = read_rvalue(s_subject);
+ if (subject == NULL) {
+ ir_read_error(NULL, "when reading the subject of a record_ref");
+ return NULL;
+ }
+ return new(mem_ctx) ir_dereference_record(subject, s_field->value());
+ }
+ return NULL;
+}
+
+ir_texture *
+ir_reader::read_texture(s_expression *expr)
+{
+ s_symbol *tag = NULL;
+ s_expression *s_sampler = NULL;
+ s_expression *s_coord = NULL;
+ s_list *s_offset = NULL;
+ s_expression *s_proj = NULL;
+ s_list *s_shadow = NULL;
+ s_expression *s_lod = NULL;
+
+ ir_texture_opcode op = ir_tex; /* silence warning */
+
+ s_pattern tex_pattern[] =
+ { "tex", s_sampler, s_coord, s_offset, s_proj, s_shadow };
+ s_pattern txf_pattern[] =
+ { "txf", s_sampler, s_coord, s_offset, s_lod };
+ s_pattern other_pattern[] =
+ { tag, s_sampler, s_coord, s_offset, s_proj, s_shadow, s_lod };
+
+ if (MATCH(expr, tex_pattern)) {
+ op = ir_tex;
+ } else if (MATCH(expr, txf_pattern)) {
+ op = ir_txf;
+ } else if (MATCH(expr, other_pattern)) {
+ op = ir_texture::get_opcode(tag->value());
+ if (op == -1)
+ return NULL;
+ } else {
+ ir_read_error(NULL, "unexpected texture pattern");
+ return NULL;
+ }
+
+ ir_texture *tex = new(mem_ctx) ir_texture(op);
+
+ // Read sampler (must be a deref)
+ ir_dereference *sampler = read_dereference(s_sampler);
+ if (sampler == NULL) {
+ ir_read_error(NULL, "when reading sampler in (%s ...)",
+ tex->opcode_string());
+ return NULL;
+ }
+ tex->set_sampler(sampler);
+
+ // Read coordinate (any rvalue)
+ tex->coordinate = read_rvalue(s_coord);
+ if (tex->coordinate == NULL) {
+ ir_read_error(NULL, "when reading coordinate in (%s ...)",
+ tex->opcode_string());
+ return NULL;
+ }
+
+ // Read texel offset, i.e. (0 0 0)
+ s_int *offset_x;
+ s_int *offset_y;
+ s_int *offset_z;
+ s_pattern offset_pat[] = { offset_x, offset_y, offset_z };
+ if (!MATCH(s_offset, offset_pat)) {
+ ir_read_error(s_offset, "expected (<int> <int> <int>)");
+ return NULL;
+ }
+ tex->offsets[0] = offset_x->value();
+ tex->offsets[1] = offset_y->value();
+ tex->offsets[2] = offset_z->value();
+
+ if (op != ir_txf) {
+ s_int *proj_as_int = SX_AS_INT(s_proj);
+ if (proj_as_int && proj_as_int->value() == 1) {
+ tex->projector = NULL;
+ } else {
+ tex->projector = read_rvalue(s_proj);
+ if (tex->projector == NULL) {
+ ir_read_error(NULL, "when reading projective divide in (%s ..)",
+ tex->opcode_string());
+ return NULL;
+ }
+ }
+
+ if (s_shadow->subexpressions.is_empty()) {
+ tex->shadow_comparitor = NULL;
+ } else {
+ tex->shadow_comparitor = read_rvalue(s_shadow);
+ if (tex->shadow_comparitor == NULL) {
+ ir_read_error(NULL, "when reading shadow comparitor in (%s ..)",
+ tex->opcode_string());
+ return NULL;
+ }
+ }
+ }
+
+ switch (op) {
+ case ir_txb:
+ tex->lod_info.bias = read_rvalue(s_lod);
+ if (tex->lod_info.bias == NULL) {
+ ir_read_error(NULL, "when reading LOD bias in (txb ...)");
+ return NULL;
+ }
+ break;
+ case ir_txl:
+ case ir_txf:
+ tex->lod_info.lod = read_rvalue(s_lod);
+ if (tex->lod_info.lod == NULL) {
+ ir_read_error(NULL, "when reading LOD in (%s ...)",
+ tex->opcode_string());
+ return NULL;
+ }
+ break;
+ case ir_txd: {
+ s_expression *s_dx, *s_dy;
+ s_pattern dxdy_pat[] = { s_dx, s_dy };
+ if (!MATCH(s_lod, dxdy_pat)) {
+ ir_read_error(s_lod, "expected (dPdx dPdy) in (txd ...)");
+ return NULL;
+ }
+ tex->lod_info.grad.dPdx = read_rvalue(s_dx);
+ if (tex->lod_info.grad.dPdx == NULL) {
+ ir_read_error(NULL, "when reading dPdx in (txd ...)");
+ return NULL;
+ }
+ tex->lod_info.grad.dPdy = read_rvalue(s_dy);
+ if (tex->lod_info.grad.dPdy == NULL) {
+ ir_read_error(NULL, "when reading dPdy in (txd ...)");
+ return NULL;
+ }
+ break;
+ }
+ default:
+ // tex doesn't have any extra parameters.
+ break;
+ };
+ return tex;
+}
diff --git a/mesalib/src/glsl/link_functions.cpp b/mesalib/src/glsl/link_functions.cpp
index ea9129fe3..861fa39b5 100644
--- a/mesalib/src/glsl/link_functions.cpp
+++ b/mesalib/src/glsl/link_functions.cpp
@@ -1,258 +1,270 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice (including the next
- * paragraph) shall be included in all copies or substantial portions of the
- * Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-#include <cstdlib>
-#include <cstdio>
-#include <cstdarg>
-
-#include "main/core.h"
-#include "glsl_symbol_table.h"
-#include "glsl_parser_extras.h"
-#include "ir.h"
-#include "program.h"
-#include "program/hash_table.h"
-#include "linker.h"
-
-static ir_function_signature *
-find_matching_signature(const char *name, const exec_list *actual_parameters,
- gl_shader **shader_list, unsigned num_shaders);
-
-class call_link_visitor : public ir_hierarchical_visitor {
-public:
- call_link_visitor(gl_shader_program *prog, gl_shader *linked,
- gl_shader **shader_list, unsigned num_shaders)
- {
- this->prog = prog;
- this->shader_list = shader_list;
- this->num_shaders = num_shaders;
- this->success = true;
- this->linked = linked;
-
- this->locals = hash_table_ctor(0, hash_table_pointer_hash,
- hash_table_pointer_compare);
- }
-
- ~call_link_visitor()
- {
- hash_table_dtor(this->locals);
- }
-
- virtual ir_visitor_status visit(ir_variable *ir)
- {
- hash_table_insert(locals, ir, ir);
- return visit_continue;
- }
-
- virtual ir_visitor_status visit_enter(ir_call *ir)
- {
- /* If ir is an ir_call from a function that was imported from another
- * shader callee will point to an ir_function_signature in the original
- * shader. In this case the function signature MUST NOT BE MODIFIED.
- * Doing so will modify the original shader. This may prevent that
- * shader from being linkable in other programs.
- */
- const ir_function_signature *const callee = ir->get_callee();
- assert(callee != NULL);
- const char *const name = callee->function_name();
-
- /* Determine if the requested function signature already exists in the
- * final linked shader. If it does, use it as the target of the call.
- */
- ir_function_signature *sig =
- find_matching_signature(name, &callee->parameters, &linked, 1);
- if (sig != NULL) {
- ir->set_callee(sig);
- return visit_continue;
- }
-
- /* Try to find the signature in one of the other shaders that is being
- * linked. If it's not found there, return an error.
- */
- sig = find_matching_signature(name, &ir->actual_parameters, shader_list,
- num_shaders);
- if (sig == NULL) {
- /* FINISHME: Log the full signature of unresolved function.
- */
- linker_error_printf(this->prog, "unresolved reference to function "
- "`%s'\n", name);
- this->success = false;
- return visit_stop;
- }
-
- /* Find the prototype information in the linked shader. Generate any
- * details that may be missing.
- */
- ir_function *f = linked->symbols->get_function(name);
- if (f == NULL)
- f = new(linked) ir_function(name);
-
- ir_function_signature *linked_sig =
- f->exact_matching_signature(&callee->parameters);
- if (linked_sig == NULL) {
- linked_sig = new(linked) ir_function_signature(callee->return_type);
- f->add_signature(linked_sig);
- }
-
- /* At this point linked_sig and called may be the same. If ir is an
- * ir_call from linked then linked_sig and callee will be
- * ir_function_signatures that have no definitions (is_defined is false).
- */
- assert(!linked_sig->is_defined);
- assert(linked_sig->body.is_empty());
-
- /* Create an in-place clone of the function definition. This multistep
- * process introduces some complexity here, but it has some advantages.
- * The parameter list and the and function body are cloned separately.
- * The clone of the parameter list is used to prime the hashtable used
- * to replace variable references in the cloned body.
- *
- * The big advantage is that the ir_function_signature does not change.
- * This means that we don't have to process the rest of the IR tree to
- * patch ir_call nodes. In addition, there is no way to remove or
- * replace signature stored in a function. One could easily be added,
- * but this avoids the need.
- */
- struct hash_table *ht = hash_table_ctor(0, hash_table_pointer_hash,
- hash_table_pointer_compare);
- exec_list formal_parameters;
- foreach_list_const(node, &sig->parameters) {
- const ir_instruction *const original = (ir_instruction *) node;
- assert(const_cast<ir_instruction *>(original)->as_variable());
-
- ir_instruction *copy = original->clone(linked, ht);
- formal_parameters.push_tail(copy);
- }
-
- linked_sig->replace_parameters(&formal_parameters);
-
- foreach_list_const(node, &sig->body) {
- const ir_instruction *const original = (ir_instruction *) node;
-
- ir_instruction *copy = original->clone(linked, ht);
- linked_sig->body.push_tail(copy);
- }
-
- linked_sig->is_defined = true;
- hash_table_dtor(ht);
-
- /* Patch references inside the function to things outside the function
- * (i.e., function calls and global variables).
- */
- linked_sig->accept(this);
-
- ir->set_callee(linked_sig);
-
- return visit_continue;
- }
-
- virtual ir_visitor_status visit(ir_dereference_variable *ir)
- {
- if (hash_table_find(locals, ir->var) == NULL) {
- /* The non-function variable must be a global, so try to find the
- * variable in the shader's symbol table. If the variable is not
- * found, then it's a global that *MUST* be defined in the original
- * shader.
- */
- ir_variable *var = linked->symbols->get_variable(ir->var->name);
- if (var == NULL) {
- /* Clone the ir_variable that the dereference already has and add
- * it to the linked shader.
- */
- var = ir->var->clone(linked, NULL);
- linked->symbols->add_variable(var);
- linked->ir->push_head(var);
- }
-
- ir->var = var;
- }
-
- return visit_continue;
- }
-
- /** Was function linking successful? */
- bool success;
-
-private:
- /**
- * Shader program being linked
- *
- * This is only used for logging error messages.
- */
- gl_shader_program *prog;
-
- /** List of shaders available for linking. */
- gl_shader **shader_list;
-
- /** Number of shaders available for linking. */
- unsigned num_shaders;
-
- /**
- * Final linked shader
- *
- * This is used two ways. It is used to find global variables in the
- * linked shader that are accessed by the function. It is also used to add
- * global variables from the shader where the function originated.
- */
- gl_shader *linked;
-
- /**
- * Table of variables local to the function.
- */
- hash_table *locals;
-};
-
-
-/**
- * Searches a list of shaders for a particular function definition
- */
-ir_function_signature *
-find_matching_signature(const char *name, const exec_list *actual_parameters,
- gl_shader **shader_list, unsigned num_shaders)
-{
- for (unsigned i = 0; i < num_shaders; i++) {
- ir_function *const f = shader_list[i]->symbols->get_function(name);
-
- if (f == NULL)
- continue;
-
- ir_function_signature *sig = f->matching_signature(actual_parameters);
-
- if ((sig == NULL) || !sig->is_defined)
- continue;
-
- return sig;
- }
-
- return NULL;
-}
-
-
-bool
-link_function_calls(gl_shader_program *prog, gl_shader *main,
- gl_shader **shader_list, unsigned num_shaders)
-{
- call_link_visitor v(prog, main, shader_list, num_shaders);
-
- v.run(main->ir);
- return v.success;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#include <cstdlib>
+#include <cstdio>
+#include <cstdarg>
+
+#include "main/core.h"
+#include "glsl_symbol_table.h"
+#include "glsl_parser_extras.h"
+#include "ir.h"
+#include "program.h"
+#include "program/hash_table.h"
+#include "linker.h"
+
+static ir_function_signature *
+find_matching_signature(const char *name, const exec_list *actual_parameters,
+ gl_shader **shader_list, unsigned num_shaders);
+
+class call_link_visitor : public ir_hierarchical_visitor {
+public:
+ call_link_visitor(gl_shader_program *prog, gl_shader *linked,
+ gl_shader **shader_list, unsigned num_shaders)
+ {
+ this->prog = prog;
+ this->shader_list = shader_list;
+ this->num_shaders = num_shaders;
+ this->success = true;
+ this->linked = linked;
+
+ this->locals = hash_table_ctor(0, hash_table_pointer_hash,
+ hash_table_pointer_compare);
+ }
+
+ ~call_link_visitor()
+ {
+ hash_table_dtor(this->locals);
+ }
+
+ virtual ir_visitor_status visit(ir_variable *ir)
+ {
+ hash_table_insert(locals, ir, ir);
+ return visit_continue;
+ }
+
+ virtual ir_visitor_status visit_enter(ir_call *ir)
+ {
+ /* If ir is an ir_call from a function that was imported from another
+ * shader callee will point to an ir_function_signature in the original
+ * shader. In this case the function signature MUST NOT BE MODIFIED.
+ * Doing so will modify the original shader. This may prevent that
+ * shader from being linkable in other programs.
+ */
+ const ir_function_signature *const callee = ir->get_callee();
+ assert(callee != NULL);
+ const char *const name = callee->function_name();
+
+ /* Determine if the requested function signature already exists in the
+ * final linked shader. If it does, use it as the target of the call.
+ */
+ ir_function_signature *sig =
+ find_matching_signature(name, &callee->parameters, &linked, 1);
+ if (sig != NULL) {
+ ir->set_callee(sig);
+ return visit_continue;
+ }
+
+ /* Try to find the signature in one of the other shaders that is being
+ * linked. If it's not found there, return an error.
+ */
+ sig = find_matching_signature(name, &ir->actual_parameters, shader_list,
+ num_shaders);
+ if (sig == NULL) {
+ /* FINISHME: Log the full signature of unresolved function.
+ */
+ linker_error_printf(this->prog, "unresolved reference to function "
+ "`%s'\n", name);
+ this->success = false;
+ return visit_stop;
+ }
+
+ /* Find the prototype information in the linked shader. Generate any
+ * details that may be missing.
+ */
+ ir_function *f = linked->symbols->get_function(name);
+ if (f == NULL)
+ f = new(linked) ir_function(name);
+
+ ir_function_signature *linked_sig =
+ f->exact_matching_signature(&callee->parameters);
+ if (linked_sig == NULL) {
+ linked_sig = new(linked) ir_function_signature(callee->return_type);
+ f->add_signature(linked_sig);
+ }
+
+ /* At this point linked_sig and called may be the same. If ir is an
+ * ir_call from linked then linked_sig and callee will be
+ * ir_function_signatures that have no definitions (is_defined is false).
+ */
+ assert(!linked_sig->is_defined);
+ assert(linked_sig->body.is_empty());
+
+ /* Create an in-place clone of the function definition. This multistep
+ * process introduces some complexity here, but it has some advantages.
+ * The parameter list and the and function body are cloned separately.
+ * The clone of the parameter list is used to prime the hashtable used
+ * to replace variable references in the cloned body.
+ *
+ * The big advantage is that the ir_function_signature does not change.
+ * This means that we don't have to process the rest of the IR tree to
+ * patch ir_call nodes. In addition, there is no way to remove or
+ * replace signature stored in a function. One could easily be added,
+ * but this avoids the need.
+ */
+ struct hash_table *ht = hash_table_ctor(0, hash_table_pointer_hash,
+ hash_table_pointer_compare);
+ exec_list formal_parameters;
+ foreach_list_const(node, &sig->parameters) {
+ const ir_instruction *const original = (ir_instruction *) node;
+ assert(const_cast<ir_instruction *>(original)->as_variable());
+
+ ir_instruction *copy = original->clone(linked, ht);
+ formal_parameters.push_tail(copy);
+ }
+
+ linked_sig->replace_parameters(&formal_parameters);
+
+ foreach_list_const(node, &sig->body) {
+ const ir_instruction *const original = (ir_instruction *) node;
+
+ ir_instruction *copy = original->clone(linked, ht);
+ linked_sig->body.push_tail(copy);
+ }
+
+ linked_sig->is_defined = true;
+ hash_table_dtor(ht);
+
+ /* Patch references inside the function to things outside the function
+ * (i.e., function calls and global variables).
+ */
+ linked_sig->accept(this);
+
+ ir->set_callee(linked_sig);
+
+ return visit_continue;
+ }
+
+ virtual ir_visitor_status visit(ir_dereference_variable *ir)
+ {
+ if (hash_table_find(locals, ir->var) == NULL) {
+ /* The non-function variable must be a global, so try to find the
+ * variable in the shader's symbol table. If the variable is not
+ * found, then it's a global that *MUST* be defined in the original
+ * shader.
+ */
+ ir_variable *var = linked->symbols->get_variable(ir->var->name);
+ if (var == NULL) {
+ /* Clone the ir_variable that the dereference already has and add
+ * it to the linked shader.
+ */
+ var = ir->var->clone(linked, NULL);
+ linked->symbols->add_variable(var);
+ linked->ir->push_head(var);
+ } else if (var->type->is_array()) {
+ /* It is possible to have a global array declared in multiple
+ * shaders without a size. The array is implicitly sized by the
+ * maximal access to it in *any* shader. Because of this, we
+ * need to track the maximal access to the array as linking pulls
+ * more functions in that access the array.
+ */
+ var->max_array_access =
+ MAX2(var->max_array_access, ir->var->max_array_access);
+
+ if (var->type->length == 0 && ir->var->type->length != 0)
+ var->type = ir->var->type;
+ }
+
+ ir->var = var;
+ }
+
+ return visit_continue;
+ }
+
+ /** Was function linking successful? */
+ bool success;
+
+private:
+ /**
+ * Shader program being linked
+ *
+ * This is only used for logging error messages.
+ */
+ gl_shader_program *prog;
+
+ /** List of shaders available for linking. */
+ gl_shader **shader_list;
+
+ /** Number of shaders available for linking. */
+ unsigned num_shaders;
+
+ /**
+ * Final linked shader
+ *
+ * This is used two ways. It is used to find global variables in the
+ * linked shader that are accessed by the function. It is also used to add
+ * global variables from the shader where the function originated.
+ */
+ gl_shader *linked;
+
+ /**
+ * Table of variables local to the function.
+ */
+ hash_table *locals;
+};
+
+
+/**
+ * Searches a list of shaders for a particular function definition
+ */
+ir_function_signature *
+find_matching_signature(const char *name, const exec_list *actual_parameters,
+ gl_shader **shader_list, unsigned num_shaders)
+{
+ for (unsigned i = 0; i < num_shaders; i++) {
+ ir_function *const f = shader_list[i]->symbols->get_function(name);
+
+ if (f == NULL)
+ continue;
+
+ ir_function_signature *sig = f->matching_signature(actual_parameters);
+
+ if ((sig == NULL) || !sig->is_defined)
+ continue;
+
+ return sig;
+ }
+
+ return NULL;
+}
+
+
+bool
+link_function_calls(gl_shader_program *prog, gl_shader *main,
+ gl_shader **shader_list, unsigned num_shaders)
+{
+ call_link_visitor v(prog, main, shader_list, num_shaders);
+
+ v.run(main->ir);
+ return v.success;
+}
diff --git a/mesalib/src/glsl/linker.cpp b/mesalib/src/glsl/linker.cpp
index 9f4b4149c..bf7a56353 100644
--- a/mesalib/src/glsl/linker.cpp
+++ b/mesalib/src/glsl/linker.cpp
@@ -1,1676 +1,1672 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice (including the next
- * paragraph) shall be included in all copies or substantial portions of the
- * Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-/**
- * \file linker.cpp
- * GLSL linker implementation
- *
- * Given a set of shaders that are to be linked to generate a final program,
- * there are three distinct stages.
- *
- * In the first stage shaders are partitioned into groups based on the shader
- * type. All shaders of a particular type (e.g., vertex shaders) are linked
- * together.
- *
- * - Undefined references in each shader are resolve to definitions in
- * another shader.
- * - Types and qualifiers of uniforms, outputs, and global variables defined
- * in multiple shaders with the same name are verified to be the same.
- * - Initializers for uniforms and global variables defined
- * in multiple shaders with the same name are verified to be the same.
- *
- * The result, in the terminology of the GLSL spec, is a set of shader
- * executables for each processing unit.
- *
- * After the first stage is complete, a series of semantic checks are performed
- * on each of the shader executables.
- *
- * - Each shader executable must define a \c main function.
- * - Each vertex shader executable must write to \c gl_Position.
- * - Each fragment shader executable must write to either \c gl_FragData or
- * \c gl_FragColor.
- *
- * In the final stage individual shader executables are linked to create a
- * complete exectuable.
- *
- * - Types of uniforms defined in multiple shader stages with the same name
- * are verified to be the same.
- * - Initializers for uniforms defined in multiple shader stages with the
- * same name are verified to be the same.
- * - Types and qualifiers of outputs defined in one stage are verified to
- * be the same as the types and qualifiers of inputs defined with the same
- * name in a later stage.
- *
- * \author Ian Romanick <ian.d.romanick@intel.com>
- */
-#include <cstdlib>
-#include <cstdio>
-#include <cstdarg>
-#include <climits>
-
-#include "main/core.h"
-#include "glsl_symbol_table.h"
-#include "ir.h"
-#include "program.h"
-#include "program/hash_table.h"
-#include "linker.h"
-#include "ir_optimization.h"
-
-extern "C" {
-#include "main/shaderobj.h"
-}
-
-/**
- * Visitor that determines whether or not a variable is ever written.
- */
-class find_assignment_visitor : public ir_hierarchical_visitor {
-public:
- find_assignment_visitor(const char *name)
- : name(name), found(false)
- {
- /* empty */
- }
-
- virtual ir_visitor_status visit_enter(ir_assignment *ir)
- {
- ir_variable *const var = ir->lhs->variable_referenced();
-
- if (strcmp(name, var->name) == 0) {
- found = true;
- return visit_stop;
- }
-
- return visit_continue_with_parent;
- }
-
- virtual ir_visitor_status visit_enter(ir_call *ir)
- {
- exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
- foreach_iter(exec_list_iterator, iter, *ir) {
- ir_rvalue *param_rval = (ir_rvalue *)iter.get();
- ir_variable *sig_param = (ir_variable *)sig_iter.get();
-
- if (sig_param->mode == ir_var_out ||
- sig_param->mode == ir_var_inout) {
- ir_variable *var = param_rval->variable_referenced();
- if (var && strcmp(name, var->name) == 0) {
- found = true;
- return visit_stop;
- }
- }
- sig_iter.next();
- }
-
- return visit_continue_with_parent;
- }
-
- bool variable_found()
- {
- return found;
- }
-
-private:
- const char *name; /**< Find writes to a variable with this name. */
- bool found; /**< Was a write to the variable found? */
-};
-
-
-/**
- * Visitor that determines whether or not a variable is ever read.
- */
-class find_deref_visitor : public ir_hierarchical_visitor {
-public:
- find_deref_visitor(const char *name)
- : name(name), found(false)
- {
- /* empty */
- }
-
- virtual ir_visitor_status visit(ir_dereference_variable *ir)
- {
- if (strcmp(this->name, ir->var->name) == 0) {
- this->found = true;
- return visit_stop;
- }
-
- return visit_continue;
- }
-
- bool variable_found() const
- {
- return this->found;
- }
-
-private:
- const char *name; /**< Find writes to a variable with this name. */
- bool found; /**< Was a write to the variable found? */
-};
-
-
-void
-linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
-{
- va_list ap;
-
- prog->InfoLog = talloc_strdup_append(prog->InfoLog, "error: ");
- va_start(ap, fmt);
- prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, ap);
- va_end(ap);
-}
-
-
-void
-invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
- int generic_base)
-{
- foreach_list(node, sh->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != (unsigned) mode))
- continue;
-
- /* Only assign locations for generic attributes / varyings / etc.
- */
- if ((var->location >= generic_base) && !var->explicit_location)
- var->location = -1;
- }
-}
-
-
-/**
- * Determine the number of attribute slots required for a particular type
- *
- * This code is here because it implements the language rules of a specific
- * GLSL version. Since it's a property of the language and not a property of
- * types in general, it doesn't really belong in glsl_type.
- */
-unsigned
-count_attribute_slots(const glsl_type *t)
-{
- /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
- *
- * "A scalar input counts the same amount against this limit as a vec4,
- * so applications may want to consider packing groups of four
- * unrelated float inputs together into a vector to better utilize the
- * capabilities of the underlying hardware. A matrix input will use up
- * multiple locations. The number of locations used will equal the
- * number of columns in the matrix."
- *
- * The spec does not explicitly say how arrays are counted. However, it
- * should be safe to assume the total number of slots consumed by an array
- * is the number of entries in the array multiplied by the number of slots
- * consumed by a single element of the array.
- */
-
- if (t->is_array())
- return t->array_size() * count_attribute_slots(t->element_type());
-
- if (t->is_matrix())
- return t->matrix_columns;
-
- return 1;
-}
-
-
-/**
- * Verify that a vertex shader executable meets all semantic requirements
- *
- * \param shader Vertex shader executable to be verified
- */
-bool
-validate_vertex_shader_executable(struct gl_shader_program *prog,
- struct gl_shader *shader)
-{
- if (shader == NULL)
- return true;
-
- find_assignment_visitor find("gl_Position");
- find.run(shader->ir);
- if (!find.variable_found()) {
- linker_error_printf(prog,
- "vertex shader does not write to `gl_Position'\n");
- return false;
- }
-
- return true;
-}
-
-
-/**
- * Verify that a fragment shader executable meets all semantic requirements
- *
- * \param shader Fragment shader executable to be verified
- */
-bool
-validate_fragment_shader_executable(struct gl_shader_program *prog,
- struct gl_shader *shader)
-{
- if (shader == NULL)
- return true;
-
- find_assignment_visitor frag_color("gl_FragColor");
- find_assignment_visitor frag_data("gl_FragData");
-
- frag_color.run(shader->ir);
- frag_data.run(shader->ir);
-
- if (frag_color.variable_found() && frag_data.variable_found()) {
- linker_error_printf(prog, "fragment shader writes to both "
- "`gl_FragColor' and `gl_FragData'\n");
- return false;
- }
-
- return true;
-}
-
-
-/**
- * Generate a string describing the mode of a variable
- */
-static const char *
-mode_string(const ir_variable *var)
-{
- switch (var->mode) {
- case ir_var_auto:
- return (var->read_only) ? "global constant" : "global variable";
-
- case ir_var_uniform: return "uniform";
- case ir_var_in: return "shader input";
- case ir_var_out: return "shader output";
- case ir_var_inout: return "shader inout";
-
- case ir_var_temporary:
- default:
- assert(!"Should not get here.");
- return "invalid variable";
- }
-}
-
-
-/**
- * Perform validation of global variables used across multiple shaders
- */
-bool
-cross_validate_globals(struct gl_shader_program *prog,
- struct gl_shader **shader_list,
- unsigned num_shaders,
- bool uniforms_only)
-{
- /* Examine all of the uniforms in all of the shaders and cross validate
- * them.
- */
- glsl_symbol_table variables;
- for (unsigned i = 0; i < num_shaders; i++) {
- if (shader_list[i] == NULL)
- continue;
-
- foreach_list(node, shader_list[i]->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if (var == NULL)
- continue;
-
- if (uniforms_only && (var->mode != ir_var_uniform))
- continue;
-
- /* Don't cross validate temporaries that are at global scope. These
- * will eventually get pulled into the shaders 'main'.
- */
- if (var->mode == ir_var_temporary)
- continue;
-
- /* If a global with this name has already been seen, verify that the
- * new instance has the same type. In addition, if the globals have
- * initializers, the values of the initializers must be the same.
- */
- ir_variable *const existing = variables.get_variable(var->name);
- if (existing != NULL) {
- if (var->type != existing->type) {
- /* Consider the types to be "the same" if both types are arrays
- * of the same type and one of the arrays is implicitly sized.
- * In addition, set the type of the linked variable to the
- * explicitly sized array.
- */
- if (var->type->is_array()
- && existing->type->is_array()
- && (var->type->fields.array == existing->type->fields.array)
- && ((var->type->length == 0)
- || (existing->type->length == 0))) {
- if (existing->type->length == 0) {
- existing->type = var->type;
- existing->max_array_access =
- MAX2(existing->max_array_access,
- var->max_array_access);
- }
- } else {
- linker_error_printf(prog, "%s `%s' declared as type "
- "`%s' and type `%s'\n",
- mode_string(var),
- var->name, var->type->name,
- existing->type->name);
- return false;
- }
- }
-
- if (var->explicit_location) {
- if (existing->explicit_location
- && (var->location != existing->location)) {
- linker_error_printf(prog, "explicit locations for %s "
- "`%s' have differing values\n",
- mode_string(var), var->name);
- return false;
- }
-
- existing->location = var->location;
- existing->explicit_location = true;
- }
-
- /* FINISHME: Handle non-constant initializers.
- */
- if (var->constant_value != NULL) {
- if (existing->constant_value != NULL) {
- if (!var->constant_value->has_value(existing->constant_value)) {
- linker_error_printf(prog, "initializers for %s "
- "`%s' have differing values\n",
- mode_string(var), var->name);
- return false;
- }
- } else
- /* If the first-seen instance of a particular uniform did not
- * have an initializer but a later instance does, copy the
- * initializer to the version stored in the symbol table.
- */
- /* FINISHME: This is wrong. The constant_value field should
- * FINISHME: not be modified! Imagine a case where a shader
- * FINISHME: without an initializer is linked in two different
- * FINISHME: programs with shaders that have differing
- * FINISHME: initializers. Linking with the first will
- * FINISHME: modify the shader, and linking with the second
- * FINISHME: will fail.
- */
- existing->constant_value =
- var->constant_value->clone(talloc_parent(existing), NULL);
- }
-
- if (existing->invariant != var->invariant) {
- linker_error_printf(prog, "declarations for %s `%s' have "
- "mismatching invariant qualifiers\n",
- mode_string(var), var->name);
- return false;
- }
- if (existing->centroid != var->centroid) {
- linker_error_printf(prog, "declarations for %s `%s' have "
- "mismatching centroid qualifiers\n",
- mode_string(var), var->name);
- return false;
- }
- } else
- variables.add_variable(var);
- }
- }
-
- return true;
-}
-
-
-/**
- * Perform validation of uniforms used across multiple shader stages
- */
-bool
-cross_validate_uniforms(struct gl_shader_program *prog)
-{
- return cross_validate_globals(prog, prog->_LinkedShaders,
- MESA_SHADER_TYPES, true);
-}
-
-
-/**
- * Validate that outputs from one stage match inputs of another
- */
-bool
-cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
- gl_shader *producer, gl_shader *consumer)
-{
- glsl_symbol_table parameters;
- /* FINISHME: Figure these out dynamically. */
- const char *const producer_stage = "vertex";
- const char *const consumer_stage = "fragment";
-
- /* Find all shader outputs in the "producer" stage.
- */
- foreach_list(node, producer->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- /* FINISHME: For geometry shaders, this should also look for inout
- * FINISHME: variables.
- */
- if ((var == NULL) || (var->mode != ir_var_out))
- continue;
-
- parameters.add_variable(var);
- }
-
-
- /* Find all shader inputs in the "consumer" stage. Any variables that have
- * matching outputs already in the symbol table must have the same type and
- * qualifiers.
- */
- foreach_list(node, consumer->ir) {
- ir_variable *const input = ((ir_instruction *) node)->as_variable();
-
- /* FINISHME: For geometry shaders, this should also look for inout
- * FINISHME: variables.
- */
- if ((input == NULL) || (input->mode != ir_var_in))
- continue;
-
- ir_variable *const output = parameters.get_variable(input->name);
- if (output != NULL) {
- /* Check that the types match between stages.
- */
- if (input->type != output->type) {
- /* There is a bit of a special case for gl_TexCoord. This
- * built-in is unsized by default. Appliations that variable
- * access it must redeclare it with a size. There is some
- * language in the GLSL spec that implies the fragment shader
- * and vertex shader do not have to agree on this size. Other
- * driver behave this way, and one or two applications seem to
- * rely on it.
- *
- * Neither declaration needs to be modified here because the array
- * sizes are fixed later when update_array_sizes is called.
- *
- * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
- *
- * "Unlike user-defined varying variables, the built-in
- * varying variables don't have a strict one-to-one
- * correspondence between the vertex language and the
- * fragment language."
- */
- if (!output->type->is_array()
- || (strncmp("gl_", output->name, 3) != 0)) {
- linker_error_printf(prog,
- "%s shader output `%s' declared as "
- "type `%s', but %s shader input declared "
- "as type `%s'\n",
- producer_stage, output->name,
- output->type->name,
- consumer_stage, input->type->name);
- return false;
- }
- }
-
- /* Check that all of the qualifiers match between stages.
- */
- if (input->centroid != output->centroid) {
- linker_error_printf(prog,
- "%s shader output `%s' %s centroid qualifier, "
- "but %s shader input %s centroid qualifier\n",
- producer_stage,
- output->name,
- (output->centroid) ? "has" : "lacks",
- consumer_stage,
- (input->centroid) ? "has" : "lacks");
- return false;
- }
-
- if (input->invariant != output->invariant) {
- linker_error_printf(prog,
- "%s shader output `%s' %s invariant qualifier, "
- "but %s shader input %s invariant qualifier\n",
- producer_stage,
- output->name,
- (output->invariant) ? "has" : "lacks",
- consumer_stage,
- (input->invariant) ? "has" : "lacks");
- return false;
- }
-
- if (input->interpolation != output->interpolation) {
- linker_error_printf(prog,
- "%s shader output `%s' specifies %s "
- "interpolation qualifier, "
- "but %s shader input specifies %s "
- "interpolation qualifier\n",
- producer_stage,
- output->name,
- output->interpolation_string(),
- consumer_stage,
- input->interpolation_string());
- return false;
- }
- }
- }
-
- return true;
-}
-
-
-/**
- * Populates a shaders symbol table with all global declarations
- */
-static void
-populate_symbol_table(gl_shader *sh)
-{
- sh->symbols = new(sh) glsl_symbol_table;
-
- foreach_list(node, sh->ir) {
- ir_instruction *const inst = (ir_instruction *) node;
- ir_variable *var;
- ir_function *func;
-
- if ((func = inst->as_function()) != NULL) {
- sh->symbols->add_function(func);
- } else if ((var = inst->as_variable()) != NULL) {
- sh->symbols->add_variable(var);
- }
- }
-}
-
-
-/**
- * Remap variables referenced in an instruction tree
- *
- * This is used when instruction trees are cloned from one shader and placed in
- * another. These trees will contain references to \c ir_variable nodes that
- * do not exist in the target shader. This function finds these \c ir_variable
- * references and replaces the references with matching variables in the target
- * shader.
- *
- * If there is no matching variable in the target shader, a clone of the
- * \c ir_variable is made and added to the target shader. The new variable is
- * added to \b both the instruction stream and the symbol table.
- *
- * \param inst IR tree that is to be processed.
- * \param symbols Symbol table containing global scope symbols in the
- * linked shader.
- * \param instructions Instruction stream where new variable declarations
- * should be added.
- */
-void
-remap_variables(ir_instruction *inst, struct gl_shader *target,
- hash_table *temps)
-{
- class remap_visitor : public ir_hierarchical_visitor {
- public:
- remap_visitor(struct gl_shader *target,
- hash_table *temps)
- {
- this->target = target;
- this->symbols = target->symbols;
- this->instructions = target->ir;
- this->temps = temps;
- }
-
- virtual ir_visitor_status visit(ir_dereference_variable *ir)
- {
- if (ir->var->mode == ir_var_temporary) {
- ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
-
- assert(var != NULL);
- ir->var = var;
- return visit_continue;
- }
-
- ir_variable *const existing =
- this->symbols->get_variable(ir->var->name);
- if (existing != NULL)
- ir->var = existing;
- else {
- ir_variable *copy = ir->var->clone(this->target, NULL);
-
- this->symbols->add_variable(copy);
- this->instructions->push_head(copy);
- ir->var = copy;
- }
-
- return visit_continue;
- }
-
- private:
- struct gl_shader *target;
- glsl_symbol_table *symbols;
- exec_list *instructions;
- hash_table *temps;
- };
-
- remap_visitor v(target, temps);
-
- inst->accept(&v);
-}
-
-
-/**
- * Move non-declarations from one instruction stream to another
- *
- * The intended usage pattern of this function is to pass the pointer to the
- * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
- * pointer) for \c last and \c false for \c make_copies on the first
- * call. Successive calls pass the return value of the previous call for
- * \c last and \c true for \c make_copies.
- *
- * \param instructions Source instruction stream
- * \param last Instruction after which new instructions should be
- * inserted in the target instruction stream
- * \param make_copies Flag selecting whether instructions in \c instructions
- * should be copied (via \c ir_instruction::clone) into the
- * target list or moved.
- *
- * \return
- * The new "last" instruction in the target instruction stream. This pointer
- * is suitable for use as the \c last parameter of a later call to this
- * function.
- */
-exec_node *
-move_non_declarations(exec_list *instructions, exec_node *last,
- bool make_copies, gl_shader *target)
-{
- hash_table *temps = NULL;
-
- if (make_copies)
- temps = hash_table_ctor(0, hash_table_pointer_hash,
- hash_table_pointer_compare);
-
- foreach_list_safe(node, instructions) {
- ir_instruction *inst = (ir_instruction *) node;
-
- if (inst->as_function())
- continue;
-
- ir_variable *var = inst->as_variable();
- if ((var != NULL) && (var->mode != ir_var_temporary))
- continue;
-
- assert(inst->as_assignment()
- || ((var != NULL) && (var->mode == ir_var_temporary)));
-
- if (make_copies) {
- inst = inst->clone(target, NULL);
-
- if (var != NULL)
- hash_table_insert(temps, inst, var);
- else
- remap_variables(inst, target, temps);
- } else {
- inst->remove();
- }
-
- last->insert_after(inst);
- last = inst;
- }
-
- if (make_copies)
- hash_table_dtor(temps);
-
- return last;
-}
-
-/**
- * Get the function signature for main from a shader
- */
-static ir_function_signature *
-get_main_function_signature(gl_shader *sh)
-{
- ir_function *const f = sh->symbols->get_function("main");
- if (f != NULL) {
- exec_list void_parameters;
-
- /* Look for the 'void main()' signature and ensure that it's defined.
- * This keeps the linker from accidentally pick a shader that just
- * contains a prototype for main.
- *
- * We don't have to check for multiple definitions of main (in multiple
- * shaders) because that would have already been caught above.
- */
- ir_function_signature *sig = f->matching_signature(&void_parameters);
- if ((sig != NULL) && sig->is_defined) {
- return sig;
- }
- }
-
- return NULL;
-}
-
-
-/**
- * Combine a group of shaders for a single stage to generate a linked shader
- *
- * \note
- * If this function is supplied a single shader, it is cloned, and the new
- * shader is returned.
- */
-static struct gl_shader *
-link_intrastage_shaders(void *mem_ctx,
- struct gl_context *ctx,
- struct gl_shader_program *prog,
- struct gl_shader **shader_list,
- unsigned num_shaders)
-{
- /* Check that global variables defined in multiple shaders are consistent.
- */
- if (!cross_validate_globals(prog, shader_list, num_shaders, false))
- return NULL;
-
- /* Check that there is only a single definition of each function signature
- * across all shaders.
- */
- for (unsigned i = 0; i < (num_shaders - 1); i++) {
- foreach_list(node, shader_list[i]->ir) {
- ir_function *const f = ((ir_instruction *) node)->as_function();
-
- if (f == NULL)
- continue;
-
- for (unsigned j = i + 1; j < num_shaders; j++) {
- ir_function *const other =
- shader_list[j]->symbols->get_function(f->name);
-
- /* If the other shader has no function (and therefore no function
- * signatures) with the same name, skip to the next shader.
- */
- if (other == NULL)
- continue;
-
- foreach_iter (exec_list_iterator, iter, *f) {
- ir_function_signature *sig =
- (ir_function_signature *) iter.get();
-
- if (!sig->is_defined || sig->is_builtin)
- continue;
-
- ir_function_signature *other_sig =
- other->exact_matching_signature(& sig->parameters);
-
- if ((other_sig != NULL) && other_sig->is_defined
- && !other_sig->is_builtin) {
- linker_error_printf(prog,
- "function `%s' is multiply defined",
- f->name);
- return NULL;
- }
- }
- }
- }
- }
-
- /* Find the shader that defines main, and make a clone of it.
- *
- * Starting with the clone, search for undefined references. If one is
- * found, find the shader that defines it. Clone the reference and add
- * it to the shader. Repeat until there are no undefined references or
- * until a reference cannot be resolved.
- */
- gl_shader *main = NULL;
- for (unsigned i = 0; i < num_shaders; i++) {
- if (get_main_function_signature(shader_list[i]) != NULL) {
- main = shader_list[i];
- break;
- }
- }
-
- if (main == NULL) {
- linker_error_printf(prog, "%s shader lacks `main'\n",
- (shader_list[0]->Type == GL_VERTEX_SHADER)
- ? "vertex" : "fragment");
- return NULL;
- }
-
- gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
- linked->ir = new(linked) exec_list;
- clone_ir_list(mem_ctx, linked->ir, main->ir);
-
- populate_symbol_table(linked);
-
- /* The a pointer to the main function in the final linked shader (i.e., the
- * copy of the original shader that contained the main function).
- */
- ir_function_signature *const main_sig = get_main_function_signature(linked);
-
- /* Move any instructions other than variable declarations or function
- * declarations into main.
- */
- exec_node *insertion_point =
- move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
- linked);
-
- for (unsigned i = 0; i < num_shaders; i++) {
- if (shader_list[i] == main)
- continue;
-
- insertion_point = move_non_declarations(shader_list[i]->ir,
- insertion_point, true, linked);
- }
-
- /* Resolve initializers for global variables in the linked shader.
- */
- unsigned num_linking_shaders = num_shaders;
- for (unsigned i = 0; i < num_shaders; i++)
- num_linking_shaders += shader_list[i]->num_builtins_to_link;
-
- gl_shader **linking_shaders =
- (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
-
- memcpy(linking_shaders, shader_list,
- sizeof(linking_shaders[0]) * num_shaders);
-
- unsigned idx = num_shaders;
- for (unsigned i = 0; i < num_shaders; i++) {
- memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
- sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
- idx += shader_list[i]->num_builtins_to_link;
- }
-
- assert(idx == num_linking_shaders);
-
- if (!link_function_calls(prog, linked, linking_shaders,
- num_linking_shaders)) {
- ctx->Driver.DeleteShader(ctx, linked);
- linked = NULL;
- }
-
- free(linking_shaders);
-
- /* Make a pass over all global variables to ensure that arrays with
- * unspecified sizes have a size specified. The size is inferred from the
- * max_array_access field.
- */
- if (linked != NULL) {
- foreach_list(node, linked->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if (var == NULL)
- continue;
-
- if ((var->mode != ir_var_auto) && (var->mode != ir_var_temporary))
- continue;
-
- if (!var->type->is_array() || (var->type->length != 0))
- continue;
-
- const glsl_type *type =
- glsl_type::get_array_instance(var->type->fields.array,
- var->max_array_access);
-
- assert(type != NULL);
- var->type = type;
- }
- }
-
- return linked;
-}
-
-
-struct uniform_node {
- exec_node link;
- struct gl_uniform *u;
- unsigned slots;
-};
-
-/**
- * Update the sizes of linked shader uniform arrays to the maximum
- * array index used.
- *
- * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
- *
- * If one or more elements of an array are active,
- * GetActiveUniform will return the name of the array in name,
- * subject to the restrictions listed above. The type of the array
- * is returned in type. The size parameter contains the highest
- * array element index used, plus one. The compiler or linker
- * determines the highest index used. There will be only one
- * active uniform reported by the GL per uniform array.
-
- */
-static void
-update_array_sizes(struct gl_shader_program *prog)
-{
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- foreach_list(node, prog->_LinkedShaders[i]->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != ir_var_uniform &&
- var->mode != ir_var_in &&
- var->mode != ir_var_out) ||
- !var->type->is_array())
- continue;
-
- unsigned int size = var->max_array_access;
- for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
- if (prog->_LinkedShaders[j] == NULL)
- continue;
-
- foreach_list(node2, prog->_LinkedShaders[j]->ir) {
- ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
- if (!other_var)
- continue;
-
- if (strcmp(var->name, other_var->name) == 0 &&
- other_var->max_array_access > size) {
- size = other_var->max_array_access;
- }
- }
- }
-
- if (size + 1 != var->type->fields.array->length) {
- var->type = glsl_type::get_array_instance(var->type->fields.array,
- size + 1);
- /* FINISHME: We should update the types of array
- * dereferences of this variable now.
- */
- }
- }
- }
-}
-
-static void
-add_uniform(void *mem_ctx, exec_list *uniforms, struct hash_table *ht,
- const char *name, const glsl_type *type, GLenum shader_type,
- unsigned *next_shader_pos, unsigned *total_uniforms)
-{
- if (type->is_record()) {
- for (unsigned int i = 0; i < type->length; i++) {
- const glsl_type *field_type = type->fields.structure[i].type;
- char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
- type->fields.structure[i].name);
-
- add_uniform(mem_ctx, uniforms, ht, field_name, field_type,
- shader_type, next_shader_pos, total_uniforms);
- }
- } else {
- uniform_node *n = (uniform_node *) hash_table_find(ht, name);
- unsigned int vec4_slots;
- const glsl_type *array_elem_type = NULL;
-
- if (type->is_array()) {
- array_elem_type = type->fields.array;
- /* Array of structures. */
- if (array_elem_type->is_record()) {
- for (unsigned int i = 0; i < type->length; i++) {
- char *elem_name = talloc_asprintf(mem_ctx, "%s[%d]", name, i);
- add_uniform(mem_ctx, uniforms, ht, elem_name, array_elem_type,
- shader_type, next_shader_pos, total_uniforms);
- }
- return;
- }
- }
-
- /* Fix the storage size of samplers at 1 vec4 each. Be sure to pad out
- * vectors to vec4 slots.
- */
- if (type->is_array()) {
- if (array_elem_type->is_sampler())
- vec4_slots = type->length;
- else
- vec4_slots = type->length * array_elem_type->matrix_columns;
- } else if (type->is_sampler()) {
- vec4_slots = 1;
- } else {
- vec4_slots = type->matrix_columns;
- }
-
- if (n == NULL) {
- n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
- n->u = (gl_uniform *) calloc(1, sizeof(struct gl_uniform));
- n->slots = vec4_slots;
-
- n->u->Name = strdup(name);
- n->u->Type = type;
- n->u->VertPos = -1;
- n->u->FragPos = -1;
- n->u->GeomPos = -1;
- (*total_uniforms)++;
-
- hash_table_insert(ht, n, name);
- uniforms->push_tail(& n->link);
- }
-
- switch (shader_type) {
- case GL_VERTEX_SHADER:
- n->u->VertPos = *next_shader_pos;
- break;
- case GL_FRAGMENT_SHADER:
- n->u->FragPos = *next_shader_pos;
- break;
- case GL_GEOMETRY_SHADER:
- n->u->GeomPos = *next_shader_pos;
- break;
- }
-
- (*next_shader_pos) += vec4_slots;
- }
-}
-
-void
-assign_uniform_locations(struct gl_shader_program *prog)
-{
- /* */
- exec_list uniforms;
- unsigned total_uniforms = 0;
- hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
- hash_table_string_compare);
- void *mem_ctx = talloc_new(NULL);
-
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- unsigned next_position = 0;
-
- foreach_list(node, prog->_LinkedShaders[i]->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != ir_var_uniform))
- continue;
-
- if (strncmp(var->name, "gl_", 3) == 0) {
- /* At the moment, we don't allocate uniform locations for
- * builtin uniforms. It's permitted by spec, and we'll
- * likely switch to doing that at some point, but not yet.
- */
- continue;
- }
-
- var->location = next_position;
- add_uniform(mem_ctx, &uniforms, ht, var->name, var->type,
- prog->_LinkedShaders[i]->Type,
- &next_position, &total_uniforms);
- }
- }
-
- talloc_free(mem_ctx);
-
- gl_uniform_list *ul = (gl_uniform_list *)
- calloc(1, sizeof(gl_uniform_list));
-
- ul->Size = total_uniforms;
- ul->NumUniforms = total_uniforms;
- ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
-
- unsigned idx = 0;
- uniform_node *next;
- for (uniform_node *node = (uniform_node *) uniforms.head
- ; node->link.next != NULL
- ; node = next) {
- next = (uniform_node *) node->link.next;
-
- node->link.remove();
- memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform));
- idx++;
-
- free(node->u);
- free(node);
- }
-
- hash_table_dtor(ht);
-
- prog->Uniforms = ul;
-}
-
-
-/**
- * Find a contiguous set of available bits in a bitmask
- *
- * \param used_mask Bits representing used (1) and unused (0) locations
- * \param needed_count Number of contiguous bits needed.
- *
- * \return
- * Base location of the available bits on success or -1 on failure.
- */
-int
-find_available_slots(unsigned used_mask, unsigned needed_count)
-{
- unsigned needed_mask = (1 << needed_count) - 1;
- const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
-
- /* The comparison to 32 is redundant, but without it GCC emits "warning:
- * cannot optimize possibly infinite loops" for the loop below.
- */
- if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
- return -1;
-
- for (int i = 0; i <= max_bit_to_test; i++) {
- if ((needed_mask & ~used_mask) == needed_mask)
- return i;
-
- needed_mask <<= 1;
- }
-
- return -1;
-}
-
-
-bool
-assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
-{
- /* Mark invalid attribute locations as being used.
- */
- unsigned used_locations = (max_attribute_index >= 32)
- ? ~0 : ~((1 << max_attribute_index) - 1);
-
- gl_shader *const sh = prog->_LinkedShaders[0];
- assert(sh->Type == GL_VERTEX_SHADER);
-
- /* Operate in a total of four passes.
- *
- * 1. Invalidate the location assignments for all vertex shader inputs.
- *
- * 2. Assign locations for inputs that have user-defined (via
- * glBindVertexAttribLocation) locatoins.
- *
- * 3. Sort the attributes without assigned locations by number of slots
- * required in decreasing order. Fragmentation caused by attribute
- * locations assigned by the application may prevent large attributes
- * from having enough contiguous space.
- *
- * 4. Assign locations to any inputs without assigned locations.
- */
-
- invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
-
- if (prog->Attributes != NULL) {
- for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
- ir_variable *const var =
- sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
-
- /* Note: attributes that occupy multiple slots, such as arrays or
- * matrices, may appear in the attrib array multiple times.
- */
- if ((var == NULL) || (var->location != -1))
- continue;
-
- /* From page 61 of the OpenGL 4.0 spec:
- *
- * "LinkProgram will fail if the attribute bindings assigned by
- * BindAttribLocation do not leave not enough space to assign a
- * location for an active matrix attribute or an active attribute
- * array, both of which require multiple contiguous generic
- * attributes."
- *
- * Previous versions of the spec contain similar language but omit the
- * bit about attribute arrays.
- *
- * Page 61 of the OpenGL 4.0 spec also says:
- *
- * "It is possible for an application to bind more than one
- * attribute name to the same location. This is referred to as
- * aliasing. This will only work if only one of the aliased
- * attributes is active in the executable program, or if no path
- * through the shader consumes more than one attribute of a set
- * of attributes aliased to the same location. A link error can
- * occur if the linker determines that every path through the
- * shader consumes multiple aliased attributes, but
- * implementations are not required to generate an error in this
- * case."
- *
- * These two paragraphs are either somewhat contradictory, or I don't
- * fully understand one or both of them.
- */
- /* FINISHME: The code as currently written does not support attribute
- * FINISHME: location aliasing (see comment above).
- */
- const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
- const unsigned slots = count_attribute_slots(var->type);
-
- /* Mask representing the contiguous slots that will be used by this
- * attribute.
- */
- const unsigned use_mask = (1 << slots) - 1;
-
- /* Generate a link error if the set of bits requested for this
- * attribute overlaps any previously allocated bits.
- */
- if ((~(use_mask << attr) & used_locations) != used_locations) {
- linker_error_printf(prog,
- "insufficient contiguous attribute locations "
- "available for vertex shader input `%s'",
- var->name);
- return false;
- }
-
- var->location = VERT_ATTRIB_GENERIC0 + attr;
- used_locations |= (use_mask << attr);
- }
- }
-
- /* Temporary storage for the set of attributes that need locations assigned.
- */
- struct temp_attr {
- unsigned slots;
- ir_variable *var;
-
- /* Used below in the call to qsort. */
- static int compare(const void *a, const void *b)
- {
- const temp_attr *const l = (const temp_attr *) a;
- const temp_attr *const r = (const temp_attr *) b;
-
- /* Reversed because we want a descending order sort below. */
- return r->slots - l->slots;
- }
- } to_assign[16];
-
- unsigned num_attr = 0;
-
- foreach_list(node, sh->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != ir_var_in))
- continue;
-
- if (var->explicit_location) {
- const unsigned slots = count_attribute_slots(var->type);
- const unsigned use_mask = (1 << slots) - 1;
- const int attr = var->location - VERT_ATTRIB_GENERIC0;
-
- if ((var->location >= (int)(max_attribute_index + VERT_ATTRIB_GENERIC0))
- || (var->location < 0)) {
- linker_error_printf(prog,
- "invalid explicit location %d specified for "
- "`%s'\n",
- (var->location < 0) ? var->location : attr,
- var->name);
- return false;
- } else if (var->location >= VERT_ATTRIB_GENERIC0) {
- used_locations |= (use_mask << attr);
- }
- }
-
- /* The location was explicitly assigned, nothing to do here.
- */
- if (var->location != -1)
- continue;
-
- to_assign[num_attr].slots = count_attribute_slots(var->type);
- to_assign[num_attr].var = var;
- num_attr++;
- }
-
- /* If all of the attributes were assigned locations by the application (or
- * are built-in attributes with fixed locations), return early. This should
- * be the common case.
- */
- if (num_attr == 0)
- return true;
-
- qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
-
- /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
- * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
- * to prevent it from being automatically allocated below.
- */
- find_deref_visitor find("gl_Vertex");
- find.run(sh->ir);
- if (find.variable_found())
- used_locations |= (1 << 0);
-
- for (unsigned i = 0; i < num_attr; i++) {
- /* Mask representing the contiguous slots that will be used by this
- * attribute.
- */
- const unsigned use_mask = (1 << to_assign[i].slots) - 1;
-
- int location = find_available_slots(used_locations, to_assign[i].slots);
-
- if (location < 0) {
- linker_error_printf(prog,
- "insufficient contiguous attribute locations "
- "available for vertex shader input `%s'",
- to_assign[i].var->name);
- return false;
- }
-
- to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
- used_locations |= (use_mask << location);
- }
-
- return true;
-}
-
-
-/**
- * Demote shader inputs and outputs that are not used in other stages
- */
-void
-demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
-{
- foreach_list(node, sh->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != int(mode)))
- continue;
-
- /* A shader 'in' or 'out' variable is only really an input or output if
- * its value is used by other shader stages. This will cause the variable
- * to have a location assigned.
- */
- if (var->location == -1) {
- var->mode = ir_var_auto;
- }
- }
-}
-
-
-void
-assign_varying_locations(struct gl_shader_program *prog,
- gl_shader *producer, gl_shader *consumer)
-{
- /* FINISHME: Set dynamically when geometry shader support is added. */
- unsigned output_index = VERT_RESULT_VAR0;
- unsigned input_index = FRAG_ATTRIB_VAR0;
-
- /* Operate in a total of three passes.
- *
- * 1. Assign locations for any matching inputs and outputs.
- *
- * 2. Mark output variables in the producer that do not have locations as
- * not being outputs. This lets the optimizer eliminate them.
- *
- * 3. Mark input variables in the consumer that do not have locations as
- * not being inputs. This lets the optimizer eliminate them.
- */
-
- invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
- invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
-
- foreach_list(node, producer->ir) {
- ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
-
- if ((output_var == NULL) || (output_var->mode != ir_var_out)
- || (output_var->location != -1))
- continue;
-
- ir_variable *const input_var =
- consumer->symbols->get_variable(output_var->name);
-
- if ((input_var == NULL) || (input_var->mode != ir_var_in))
- continue;
-
- assert(input_var->location == -1);
-
- output_var->location = output_index;
- input_var->location = input_index;
-
- /* FINISHME: Support for "varying" records in GLSL 1.50. */
- assert(!output_var->type->is_record());
-
- if (output_var->type->is_array()) {
- const unsigned slots = output_var->type->length
- * output_var->type->fields.array->matrix_columns;
-
- output_index += slots;
- input_index += slots;
- } else {
- const unsigned slots = output_var->type->matrix_columns;
-
- output_index += slots;
- input_index += slots;
- }
- }
-
- foreach_list(node, consumer->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != ir_var_in))
- continue;
-
- if (var->location == -1) {
- if (prog->Version <= 120) {
- /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
- *
- * Only those varying variables used (i.e. read) in
- * the fragment shader executable must be written to
- * by the vertex shader executable; declaring
- * superfluous varying variables in a vertex shader is
- * permissible.
- *
- * We interpret this text as meaning that the VS must
- * write the variable for the FS to read it. See
- * "glsl1-varying read but not written" in piglit.
- */
-
- linker_error_printf(prog, "fragment shader varying %s not written "
- "by vertex shader\n.", var->name);
- prog->LinkStatus = false;
- }
-
- /* An 'in' variable is only really a shader input if its
- * value is written by the previous stage.
- */
- var->mode = ir_var_auto;
- }
- }
-}
-
-
-void
-link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
-{
- void *mem_ctx = talloc_init("temporary linker context");
-
- prog->LinkStatus = false;
- prog->Validated = false;
- prog->_Used = false;
-
- if (prog->InfoLog != NULL)
- talloc_free(prog->InfoLog);
-
- prog->InfoLog = talloc_strdup(NULL, "");
-
- /* Separate the shaders into groups based on their type.
- */
- struct gl_shader **vert_shader_list;
- unsigned num_vert_shaders = 0;
- struct gl_shader **frag_shader_list;
- unsigned num_frag_shaders = 0;
-
- vert_shader_list = (struct gl_shader **)
- calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
- frag_shader_list = &vert_shader_list[prog->NumShaders];
-
- unsigned min_version = UINT_MAX;
- unsigned max_version = 0;
- for (unsigned i = 0; i < prog->NumShaders; i++) {
- min_version = MIN2(min_version, prog->Shaders[i]->Version);
- max_version = MAX2(max_version, prog->Shaders[i]->Version);
-
- switch (prog->Shaders[i]->Type) {
- case GL_VERTEX_SHADER:
- vert_shader_list[num_vert_shaders] = prog->Shaders[i];
- num_vert_shaders++;
- break;
- case GL_FRAGMENT_SHADER:
- frag_shader_list[num_frag_shaders] = prog->Shaders[i];
- num_frag_shaders++;
- break;
- case GL_GEOMETRY_SHADER:
- /* FINISHME: Support geometry shaders. */
- assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
- break;
- }
- }
-
- /* Previous to GLSL version 1.30, different compilation units could mix and
- * match shading language versions. With GLSL 1.30 and later, the versions
- * of all shaders must match.
- */
- assert(min_version >= 100);
- assert(max_version <= 130);
- if ((max_version >= 130 || min_version == 100)
- && min_version != max_version) {
- linker_error_printf(prog, "all shaders must use same shading "
- "language version\n");
- goto done;
- }
-
- prog->Version = max_version;
-
- for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] != NULL)
- ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
-
- prog->_LinkedShaders[i] = NULL;
- }
-
- /* Link all shaders for a particular stage and validate the result.
- */
- if (num_vert_shaders > 0) {
- gl_shader *const sh =
- link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
- num_vert_shaders);
-
- if (sh == NULL)
- goto done;
-
- if (!validate_vertex_shader_executable(prog, sh))
- goto done;
-
- _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
- sh);
- }
-
- if (num_frag_shaders > 0) {
- gl_shader *const sh =
- link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
- num_frag_shaders);
-
- if (sh == NULL)
- goto done;
-
- if (!validate_fragment_shader_executable(prog, sh))
- goto done;
-
- _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
- sh);
- }
-
- /* Here begins the inter-stage linking phase. Some initial validation is
- * performed, then locations are assigned for uniforms, attributes, and
- * varyings.
- */
- if (cross_validate_uniforms(prog)) {
- unsigned prev;
-
- for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
- if (prog->_LinkedShaders[prev] != NULL)
- break;
- }
-
- /* Validate the inputs of each stage with the output of the preceeding
- * stage.
- */
- for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- if (!cross_validate_outputs_to_inputs(prog,
- prog->_LinkedShaders[prev],
- prog->_LinkedShaders[i]))
- goto done;
-
- prev = i;
- }
-
- prog->LinkStatus = true;
- }
-
- /* Do common optimization before assigning storage for attributes,
- * uniforms, and varyings. Later optimization could possibly make
- * some of that unused.
- */
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, 32))
- ;
- }
-
- update_array_sizes(prog);
-
- assign_uniform_locations(prog);
-
- if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
- /* FINISHME: The value of the max_attribute_index parameter is
- * FINISHME: implementation dependent based on the value of
- * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
- * FINISHME: at least 16, so hardcode 16 for now.
- */
- if (!assign_attribute_locations(prog, 16)) {
- prog->LinkStatus = false;
- goto done;
- }
- }
-
- unsigned prev;
- for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
- if (prog->_LinkedShaders[prev] != NULL)
- break;
- }
-
- for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- assign_varying_locations(prog,
- prog->_LinkedShaders[prev],
- prog->_LinkedShaders[i]);
- prev = i;
- }
-
- if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
- demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
- ir_var_out);
- }
-
- if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
- gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
-
- demote_shader_inputs_and_outputs(sh, ir_var_in);
- demote_shader_inputs_and_outputs(sh, ir_var_inout);
- demote_shader_inputs_and_outputs(sh, ir_var_out);
- }
-
- if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
- gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
-
- demote_shader_inputs_and_outputs(sh, ir_var_in);
- }
-
- /* FINISHME: Assign fragment shader output locations. */
-
-done:
- free(vert_shader_list);
-
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- /* Retain any live IR, but trash the rest. */
- reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
- }
-
- talloc_free(mem_ctx);
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+/**
+ * \file linker.cpp
+ * GLSL linker implementation
+ *
+ * Given a set of shaders that are to be linked to generate a final program,
+ * there are three distinct stages.
+ *
+ * In the first stage shaders are partitioned into groups based on the shader
+ * type. All shaders of a particular type (e.g., vertex shaders) are linked
+ * together.
+ *
+ * - Undefined references in each shader are resolve to definitions in
+ * another shader.
+ * - Types and qualifiers of uniforms, outputs, and global variables defined
+ * in multiple shaders with the same name are verified to be the same.
+ * - Initializers for uniforms and global variables defined
+ * in multiple shaders with the same name are verified to be the same.
+ *
+ * The result, in the terminology of the GLSL spec, is a set of shader
+ * executables for each processing unit.
+ *
+ * After the first stage is complete, a series of semantic checks are performed
+ * on each of the shader executables.
+ *
+ * - Each shader executable must define a \c main function.
+ * - Each vertex shader executable must write to \c gl_Position.
+ * - Each fragment shader executable must write to either \c gl_FragData or
+ * \c gl_FragColor.
+ *
+ * In the final stage individual shader executables are linked to create a
+ * complete exectuable.
+ *
+ * - Types of uniforms defined in multiple shader stages with the same name
+ * are verified to be the same.
+ * - Initializers for uniforms defined in multiple shader stages with the
+ * same name are verified to be the same.
+ * - Types and qualifiers of outputs defined in one stage are verified to
+ * be the same as the types and qualifiers of inputs defined with the same
+ * name in a later stage.
+ *
+ * \author Ian Romanick <ian.d.romanick@intel.com>
+ */
+#include <cstdlib>
+#include <cstdio>
+#include <cstdarg>
+#include <climits>
+
+#include "main/core.h"
+#include "glsl_symbol_table.h"
+#include "ir.h"
+#include "program.h"
+#include "program/hash_table.h"
+#include "linker.h"
+#include "ir_optimization.h"
+
+extern "C" {
+#include "main/shaderobj.h"
+}
+
+/**
+ * Visitor that determines whether or not a variable is ever written.
+ */
+class find_assignment_visitor : public ir_hierarchical_visitor {
+public:
+ find_assignment_visitor(const char *name)
+ : name(name), found(false)
+ {
+ /* empty */
+ }
+
+ virtual ir_visitor_status visit_enter(ir_assignment *ir)
+ {
+ ir_variable *const var = ir->lhs->variable_referenced();
+
+ if (strcmp(name, var->name) == 0) {
+ found = true;
+ return visit_stop;
+ }
+
+ return visit_continue_with_parent;
+ }
+
+ virtual ir_visitor_status visit_enter(ir_call *ir)
+ {
+ exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
+ foreach_iter(exec_list_iterator, iter, *ir) {
+ ir_rvalue *param_rval = (ir_rvalue *)iter.get();
+ ir_variable *sig_param = (ir_variable *)sig_iter.get();
+
+ if (sig_param->mode == ir_var_out ||
+ sig_param->mode == ir_var_inout) {
+ ir_variable *var = param_rval->variable_referenced();
+ if (var && strcmp(name, var->name) == 0) {
+ found = true;
+ return visit_stop;
+ }
+ }
+ sig_iter.next();
+ }
+
+ return visit_continue_with_parent;
+ }
+
+ bool variable_found()
+ {
+ return found;
+ }
+
+private:
+ const char *name; /**< Find writes to a variable with this name. */
+ bool found; /**< Was a write to the variable found? */
+};
+
+
+/**
+ * Visitor that determines whether or not a variable is ever read.
+ */
+class find_deref_visitor : public ir_hierarchical_visitor {
+public:
+ find_deref_visitor(const char *name)
+ : name(name), found(false)
+ {
+ /* empty */
+ }
+
+ virtual ir_visitor_status visit(ir_dereference_variable *ir)
+ {
+ if (strcmp(this->name, ir->var->name) == 0) {
+ this->found = true;
+ return visit_stop;
+ }
+
+ return visit_continue;
+ }
+
+ bool variable_found() const
+ {
+ return this->found;
+ }
+
+private:
+ const char *name; /**< Find writes to a variable with this name. */
+ bool found; /**< Was a write to the variable found? */
+};
+
+
+void
+linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
+{
+ va_list ap;
+
+ prog->InfoLog = talloc_strdup_append(prog->InfoLog, "error: ");
+ va_start(ap, fmt);
+ prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, ap);
+ va_end(ap);
+}
+
+
+void
+invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
+ int generic_base)
+{
+ foreach_list(node, sh->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != (unsigned) mode))
+ continue;
+
+ /* Only assign locations for generic attributes / varyings / etc.
+ */
+ if ((var->location >= generic_base) && !var->explicit_location)
+ var->location = -1;
+ }
+}
+
+
+/**
+ * Determine the number of attribute slots required for a particular type
+ *
+ * This code is here because it implements the language rules of a specific
+ * GLSL version. Since it's a property of the language and not a property of
+ * types in general, it doesn't really belong in glsl_type.
+ */
+unsigned
+count_attribute_slots(const glsl_type *t)
+{
+ /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "A scalar input counts the same amount against this limit as a vec4,
+ * so applications may want to consider packing groups of four
+ * unrelated float inputs together into a vector to better utilize the
+ * capabilities of the underlying hardware. A matrix input will use up
+ * multiple locations. The number of locations used will equal the
+ * number of columns in the matrix."
+ *
+ * The spec does not explicitly say how arrays are counted. However, it
+ * should be safe to assume the total number of slots consumed by an array
+ * is the number of entries in the array multiplied by the number of slots
+ * consumed by a single element of the array.
+ */
+
+ if (t->is_array())
+ return t->array_size() * count_attribute_slots(t->element_type());
+
+ if (t->is_matrix())
+ return t->matrix_columns;
+
+ return 1;
+}
+
+
+/**
+ * Verify that a vertex shader executable meets all semantic requirements
+ *
+ * \param shader Vertex shader executable to be verified
+ */
+bool
+validate_vertex_shader_executable(struct gl_shader_program *prog,
+ struct gl_shader *shader)
+{
+ if (shader == NULL)
+ return true;
+
+ find_assignment_visitor find("gl_Position");
+ find.run(shader->ir);
+ if (!find.variable_found()) {
+ linker_error_printf(prog,
+ "vertex shader does not write to `gl_Position'\n");
+ return false;
+ }
+
+ return true;
+}
+
+
+/**
+ * Verify that a fragment shader executable meets all semantic requirements
+ *
+ * \param shader Fragment shader executable to be verified
+ */
+bool
+validate_fragment_shader_executable(struct gl_shader_program *prog,
+ struct gl_shader *shader)
+{
+ if (shader == NULL)
+ return true;
+
+ find_assignment_visitor frag_color("gl_FragColor");
+ find_assignment_visitor frag_data("gl_FragData");
+
+ frag_color.run(shader->ir);
+ frag_data.run(shader->ir);
+
+ if (frag_color.variable_found() && frag_data.variable_found()) {
+ linker_error_printf(prog, "fragment shader writes to both "
+ "`gl_FragColor' and `gl_FragData'\n");
+ return false;
+ }
+
+ return true;
+}
+
+
+/**
+ * Generate a string describing the mode of a variable
+ */
+static const char *
+mode_string(const ir_variable *var)
+{
+ switch (var->mode) {
+ case ir_var_auto:
+ return (var->read_only) ? "global constant" : "global variable";
+
+ case ir_var_uniform: return "uniform";
+ case ir_var_in: return "shader input";
+ case ir_var_out: return "shader output";
+ case ir_var_inout: return "shader inout";
+
+ case ir_var_temporary:
+ default:
+ assert(!"Should not get here.");
+ return "invalid variable";
+ }
+}
+
+
+/**
+ * Perform validation of global variables used across multiple shaders
+ */
+bool
+cross_validate_globals(struct gl_shader_program *prog,
+ struct gl_shader **shader_list,
+ unsigned num_shaders,
+ bool uniforms_only)
+{
+ /* Examine all of the uniforms in all of the shaders and cross validate
+ * them.
+ */
+ glsl_symbol_table variables;
+ for (unsigned i = 0; i < num_shaders; i++) {
+ if (shader_list[i] == NULL)
+ continue;
+
+ foreach_list(node, shader_list[i]->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if (var == NULL)
+ continue;
+
+ if (uniforms_only && (var->mode != ir_var_uniform))
+ continue;
+
+ /* Don't cross validate temporaries that are at global scope. These
+ * will eventually get pulled into the shaders 'main'.
+ */
+ if (var->mode == ir_var_temporary)
+ continue;
+
+ /* If a global with this name has already been seen, verify that the
+ * new instance has the same type. In addition, if the globals have
+ * initializers, the values of the initializers must be the same.
+ */
+ ir_variable *const existing = variables.get_variable(var->name);
+ if (existing != NULL) {
+ if (var->type != existing->type) {
+ /* Consider the types to be "the same" if both types are arrays
+ * of the same type and one of the arrays is implicitly sized.
+ * In addition, set the type of the linked variable to the
+ * explicitly sized array.
+ */
+ if (var->type->is_array()
+ && existing->type->is_array()
+ && (var->type->fields.array == existing->type->fields.array)
+ && ((var->type->length == 0)
+ || (existing->type->length == 0))) {
+ if (var->type->length != 0) {
+ existing->type = var->type;
+ }
+ } else {
+ linker_error_printf(prog, "%s `%s' declared as type "
+ "`%s' and type `%s'\n",
+ mode_string(var),
+ var->name, var->type->name,
+ existing->type->name);
+ return false;
+ }
+ }
+
+ if (var->explicit_location) {
+ if (existing->explicit_location
+ && (var->location != existing->location)) {
+ linker_error_printf(prog, "explicit locations for %s "
+ "`%s' have differing values\n",
+ mode_string(var), var->name);
+ return false;
+ }
+
+ existing->location = var->location;
+ existing->explicit_location = true;
+ }
+
+ /* FINISHME: Handle non-constant initializers.
+ */
+ if (var->constant_value != NULL) {
+ if (existing->constant_value != NULL) {
+ if (!var->constant_value->has_value(existing->constant_value)) {
+ linker_error_printf(prog, "initializers for %s "
+ "`%s' have differing values\n",
+ mode_string(var), var->name);
+ return false;
+ }
+ } else
+ /* If the first-seen instance of a particular uniform did not
+ * have an initializer but a later instance does, copy the
+ * initializer to the version stored in the symbol table.
+ */
+ /* FINISHME: This is wrong. The constant_value field should
+ * FINISHME: not be modified! Imagine a case where a shader
+ * FINISHME: without an initializer is linked in two different
+ * FINISHME: programs with shaders that have differing
+ * FINISHME: initializers. Linking with the first will
+ * FINISHME: modify the shader, and linking with the second
+ * FINISHME: will fail.
+ */
+ existing->constant_value =
+ var->constant_value->clone(talloc_parent(existing), NULL);
+ }
+
+ if (existing->invariant != var->invariant) {
+ linker_error_printf(prog, "declarations for %s `%s' have "
+ "mismatching invariant qualifiers\n",
+ mode_string(var), var->name);
+ return false;
+ }
+ if (existing->centroid != var->centroid) {
+ linker_error_printf(prog, "declarations for %s `%s' have "
+ "mismatching centroid qualifiers\n",
+ mode_string(var), var->name);
+ return false;
+ }
+ } else
+ variables.add_variable(var);
+ }
+ }
+
+ return true;
+}
+
+
+/**
+ * Perform validation of uniforms used across multiple shader stages
+ */
+bool
+cross_validate_uniforms(struct gl_shader_program *prog)
+{
+ return cross_validate_globals(prog, prog->_LinkedShaders,
+ MESA_SHADER_TYPES, true);
+}
+
+
+/**
+ * Validate that outputs from one stage match inputs of another
+ */
+bool
+cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
+ gl_shader *producer, gl_shader *consumer)
+{
+ glsl_symbol_table parameters;
+ /* FINISHME: Figure these out dynamically. */
+ const char *const producer_stage = "vertex";
+ const char *const consumer_stage = "fragment";
+
+ /* Find all shader outputs in the "producer" stage.
+ */
+ foreach_list(node, producer->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ /* FINISHME: For geometry shaders, this should also look for inout
+ * FINISHME: variables.
+ */
+ if ((var == NULL) || (var->mode != ir_var_out))
+ continue;
+
+ parameters.add_variable(var);
+ }
+
+
+ /* Find all shader inputs in the "consumer" stage. Any variables that have
+ * matching outputs already in the symbol table must have the same type and
+ * qualifiers.
+ */
+ foreach_list(node, consumer->ir) {
+ ir_variable *const input = ((ir_instruction *) node)->as_variable();
+
+ /* FINISHME: For geometry shaders, this should also look for inout
+ * FINISHME: variables.
+ */
+ if ((input == NULL) || (input->mode != ir_var_in))
+ continue;
+
+ ir_variable *const output = parameters.get_variable(input->name);
+ if (output != NULL) {
+ /* Check that the types match between stages.
+ */
+ if (input->type != output->type) {
+ /* There is a bit of a special case for gl_TexCoord. This
+ * built-in is unsized by default. Appliations that variable
+ * access it must redeclare it with a size. There is some
+ * language in the GLSL spec that implies the fragment shader
+ * and vertex shader do not have to agree on this size. Other
+ * driver behave this way, and one or two applications seem to
+ * rely on it.
+ *
+ * Neither declaration needs to be modified here because the array
+ * sizes are fixed later when update_array_sizes is called.
+ *
+ * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
+ *
+ * "Unlike user-defined varying variables, the built-in
+ * varying variables don't have a strict one-to-one
+ * correspondence between the vertex language and the
+ * fragment language."
+ */
+ if (!output->type->is_array()
+ || (strncmp("gl_", output->name, 3) != 0)) {
+ linker_error_printf(prog,
+ "%s shader output `%s' declared as "
+ "type `%s', but %s shader input declared "
+ "as type `%s'\n",
+ producer_stage, output->name,
+ output->type->name,
+ consumer_stage, input->type->name);
+ return false;
+ }
+ }
+
+ /* Check that all of the qualifiers match between stages.
+ */
+ if (input->centroid != output->centroid) {
+ linker_error_printf(prog,
+ "%s shader output `%s' %s centroid qualifier, "
+ "but %s shader input %s centroid qualifier\n",
+ producer_stage,
+ output->name,
+ (output->centroid) ? "has" : "lacks",
+ consumer_stage,
+ (input->centroid) ? "has" : "lacks");
+ return false;
+ }
+
+ if (input->invariant != output->invariant) {
+ linker_error_printf(prog,
+ "%s shader output `%s' %s invariant qualifier, "
+ "but %s shader input %s invariant qualifier\n",
+ producer_stage,
+ output->name,
+ (output->invariant) ? "has" : "lacks",
+ consumer_stage,
+ (input->invariant) ? "has" : "lacks");
+ return false;
+ }
+
+ if (input->interpolation != output->interpolation) {
+ linker_error_printf(prog,
+ "%s shader output `%s' specifies %s "
+ "interpolation qualifier, "
+ "but %s shader input specifies %s "
+ "interpolation qualifier\n",
+ producer_stage,
+ output->name,
+ output->interpolation_string(),
+ consumer_stage,
+ input->interpolation_string());
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+
+/**
+ * Populates a shaders symbol table with all global declarations
+ */
+static void
+populate_symbol_table(gl_shader *sh)
+{
+ sh->symbols = new(sh) glsl_symbol_table;
+
+ foreach_list(node, sh->ir) {
+ ir_instruction *const inst = (ir_instruction *) node;
+ ir_variable *var;
+ ir_function *func;
+
+ if ((func = inst->as_function()) != NULL) {
+ sh->symbols->add_function(func);
+ } else if ((var = inst->as_variable()) != NULL) {
+ sh->symbols->add_variable(var);
+ }
+ }
+}
+
+
+/**
+ * Remap variables referenced in an instruction tree
+ *
+ * This is used when instruction trees are cloned from one shader and placed in
+ * another. These trees will contain references to \c ir_variable nodes that
+ * do not exist in the target shader. This function finds these \c ir_variable
+ * references and replaces the references with matching variables in the target
+ * shader.
+ *
+ * If there is no matching variable in the target shader, a clone of the
+ * \c ir_variable is made and added to the target shader. The new variable is
+ * added to \b both the instruction stream and the symbol table.
+ *
+ * \param inst IR tree that is to be processed.
+ * \param symbols Symbol table containing global scope symbols in the
+ * linked shader.
+ * \param instructions Instruction stream where new variable declarations
+ * should be added.
+ */
+void
+remap_variables(ir_instruction *inst, struct gl_shader *target,
+ hash_table *temps)
+{
+ class remap_visitor : public ir_hierarchical_visitor {
+ public:
+ remap_visitor(struct gl_shader *target,
+ hash_table *temps)
+ {
+ this->target = target;
+ this->symbols = target->symbols;
+ this->instructions = target->ir;
+ this->temps = temps;
+ }
+
+ virtual ir_visitor_status visit(ir_dereference_variable *ir)
+ {
+ if (ir->var->mode == ir_var_temporary) {
+ ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
+
+ assert(var != NULL);
+ ir->var = var;
+ return visit_continue;
+ }
+
+ ir_variable *const existing =
+ this->symbols->get_variable(ir->var->name);
+ if (existing != NULL)
+ ir->var = existing;
+ else {
+ ir_variable *copy = ir->var->clone(this->target, NULL);
+
+ this->symbols->add_variable(copy);
+ this->instructions->push_head(copy);
+ ir->var = copy;
+ }
+
+ return visit_continue;
+ }
+
+ private:
+ struct gl_shader *target;
+ glsl_symbol_table *symbols;
+ exec_list *instructions;
+ hash_table *temps;
+ };
+
+ remap_visitor v(target, temps);
+
+ inst->accept(&v);
+}
+
+
+/**
+ * Move non-declarations from one instruction stream to another
+ *
+ * The intended usage pattern of this function is to pass the pointer to the
+ * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
+ * pointer) for \c last and \c false for \c make_copies on the first
+ * call. Successive calls pass the return value of the previous call for
+ * \c last and \c true for \c make_copies.
+ *
+ * \param instructions Source instruction stream
+ * \param last Instruction after which new instructions should be
+ * inserted in the target instruction stream
+ * \param make_copies Flag selecting whether instructions in \c instructions
+ * should be copied (via \c ir_instruction::clone) into the
+ * target list or moved.
+ *
+ * \return
+ * The new "last" instruction in the target instruction stream. This pointer
+ * is suitable for use as the \c last parameter of a later call to this
+ * function.
+ */
+exec_node *
+move_non_declarations(exec_list *instructions, exec_node *last,
+ bool make_copies, gl_shader *target)
+{
+ hash_table *temps = NULL;
+
+ if (make_copies)
+ temps = hash_table_ctor(0, hash_table_pointer_hash,
+ hash_table_pointer_compare);
+
+ foreach_list_safe(node, instructions) {
+ ir_instruction *inst = (ir_instruction *) node;
+
+ if (inst->as_function())
+ continue;
+
+ ir_variable *var = inst->as_variable();
+ if ((var != NULL) && (var->mode != ir_var_temporary))
+ continue;
+
+ assert(inst->as_assignment()
+ || ((var != NULL) && (var->mode == ir_var_temporary)));
+
+ if (make_copies) {
+ inst = inst->clone(target, NULL);
+
+ if (var != NULL)
+ hash_table_insert(temps, inst, var);
+ else
+ remap_variables(inst, target, temps);
+ } else {
+ inst->remove();
+ }
+
+ last->insert_after(inst);
+ last = inst;
+ }
+
+ if (make_copies)
+ hash_table_dtor(temps);
+
+ return last;
+}
+
+/**
+ * Get the function signature for main from a shader
+ */
+static ir_function_signature *
+get_main_function_signature(gl_shader *sh)
+{
+ ir_function *const f = sh->symbols->get_function("main");
+ if (f != NULL) {
+ exec_list void_parameters;
+
+ /* Look for the 'void main()' signature and ensure that it's defined.
+ * This keeps the linker from accidentally pick a shader that just
+ * contains a prototype for main.
+ *
+ * We don't have to check for multiple definitions of main (in multiple
+ * shaders) because that would have already been caught above.
+ */
+ ir_function_signature *sig = f->matching_signature(&void_parameters);
+ if ((sig != NULL) && sig->is_defined) {
+ return sig;
+ }
+ }
+
+ return NULL;
+}
+
+
+/**
+ * Combine a group of shaders for a single stage to generate a linked shader
+ *
+ * \note
+ * If this function is supplied a single shader, it is cloned, and the new
+ * shader is returned.
+ */
+static struct gl_shader *
+link_intrastage_shaders(void *mem_ctx,
+ struct gl_context *ctx,
+ struct gl_shader_program *prog,
+ struct gl_shader **shader_list,
+ unsigned num_shaders)
+{
+ /* Check that global variables defined in multiple shaders are consistent.
+ */
+ if (!cross_validate_globals(prog, shader_list, num_shaders, false))
+ return NULL;
+
+ /* Check that there is only a single definition of each function signature
+ * across all shaders.
+ */
+ for (unsigned i = 0; i < (num_shaders - 1); i++) {
+ foreach_list(node, shader_list[i]->ir) {
+ ir_function *const f = ((ir_instruction *) node)->as_function();
+
+ if (f == NULL)
+ continue;
+
+ for (unsigned j = i + 1; j < num_shaders; j++) {
+ ir_function *const other =
+ shader_list[j]->symbols->get_function(f->name);
+
+ /* If the other shader has no function (and therefore no function
+ * signatures) with the same name, skip to the next shader.
+ */
+ if (other == NULL)
+ continue;
+
+ foreach_iter (exec_list_iterator, iter, *f) {
+ ir_function_signature *sig =
+ (ir_function_signature *) iter.get();
+
+ if (!sig->is_defined || sig->is_builtin)
+ continue;
+
+ ir_function_signature *other_sig =
+ other->exact_matching_signature(& sig->parameters);
+
+ if ((other_sig != NULL) && other_sig->is_defined
+ && !other_sig->is_builtin) {
+ linker_error_printf(prog,
+ "function `%s' is multiply defined",
+ f->name);
+ return NULL;
+ }
+ }
+ }
+ }
+ }
+
+ /* Find the shader that defines main, and make a clone of it.
+ *
+ * Starting with the clone, search for undefined references. If one is
+ * found, find the shader that defines it. Clone the reference and add
+ * it to the shader. Repeat until there are no undefined references or
+ * until a reference cannot be resolved.
+ */
+ gl_shader *main = NULL;
+ for (unsigned i = 0; i < num_shaders; i++) {
+ if (get_main_function_signature(shader_list[i]) != NULL) {
+ main = shader_list[i];
+ break;
+ }
+ }
+
+ if (main == NULL) {
+ linker_error_printf(prog, "%s shader lacks `main'\n",
+ (shader_list[0]->Type == GL_VERTEX_SHADER)
+ ? "vertex" : "fragment");
+ return NULL;
+ }
+
+ gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
+ linked->ir = new(linked) exec_list;
+ clone_ir_list(mem_ctx, linked->ir, main->ir);
+
+ populate_symbol_table(linked);
+
+ /* The a pointer to the main function in the final linked shader (i.e., the
+ * copy of the original shader that contained the main function).
+ */
+ ir_function_signature *const main_sig = get_main_function_signature(linked);
+
+ /* Move any instructions other than variable declarations or function
+ * declarations into main.
+ */
+ exec_node *insertion_point =
+ move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
+ linked);
+
+ for (unsigned i = 0; i < num_shaders; i++) {
+ if (shader_list[i] == main)
+ continue;
+
+ insertion_point = move_non_declarations(shader_list[i]->ir,
+ insertion_point, true, linked);
+ }
+
+ /* Resolve initializers for global variables in the linked shader.
+ */
+ unsigned num_linking_shaders = num_shaders;
+ for (unsigned i = 0; i < num_shaders; i++)
+ num_linking_shaders += shader_list[i]->num_builtins_to_link;
+
+ gl_shader **linking_shaders =
+ (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
+
+ memcpy(linking_shaders, shader_list,
+ sizeof(linking_shaders[0]) * num_shaders);
+
+ unsigned idx = num_shaders;
+ for (unsigned i = 0; i < num_shaders; i++) {
+ memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
+ sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
+ idx += shader_list[i]->num_builtins_to_link;
+ }
+
+ assert(idx == num_linking_shaders);
+
+ if (!link_function_calls(prog, linked, linking_shaders,
+ num_linking_shaders)) {
+ ctx->Driver.DeleteShader(ctx, linked);
+ linked = NULL;
+ }
+
+ free(linking_shaders);
+
+ /* Make a pass over all variable declarations to ensure that arrays with
+ * unspecified sizes have a size specified. The size is inferred from the
+ * max_array_access field.
+ */
+ if (linked != NULL) {
+ class array_sizing_visitor : public ir_hierarchical_visitor {
+ public:
+ virtual ir_visitor_status visit(ir_variable *var)
+ {
+ if (var->type->is_array() && (var->type->length == 0)) {
+ const glsl_type *type =
+ glsl_type::get_array_instance(var->type->fields.array,
+ var->max_array_access);
+
+ assert(type != NULL);
+ var->type = type;
+ }
+
+ return visit_continue;
+ }
+ } v;
+
+ v.run(linked->ir);
+ }
+
+ return linked;
+}
+
+
+struct uniform_node {
+ exec_node link;
+ struct gl_uniform *u;
+ unsigned slots;
+};
+
+/**
+ * Update the sizes of linked shader uniform arrays to the maximum
+ * array index used.
+ *
+ * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
+ *
+ * If one or more elements of an array are active,
+ * GetActiveUniform will return the name of the array in name,
+ * subject to the restrictions listed above. The type of the array
+ * is returned in type. The size parameter contains the highest
+ * array element index used, plus one. The compiler or linker
+ * determines the highest index used. There will be only one
+ * active uniform reported by the GL per uniform array.
+
+ */
+static void
+update_array_sizes(struct gl_shader_program *prog)
+{
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ foreach_list(node, prog->_LinkedShaders[i]->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != ir_var_uniform &&
+ var->mode != ir_var_in &&
+ var->mode != ir_var_out) ||
+ !var->type->is_array())
+ continue;
+
+ unsigned int size = var->max_array_access;
+ for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
+ if (prog->_LinkedShaders[j] == NULL)
+ continue;
+
+ foreach_list(node2, prog->_LinkedShaders[j]->ir) {
+ ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
+ if (!other_var)
+ continue;
+
+ if (strcmp(var->name, other_var->name) == 0 &&
+ other_var->max_array_access > size) {
+ size = other_var->max_array_access;
+ }
+ }
+ }
+
+ if (size + 1 != var->type->fields.array->length) {
+ var->type = glsl_type::get_array_instance(var->type->fields.array,
+ size + 1);
+ /* FINISHME: We should update the types of array
+ * dereferences of this variable now.
+ */
+ }
+ }
+ }
+}
+
+static void
+add_uniform(void *mem_ctx, exec_list *uniforms, struct hash_table *ht,
+ const char *name, const glsl_type *type, GLenum shader_type,
+ unsigned *next_shader_pos, unsigned *total_uniforms)
+{
+ if (type->is_record()) {
+ for (unsigned int i = 0; i < type->length; i++) {
+ const glsl_type *field_type = type->fields.structure[i].type;
+ char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
+ type->fields.structure[i].name);
+
+ add_uniform(mem_ctx, uniforms, ht, field_name, field_type,
+ shader_type, next_shader_pos, total_uniforms);
+ }
+ } else {
+ uniform_node *n = (uniform_node *) hash_table_find(ht, name);
+ unsigned int vec4_slots;
+ const glsl_type *array_elem_type = NULL;
+
+ if (type->is_array()) {
+ array_elem_type = type->fields.array;
+ /* Array of structures. */
+ if (array_elem_type->is_record()) {
+ for (unsigned int i = 0; i < type->length; i++) {
+ char *elem_name = talloc_asprintf(mem_ctx, "%s[%d]", name, i);
+ add_uniform(mem_ctx, uniforms, ht, elem_name, array_elem_type,
+ shader_type, next_shader_pos, total_uniforms);
+ }
+ return;
+ }
+ }
+
+ /* Fix the storage size of samplers at 1 vec4 each. Be sure to pad out
+ * vectors to vec4 slots.
+ */
+ if (type->is_array()) {
+ if (array_elem_type->is_sampler())
+ vec4_slots = type->length;
+ else
+ vec4_slots = type->length * array_elem_type->matrix_columns;
+ } else if (type->is_sampler()) {
+ vec4_slots = 1;
+ } else {
+ vec4_slots = type->matrix_columns;
+ }
+
+ if (n == NULL) {
+ n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
+ n->u = (gl_uniform *) calloc(1, sizeof(struct gl_uniform));
+ n->slots = vec4_slots;
+
+ n->u->Name = strdup(name);
+ n->u->Type = type;
+ n->u->VertPos = -1;
+ n->u->FragPos = -1;
+ n->u->GeomPos = -1;
+ (*total_uniforms)++;
+
+ hash_table_insert(ht, n, name);
+ uniforms->push_tail(& n->link);
+ }
+
+ switch (shader_type) {
+ case GL_VERTEX_SHADER:
+ n->u->VertPos = *next_shader_pos;
+ break;
+ case GL_FRAGMENT_SHADER:
+ n->u->FragPos = *next_shader_pos;
+ break;
+ case GL_GEOMETRY_SHADER:
+ n->u->GeomPos = *next_shader_pos;
+ break;
+ }
+
+ (*next_shader_pos) += vec4_slots;
+ }
+}
+
+void
+assign_uniform_locations(struct gl_shader_program *prog)
+{
+ /* */
+ exec_list uniforms;
+ unsigned total_uniforms = 0;
+ hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
+ hash_table_string_compare);
+ void *mem_ctx = talloc_new(NULL);
+
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ unsigned next_position = 0;
+
+ foreach_list(node, prog->_LinkedShaders[i]->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != ir_var_uniform))
+ continue;
+
+ if (strncmp(var->name, "gl_", 3) == 0) {
+ /* At the moment, we don't allocate uniform locations for
+ * builtin uniforms. It's permitted by spec, and we'll
+ * likely switch to doing that at some point, but not yet.
+ */
+ continue;
+ }
+
+ var->location = next_position;
+ add_uniform(mem_ctx, &uniforms, ht, var->name, var->type,
+ prog->_LinkedShaders[i]->Type,
+ &next_position, &total_uniforms);
+ }
+ }
+
+ talloc_free(mem_ctx);
+
+ gl_uniform_list *ul = (gl_uniform_list *)
+ calloc(1, sizeof(gl_uniform_list));
+
+ ul->Size = total_uniforms;
+ ul->NumUniforms = total_uniforms;
+ ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
+
+ unsigned idx = 0;
+ uniform_node *next;
+ for (uniform_node *node = (uniform_node *) uniforms.head
+ ; node->link.next != NULL
+ ; node = next) {
+ next = (uniform_node *) node->link.next;
+
+ node->link.remove();
+ memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform));
+ idx++;
+
+ free(node->u);
+ free(node);
+ }
+
+ hash_table_dtor(ht);
+
+ prog->Uniforms = ul;
+}
+
+
+/**
+ * Find a contiguous set of available bits in a bitmask
+ *
+ * \param used_mask Bits representing used (1) and unused (0) locations
+ * \param needed_count Number of contiguous bits needed.
+ *
+ * \return
+ * Base location of the available bits on success or -1 on failure.
+ */
+int
+find_available_slots(unsigned used_mask, unsigned needed_count)
+{
+ unsigned needed_mask = (1 << needed_count) - 1;
+ const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
+
+ /* The comparison to 32 is redundant, but without it GCC emits "warning:
+ * cannot optimize possibly infinite loops" for the loop below.
+ */
+ if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
+ return -1;
+
+ for (int i = 0; i <= max_bit_to_test; i++) {
+ if ((needed_mask & ~used_mask) == needed_mask)
+ return i;
+
+ needed_mask <<= 1;
+ }
+
+ return -1;
+}
+
+
+bool
+assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
+{
+ /* Mark invalid attribute locations as being used.
+ */
+ unsigned used_locations = (max_attribute_index >= 32)
+ ? ~0 : ~((1 << max_attribute_index) - 1);
+
+ gl_shader *const sh = prog->_LinkedShaders[0];
+ assert(sh->Type == GL_VERTEX_SHADER);
+
+ /* Operate in a total of four passes.
+ *
+ * 1. Invalidate the location assignments for all vertex shader inputs.
+ *
+ * 2. Assign locations for inputs that have user-defined (via
+ * glBindVertexAttribLocation) locatoins.
+ *
+ * 3. Sort the attributes without assigned locations by number of slots
+ * required in decreasing order. Fragmentation caused by attribute
+ * locations assigned by the application may prevent large attributes
+ * from having enough contiguous space.
+ *
+ * 4. Assign locations to any inputs without assigned locations.
+ */
+
+ invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
+
+ if (prog->Attributes != NULL) {
+ for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
+ ir_variable *const var =
+ sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
+
+ /* Note: attributes that occupy multiple slots, such as arrays or
+ * matrices, may appear in the attrib array multiple times.
+ */
+ if ((var == NULL) || (var->location != -1))
+ continue;
+
+ /* From page 61 of the OpenGL 4.0 spec:
+ *
+ * "LinkProgram will fail if the attribute bindings assigned by
+ * BindAttribLocation do not leave not enough space to assign a
+ * location for an active matrix attribute or an active attribute
+ * array, both of which require multiple contiguous generic
+ * attributes."
+ *
+ * Previous versions of the spec contain similar language but omit the
+ * bit about attribute arrays.
+ *
+ * Page 61 of the OpenGL 4.0 spec also says:
+ *
+ * "It is possible for an application to bind more than one
+ * attribute name to the same location. This is referred to as
+ * aliasing. This will only work if only one of the aliased
+ * attributes is active in the executable program, or if no path
+ * through the shader consumes more than one attribute of a set
+ * of attributes aliased to the same location. A link error can
+ * occur if the linker determines that every path through the
+ * shader consumes multiple aliased attributes, but
+ * implementations are not required to generate an error in this
+ * case."
+ *
+ * These two paragraphs are either somewhat contradictory, or I don't
+ * fully understand one or both of them.
+ */
+ /* FINISHME: The code as currently written does not support attribute
+ * FINISHME: location aliasing (see comment above).
+ */
+ const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
+ const unsigned slots = count_attribute_slots(var->type);
+
+ /* Mask representing the contiguous slots that will be used by this
+ * attribute.
+ */
+ const unsigned use_mask = (1 << slots) - 1;
+
+ /* Generate a link error if the set of bits requested for this
+ * attribute overlaps any previously allocated bits.
+ */
+ if ((~(use_mask << attr) & used_locations) != used_locations) {
+ linker_error_printf(prog,
+ "insufficient contiguous attribute locations "
+ "available for vertex shader input `%s'",
+ var->name);
+ return false;
+ }
+
+ var->location = VERT_ATTRIB_GENERIC0 + attr;
+ used_locations |= (use_mask << attr);
+ }
+ }
+
+ /* Temporary storage for the set of attributes that need locations assigned.
+ */
+ struct temp_attr {
+ unsigned slots;
+ ir_variable *var;
+
+ /* Used below in the call to qsort. */
+ static int compare(const void *a, const void *b)
+ {
+ const temp_attr *const l = (const temp_attr *) a;
+ const temp_attr *const r = (const temp_attr *) b;
+
+ /* Reversed because we want a descending order sort below. */
+ return r->slots - l->slots;
+ }
+ } to_assign[16];
+
+ unsigned num_attr = 0;
+
+ foreach_list(node, sh->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != ir_var_in))
+ continue;
+
+ if (var->explicit_location) {
+ const unsigned slots = count_attribute_slots(var->type);
+ const unsigned use_mask = (1 << slots) - 1;
+ const int attr = var->location - VERT_ATTRIB_GENERIC0;
+
+ if ((var->location >= (int)(max_attribute_index + VERT_ATTRIB_GENERIC0))
+ || (var->location < 0)) {
+ linker_error_printf(prog,
+ "invalid explicit location %d specified for "
+ "`%s'\n",
+ (var->location < 0) ? var->location : attr,
+ var->name);
+ return false;
+ } else if (var->location >= VERT_ATTRIB_GENERIC0) {
+ used_locations |= (use_mask << attr);
+ }
+ }
+
+ /* The location was explicitly assigned, nothing to do here.
+ */
+ if (var->location != -1)
+ continue;
+
+ to_assign[num_attr].slots = count_attribute_slots(var->type);
+ to_assign[num_attr].var = var;
+ num_attr++;
+ }
+
+ /* If all of the attributes were assigned locations by the application (or
+ * are built-in attributes with fixed locations), return early. This should
+ * be the common case.
+ */
+ if (num_attr == 0)
+ return true;
+
+ qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
+
+ /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
+ * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
+ * to prevent it from being automatically allocated below.
+ */
+ find_deref_visitor find("gl_Vertex");
+ find.run(sh->ir);
+ if (find.variable_found())
+ used_locations |= (1 << 0);
+
+ for (unsigned i = 0; i < num_attr; i++) {
+ /* Mask representing the contiguous slots that will be used by this
+ * attribute.
+ */
+ const unsigned use_mask = (1 << to_assign[i].slots) - 1;
+
+ int location = find_available_slots(used_locations, to_assign[i].slots);
+
+ if (location < 0) {
+ linker_error_printf(prog,
+ "insufficient contiguous attribute locations "
+ "available for vertex shader input `%s'",
+ to_assign[i].var->name);
+ return false;
+ }
+
+ to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
+ used_locations |= (use_mask << location);
+ }
+
+ return true;
+}
+
+
+/**
+ * Demote shader inputs and outputs that are not used in other stages
+ */
+void
+demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
+{
+ foreach_list(node, sh->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != int(mode)))
+ continue;
+
+ /* A shader 'in' or 'out' variable is only really an input or output if
+ * its value is used by other shader stages. This will cause the variable
+ * to have a location assigned.
+ */
+ if (var->location == -1) {
+ var->mode = ir_var_auto;
+ }
+ }
+}
+
+
+void
+assign_varying_locations(struct gl_shader_program *prog,
+ gl_shader *producer, gl_shader *consumer)
+{
+ /* FINISHME: Set dynamically when geometry shader support is added. */
+ unsigned output_index = VERT_RESULT_VAR0;
+ unsigned input_index = FRAG_ATTRIB_VAR0;
+
+ /* Operate in a total of three passes.
+ *
+ * 1. Assign locations for any matching inputs and outputs.
+ *
+ * 2. Mark output variables in the producer that do not have locations as
+ * not being outputs. This lets the optimizer eliminate them.
+ *
+ * 3. Mark input variables in the consumer that do not have locations as
+ * not being inputs. This lets the optimizer eliminate them.
+ */
+
+ invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
+ invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
+
+ foreach_list(node, producer->ir) {
+ ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
+
+ if ((output_var == NULL) || (output_var->mode != ir_var_out)
+ || (output_var->location != -1))
+ continue;
+
+ ir_variable *const input_var =
+ consumer->symbols->get_variable(output_var->name);
+
+ if ((input_var == NULL) || (input_var->mode != ir_var_in))
+ continue;
+
+ assert(input_var->location == -1);
+
+ output_var->location = output_index;
+ input_var->location = input_index;
+
+ /* FINISHME: Support for "varying" records in GLSL 1.50. */
+ assert(!output_var->type->is_record());
+
+ if (output_var->type->is_array()) {
+ const unsigned slots = output_var->type->length
+ * output_var->type->fields.array->matrix_columns;
+
+ output_index += slots;
+ input_index += slots;
+ } else {
+ const unsigned slots = output_var->type->matrix_columns;
+
+ output_index += slots;
+ input_index += slots;
+ }
+ }
+
+ foreach_list(node, consumer->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != ir_var_in))
+ continue;
+
+ if (var->location == -1) {
+ if (prog->Version <= 120) {
+ /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
+ *
+ * Only those varying variables used (i.e. read) in
+ * the fragment shader executable must be written to
+ * by the vertex shader executable; declaring
+ * superfluous varying variables in a vertex shader is
+ * permissible.
+ *
+ * We interpret this text as meaning that the VS must
+ * write the variable for the FS to read it. See
+ * "glsl1-varying read but not written" in piglit.
+ */
+
+ linker_error_printf(prog, "fragment shader varying %s not written "
+ "by vertex shader\n.", var->name);
+ prog->LinkStatus = false;
+ }
+
+ /* An 'in' variable is only really a shader input if its
+ * value is written by the previous stage.
+ */
+ var->mode = ir_var_auto;
+ }
+ }
+}
+
+
+void
+link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
+{
+ void *mem_ctx = talloc_init("temporary linker context");
+
+ prog->LinkStatus = false;
+ prog->Validated = false;
+ prog->_Used = false;
+
+ if (prog->InfoLog != NULL)
+ talloc_free(prog->InfoLog);
+
+ prog->InfoLog = talloc_strdup(NULL, "");
+
+ /* Separate the shaders into groups based on their type.
+ */
+ struct gl_shader **vert_shader_list;
+ unsigned num_vert_shaders = 0;
+ struct gl_shader **frag_shader_list;
+ unsigned num_frag_shaders = 0;
+
+ vert_shader_list = (struct gl_shader **)
+ calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
+ frag_shader_list = &vert_shader_list[prog->NumShaders];
+
+ unsigned min_version = UINT_MAX;
+ unsigned max_version = 0;
+ for (unsigned i = 0; i < prog->NumShaders; i++) {
+ min_version = MIN2(min_version, prog->Shaders[i]->Version);
+ max_version = MAX2(max_version, prog->Shaders[i]->Version);
+
+ switch (prog->Shaders[i]->Type) {
+ case GL_VERTEX_SHADER:
+ vert_shader_list[num_vert_shaders] = prog->Shaders[i];
+ num_vert_shaders++;
+ break;
+ case GL_FRAGMENT_SHADER:
+ frag_shader_list[num_frag_shaders] = prog->Shaders[i];
+ num_frag_shaders++;
+ break;
+ case GL_GEOMETRY_SHADER:
+ /* FINISHME: Support geometry shaders. */
+ assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
+ break;
+ }
+ }
+
+ /* Previous to GLSL version 1.30, different compilation units could mix and
+ * match shading language versions. With GLSL 1.30 and later, the versions
+ * of all shaders must match.
+ */
+ assert(min_version >= 100);
+ assert(max_version <= 130);
+ if ((max_version >= 130 || min_version == 100)
+ && min_version != max_version) {
+ linker_error_printf(prog, "all shaders must use same shading "
+ "language version\n");
+ goto done;
+ }
+
+ prog->Version = max_version;
+
+ for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] != NULL)
+ ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
+
+ prog->_LinkedShaders[i] = NULL;
+ }
+
+ /* Link all shaders for a particular stage and validate the result.
+ */
+ if (num_vert_shaders > 0) {
+ gl_shader *const sh =
+ link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
+ num_vert_shaders);
+
+ if (sh == NULL)
+ goto done;
+
+ if (!validate_vertex_shader_executable(prog, sh))
+ goto done;
+
+ _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
+ sh);
+ }
+
+ if (num_frag_shaders > 0) {
+ gl_shader *const sh =
+ link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
+ num_frag_shaders);
+
+ if (sh == NULL)
+ goto done;
+
+ if (!validate_fragment_shader_executable(prog, sh))
+ goto done;
+
+ _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
+ sh);
+ }
+
+ /* Here begins the inter-stage linking phase. Some initial validation is
+ * performed, then locations are assigned for uniforms, attributes, and
+ * varyings.
+ */
+ if (cross_validate_uniforms(prog)) {
+ unsigned prev;
+
+ for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
+ if (prog->_LinkedShaders[prev] != NULL)
+ break;
+ }
+
+ /* Validate the inputs of each stage with the output of the preceeding
+ * stage.
+ */
+ for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ if (!cross_validate_outputs_to_inputs(prog,
+ prog->_LinkedShaders[prev],
+ prog->_LinkedShaders[i]))
+ goto done;
+
+ prev = i;
+ }
+
+ prog->LinkStatus = true;
+ }
+
+ /* Do common optimization before assigning storage for attributes,
+ * uniforms, and varyings. Later optimization could possibly make
+ * some of that unused.
+ */
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, 32))
+ ;
+ }
+
+ update_array_sizes(prog);
+
+ assign_uniform_locations(prog);
+
+ if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
+ /* FINISHME: The value of the max_attribute_index parameter is
+ * FINISHME: implementation dependent based on the value of
+ * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
+ * FINISHME: at least 16, so hardcode 16 for now.
+ */
+ if (!assign_attribute_locations(prog, 16)) {
+ prog->LinkStatus = false;
+ goto done;
+ }
+ }
+
+ unsigned prev;
+ for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
+ if (prog->_LinkedShaders[prev] != NULL)
+ break;
+ }
+
+ for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ assign_varying_locations(prog,
+ prog->_LinkedShaders[prev],
+ prog->_LinkedShaders[i]);
+ prev = i;
+ }
+
+ if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
+ demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
+ ir_var_out);
+ }
+
+ if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
+ gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
+
+ demote_shader_inputs_and_outputs(sh, ir_var_in);
+ demote_shader_inputs_and_outputs(sh, ir_var_inout);
+ demote_shader_inputs_and_outputs(sh, ir_var_out);
+ }
+
+ if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
+ gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
+
+ demote_shader_inputs_and_outputs(sh, ir_var_in);
+ }
+
+ /* FINISHME: Assign fragment shader output locations. */
+
+done:
+ free(vert_shader_list);
+
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ /* Retain any live IR, but trash the rest. */
+ reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
+ }
+
+ talloc_free(mem_ctx);
+}
diff --git a/mesalib/src/mesa/main/teximage.c b/mesalib/src/mesa/main/teximage.c
index c3cd6b66a..7f630e23c 100644
--- a/mesalib/src/mesa/main/teximage.c
+++ b/mesalib/src/mesa/main/teximage.c
@@ -703,6 +703,9 @@ _mesa_select_tex_object(struct gl_context *ctx,
const struct gl_texture_unit *texUnit,
GLenum target)
{
+ const GLboolean arrayTex = (ctx->Extensions.MESA_texture_array ||
+ ctx->Extensions.EXT_texture_array);
+
switch (target) {
case GL_TEXTURE_1D:
return texUnit->CurrentTex[TEXTURE_1D_INDEX];
@@ -735,17 +738,13 @@ _mesa_select_tex_object(struct gl_context *ctx,
return ctx->Extensions.NV_texture_rectangle
? ctx->Texture.ProxyTex[TEXTURE_RECT_INDEX] : NULL;
case GL_TEXTURE_1D_ARRAY_EXT:
- return ctx->Extensions.MESA_texture_array
- ? texUnit->CurrentTex[TEXTURE_1D_ARRAY_INDEX] : NULL;
+ return arrayTex ? texUnit->CurrentTex[TEXTURE_1D_ARRAY_INDEX] : NULL;
case GL_PROXY_TEXTURE_1D_ARRAY_EXT:
- return ctx->Extensions.MESA_texture_array
- ? ctx->Texture.ProxyTex[TEXTURE_1D_ARRAY_INDEX] : NULL;
+ return arrayTex ? ctx->Texture.ProxyTex[TEXTURE_1D_ARRAY_INDEX] : NULL;
case GL_TEXTURE_2D_ARRAY_EXT:
- return ctx->Extensions.MESA_texture_array
- ? texUnit->CurrentTex[TEXTURE_2D_ARRAY_INDEX] : NULL;
+ return arrayTex ? texUnit->CurrentTex[TEXTURE_2D_ARRAY_INDEX] : NULL;
case GL_PROXY_TEXTURE_2D_ARRAY_EXT:
- return ctx->Extensions.MESA_texture_array
- ? ctx->Texture.ProxyTex[TEXTURE_2D_ARRAY_INDEX] : NULL;
+ return arrayTex ? ctx->Texture.ProxyTex[TEXTURE_2D_ARRAY_INDEX] : NULL;
default:
_mesa_problem(NULL, "bad target in _mesa_select_tex_object()");
return NULL;
@@ -930,7 +929,8 @@ _mesa_max_texture_levels(struct gl_context *ctx, GLenum target)
case GL_PROXY_TEXTURE_1D_ARRAY_EXT:
case GL_TEXTURE_2D_ARRAY_EXT:
case GL_PROXY_TEXTURE_2D_ARRAY_EXT:
- return ctx->Extensions.MESA_texture_array
+ return (ctx->Extensions.MESA_texture_array ||
+ ctx->Extensions.EXT_texture_array)
? ctx->Const.MaxTextureLevels : 0;
default:
return 0; /* bad target */
@@ -1382,7 +1382,8 @@ target_can_be_compressed(const struct gl_context *ctx, GLenum target,
return ctx->Extensions.ARB_texture_cube_map;
case GL_PROXY_TEXTURE_2D_ARRAY_EXT:
case GL_TEXTURE_2D_ARRAY_EXT:
- return ctx->Extensions.MESA_texture_array;
+ return (ctx->Extensions.MESA_texture_array ||
+ ctx->Extensions.MESA_texture_array);
default:
return GL_FALSE;
}
@@ -1423,7 +1424,8 @@ legal_teximage_target(struct gl_context *ctx, GLuint dims, GLenum target)
return ctx->Extensions.NV_texture_rectangle;
case GL_TEXTURE_1D_ARRAY_EXT:
case GL_PROXY_TEXTURE_1D_ARRAY_EXT:
- return ctx->Extensions.MESA_texture_array;
+ return (ctx->Extensions.MESA_texture_array ||
+ ctx->Extensions.EXT_texture_array);
default:
return GL_FALSE;
}
@@ -1434,7 +1436,8 @@ legal_teximage_target(struct gl_context *ctx, GLuint dims, GLenum target)
return GL_TRUE;
case GL_TEXTURE_2D_ARRAY_EXT:
case GL_PROXY_TEXTURE_2D_ARRAY_EXT:
- return ctx->Extensions.MESA_texture_array;
+ return (ctx->Extensions.MESA_texture_array ||
+ ctx->Extensions.EXT_texture_array);
default:
return GL_FALSE;
}
@@ -1471,7 +1474,8 @@ legal_texsubimage_target(struct gl_context *ctx, GLuint dims, GLenum target)
case GL_TEXTURE_RECTANGLE_NV:
return ctx->Extensions.NV_texture_rectangle;
case GL_TEXTURE_1D_ARRAY_EXT:
- return ctx->Extensions.MESA_texture_array;
+ return (ctx->Extensions.MESA_texture_array ||
+ ctx->Extensions.EXT_texture_array);
default:
return GL_FALSE;
}
@@ -1480,7 +1484,8 @@ legal_texsubimage_target(struct gl_context *ctx, GLuint dims, GLenum target)
case GL_TEXTURE_3D:
return GL_TRUE;
case GL_TEXTURE_2D_ARRAY_EXT:
- return ctx->Extensions.MESA_texture_array;
+ return (ctx->Extensions.MESA_texture_array ||
+ ctx->Extensions.EXT_texture_array);
default:
return GL_FALSE;
}
diff --git a/mesalib/src/mesa/main/texparam.c b/mesalib/src/mesa/main/texparam.c
index 4909b76cb..6e14face4 100644
--- a/mesalib/src/mesa/main/texparam.c
+++ b/mesalib/src/mesa/main/texparam.c
@@ -33,6 +33,7 @@
#include "main/glheader.h"
#include "main/colormac.h"
#include "main/context.h"
+#include "main/enums.h"
#include "main/formats.h"
#include "main/macros.h"
#include "main/mfeatures.h"
@@ -116,12 +117,14 @@ get_texobj(struct gl_context *ctx, GLenum target, GLboolean get)
}
break;
case GL_TEXTURE_1D_ARRAY_EXT:
- if (ctx->Extensions.MESA_texture_array) {
+ if (ctx->Extensions.MESA_texture_array ||
+ ctx->Extensions.EXT_texture_array) {
return texUnit->CurrentTex[TEXTURE_1D_ARRAY_INDEX];
}
break;
case GL_TEXTURE_2D_ARRAY_EXT:
- if (ctx->Extensions.MESA_texture_array) {
+ if (ctx->Extensions.MESA_texture_array ||
+ ctx->Extensions.EXT_texture_array) {
return texUnit->CurrentTex[TEXTURE_2D_ARRAY_INDEX];
}
break;
@@ -231,8 +234,7 @@ set_tex_parameteri(struct gl_context *ctx,
}
/* fall-through */
default:
- _mesa_error( ctx, GL_INVALID_ENUM, "glTexParameter(param=0x%x)",
- params[0] );
+ goto invalid_param;
}
return GL_FALSE;
@@ -246,8 +248,7 @@ set_tex_parameteri(struct gl_context *ctx,
texObj->MagFilter = params[0];
return GL_TRUE;
default:
- _mesa_error( ctx, GL_INVALID_ENUM, "glTexParameter(param=0x%x)",
- params[0]);
+ goto invalid_param;
}
return GL_FALSE;
@@ -315,21 +316,18 @@ set_tex_parameteri(struct gl_context *ctx,
return GL_FALSE;
case GL_TEXTURE_COMPARE_MODE_ARB:
- if (ctx->Extensions.ARB_shadow &&
- (params[0] == GL_NONE ||
- params[0] == GL_COMPARE_R_TO_TEXTURE_ARB)) {
- if (texObj->CompareMode != params[0]) {
+ if (ctx->Extensions.ARB_shadow) {
+ if (texObj->CompareMode == params[0])
+ return GL_FALSE;
+ if (params[0] == GL_NONE ||
+ params[0] == GL_COMPARE_R_TO_TEXTURE_ARB) {
flush(ctx);
texObj->CompareMode = params[0];
return GL_TRUE;
}
- return GL_FALSE;
- }
- else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glTexParameter(GL_TEXTURE_COMPARE_MODE_ARB)");
+ goto invalid_param;
}
- return GL_FALSE;
+ goto invalid_pname;
case GL_TEXTURE_COMPARE_FUNC_ARB:
if (ctx->Extensions.ARB_shadow) {
@@ -354,32 +352,26 @@ set_tex_parameteri(struct gl_context *ctx,
}
/* fall-through */
default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glTexParameter(GL_TEXTURE_COMPARE_FUNC_ARB)");
+ goto invalid_param;
}
}
- else {
- _mesa_error(ctx, GL_INVALID_ENUM, "glTexParameter(pname=0x%x)", pname);
- }
- return GL_FALSE;
+ goto invalid_pname;
case GL_DEPTH_TEXTURE_MODE_ARB:
- if (ctx->Extensions.ARB_depth_texture &&
- (params[0] == GL_LUMINANCE ||
- params[0] == GL_INTENSITY ||
- params[0] == GL_ALPHA ||
- (ctx->Extensions.ARB_texture_rg && params[0] == GL_RED))) {
- if (texObj->DepthMode != params[0]) {
+ if (ctx->Extensions.ARB_depth_texture) {
+ if (texObj->DepthMode == params[0])
+ return GL_FALSE;
+ if (params[0] == GL_LUMINANCE ||
+ params[0] == GL_INTENSITY ||
+ params[0] == GL_ALPHA ||
+ (ctx->Extensions.ARB_texture_rg && params[0] == GL_RED)) {
flush(ctx);
texObj->DepthMode = params[0];
return GL_TRUE;
}
+ goto invalid_param;
}
- else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glTexParameter(GL_DEPTH_TEXTURE_MODE_ARB)");
- }
- return GL_FALSE;
+ goto invalid_pname;
#if FEATURE_OES_draw_texture
case GL_TEXTURE_CROP_RECT_OES:
@@ -410,8 +402,7 @@ set_tex_parameteri(struct gl_context *ctx,
return GL_TRUE;
}
}
- _mesa_error(ctx, GL_INVALID_ENUM, "glTexParameter(pname=0x%x)", pname);
- return GL_FALSE;
+ goto invalid_pname;
case GL_TEXTURE_SWIZZLE_RGBA_EXT:
if (ctx->Extensions.EXT_texture_swizzle) {
@@ -431,8 +422,8 @@ set_tex_parameteri(struct gl_context *ctx,
}
return GL_TRUE;
}
- _mesa_error(ctx, GL_INVALID_ENUM, "glTexParameter(pname=0x%x)", pname);
- return GL_FALSE;
+ goto invalid_pname;
+
case GL_TEXTURE_SRGB_DECODE_EXT:
if (ctx->Extensions.EXT_texture_sRGB_decode) {
GLenum decode = params[0];
@@ -445,11 +436,20 @@ set_tex_parameteri(struct gl_context *ctx,
return GL_TRUE;
}
}
- _mesa_error(ctx, GL_INVALID_ENUM, "glTexParameter(pname=0x%x)", pname);
- return GL_FALSE;
+ goto invalid_pname;
+
default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glTexParameter(pname=0x%x)", pname);
+ goto invalid_pname;
}
+
+invalid_pname:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glTexParameter(pname=%s)",
+ _mesa_lookup_enum_by_nr(pname));
+ return GL_FALSE;
+
+invalid_param:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glTexParameter(param=%s)",
+ _mesa_lookup_enum_by_nr(params[0]));
return GL_FALSE;
}
@@ -834,7 +834,6 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
const struct gl_texture_unit *texUnit;
struct gl_texture_object *texObj;
const struct gl_texture_image *img = NULL;
- GLboolean isProxy;
GLint maxLevels;
gl_format texFormat;
GET_CURRENT_CONTEXT(ctx);
@@ -862,7 +861,6 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
}
texObj = _mesa_select_tex_object(ctx, texUnit, target);
- _mesa_lock_texture(ctx, texObj);
img = _mesa_select_tex_image(ctx, texObj, target, level);
if (!img || !img->TexFormat) {
@@ -871,13 +869,11 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
*params = 1;
else
*params = 0;
- goto out;
+ return;
}
texFormat = img->TexFormat;
- isProxy = _mesa_is_proxy_texture(target);
-
switch (pname) {
case GL_TEXTURE_WIDTH:
*params = img->Width;
@@ -889,9 +885,9 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
*params = img->Depth;
break;
case GL_TEXTURE_INTERNAL_FORMAT:
- if (_mesa_is_format_compressed(img->TexFormat)) {
+ if (_mesa_is_format_compressed(texFormat)) {
/* need to return the actual compressed format */
- *params = _mesa_compressed_format_to_glenum(ctx, img->TexFormat);
+ *params = _mesa_compressed_format_to_glenum(ctx, texFormat);
}
else {
/* return the user's requested internal format */
@@ -962,8 +958,7 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
if (ctx->Extensions.ARB_depth_texture)
*params = _mesa_get_format_bits(texFormat, pname);
else
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
break;
case GL_TEXTURE_STENCIL_SIZE_EXT:
if (ctx->Extensions.EXT_packed_depth_stencil ||
@@ -971,8 +966,7 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
*params = _mesa_get_format_bits(texFormat, pname);
}
else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
}
break;
case GL_TEXTURE_SHARED_SIZE:
@@ -983,14 +977,14 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
*params = 0;
}
else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
}
break;
/* GL_ARB_texture_compression */
case GL_TEXTURE_COMPRESSED_IMAGE_SIZE:
- if (_mesa_is_format_compressed(img->TexFormat) && !isProxy) {
+ if (_mesa_is_format_compressed(texFormat) &&
+ !_mesa_is_proxy_texture(target)) {
*params = _mesa_format_image_size(texFormat, img->Width,
img->Height, img->Depth);
}
@@ -1000,7 +994,7 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
}
break;
case GL_TEXTURE_COMPRESSED:
- *params = (GLint) _mesa_is_format_compressed(img->TexFormat);
+ *params = (GLint) _mesa_is_format_compressed(texFormat);
break;
/* GL_ARB_texture_float */
@@ -1010,8 +1004,7 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
_mesa_get_format_datatype(texFormat) : GL_NONE;
}
else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
}
break;
case GL_TEXTURE_GREEN_TYPE_ARB:
@@ -1020,8 +1013,7 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
_mesa_get_format_datatype(texFormat) : GL_NONE;
}
else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
}
break;
case GL_TEXTURE_BLUE_TYPE_ARB:
@@ -1030,8 +1022,7 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
_mesa_get_format_datatype(texFormat) : GL_NONE;
}
else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
}
break;
case GL_TEXTURE_ALPHA_TYPE_ARB:
@@ -1040,8 +1031,7 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
_mesa_get_format_datatype(texFormat) : GL_NONE;
}
else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
}
break;
case GL_TEXTURE_LUMINANCE_TYPE_ARB:
@@ -1050,8 +1040,7 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
_mesa_get_format_datatype(texFormat) : GL_NONE;
}
else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
}
break;
case GL_TEXTURE_INTENSITY_TYPE_ARB:
@@ -1060,8 +1049,7 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
_mesa_get_format_datatype(texFormat) : GL_NONE;
}
else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
}
break;
case GL_TEXTURE_DEPTH_TYPE_ARB:
@@ -1070,18 +1058,21 @@ _mesa_GetTexLevelParameteriv( GLenum target, GLint level,
_mesa_get_format_datatype(texFormat) : GL_NONE;
}
else {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
}
break;
default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetTexLevelParameter[if]v(pname)");
+ goto invalid_pname;
}
- out:
- _mesa_unlock_texture(ctx, texObj);
+ /* no error if we get here */
+ return;
+
+invalid_pname:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glGetTexLevelParameter[if]v(pname=%s)",
+ _mesa_lookup_enum_by_nr(pname));
}
diff --git a/mesalib/src/mesa/program/ir_to_mesa.cpp b/mesalib/src/mesa/program/ir_to_mesa.cpp
index ae2742afd..ee3eae6cf 100644
--- a/mesalib/src/mesa/program/ir_to_mesa.cpp
+++ b/mesalib/src/mesa/program/ir_to_mesa.cpp
@@ -1,3210 +1,3214 @@
-/*
- * Copyright (C) 2005-2007 Brian Paul All Rights Reserved.
- * Copyright (C) 2008 VMware, Inc. All Rights Reserved.
- * Copyright © 2010 Intel Corporation
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice (including the next
- * paragraph) shall be included in all copies or substantial portions of the
- * Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-/**
- * \file ir_to_mesa.cpp
- *
- * Translate GLSL IR to Mesa's gl_program representation.
- */
-
-#include <stdio.h>
-#include "main/compiler.h"
-#include "ir.h"
-#include "ir_visitor.h"
-#include "ir_print_visitor.h"
-#include "ir_expression_flattening.h"
-#include "glsl_types.h"
-#include "glsl_parser_extras.h"
-#include "../glsl/program.h"
-#include "ir_optimization.h"
-#include "ast.h"
-
-extern "C" {
-#include "main/mtypes.h"
-#include "main/shaderapi.h"
-#include "main/shaderobj.h"
-#include "main/uniforms.h"
-#include "program/hash_table.h"
-#include "program/prog_instruction.h"
-#include "program/prog_optimize.h"
-#include "program/prog_print.h"
-#include "program/program.h"
-#include "program/prog_uniform.h"
-#include "program/prog_parameter.h"
-#include "program/sampler.h"
-}
-
-static int swizzle_for_size(int size);
-
-/**
- * This struct is a corresponding struct to Mesa prog_src_register, with
- * wider fields.
- */
-typedef struct ir_to_mesa_src_reg {
- ir_to_mesa_src_reg(int file, int index, const glsl_type *type)
- {
- this->file = (gl_register_file) file;
- this->index = index;
- if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
- this->swizzle = swizzle_for_size(type->vector_elements);
- else
- this->swizzle = SWIZZLE_XYZW;
- this->negate = 0;
- this->reladdr = NULL;
- }
-
- ir_to_mesa_src_reg()
- {
- this->file = PROGRAM_UNDEFINED;
- this->index = 0;
- this->swizzle = 0;
- this->negate = 0;
- this->reladdr = NULL;
- }
-
- gl_register_file file; /**< PROGRAM_* from Mesa */
- int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
- GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
- int negate; /**< NEGATE_XYZW mask from mesa */
- /** Register index should be offset by the integer in this reg. */
- ir_to_mesa_src_reg *reladdr;
-} ir_to_mesa_src_reg;
-
-typedef struct ir_to_mesa_dst_reg {
- int file; /**< PROGRAM_* from Mesa */
- int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
- int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
- GLuint cond_mask:4;
- /** Register index should be offset by the integer in this reg. */
- ir_to_mesa_src_reg *reladdr;
-} ir_to_mesa_dst_reg;
-
-extern ir_to_mesa_src_reg ir_to_mesa_undef;
-
-class ir_to_mesa_instruction : public exec_node {
-public:
- /* Callers of this talloc-based new need not call delete. It's
- * easier to just talloc_free 'ctx' (or any of its ancestors). */
- static void* operator new(size_t size, void *ctx)
- {
- void *node;
-
- node = talloc_zero_size(ctx, size);
- assert(node != NULL);
-
- return node;
- }
-
- enum prog_opcode op;
- ir_to_mesa_dst_reg dst_reg;
- ir_to_mesa_src_reg src_reg[3];
- /** Pointer to the ir source this tree came from for debugging */
- ir_instruction *ir;
- GLboolean cond_update;
- bool saturate;
- int sampler; /**< sampler index */
- int tex_target; /**< One of TEXTURE_*_INDEX */
- GLboolean tex_shadow;
-
- class function_entry *function; /* Set on OPCODE_CAL or OPCODE_BGNSUB */
-};
-
-class variable_storage : public exec_node {
-public:
- variable_storage(ir_variable *var, gl_register_file file, int index)
- : file(file), index(index), var(var)
- {
- /* empty */
- }
-
- gl_register_file file;
- int index;
- ir_variable *var; /* variable that maps to this, if any */
-};
-
-class function_entry : public exec_node {
-public:
- ir_function_signature *sig;
-
- /**
- * identifier of this function signature used by the program.
- *
- * At the point that Mesa instructions for function calls are
- * generated, we don't know the address of the first instruction of
- * the function body. So we make the BranchTarget that is called a
- * small integer and rewrite them during set_branchtargets().
- */
- int sig_id;
-
- /**
- * Pointer to first instruction of the function body.
- *
- * Set during function body emits after main() is processed.
- */
- ir_to_mesa_instruction *bgn_inst;
-
- /**
- * Index of the first instruction of the function body in actual
- * Mesa IR.
- *
- * Set after convertion from ir_to_mesa_instruction to prog_instruction.
- */
- int inst;
-
- /** Storage for the return value. */
- ir_to_mesa_src_reg return_reg;
-};
-
-class ir_to_mesa_visitor : public ir_visitor {
-public:
- ir_to_mesa_visitor();
- ~ir_to_mesa_visitor();
-
- function_entry *current_function;
-
- struct gl_context *ctx;
- struct gl_program *prog;
- struct gl_shader_program *shader_program;
- struct gl_shader_compiler_options *options;
-
- int next_temp;
-
- variable_storage *find_variable_storage(ir_variable *var);
-
- function_entry *get_function_signature(ir_function_signature *sig);
-
- ir_to_mesa_src_reg get_temp(const glsl_type *type);
- void reladdr_to_temp(ir_instruction *ir,
- ir_to_mesa_src_reg *reg, int *num_reladdr);
-
- struct ir_to_mesa_src_reg src_reg_for_float(float val);
-
- /**
- * \name Visit methods
- *
- * As typical for the visitor pattern, there must be one \c visit method for
- * each concrete subclass of \c ir_instruction. Virtual base classes within
- * the hierarchy should not have \c visit methods.
- */
- /*@{*/
- virtual void visit(ir_variable *);
- virtual void visit(ir_loop *);
- virtual void visit(ir_loop_jump *);
- virtual void visit(ir_function_signature *);
- virtual void visit(ir_function *);
- virtual void visit(ir_expression *);
- virtual void visit(ir_swizzle *);
- virtual void visit(ir_dereference_variable *);
- virtual void visit(ir_dereference_array *);
- virtual void visit(ir_dereference_record *);
- virtual void visit(ir_assignment *);
- virtual void visit(ir_constant *);
- virtual void visit(ir_call *);
- virtual void visit(ir_return *);
- virtual void visit(ir_discard *);
- virtual void visit(ir_texture *);
- virtual void visit(ir_if *);
- /*@}*/
-
- struct ir_to_mesa_src_reg result;
-
- /** List of variable_storage */
- exec_list variables;
-
- /** List of function_entry */
- exec_list function_signatures;
- int next_signature_id;
-
- /** List of ir_to_mesa_instruction */
- exec_list instructions;
-
- ir_to_mesa_instruction *ir_to_mesa_emit_op0(ir_instruction *ir,
- enum prog_opcode op);
-
- ir_to_mesa_instruction *ir_to_mesa_emit_op1(ir_instruction *ir,
- enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0);
-
- ir_to_mesa_instruction *ir_to_mesa_emit_op2(ir_instruction *ir,
- enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0,
- ir_to_mesa_src_reg src1);
-
- ir_to_mesa_instruction *ir_to_mesa_emit_op3(ir_instruction *ir,
- enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0,
- ir_to_mesa_src_reg src1,
- ir_to_mesa_src_reg src2);
-
- /**
- * Emit the correct dot-product instruction for the type of arguments
- *
- * \sa ir_to_mesa_emit_op2
- */
- void ir_to_mesa_emit_dp(ir_instruction *ir,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0,
- ir_to_mesa_src_reg src1,
- unsigned elements);
-
- void ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
- enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0);
-
- void ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
- enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0,
- ir_to_mesa_src_reg src1);
-
- void emit_scs(ir_instruction *ir, enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- const ir_to_mesa_src_reg &src);
-
- GLboolean try_emit_mad(ir_expression *ir,
- int mul_operand);
- GLboolean try_emit_sat(ir_expression *ir);
-
- void emit_swz(ir_expression *ir);
-
- bool process_move_condition(ir_rvalue *ir);
-
- void copy_propagate(void);
-
- void *mem_ctx;
-};
-
-ir_to_mesa_src_reg ir_to_mesa_undef = ir_to_mesa_src_reg(PROGRAM_UNDEFINED, 0, NULL);
-
-ir_to_mesa_dst_reg ir_to_mesa_undef_dst = {
- PROGRAM_UNDEFINED, 0, SWIZZLE_NOOP, COND_TR, NULL,
-};
-
-ir_to_mesa_dst_reg ir_to_mesa_address_reg = {
- PROGRAM_ADDRESS, 0, WRITEMASK_X, COND_TR, NULL
-};
-
-static void
-fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
-
-static void
-fail_link(struct gl_shader_program *prog, const char *fmt, ...)
-{
- va_list args;
- va_start(args, fmt);
- prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, args);
- va_end(args);
-
- prog->LinkStatus = GL_FALSE;
-}
-
-static int
-swizzle_for_size(int size)
-{
- int size_swizzles[4] = {
- MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
- MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
- MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
- MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
- };
-
- assert((size >= 1) && (size <= 4));
- return size_swizzles[size - 1];
-}
-
-ir_to_mesa_instruction *
-ir_to_mesa_visitor::ir_to_mesa_emit_op3(ir_instruction *ir,
- enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0,
- ir_to_mesa_src_reg src1,
- ir_to_mesa_src_reg src2)
-{
- ir_to_mesa_instruction *inst = new(mem_ctx) ir_to_mesa_instruction();
- int num_reladdr = 0;
-
- /* If we have to do relative addressing, we want to load the ARL
- * reg directly for one of the regs, and preload the other reladdr
- * sources into temps.
- */
- num_reladdr += dst.reladdr != NULL;
- num_reladdr += src0.reladdr != NULL;
- num_reladdr += src1.reladdr != NULL;
- num_reladdr += src2.reladdr != NULL;
-
- reladdr_to_temp(ir, &src2, &num_reladdr);
- reladdr_to_temp(ir, &src1, &num_reladdr);
- reladdr_to_temp(ir, &src0, &num_reladdr);
-
- if (dst.reladdr) {
- ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg,
- *dst.reladdr);
-
- num_reladdr--;
- }
- assert(num_reladdr == 0);
-
- inst->op = op;
- inst->dst_reg = dst;
- inst->src_reg[0] = src0;
- inst->src_reg[1] = src1;
- inst->src_reg[2] = src2;
- inst->ir = ir;
-
- inst->function = NULL;
-
- this->instructions.push_tail(inst);
-
- return inst;
-}
-
-
-ir_to_mesa_instruction *
-ir_to_mesa_visitor::ir_to_mesa_emit_op2(ir_instruction *ir,
- enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0,
- ir_to_mesa_src_reg src1)
-{
- return ir_to_mesa_emit_op3(ir, op, dst, src0, src1, ir_to_mesa_undef);
-}
-
-ir_to_mesa_instruction *
-ir_to_mesa_visitor::ir_to_mesa_emit_op1(ir_instruction *ir,
- enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0)
-{
- assert(dst.writemask != 0);
- return ir_to_mesa_emit_op3(ir, op, dst,
- src0, ir_to_mesa_undef, ir_to_mesa_undef);
-}
-
-ir_to_mesa_instruction *
-ir_to_mesa_visitor::ir_to_mesa_emit_op0(ir_instruction *ir,
- enum prog_opcode op)
-{
- return ir_to_mesa_emit_op3(ir, op, ir_to_mesa_undef_dst,
- ir_to_mesa_undef,
- ir_to_mesa_undef,
- ir_to_mesa_undef);
-}
-
-void
-ir_to_mesa_visitor::ir_to_mesa_emit_dp(ir_instruction *ir,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0,
- ir_to_mesa_src_reg src1,
- unsigned elements)
-{
- static const gl_inst_opcode dot_opcodes[] = {
- OPCODE_DP2, OPCODE_DP3, OPCODE_DP4
- };
-
- ir_to_mesa_emit_op3(ir, dot_opcodes[elements - 2],
- dst, src0, src1, ir_to_mesa_undef);
-}
-
-inline ir_to_mesa_dst_reg
-ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg reg)
-{
- ir_to_mesa_dst_reg dst_reg;
-
- dst_reg.file = reg.file;
- dst_reg.index = reg.index;
- dst_reg.writemask = WRITEMASK_XYZW;
- dst_reg.cond_mask = COND_TR;
- dst_reg.reladdr = reg.reladdr;
-
- return dst_reg;
-}
-
-inline ir_to_mesa_src_reg
-ir_to_mesa_src_reg_from_dst(ir_to_mesa_dst_reg reg)
-{
- return ir_to_mesa_src_reg(reg.file, reg.index, NULL);
-}
-
-/**
- * Emits Mesa scalar opcodes to produce unique answers across channels.
- *
- * Some Mesa opcodes are scalar-only, like ARB_fp/vp. The src X
- * channel determines the result across all channels. So to do a vec4
- * of this operation, we want to emit a scalar per source channel used
- * to produce dest channels.
- */
-void
-ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
- enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg orig_src0,
- ir_to_mesa_src_reg orig_src1)
-{
- int i, j;
- int done_mask = ~dst.writemask;
-
- /* Mesa RCP is a scalar operation splatting results to all channels,
- * like ARB_fp/vp. So emit as many RCPs as necessary to cover our
- * dst channels.
- */
- for (i = 0; i < 4; i++) {
- GLuint this_mask = (1 << i);
- ir_to_mesa_instruction *inst;
- ir_to_mesa_src_reg src0 = orig_src0;
- ir_to_mesa_src_reg src1 = orig_src1;
-
- if (done_mask & this_mask)
- continue;
-
- GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
- GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
- for (j = i + 1; j < 4; j++) {
- /* If there is another enabled component in the destination that is
- * derived from the same inputs, generate its value on this pass as
- * well.
- */
- if (!(done_mask & (1 << j)) &&
- GET_SWZ(src0.swizzle, j) == src0_swiz &&
- GET_SWZ(src1.swizzle, j) == src1_swiz) {
- this_mask |= (1 << j);
- }
- }
- src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
- src0_swiz, src0_swiz);
- src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
- src1_swiz, src1_swiz);
-
- inst = ir_to_mesa_emit_op2(ir, op,
- dst,
- src0,
- src1);
- inst->dst_reg.writemask = this_mask;
- done_mask |= this_mask;
- }
-}
-
-void
-ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
- enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- ir_to_mesa_src_reg src0)
-{
- ir_to_mesa_src_reg undef = ir_to_mesa_undef;
-
- undef.swizzle = SWIZZLE_XXXX;
-
- ir_to_mesa_emit_scalar_op2(ir, op, dst, src0, undef);
-}
-
-/**
- * Emit an OPCODE_SCS instruction
- *
- * The \c SCS opcode functions a bit differently than the other Mesa (or
- * ARB_fragment_program) opcodes. Instead of splatting its result across all
- * four components of the destination, it writes one value to the \c x
- * component and another value to the \c y component.
- *
- * \param ir IR instruction being processed
- * \param op Either \c OPCODE_SIN or \c OPCODE_COS depending on which
- * value is desired.
- * \param dst Destination register
- * \param src Source register
- */
-void
-ir_to_mesa_visitor::emit_scs(ir_instruction *ir, enum prog_opcode op,
- ir_to_mesa_dst_reg dst,
- const ir_to_mesa_src_reg &src)
-{
- /* Vertex programs cannot use the SCS opcode.
- */
- if (this->prog->Target == GL_VERTEX_PROGRAM_ARB) {
- ir_to_mesa_emit_scalar_op1(ir, op, dst, src);
- return;
- }
-
- const unsigned component = (op == OPCODE_SIN) ? 0 : 1;
- const unsigned scs_mask = (1U << component);
- int done_mask = ~dst.writemask;
- ir_to_mesa_src_reg tmp;
-
- assert(op == OPCODE_SIN || op == OPCODE_COS);
-
- /* If there are compnents in the destination that differ from the component
- * that will be written by the SCS instrution, we'll need a temporary.
- */
- if (scs_mask != unsigned(dst.writemask)) {
- tmp = get_temp(glsl_type::vec4_type);
- }
-
- for (unsigned i = 0; i < 4; i++) {
- unsigned this_mask = (1U << i);
- ir_to_mesa_src_reg src0 = src;
-
- if ((done_mask & this_mask) != 0)
- continue;
-
- /* The source swizzle specified which component of the source generates
- * sine / cosine for the current component in the destination. The SCS
- * instruction requires that this value be swizzle to the X component.
- * Replace the current swizzle with a swizzle that puts the source in
- * the X component.
- */
- unsigned src0_swiz = GET_SWZ(src.swizzle, i);
-
- src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
- src0_swiz, src0_swiz);
- for (unsigned j = i + 1; j < 4; j++) {
- /* If there is another enabled component in the destination that is
- * derived from the same inputs, generate its value on this pass as
- * well.
- */
- if (!(done_mask & (1 << j)) &&
- GET_SWZ(src0.swizzle, j) == src0_swiz) {
- this_mask |= (1 << j);
- }
- }
-
- if (this_mask != scs_mask) {
- ir_to_mesa_instruction *inst;
- ir_to_mesa_dst_reg tmp_dst = ir_to_mesa_dst_reg_from_src(tmp);
-
- /* Emit the SCS instruction.
- */
- inst = ir_to_mesa_emit_op1(ir, OPCODE_SCS, tmp_dst, src0);
- inst->dst_reg.writemask = scs_mask;
-
- /* Move the result of the SCS instruction to the desired location in
- * the destination.
- */
- tmp.swizzle = MAKE_SWIZZLE4(component, component,
- component, component);
- inst = ir_to_mesa_emit_op1(ir, OPCODE_SCS, dst, tmp);
- inst->dst_reg.writemask = this_mask;
- } else {
- /* Emit the SCS instruction to write directly to the destination.
- */
- ir_to_mesa_instruction *inst =
- ir_to_mesa_emit_op1(ir, OPCODE_SCS, dst, src0);
- inst->dst_reg.writemask = scs_mask;
- }
-
- done_mask |= this_mask;
- }
-}
-
-struct ir_to_mesa_src_reg
-ir_to_mesa_visitor::src_reg_for_float(float val)
-{
- ir_to_mesa_src_reg src_reg(PROGRAM_CONSTANT, -1, NULL);
-
- src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
- &val, 1, &src_reg.swizzle);
-
- return src_reg;
-}
-
-static int
-type_size(const struct glsl_type *type)
-{
- unsigned int i;
- int size;
-
- switch (type->base_type) {
- case GLSL_TYPE_UINT:
- case GLSL_TYPE_INT:
- case GLSL_TYPE_FLOAT:
- case GLSL_TYPE_BOOL:
- if (type->is_matrix()) {
- return type->matrix_columns;
- } else {
- /* Regardless of size of vector, it gets a vec4. This is bad
- * packing for things like floats, but otherwise arrays become a
- * mess. Hopefully a later pass over the code can pack scalars
- * down if appropriate.
- */
- return 1;
- }
- case GLSL_TYPE_ARRAY:
- return type_size(type->fields.array) * type->length;
- case GLSL_TYPE_STRUCT:
- size = 0;
- for (i = 0; i < type->length; i++) {
- size += type_size(type->fields.structure[i].type);
- }
- return size;
- case GLSL_TYPE_SAMPLER:
- /* Samplers take up one slot in UNIFORMS[], but they're baked in
- * at link time.
- */
- return 1;
- default:
- assert(0);
- return 0;
- }
-}
-
-/**
- * In the initial pass of codegen, we assign temporary numbers to
- * intermediate results. (not SSA -- variable assignments will reuse
- * storage). Actual register allocation for the Mesa VM occurs in a
- * pass over the Mesa IR later.
- */
-ir_to_mesa_src_reg
-ir_to_mesa_visitor::get_temp(const glsl_type *type)
-{
- ir_to_mesa_src_reg src_reg;
- int swizzle[4];
- int i;
-
- src_reg.file = PROGRAM_TEMPORARY;
- src_reg.index = next_temp;
- src_reg.reladdr = NULL;
- next_temp += type_size(type);
-
- if (type->is_array() || type->is_record()) {
- src_reg.swizzle = SWIZZLE_NOOP;
- } else {
- for (i = 0; i < type->vector_elements; i++)
- swizzle[i] = i;
- for (; i < 4; i++)
- swizzle[i] = type->vector_elements - 1;
- src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1],
- swizzle[2], swizzle[3]);
- }
- src_reg.negate = 0;
-
- return src_reg;
-}
-
-variable_storage *
-ir_to_mesa_visitor::find_variable_storage(ir_variable *var)
-{
-
- variable_storage *entry;
-
- foreach_iter(exec_list_iterator, iter, this->variables) {
- entry = (variable_storage *)iter.get();
-
- if (entry->var == var)
- return entry;
- }
-
- return NULL;
-}
-
-void
-ir_to_mesa_visitor::visit(ir_variable *ir)
-{
- if (strcmp(ir->name, "gl_FragCoord") == 0) {
- struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
-
- fp->OriginUpperLeft = ir->origin_upper_left;
- fp->PixelCenterInteger = ir->pixel_center_integer;
- }
-
- if (ir->mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
- unsigned int i;
- const struct gl_builtin_uniform_desc *statevar;
-
- for (i = 0; _mesa_builtin_uniform_desc[i].name; i++) {
- if (strcmp(ir->name, _mesa_builtin_uniform_desc[i].name) == 0)
- break;
- }
-
- if (!_mesa_builtin_uniform_desc[i].name) {
- fail_link(this->shader_program,
- "Failed to find builtin uniform `%s'\n", ir->name);
- return;
- }
-
- statevar = &_mesa_builtin_uniform_desc[i];
-
- int array_count;
- if (ir->type->is_array()) {
- array_count = ir->type->length;
- } else {
- array_count = 1;
- }
-
- /* Check if this statevar's setup in the STATE file exactly
- * matches how we'll want to reference it as a
- * struct/array/whatever. If not, then we need to move it into
- * temporary storage and hope that it'll get copy-propagated
- * out.
- */
- for (i = 0; i < statevar->num_elements; i++) {
- if (statevar->elements[i].swizzle != SWIZZLE_XYZW) {
- break;
- }
- }
-
- struct variable_storage *storage;
- ir_to_mesa_dst_reg dst;
- if (i == statevar->num_elements) {
- /* We'll set the index later. */
- storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
- this->variables.push_tail(storage);
-
- dst = ir_to_mesa_undef_dst;
- } else {
- storage = new(mem_ctx) variable_storage(ir, PROGRAM_TEMPORARY,
- this->next_temp);
- this->variables.push_tail(storage);
- this->next_temp += type_size(ir->type);
-
- dst = ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg(PROGRAM_TEMPORARY,
- storage->index,
- NULL));
- }
-
-
- for (int a = 0; a < array_count; a++) {
- for (unsigned int i = 0; i < statevar->num_elements; i++) {
- struct gl_builtin_uniform_element *element = &statevar->elements[i];
- int tokens[STATE_LENGTH];
-
- memcpy(tokens, element->tokens, sizeof(element->tokens));
- if (ir->type->is_array()) {
- tokens[1] = a;
- }
-
- int index = _mesa_add_state_reference(this->prog->Parameters,
- (gl_state_index *)tokens);
-
- if (storage->file == PROGRAM_STATE_VAR) {
- if (storage->index == -1) {
- storage->index = index;
- } else {
- assert(index ==
- (int)(storage->index + a * statevar->num_elements + i));
- }
- } else {
- ir_to_mesa_src_reg src(PROGRAM_STATE_VAR, index, NULL);
- src.swizzle = element->swizzle;
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, dst, src);
- /* even a float takes up a whole vec4 reg in a struct/array. */
- dst.index++;
- }
- }
- }
- if (storage->file == PROGRAM_TEMPORARY &&
- dst.index != storage->index + type_size(ir->type)) {
- fail_link(this->shader_program,
- "failed to load builtin uniform `%s' (%d/%d regs loaded)\n",
- ir->name, dst.index - storage->index,
- type_size(ir->type));
- }
- }
-}
-
-void
-ir_to_mesa_visitor::visit(ir_loop *ir)
-{
- ir_dereference_variable *counter = NULL;
-
- if (ir->counter != NULL)
- counter = new(ir) ir_dereference_variable(ir->counter);
-
- if (ir->from != NULL) {
- assert(ir->counter != NULL);
-
- ir_assignment *a = new(ir) ir_assignment(counter, ir->from, NULL);
-
- a->accept(this);
- delete a;
- }
-
- ir_to_mesa_emit_op0(NULL, OPCODE_BGNLOOP);
-
- if (ir->to) {
- ir_expression *e =
- new(ir) ir_expression(ir->cmp, glsl_type::bool_type,
- counter, ir->to);
- ir_if *if_stmt = new(ir) ir_if(e);
-
- ir_loop_jump *brk = new(ir) ir_loop_jump(ir_loop_jump::jump_break);
-
- if_stmt->then_instructions.push_tail(brk);
-
- if_stmt->accept(this);
-
- delete if_stmt;
- delete e;
- delete brk;
- }
-
- visit_exec_list(&ir->body_instructions, this);
-
- if (ir->increment) {
- ir_expression *e =
- new(ir) ir_expression(ir_binop_add, counter->type,
- counter, ir->increment);
-
- ir_assignment *a = new(ir) ir_assignment(counter, e, NULL);
-
- a->accept(this);
- delete a;
- delete e;
- }
-
- ir_to_mesa_emit_op0(NULL, OPCODE_ENDLOOP);
-}
-
-void
-ir_to_mesa_visitor::visit(ir_loop_jump *ir)
-{
- switch (ir->mode) {
- case ir_loop_jump::jump_break:
- ir_to_mesa_emit_op0(NULL, OPCODE_BRK);
- break;
- case ir_loop_jump::jump_continue:
- ir_to_mesa_emit_op0(NULL, OPCODE_CONT);
- break;
- }
-}
-
-
-void
-ir_to_mesa_visitor::visit(ir_function_signature *ir)
-{
- assert(0);
- (void)ir;
-}
-
-void
-ir_to_mesa_visitor::visit(ir_function *ir)
-{
- /* Ignore function bodies other than main() -- we shouldn't see calls to
- * them since they should all be inlined before we get to ir_to_mesa.
- */
- if (strcmp(ir->name, "main") == 0) {
- const ir_function_signature *sig;
- exec_list empty;
-
- sig = ir->matching_signature(&empty);
-
- assert(sig);
-
- foreach_iter(exec_list_iterator, iter, sig->body) {
- ir_instruction *ir = (ir_instruction *)iter.get();
-
- ir->accept(this);
- }
- }
-}
-
-GLboolean
-ir_to_mesa_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
-{
- int nonmul_operand = 1 - mul_operand;
- ir_to_mesa_src_reg a, b, c;
-
- ir_expression *expr = ir->operands[mul_operand]->as_expression();
- if (!expr || expr->operation != ir_binop_mul)
- return false;
-
- expr->operands[0]->accept(this);
- a = this->result;
- expr->operands[1]->accept(this);
- b = this->result;
- ir->operands[nonmul_operand]->accept(this);
- c = this->result;
-
- this->result = get_temp(ir->type);
- ir_to_mesa_emit_op3(ir, OPCODE_MAD,
- ir_to_mesa_dst_reg_from_src(this->result), a, b, c);
-
- return true;
-}
-
-GLboolean
-ir_to_mesa_visitor::try_emit_sat(ir_expression *ir)
-{
- /* Saturates were only introduced to vertex programs in
- * NV_vertex_program3, so don't give them to drivers in the VP.
- */
- if (this->prog->Target == GL_VERTEX_PROGRAM_ARB)
- return false;
-
- ir_rvalue *sat_src = ir->as_rvalue_to_saturate();
- if (!sat_src)
- return false;
-
- sat_src->accept(this);
- ir_to_mesa_src_reg src = this->result;
-
- this->result = get_temp(ir->type);
- ir_to_mesa_instruction *inst;
- inst = ir_to_mesa_emit_op1(ir, OPCODE_MOV,
- ir_to_mesa_dst_reg_from_src(this->result),
- src);
- inst->saturate = true;
-
- return true;
-}
-
-void
-ir_to_mesa_visitor::reladdr_to_temp(ir_instruction *ir,
- ir_to_mesa_src_reg *reg, int *num_reladdr)
-{
- if (!reg->reladdr)
- return;
-
- ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg, *reg->reladdr);
-
- if (*num_reladdr != 1) {
- ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
-
- ir_to_mesa_emit_op1(ir, OPCODE_MOV,
- ir_to_mesa_dst_reg_from_src(temp), *reg);
- *reg = temp;
- }
-
- (*num_reladdr)--;
-}
-
-void
-ir_to_mesa_visitor::emit_swz(ir_expression *ir)
-{
- /* Assume that the vector operator is in a form compatible with OPCODE_SWZ.
- * This means that each of the operands is either an immediate value of -1,
- * 0, or 1, or is a component from one source register (possibly with
- * negation).
- */
- uint8_t components[4] = { 0 };
- bool negate[4] = { false };
- ir_variable *var = NULL;
-
- for (unsigned i = 0; i < ir->type->vector_elements; i++) {
- ir_rvalue *op = ir->operands[i];
-
- assert(op->type->is_scalar());
-
- while (op != NULL) {
- switch (op->ir_type) {
- case ir_type_constant: {
-
- assert(op->type->is_scalar());
-
- const ir_constant *const c = op->as_constant();
- if (c->is_one()) {
- components[i] = SWIZZLE_ONE;
- } else if (c->is_zero()) {
- components[i] = SWIZZLE_ZERO;
- } else if (c->is_negative_one()) {
- components[i] = SWIZZLE_ONE;
- negate[i] = true;
- } else {
- assert(!"SWZ constant must be 0.0 or 1.0.");
- }
-
- op = NULL;
- break;
- }
-
- case ir_type_dereference_variable: {
- ir_dereference_variable *const deref =
- (ir_dereference_variable *) op;
-
- assert((var == NULL) || (deref->var == var));
- components[i] = SWIZZLE_X;
- var = deref->var;
- op = NULL;
- break;
- }
-
- case ir_type_expression: {
- ir_expression *const expr = (ir_expression *) op;
-
- assert(expr->operation == ir_unop_neg);
- negate[i] = true;
-
- op = expr->operands[0];
- break;
- }
-
- case ir_type_swizzle: {
- ir_swizzle *const swiz = (ir_swizzle *) op;
-
- components[i] = swiz->mask.x;
- op = swiz->val;
- break;
- }
-
- default:
- assert(!"Should not get here.");
- return;
- }
- }
- }
-
- assert(var != NULL);
-
- ir_dereference_variable *const deref =
- new(mem_ctx) ir_dereference_variable(var);
-
- this->result.file = PROGRAM_UNDEFINED;
- deref->accept(this);
- if (this->result.file == PROGRAM_UNDEFINED) {
- ir_print_visitor v;
- printf("Failed to get tree for expression operand:\n");
- deref->accept(&v);
- exit(1);
- }
-
- ir_to_mesa_src_reg src;
-
- src = this->result;
- src.swizzle = MAKE_SWIZZLE4(components[0],
- components[1],
- components[2],
- components[3]);
- src.negate = ((unsigned(negate[0]) << 0)
- | (unsigned(negate[1]) << 1)
- | (unsigned(negate[2]) << 2)
- | (unsigned(negate[3]) << 3));
-
- /* Storage for our result. Ideally for an assignment we'd be using the
- * actual storage for the result here, instead.
- */
- const ir_to_mesa_src_reg result_src = get_temp(ir->type);
- ir_to_mesa_dst_reg result_dst = ir_to_mesa_dst_reg_from_src(result_src);
-
- /* Limit writes to the channels that will be used by result_src later.
- * This does limit this temp's use as a temporary for multi-instruction
- * sequences.
- */
- result_dst.writemask = (1 << ir->type->vector_elements) - 1;
-
- ir_to_mesa_emit_op1(ir, OPCODE_SWZ, result_dst, src);
- this->result = result_src;
-}
-
-void
-ir_to_mesa_visitor::visit(ir_expression *ir)
-{
- unsigned int operand;
- struct ir_to_mesa_src_reg op[Elements(ir->operands)];
- struct ir_to_mesa_src_reg result_src;
- struct ir_to_mesa_dst_reg result_dst;
-
- /* Quick peephole: Emit OPCODE_MAD(a, b, c) instead of ADD(MUL(a, b), c)
- */
- if (ir->operation == ir_binop_add) {
- if (try_emit_mad(ir, 1))
- return;
- if (try_emit_mad(ir, 0))
- return;
- }
- if (try_emit_sat(ir))
- return;
-
- if (ir->operation == ir_quadop_vector) {
- this->emit_swz(ir);
- return;
- }
-
- for (operand = 0; operand < ir->get_num_operands(); operand++) {
- this->result.file = PROGRAM_UNDEFINED;
- ir->operands[operand]->accept(this);
- if (this->result.file == PROGRAM_UNDEFINED) {
- ir_print_visitor v;
- printf("Failed to get tree for expression operand:\n");
- ir->operands[operand]->accept(&v);
- exit(1);
- }
- op[operand] = this->result;
-
- /* Matrix expression operands should have been broken down to vector
- * operations already.
- */
- assert(!ir->operands[operand]->type->is_matrix());
- }
-
- int vector_elements = ir->operands[0]->type->vector_elements;
- if (ir->operands[1]) {
- vector_elements = MAX2(vector_elements,
- ir->operands[1]->type->vector_elements);
- }
-
- this->result.file = PROGRAM_UNDEFINED;
-
- /* Storage for our result. Ideally for an assignment we'd be using
- * the actual storage for the result here, instead.
- */
- result_src = get_temp(ir->type);
- /* convenience for the emit functions below. */
- result_dst = ir_to_mesa_dst_reg_from_src(result_src);
- /* Limit writes to the channels that will be used by result_src later.
- * This does limit this temp's use as a temporary for multi-instruction
- * sequences.
- */
- result_dst.writemask = (1 << ir->type->vector_elements) - 1;
-
- switch (ir->operation) {
- case ir_unop_logic_not:
- ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst,
- op[0], src_reg_for_float(0.0));
- break;
- case ir_unop_neg:
- op[0].negate = ~op[0].negate;
- result_src = op[0];
- break;
- case ir_unop_abs:
- ir_to_mesa_emit_op1(ir, OPCODE_ABS, result_dst, op[0]);
- break;
- case ir_unop_sign:
- ir_to_mesa_emit_op1(ir, OPCODE_SSG, result_dst, op[0]);
- break;
- case ir_unop_rcp:
- ir_to_mesa_emit_scalar_op1(ir, OPCODE_RCP, result_dst, op[0]);
- break;
-
- case ir_unop_exp2:
- ir_to_mesa_emit_scalar_op1(ir, OPCODE_EX2, result_dst, op[0]);
- break;
- case ir_unop_exp:
- case ir_unop_log:
- assert(!"not reached: should be handled by ir_explog_to_explog2");
- break;
- case ir_unop_log2:
- ir_to_mesa_emit_scalar_op1(ir, OPCODE_LG2, result_dst, op[0]);
- break;
- case ir_unop_sin:
- ir_to_mesa_emit_scalar_op1(ir, OPCODE_SIN, result_dst, op[0]);
- break;
- case ir_unop_cos:
- ir_to_mesa_emit_scalar_op1(ir, OPCODE_COS, result_dst, op[0]);
- break;
- case ir_unop_sin_reduced:
- emit_scs(ir, OPCODE_SIN, result_dst, op[0]);
- break;
- case ir_unop_cos_reduced:
- emit_scs(ir, OPCODE_COS, result_dst, op[0]);
- break;
-
- case ir_unop_dFdx:
- ir_to_mesa_emit_op1(ir, OPCODE_DDX, result_dst, op[0]);
- break;
- case ir_unop_dFdy:
- ir_to_mesa_emit_op1(ir, OPCODE_DDY, result_dst, op[0]);
- break;
-
- case ir_unop_noise: {
- const enum prog_opcode opcode =
- prog_opcode(OPCODE_NOISE1
- + (ir->operands[0]->type->vector_elements) - 1);
- assert((opcode >= OPCODE_NOISE1) && (opcode <= OPCODE_NOISE4));
-
- ir_to_mesa_emit_op1(ir, opcode, result_dst, op[0]);
- break;
- }
-
- case ir_binop_add:
- ir_to_mesa_emit_op2(ir, OPCODE_ADD, result_dst, op[0], op[1]);
- break;
- case ir_binop_sub:
- ir_to_mesa_emit_op2(ir, OPCODE_SUB, result_dst, op[0], op[1]);
- break;
-
- case ir_binop_mul:
- ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, op[0], op[1]);
- break;
- case ir_binop_div:
- assert(!"not reached: should be handled by ir_div_to_mul_rcp");
- case ir_binop_mod:
- assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
- break;
-
- case ir_binop_less:
- ir_to_mesa_emit_op2(ir, OPCODE_SLT, result_dst, op[0], op[1]);
- break;
- case ir_binop_greater:
- ir_to_mesa_emit_op2(ir, OPCODE_SGT, result_dst, op[0], op[1]);
- break;
- case ir_binop_lequal:
- ir_to_mesa_emit_op2(ir, OPCODE_SLE, result_dst, op[0], op[1]);
- break;
- case ir_binop_gequal:
- ir_to_mesa_emit_op2(ir, OPCODE_SGE, result_dst, op[0], op[1]);
- break;
- case ir_binop_equal:
- ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
- break;
- case ir_binop_nequal:
- ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
- break;
- case ir_binop_all_equal:
- /* "==" operator producing a scalar boolean. */
- if (ir->operands[0]->type->is_vector() ||
- ir->operands[1]->type->is_vector()) {
- ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
- ir_to_mesa_emit_op2(ir, OPCODE_SNE,
- ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
- ir_to_mesa_emit_dp(ir, result_dst, temp, temp, vector_elements);
- ir_to_mesa_emit_op2(ir, OPCODE_SEQ,
- result_dst, result_src, src_reg_for_float(0.0));
- } else {
- ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
- }
- break;
- case ir_binop_any_nequal:
- /* "!=" operator producing a scalar boolean. */
- if (ir->operands[0]->type->is_vector() ||
- ir->operands[1]->type->is_vector()) {
- ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
- ir_to_mesa_emit_op2(ir, OPCODE_SNE,
- ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
- ir_to_mesa_emit_dp(ir, result_dst, temp, temp, vector_elements);
- ir_to_mesa_emit_op2(ir, OPCODE_SNE,
- result_dst, result_src, src_reg_for_float(0.0));
- } else {
- ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
- }
- break;
-
- case ir_unop_any:
- assert(ir->operands[0]->type->is_vector());
- ir_to_mesa_emit_dp(ir, result_dst, op[0], op[0],
- ir->operands[0]->type->vector_elements);
- ir_to_mesa_emit_op2(ir, OPCODE_SNE,
- result_dst, result_src, src_reg_for_float(0.0));
- break;
-
- case ir_binop_logic_xor:
- ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
- break;
-
- case ir_binop_logic_or:
- /* This could be a saturated add and skip the SNE. */
- ir_to_mesa_emit_op2(ir, OPCODE_ADD,
- result_dst,
- op[0], op[1]);
-
- ir_to_mesa_emit_op2(ir, OPCODE_SNE,
- result_dst,
- result_src, src_reg_for_float(0.0));
- break;
-
- case ir_binop_logic_and:
- /* the bool args are stored as float 0.0 or 1.0, so "mul" gives us "and". */
- ir_to_mesa_emit_op2(ir, OPCODE_MUL,
- result_dst,
- op[0], op[1]);
- break;
-
- case ir_binop_dot:
- assert(ir->operands[0]->type->is_vector());
- assert(ir->operands[0]->type == ir->operands[1]->type);
- ir_to_mesa_emit_dp(ir, result_dst, op[0], op[1],
- ir->operands[0]->type->vector_elements);
- break;
-
- case ir_unop_sqrt:
- /* sqrt(x) = x * rsq(x). */
- ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
- ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, result_src, op[0]);
- /* For incoming channels <= 0, set the result to 0. */
- op[0].negate = ~op[0].negate;
- ir_to_mesa_emit_op3(ir, OPCODE_CMP, result_dst,
- op[0], result_src, src_reg_for_float(0.0));
- break;
- case ir_unop_rsq:
- ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
- break;
- case ir_unop_i2f:
- case ir_unop_b2f:
- case ir_unop_b2i:
- /* Mesa IR lacks types, ints are stored as truncated floats. */
- result_src = op[0];
- break;
- case ir_unop_f2i:
- ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
- break;
- case ir_unop_f2b:
- case ir_unop_i2b:
- ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst,
- op[0], src_reg_for_float(0.0));
- break;
- case ir_unop_trunc:
- ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
- break;
- case ir_unop_ceil:
- op[0].negate = ~op[0].negate;
- ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
- result_src.negate = ~result_src.negate;
- break;
- case ir_unop_floor:
- ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
- break;
- case ir_unop_fract:
- ir_to_mesa_emit_op1(ir, OPCODE_FRC, result_dst, op[0]);
- break;
-
- case ir_binop_min:
- ir_to_mesa_emit_op2(ir, OPCODE_MIN, result_dst, op[0], op[1]);
- break;
- case ir_binop_max:
- ir_to_mesa_emit_op2(ir, OPCODE_MAX, result_dst, op[0], op[1]);
- break;
- case ir_binop_pow:
- ir_to_mesa_emit_scalar_op2(ir, OPCODE_POW, result_dst, op[0], op[1]);
- break;
-
- case ir_unop_bit_not:
- case ir_unop_u2f:
- case ir_binop_lshift:
- case ir_binop_rshift:
- case ir_binop_bit_and:
- case ir_binop_bit_xor:
- case ir_binop_bit_or:
- case ir_unop_round_even:
- assert(!"GLSL 1.30 features unsupported");
- break;
-
- case ir_quadop_vector:
- /* This operation should have already been handled.
- */
- assert(!"Should not get here.");
- break;
- }
-
- this->result = result_src;
-}
-
-
-void
-ir_to_mesa_visitor::visit(ir_swizzle *ir)
-{
- ir_to_mesa_src_reg src_reg;
- int i;
- int swizzle[4];
-
- /* Note that this is only swizzles in expressions, not those on the left
- * hand side of an assignment, which do write masking. See ir_assignment
- * for that.
- */
-
- ir->val->accept(this);
- src_reg = this->result;
- assert(src_reg.file != PROGRAM_UNDEFINED);
-
- for (i = 0; i < 4; i++) {
- if (i < ir->type->vector_elements) {
- switch (i) {
- case 0:
- swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.x);
- break;
- case 1:
- swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.y);
- break;
- case 2:
- swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.z);
- break;
- case 3:
- swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.w);
- break;
- }
- } else {
- /* If the type is smaller than a vec4, replicate the last
- * channel out.
- */
- swizzle[i] = swizzle[ir->type->vector_elements - 1];
- }
- }
-
- src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0],
- swizzle[1],
- swizzle[2],
- swizzle[3]);
-
- this->result = src_reg;
-}
-
-void
-ir_to_mesa_visitor::visit(ir_dereference_variable *ir)
-{
- variable_storage *entry = find_variable_storage(ir->var);
-
- if (!entry) {
- switch (ir->var->mode) {
- case ir_var_uniform:
- entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_UNIFORM,
- ir->var->location);
- this->variables.push_tail(entry);
- break;
- case ir_var_in:
- case ir_var_out:
- case ir_var_inout:
- case ir_var_system_value:
- /* The linker assigns locations for varyings and attributes,
- * including deprecated builtins (like gl_Color), user-assign
- * generic attributes (glBindVertexLocation), and
- * user-defined varyings.
- *
- * FINISHME: We would hit this path for function arguments. Fix!
- */
- assert(ir->var->location != -1);
- if (ir->var->mode == ir_var_in ||
- ir->var->mode == ir_var_inout) {
- entry = new(mem_ctx) variable_storage(ir->var,
- PROGRAM_INPUT,
- ir->var->location);
-
- if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
- ir->var->location >= VERT_ATTRIB_GENERIC0) {
- _mesa_add_attribute(prog->Attributes,
- ir->var->name,
- _mesa_sizeof_glsl_type(ir->var->type->gl_type),
- ir->var->type->gl_type,
- ir->var->location - VERT_ATTRIB_GENERIC0);
- }
- } else if (ir->var->mode == ir_var_system_value) {
- entry = new(mem_ctx) variable_storage(ir->var,
- PROGRAM_SYSTEM_VALUE,
- ir->var->location);
- } else {
- entry = new(mem_ctx) variable_storage(ir->var,
- PROGRAM_OUTPUT,
- ir->var->location);
- }
-
- break;
- case ir_var_auto:
- case ir_var_temporary:
- entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_TEMPORARY,
- this->next_temp);
- this->variables.push_tail(entry);
-
- next_temp += type_size(ir->var->type);
- break;
- }
-
- if (!entry) {
- printf("Failed to make storage for %s\n", ir->var->name);
- exit(1);
- }
- }
-
- this->result = ir_to_mesa_src_reg(entry->file, entry->index, ir->var->type);
-}
-
-void
-ir_to_mesa_visitor::visit(ir_dereference_array *ir)
-{
- ir_constant *index;
- ir_to_mesa_src_reg src_reg;
- int element_size = type_size(ir->type);
-
- index = ir->array_index->constant_expression_value();
-
- ir->array->accept(this);
- src_reg = this->result;
-
- if (index) {
- src_reg.index += index->value.i[0] * element_size;
- } else {
- ir_to_mesa_src_reg array_base = this->result;
- /* Variable index array dereference. It eats the "vec4" of the
- * base of the array and an index that offsets the Mesa register
- * index.
- */
- ir->array_index->accept(this);
-
- ir_to_mesa_src_reg index_reg;
-
- if (element_size == 1) {
- index_reg = this->result;
- } else {
- index_reg = get_temp(glsl_type::float_type);
-
- ir_to_mesa_emit_op2(ir, OPCODE_MUL,
- ir_to_mesa_dst_reg_from_src(index_reg),
- this->result, src_reg_for_float(element_size));
- }
-
- src_reg.reladdr = talloc(mem_ctx, ir_to_mesa_src_reg);
- memcpy(src_reg.reladdr, &index_reg, sizeof(index_reg));
- }
-
- /* If the type is smaller than a vec4, replicate the last channel out. */
- if (ir->type->is_scalar() || ir->type->is_vector())
- src_reg.swizzle = swizzle_for_size(ir->type->vector_elements);
- else
- src_reg.swizzle = SWIZZLE_NOOP;
-
- this->result = src_reg;
-}
-
-void
-ir_to_mesa_visitor::visit(ir_dereference_record *ir)
-{
- unsigned int i;
- const glsl_type *struct_type = ir->record->type;
- int offset = 0;
-
- ir->record->accept(this);
-
- for (i = 0; i < struct_type->length; i++) {
- if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
- break;
- offset += type_size(struct_type->fields.structure[i].type);
- }
-
- /* If the type is smaller than a vec4, replicate the last channel out. */
- if (ir->type->is_scalar() || ir->type->is_vector())
- this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
- else
- this->result.swizzle = SWIZZLE_NOOP;
-
- this->result.index += offset;
-}
-
-/**
- * We want to be careful in assignment setup to hit the actual storage
- * instead of potentially using a temporary like we might with the
- * ir_dereference handler.
- */
-static struct ir_to_mesa_dst_reg
-get_assignment_lhs(ir_dereference *ir, ir_to_mesa_visitor *v)
-{
- /* The LHS must be a dereference. If the LHS is a variable indexed array
- * access of a vector, it must be separated into a series conditional moves
- * before reaching this point (see ir_vec_index_to_cond_assign).
- */
- assert(ir->as_dereference());
- ir_dereference_array *deref_array = ir->as_dereference_array();
- if (deref_array) {
- assert(!deref_array->array->type->is_vector());
- }
-
- /* Use the rvalue deref handler for the most part. We'll ignore
- * swizzles in it and write swizzles using writemask, though.
- */
- ir->accept(v);
- return ir_to_mesa_dst_reg_from_src(v->result);
-}
-
-/**
- * Process the condition of a conditional assignment
- *
- * Examines the condition of a conditional assignment to generate the optimal
- * first operand of a \c CMP instruction. If the condition is a relational
- * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
- * used as the source for the \c CMP instruction. Otherwise the comparison
- * is processed to a boolean result, and the boolean result is used as the
- * operand to the CMP instruction.
- */
-bool
-ir_to_mesa_visitor::process_move_condition(ir_rvalue *ir)
-{
- ir_rvalue *src_ir = ir;
- bool negate = true;
- bool switch_order = false;
-
- ir_expression *const expr = ir->as_expression();
- if ((expr != NULL) && (expr->get_num_operands() == 2)) {
- bool zero_on_left = false;
-
- if (expr->operands[0]->is_zero()) {
- src_ir = expr->operands[1];
- zero_on_left = true;
- } else if (expr->operands[1]->is_zero()) {
- src_ir = expr->operands[0];
- zero_on_left = false;
- }
-
- /* a is - 0 + - 0 +
- * (a < 0) T F F ( a < 0) T F F
- * (0 < a) F F T (-a < 0) F F T
- * (a <= 0) T T F (-a < 0) F F T (swap order of other operands)
- * (0 <= a) F T T ( a < 0) T F F (swap order of other operands)
- * (a > 0) F F T (-a < 0) F F T
- * (0 > a) T F F ( a < 0) T F F
- * (a >= 0) F T T ( a < 0) T F F (swap order of other operands)
- * (0 >= a) T T F (-a < 0) F F T (swap order of other operands)
- *
- * Note that exchanging the order of 0 and 'a' in the comparison simply
- * means that the value of 'a' should be negated.
- */
- if (src_ir != ir) {
- switch (expr->operation) {
- case ir_binop_less:
- switch_order = false;
- negate = zero_on_left;
- break;
-
- case ir_binop_greater:
- switch_order = false;
- negate = !zero_on_left;
- break;
-
- case ir_binop_lequal:
- switch_order = true;
- negate = !zero_on_left;
- break;
-
- case ir_binop_gequal:
- switch_order = true;
- negate = zero_on_left;
- break;
-
- default:
- /* This isn't the right kind of comparison afterall, so make sure
- * the whole condition is visited.
- */
- src_ir = ir;
- break;
- }
- }
- }
-
- src_ir->accept(this);
-
- /* We use the OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
- * condition we produced is 0.0 or 1.0. By flipping the sign, we can
- * choose which value OPCODE_CMP produces without an extra instruction
- * computing the condition.
- */
- if (negate)
- this->result.negate = ~this->result.negate;
-
- return switch_order;
-}
-
-void
-ir_to_mesa_visitor::visit(ir_assignment *ir)
-{
- struct ir_to_mesa_dst_reg l;
- struct ir_to_mesa_src_reg r;
- int i;
-
- ir->rhs->accept(this);
- r = this->result;
-
- l = get_assignment_lhs(ir->lhs, this);
-
- /* FINISHME: This should really set to the correct maximal writemask for each
- * FINISHME: component written (in the loops below). This case can only
- * FINISHME: occur for matrices, arrays, and structures.
- */
- if (ir->write_mask == 0) {
- assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
- l.writemask = WRITEMASK_XYZW;
- } else if (ir->lhs->type->is_scalar()) {
- /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
- * FINISHME: W component of fragment shader output zero, work correctly.
- */
- l.writemask = WRITEMASK_XYZW;
- } else {
- int swizzles[4];
- int first_enabled_chan = 0;
- int rhs_chan = 0;
-
- assert(ir->lhs->type->is_vector());
- l.writemask = ir->write_mask;
-
- for (int i = 0; i < 4; i++) {
- if (l.writemask & (1 << i)) {
- first_enabled_chan = GET_SWZ(r.swizzle, i);
- break;
- }
- }
-
- /* Swizzle a small RHS vector into the channels being written.
- *
- * glsl ir treats write_mask as dictating how many channels are
- * present on the RHS while Mesa IR treats write_mask as just
- * showing which channels of the vec4 RHS get written.
- */
- for (int i = 0; i < 4; i++) {
- if (l.writemask & (1 << i))
- swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
- else
- swizzles[i] = first_enabled_chan;
- }
- r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
- swizzles[2], swizzles[3]);
- }
-
- assert(l.file != PROGRAM_UNDEFINED);
- assert(r.file != PROGRAM_UNDEFINED);
-
- if (ir->condition) {
- const bool switch_order = this->process_move_condition(ir->condition);
- ir_to_mesa_src_reg condition = this->result;
-
- for (i = 0; i < type_size(ir->lhs->type); i++) {
- if (switch_order) {
- ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
- condition, ir_to_mesa_src_reg_from_dst(l), r);
- } else {
- ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
- condition, r, ir_to_mesa_src_reg_from_dst(l));
- }
-
- l.index++;
- r.index++;
- }
- } else {
- for (i = 0; i < type_size(ir->lhs->type); i++) {
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
- l.index++;
- r.index++;
- }
- }
-}
-
-
-void
-ir_to_mesa_visitor::visit(ir_constant *ir)
-{
- ir_to_mesa_src_reg src_reg;
- GLfloat stack_vals[4] = { 0 };
- GLfloat *values = stack_vals;
- unsigned int i;
-
- /* Unfortunately, 4 floats is all we can get into
- * _mesa_add_unnamed_constant. So, make a temp to store an
- * aggregate constant and move each constant value into it. If we
- * get lucky, copy propagation will eliminate the extra moves.
- */
-
- if (ir->type->base_type == GLSL_TYPE_STRUCT) {
- ir_to_mesa_src_reg temp_base = get_temp(ir->type);
- ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
-
- foreach_iter(exec_list_iterator, iter, ir->components) {
- ir_constant *field_value = (ir_constant *)iter.get();
- int size = type_size(field_value->type);
-
- assert(size > 0);
-
- field_value->accept(this);
- src_reg = this->result;
-
- for (i = 0; i < (unsigned int)size; i++) {
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
-
- src_reg.index++;
- temp.index++;
- }
- }
- this->result = temp_base;
- return;
- }
-
- if (ir->type->is_array()) {
- ir_to_mesa_src_reg temp_base = get_temp(ir->type);
- ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
- int size = type_size(ir->type->fields.array);
-
- assert(size > 0);
-
- for (i = 0; i < ir->type->length; i++) {
- ir->array_elements[i]->accept(this);
- src_reg = this->result;
- for (int j = 0; j < size; j++) {
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
-
- src_reg.index++;
- temp.index++;
- }
- }
- this->result = temp_base;
- return;
- }
-
- if (ir->type->is_matrix()) {
- ir_to_mesa_src_reg mat = get_temp(ir->type);
- ir_to_mesa_dst_reg mat_column = ir_to_mesa_dst_reg_from_src(mat);
-
- for (i = 0; i < ir->type->matrix_columns; i++) {
- assert(ir->type->base_type == GLSL_TYPE_FLOAT);
- values = &ir->value.f[i * ir->type->vector_elements];
-
- src_reg = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, NULL);
- src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
- values,
- ir->type->vector_elements,
- &src_reg.swizzle);
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, mat_column, src_reg);
-
- mat_column.index++;
- }
-
- this->result = mat;
- return;
- }
-
- src_reg.file = PROGRAM_CONSTANT;
- switch (ir->type->base_type) {
- case GLSL_TYPE_FLOAT:
- values = &ir->value.f[0];
- break;
- case GLSL_TYPE_UINT:
- for (i = 0; i < ir->type->vector_elements; i++) {
- values[i] = ir->value.u[i];
- }
- break;
- case GLSL_TYPE_INT:
- for (i = 0; i < ir->type->vector_elements; i++) {
- values[i] = ir->value.i[i];
- }
- break;
- case GLSL_TYPE_BOOL:
- for (i = 0; i < ir->type->vector_elements; i++) {
- values[i] = ir->value.b[i];
- }
- break;
- default:
- assert(!"Non-float/uint/int/bool constant");
- }
-
- this->result = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, ir->type);
- this->result.index = _mesa_add_unnamed_constant(this->prog->Parameters,
- values,
- ir->type->vector_elements,
- &this->result.swizzle);
-}
-
-function_entry *
-ir_to_mesa_visitor::get_function_signature(ir_function_signature *sig)
-{
- function_entry *entry;
-
- foreach_iter(exec_list_iterator, iter, this->function_signatures) {
- entry = (function_entry *)iter.get();
-
- if (entry->sig == sig)
- return entry;
- }
-
- entry = talloc(mem_ctx, function_entry);
- entry->sig = sig;
- entry->sig_id = this->next_signature_id++;
- entry->bgn_inst = NULL;
-
- /* Allocate storage for all the parameters. */
- foreach_iter(exec_list_iterator, iter, sig->parameters) {
- ir_variable *param = (ir_variable *)iter.get();
- variable_storage *storage;
-
- storage = find_variable_storage(param);
- assert(!storage);
-
- storage = new(mem_ctx) variable_storage(param, PROGRAM_TEMPORARY,
- this->next_temp);
- this->variables.push_tail(storage);
-
- this->next_temp += type_size(param->type);
- }
-
- if (!sig->return_type->is_void()) {
- entry->return_reg = get_temp(sig->return_type);
- } else {
- entry->return_reg = ir_to_mesa_undef;
- }
-
- this->function_signatures.push_tail(entry);
- return entry;
-}
-
-void
-ir_to_mesa_visitor::visit(ir_call *ir)
-{
- ir_to_mesa_instruction *call_inst;
- ir_function_signature *sig = ir->get_callee();
- function_entry *entry = get_function_signature(sig);
- int i;
-
- /* Process in parameters. */
- exec_list_iterator sig_iter = sig->parameters.iterator();
- foreach_iter(exec_list_iterator, iter, *ir) {
- ir_rvalue *param_rval = (ir_rvalue *)iter.get();
- ir_variable *param = (ir_variable *)sig_iter.get();
-
- if (param->mode == ir_var_in ||
- param->mode == ir_var_inout) {
- variable_storage *storage = find_variable_storage(param);
- assert(storage);
-
- param_rval->accept(this);
- ir_to_mesa_src_reg r = this->result;
-
- ir_to_mesa_dst_reg l;
- l.file = storage->file;
- l.index = storage->index;
- l.reladdr = NULL;
- l.writemask = WRITEMASK_XYZW;
- l.cond_mask = COND_TR;
-
- for (i = 0; i < type_size(param->type); i++) {
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
- l.index++;
- r.index++;
- }
- }
-
- sig_iter.next();
- }
- assert(!sig_iter.has_next());
-
- /* Emit call instruction */
- call_inst = ir_to_mesa_emit_op1(ir, OPCODE_CAL,
- ir_to_mesa_undef_dst, ir_to_mesa_undef);
- call_inst->function = entry;
-
- /* Process out parameters. */
- sig_iter = sig->parameters.iterator();
- foreach_iter(exec_list_iterator, iter, *ir) {
- ir_rvalue *param_rval = (ir_rvalue *)iter.get();
- ir_variable *param = (ir_variable *)sig_iter.get();
-
- if (param->mode == ir_var_out ||
- param->mode == ir_var_inout) {
- variable_storage *storage = find_variable_storage(param);
- assert(storage);
-
- ir_to_mesa_src_reg r;
- r.file = storage->file;
- r.index = storage->index;
- r.reladdr = NULL;
- r.swizzle = SWIZZLE_NOOP;
- r.negate = 0;
-
- param_rval->accept(this);
- ir_to_mesa_dst_reg l = ir_to_mesa_dst_reg_from_src(this->result);
-
- for (i = 0; i < type_size(param->type); i++) {
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
- l.index++;
- r.index++;
- }
- }
-
- sig_iter.next();
- }
- assert(!sig_iter.has_next());
-
- /* Process return value. */
- this->result = entry->return_reg;
-}
-
-void
-ir_to_mesa_visitor::visit(ir_texture *ir)
-{
- ir_to_mesa_src_reg result_src, coord, lod_info, projector;
- ir_to_mesa_dst_reg result_dst, coord_dst;
- ir_to_mesa_instruction *inst = NULL;
- prog_opcode opcode = OPCODE_NOP;
-
- ir->coordinate->accept(this);
-
- /* Put our coords in a temp. We'll need to modify them for shadow,
- * projection, or LOD, so the only case we'd use it as is is if
- * we're doing plain old texturing. Mesa IR optimization should
- * handle cleaning up our mess in that case.
- */
- coord = get_temp(glsl_type::vec4_type);
- coord_dst = ir_to_mesa_dst_reg_from_src(coord);
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst,
- this->result);
-
- if (ir->projector) {
- ir->projector->accept(this);
- projector = this->result;
- }
-
- /* Storage for our result. Ideally for an assignment we'd be using
- * the actual storage for the result here, instead.
- */
- result_src = get_temp(glsl_type::vec4_type);
- result_dst = ir_to_mesa_dst_reg_from_src(result_src);
-
- switch (ir->op) {
- case ir_tex:
- opcode = OPCODE_TEX;
- break;
- case ir_txb:
- opcode = OPCODE_TXB;
- ir->lod_info.bias->accept(this);
- lod_info = this->result;
- break;
- case ir_txl:
- opcode = OPCODE_TXL;
- ir->lod_info.lod->accept(this);
- lod_info = this->result;
- break;
- case ir_txd:
- case ir_txf:
- assert(!"GLSL 1.30 features unsupported");
- break;
- }
-
- if (ir->projector) {
- if (opcode == OPCODE_TEX) {
- /* Slot the projector in as the last component of the coord. */
- coord_dst.writemask = WRITEMASK_W;
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, projector);
- coord_dst.writemask = WRITEMASK_XYZW;
- opcode = OPCODE_TXP;
- } else {
- ir_to_mesa_src_reg coord_w = coord;
- coord_w.swizzle = SWIZZLE_WWWW;
-
- /* For the other TEX opcodes there's no projective version
- * since the last slot is taken up by lod info. Do the
- * projective divide now.
- */
- coord_dst.writemask = WRITEMASK_W;
- ir_to_mesa_emit_op1(ir, OPCODE_RCP, coord_dst, projector);
-
- coord_dst.writemask = WRITEMASK_XYZ;
- ir_to_mesa_emit_op2(ir, OPCODE_MUL, coord_dst, coord, coord_w);
-
- coord_dst.writemask = WRITEMASK_XYZW;
- coord.swizzle = SWIZZLE_XYZW;
- }
- }
-
- if (ir->shadow_comparitor) {
- /* Slot the shadow value in as the second to last component of the
- * coord.
- */
- ir->shadow_comparitor->accept(this);
- coord_dst.writemask = WRITEMASK_Z;
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, this->result);
- coord_dst.writemask = WRITEMASK_XYZW;
- }
-
- if (opcode == OPCODE_TXL || opcode == OPCODE_TXB) {
- /* Mesa IR stores lod or lod bias in the last channel of the coords. */
- coord_dst.writemask = WRITEMASK_W;
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, lod_info);
- coord_dst.writemask = WRITEMASK_XYZW;
- }
-
- inst = ir_to_mesa_emit_op1(ir, opcode, result_dst, coord);
-
- if (ir->shadow_comparitor)
- inst->tex_shadow = GL_TRUE;
-
- inst->sampler = _mesa_get_sampler_uniform_value(ir->sampler,
- this->shader_program,
- this->prog);
-
- const glsl_type *sampler_type = ir->sampler->type;
-
- switch (sampler_type->sampler_dimensionality) {
- case GLSL_SAMPLER_DIM_1D:
- inst->tex_target = (sampler_type->sampler_array)
- ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
- break;
- case GLSL_SAMPLER_DIM_2D:
- inst->tex_target = (sampler_type->sampler_array)
- ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
- break;
- case GLSL_SAMPLER_DIM_3D:
- inst->tex_target = TEXTURE_3D_INDEX;
- break;
- case GLSL_SAMPLER_DIM_CUBE:
- inst->tex_target = TEXTURE_CUBE_INDEX;
- break;
- case GLSL_SAMPLER_DIM_RECT:
- inst->tex_target = TEXTURE_RECT_INDEX;
- break;
- case GLSL_SAMPLER_DIM_BUF:
- assert(!"FINISHME: Implement ARB_texture_buffer_object");
- break;
- default:
- assert(!"Should not get here.");
- }
-
- this->result = result_src;
-}
-
-void
-ir_to_mesa_visitor::visit(ir_return *ir)
-{
- if (ir->get_value()) {
- ir_to_mesa_dst_reg l;
- int i;
-
- assert(current_function);
-
- ir->get_value()->accept(this);
- ir_to_mesa_src_reg r = this->result;
-
- l = ir_to_mesa_dst_reg_from_src(current_function->return_reg);
-
- for (i = 0; i < type_size(current_function->sig->return_type); i++) {
- ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
- l.index++;
- r.index++;
- }
- }
-
- ir_to_mesa_emit_op0(ir, OPCODE_RET);
-}
-
-void
-ir_to_mesa_visitor::visit(ir_discard *ir)
-{
- struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
-
- if (ir->condition) {
- ir->condition->accept(this);
- this->result.negate = ~this->result.negate;
- ir_to_mesa_emit_op1(ir, OPCODE_KIL, ir_to_mesa_undef_dst, this->result);
- } else {
- ir_to_mesa_emit_op0(ir, OPCODE_KIL_NV);
- }
-
- fp->UsesKill = GL_TRUE;
-}
-
-void
-ir_to_mesa_visitor::visit(ir_if *ir)
-{
- ir_to_mesa_instruction *cond_inst, *if_inst, *else_inst = NULL;
- ir_to_mesa_instruction *prev_inst;
-
- prev_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
-
- ir->condition->accept(this);
- assert(this->result.file != PROGRAM_UNDEFINED);
-
- if (this->options->EmitCondCodes) {
- cond_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
-
- /* See if we actually generated any instruction for generating
- * the condition. If not, then cook up a move to a temp so we
- * have something to set cond_update on.
- */
- if (cond_inst == prev_inst) {
- ir_to_mesa_src_reg temp = get_temp(glsl_type::bool_type);
- cond_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_MOV,
- ir_to_mesa_dst_reg_from_src(temp),
- result);
- }
- cond_inst->cond_update = GL_TRUE;
-
- if_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_IF);
- if_inst->dst_reg.cond_mask = COND_NE;
- } else {
- if_inst = ir_to_mesa_emit_op1(ir->condition,
- OPCODE_IF, ir_to_mesa_undef_dst,
- this->result);
- }
-
- this->instructions.push_tail(if_inst);
-
- visit_exec_list(&ir->then_instructions, this);
-
- if (!ir->else_instructions.is_empty()) {
- else_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_ELSE);
- visit_exec_list(&ir->else_instructions, this);
- }
-
- if_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_ENDIF,
- ir_to_mesa_undef_dst, ir_to_mesa_undef);
-}
-
-ir_to_mesa_visitor::ir_to_mesa_visitor()
-{
- result.file = PROGRAM_UNDEFINED;
- next_temp = 1;
- next_signature_id = 1;
- current_function = NULL;
- mem_ctx = talloc_new(NULL);
-}
-
-ir_to_mesa_visitor::~ir_to_mesa_visitor()
-{
- talloc_free(mem_ctx);
-}
-
-static struct prog_src_register
-mesa_src_reg_from_ir_src_reg(ir_to_mesa_src_reg reg)
-{
- struct prog_src_register mesa_reg;
-
- mesa_reg.File = reg.file;
- assert(reg.index < (1 << INST_INDEX_BITS));
- mesa_reg.Index = reg.index;
- mesa_reg.Swizzle = reg.swizzle;
- mesa_reg.RelAddr = reg.reladdr != NULL;
- mesa_reg.Negate = reg.negate;
- mesa_reg.Abs = 0;
- mesa_reg.HasIndex2 = GL_FALSE;
- mesa_reg.RelAddr2 = 0;
- mesa_reg.Index2 = 0;
-
- return mesa_reg;
-}
-
-static void
-set_branchtargets(ir_to_mesa_visitor *v,
- struct prog_instruction *mesa_instructions,
- int num_instructions)
-{
- int if_count = 0, loop_count = 0;
- int *if_stack, *loop_stack;
- int if_stack_pos = 0, loop_stack_pos = 0;
- int i, j;
-
- for (i = 0; i < num_instructions; i++) {
- switch (mesa_instructions[i].Opcode) {
- case OPCODE_IF:
- if_count++;
- break;
- case OPCODE_BGNLOOP:
- loop_count++;
- break;
- case OPCODE_BRK:
- case OPCODE_CONT:
- mesa_instructions[i].BranchTarget = -1;
- break;
- default:
- break;
- }
- }
-
- if_stack = talloc_zero_array(v->mem_ctx, int, if_count);
- loop_stack = talloc_zero_array(v->mem_ctx, int, loop_count);
-
- for (i = 0; i < num_instructions; i++) {
- switch (mesa_instructions[i].Opcode) {
- case OPCODE_IF:
- if_stack[if_stack_pos] = i;
- if_stack_pos++;
- break;
- case OPCODE_ELSE:
- mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
- if_stack[if_stack_pos - 1] = i;
- break;
- case OPCODE_ENDIF:
- mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
- if_stack_pos--;
- break;
- case OPCODE_BGNLOOP:
- loop_stack[loop_stack_pos] = i;
- loop_stack_pos++;
- break;
- case OPCODE_ENDLOOP:
- loop_stack_pos--;
- /* Rewrite any breaks/conts at this nesting level (haven't
- * already had a BranchTarget assigned) to point to the end
- * of the loop.
- */
- for (j = loop_stack[loop_stack_pos]; j < i; j++) {
- if (mesa_instructions[j].Opcode == OPCODE_BRK ||
- mesa_instructions[j].Opcode == OPCODE_CONT) {
- if (mesa_instructions[j].BranchTarget == -1) {
- mesa_instructions[j].BranchTarget = i;
- }
- }
- }
- /* The loop ends point at each other. */
- mesa_instructions[i].BranchTarget = loop_stack[loop_stack_pos];
- mesa_instructions[loop_stack[loop_stack_pos]].BranchTarget = i;
- break;
- case OPCODE_CAL:
- foreach_iter(exec_list_iterator, iter, v->function_signatures) {
- function_entry *entry = (function_entry *)iter.get();
-
- if (entry->sig_id == mesa_instructions[i].BranchTarget) {
- mesa_instructions[i].BranchTarget = entry->inst;
- break;
- }
- }
- break;
- default:
- break;
- }
- }
-}
-
-static void
-print_program(struct prog_instruction *mesa_instructions,
- ir_instruction **mesa_instruction_annotation,
- int num_instructions)
-{
- ir_instruction *last_ir = NULL;
- int i;
- int indent = 0;
-
- for (i = 0; i < num_instructions; i++) {
- struct prog_instruction *mesa_inst = mesa_instructions + i;
- ir_instruction *ir = mesa_instruction_annotation[i];
-
- fprintf(stdout, "%3d: ", i);
-
- if (last_ir != ir && ir) {
- int j;
-
- for (j = 0; j < indent; j++) {
- fprintf(stdout, " ");
- }
- ir->print();
- printf("\n");
- last_ir = ir;
-
- fprintf(stdout, " "); /* line number spacing. */
- }
-
- indent = _mesa_fprint_instruction_opt(stdout, mesa_inst, indent,
- PROG_PRINT_DEBUG, NULL);
- }
-}
-
-static void
-count_resources(struct gl_program *prog)
-{
- unsigned int i;
-
- prog->SamplersUsed = 0;
-
- for (i = 0; i < prog->NumInstructions; i++) {
- struct prog_instruction *inst = &prog->Instructions[i];
-
- if (_mesa_is_tex_instruction(inst->Opcode)) {
- prog->SamplerTargets[inst->TexSrcUnit] =
- (gl_texture_index)inst->TexSrcTarget;
- prog->SamplersUsed |= 1 << inst->TexSrcUnit;
- if (inst->TexShadow) {
- prog->ShadowSamplers |= 1 << inst->TexSrcUnit;
- }
- }
- }
-
- _mesa_update_shader_textures_used(prog);
-}
-
-struct uniform_sort {
- struct gl_uniform *u;
- int pos;
-};
-
-/* The shader_program->Uniforms list is almost sorted in increasing
- * uniform->{Frag,Vert}Pos locations, but not quite when there are
- * uniforms shared between targets. We need to add parameters in
- * increasing order for the targets.
- */
-static int
-sort_uniforms(const void *a, const void *b)
-{
- struct uniform_sort *u1 = (struct uniform_sort *)a;
- struct uniform_sort *u2 = (struct uniform_sort *)b;
-
- return u1->pos - u2->pos;
-}
-
-/* Add the uniforms to the parameters. The linker chose locations
- * in our parameters lists (which weren't created yet), which the
- * uniforms code will use to poke values into our parameters list
- * when uniforms are updated.
- */
-static void
-add_uniforms_to_parameters_list(struct gl_shader_program *shader_program,
- struct gl_shader *shader,
- struct gl_program *prog)
-{
- unsigned int i;
- unsigned int next_sampler = 0, num_uniforms = 0;
- struct uniform_sort *sorted_uniforms;
-
- sorted_uniforms = talloc_array(NULL, struct uniform_sort,
- shader_program->Uniforms->NumUniforms);
-
- for (i = 0; i < shader_program->Uniforms->NumUniforms; i++) {
- struct gl_uniform *uniform = shader_program->Uniforms->Uniforms + i;
- int parameter_index = -1;
-
- switch (shader->Type) {
- case GL_VERTEX_SHADER:
- parameter_index = uniform->VertPos;
- break;
- case GL_FRAGMENT_SHADER:
- parameter_index = uniform->FragPos;
- break;
- case GL_GEOMETRY_SHADER:
- parameter_index = uniform->GeomPos;
- break;
- }
-
- /* Only add uniforms used in our target. */
- if (parameter_index != -1) {
- sorted_uniforms[num_uniforms].pos = parameter_index;
- sorted_uniforms[num_uniforms].u = uniform;
- num_uniforms++;
- }
- }
-
- qsort(sorted_uniforms, num_uniforms, sizeof(struct uniform_sort),
- sort_uniforms);
-
- for (i = 0; i < num_uniforms; i++) {
- struct gl_uniform *uniform = sorted_uniforms[i].u;
- int parameter_index = sorted_uniforms[i].pos;
- const glsl_type *type = uniform->Type;
- unsigned int size;
-
- if (type->is_vector() ||
- type->is_scalar()) {
- size = type->vector_elements;
- } else {
- size = type_size(type) * 4;
- }
-
- gl_register_file file;
- if (type->is_sampler() ||
- (type->is_array() && type->fields.array->is_sampler())) {
- file = PROGRAM_SAMPLER;
- } else {
- file = PROGRAM_UNIFORM;
- }
-
- GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
- uniform->Name);
-
- if (index < 0) {
- index = _mesa_add_parameter(prog->Parameters, file,
- uniform->Name, size, type->gl_type,
- NULL, NULL, 0x0);
-
- /* Sampler uniform values are stored in prog->SamplerUnits,
- * and the entry in that array is selected by this index we
- * store in ParameterValues[].
- */
- if (file == PROGRAM_SAMPLER) {
- for (unsigned int j = 0; j < size / 4; j++)
- prog->Parameters->ParameterValues[index + j][0] = next_sampler++;
- }
-
- /* The location chosen in the Parameters list here (returned
- * from _mesa_add_uniform) has to match what the linker chose.
- */
- if (index != parameter_index) {
- fail_link(shader_program, "Allocation of uniform `%s' to target "
- "failed (%d vs %d)\n",
- uniform->Name, index, parameter_index);
- }
- }
- }
-
- talloc_free(sorted_uniforms);
-}
-
-static void
-set_uniform_initializer(struct gl_context *ctx, void *mem_ctx,
- struct gl_shader_program *shader_program,
- const char *name, const glsl_type *type,
- ir_constant *val)
-{
- if (type->is_record()) {
- ir_constant *field_constant;
-
- field_constant = (ir_constant *)val->components.get_head();
-
- for (unsigned int i = 0; i < type->length; i++) {
- const glsl_type *field_type = type->fields.structure[i].type;
- const char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
- type->fields.structure[i].name);
- set_uniform_initializer(ctx, mem_ctx, shader_program, field_name,
- field_type, field_constant);
- field_constant = (ir_constant *)field_constant->next;
- }
- return;
- }
-
- int loc = _mesa_get_uniform_location(ctx, shader_program, name);
-
- if (loc == -1) {
- fail_link(shader_program,
- "Couldn't find uniform for initializer %s\n", name);
- return;
- }
-
- for (unsigned int i = 0; i < (type->is_array() ? type->length : 1); i++) {
- ir_constant *element;
- const glsl_type *element_type;
- if (type->is_array()) {
- element = val->array_elements[i];
- element_type = type->fields.array;
- } else {
- element = val;
- element_type = type;
- }
-
- void *values;
-
- if (element_type->base_type == GLSL_TYPE_BOOL) {
- int *conv = talloc_array(mem_ctx, int, element_type->components());
- for (unsigned int j = 0; j < element_type->components(); j++) {
- conv[j] = element->value.b[j];
- }
- values = (void *)conv;
- element_type = glsl_type::get_instance(GLSL_TYPE_INT,
- element_type->vector_elements,
- 1);
- } else {
- values = &element->value;
- }
-
- if (element_type->is_matrix()) {
- _mesa_uniform_matrix(ctx, shader_program,
- element_type->matrix_columns,
- element_type->vector_elements,
- loc, 1, GL_FALSE, (GLfloat *)values);
- loc += element_type->matrix_columns;
- } else {
- _mesa_uniform(ctx, shader_program, loc, element_type->matrix_columns,
- values, element_type->gl_type);
- loc += type_size(element_type);
- }
- }
-}
-
-static void
-set_uniform_initializers(struct gl_context *ctx,
- struct gl_shader_program *shader_program)
-{
- void *mem_ctx = NULL;
-
- for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
- struct gl_shader *shader = shader_program->_LinkedShaders[i];
-
- if (shader == NULL)
- continue;
-
- foreach_iter(exec_list_iterator, iter, *shader->ir) {
- ir_instruction *ir = (ir_instruction *)iter.get();
- ir_variable *var = ir->as_variable();
-
- if (!var || var->mode != ir_var_uniform || !var->constant_value)
- continue;
-
- if (!mem_ctx)
- mem_ctx = talloc_new(NULL);
-
- set_uniform_initializer(ctx, mem_ctx, shader_program, var->name,
- var->type, var->constant_value);
- }
- }
-
- talloc_free(mem_ctx);
-}
-
-/*
- * On a basic block basis, tracks available PROGRAM_TEMPORARY register
- * channels for copy propagation and updates following instructions to
- * use the original versions.
- *
- * The ir_to_mesa_visitor lazily produces code assuming that this pass
- * will occur. As an example, a TXP production before this pass:
- *
- * 0: MOV TEMP[1], INPUT[4].xyyy;
- * 1: MOV TEMP[1].w, INPUT[4].wwww;
- * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
- *
- * and after:
- *
- * 0: MOV TEMP[1], INPUT[4].xyyy;
- * 1: MOV TEMP[1].w, INPUT[4].wwww;
- * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
- *
- * which allows for dead code elimination on TEMP[1]'s writes.
- */
-void
-ir_to_mesa_visitor::copy_propagate(void)
-{
- ir_to_mesa_instruction **acp = talloc_zero_array(mem_ctx,
- ir_to_mesa_instruction *,
- this->next_temp * 4);
-
- foreach_iter(exec_list_iterator, iter, this->instructions) {
- ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
-
- /* First, do any copy propagation possible into the src regs. */
- for (int r = 0; r < 3; r++) {
- ir_to_mesa_instruction *first = NULL;
- bool good = true;
- int acp_base = inst->src_reg[r].index * 4;
-
- if (inst->src_reg[r].file != PROGRAM_TEMPORARY ||
- inst->src_reg[r].reladdr)
- continue;
-
- /* See if we can find entries in the ACP consisting of MOVs
- * from the same src register for all the swizzled channels
- * of this src register reference.
- */
- for (int i = 0; i < 4; i++) {
- int src_chan = GET_SWZ(inst->src_reg[r].swizzle, i);
- ir_to_mesa_instruction *copy_chan = acp[acp_base + src_chan];
-
- if (!copy_chan) {
- good = false;
- break;
- }
-
- if (!first) {
- first = copy_chan;
- } else {
- if (first->src_reg[0].file != copy_chan->src_reg[0].file ||
- first->src_reg[0].index != copy_chan->src_reg[0].index) {
- good = false;
- break;
- }
- }
- }
-
- if (good) {
- /* We've now validated that we can copy-propagate to
- * replace this src register reference. Do it.
- */
- inst->src_reg[r].file = first->src_reg[0].file;
- inst->src_reg[r].index = first->src_reg[0].index;
-
- int swizzle = 0;
- for (int i = 0; i < 4; i++) {
- int src_chan = GET_SWZ(inst->src_reg[r].swizzle, i);
- ir_to_mesa_instruction *copy_inst = acp[acp_base + src_chan];
- swizzle |= (GET_SWZ(copy_inst->src_reg[0].swizzle, src_chan) <<
- (3 * i));
- }
- inst->src_reg[r].swizzle = swizzle;
- }
- }
-
- switch (inst->op) {
- case OPCODE_BGNLOOP:
- case OPCODE_ENDLOOP:
- case OPCODE_ELSE:
- case OPCODE_ENDIF:
- /* End of a basic block, clear the ACP entirely. */
- memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
- break;
-
- default:
- /* Continuing the block, clear any written channels from
- * the ACP.
- */
- if (inst->dst_reg.file == PROGRAM_TEMPORARY) {
- if (inst->dst_reg.reladdr) {
- memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
- } else {
- for (int i = 0; i < 4; i++) {
- if (inst->dst_reg.writemask & (1 << i)) {
- acp[4 * inst->dst_reg.index + i] = NULL;
- }
- }
- }
- }
- break;
- }
-
- /* If this is a copy, add it to the ACP. */
- if (inst->op == OPCODE_MOV &&
- inst->dst_reg.file == PROGRAM_TEMPORARY &&
- !inst->dst_reg.reladdr &&
- !inst->saturate &&
- !inst->src_reg[0].reladdr &&
- !inst->src_reg[0].negate) {
- for (int i = 0; i < 4; i++) {
- if (inst->dst_reg.writemask & (1 << i)) {
- acp[4 * inst->dst_reg.index + i] = inst;
- }
- }
- }
- }
-
- talloc_free(acp);
-}
-
-
-/**
- * Convert a shader's GLSL IR into a Mesa gl_program.
- */
-static struct gl_program *
-get_mesa_program(struct gl_context *ctx,
- struct gl_shader_program *shader_program,
- struct gl_shader *shader)
-{
- ir_to_mesa_visitor v;
- struct prog_instruction *mesa_instructions, *mesa_inst;
- ir_instruction **mesa_instruction_annotation;
- int i;
- struct gl_program *prog;
- GLenum target;
- const char *target_string;
- GLboolean progress;
- struct gl_shader_compiler_options *options =
- &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(shader->Type)];
-
- switch (shader->Type) {
- case GL_VERTEX_SHADER:
- target = GL_VERTEX_PROGRAM_ARB;
- target_string = "vertex";
- break;
- case GL_FRAGMENT_SHADER:
- target = GL_FRAGMENT_PROGRAM_ARB;
- target_string = "fragment";
- break;
- case GL_GEOMETRY_SHADER:
- target = GL_GEOMETRY_PROGRAM_NV;
- target_string = "geometry";
- break;
- default:
- assert(!"should not be reached");
- return NULL;
- }
-
- validate_ir_tree(shader->ir);
-
- prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
- if (!prog)
- return NULL;
- prog->Parameters = _mesa_new_parameter_list();
- prog->Varying = _mesa_new_parameter_list();
- prog->Attributes = _mesa_new_parameter_list();
- v.ctx = ctx;
- v.prog = prog;
- v.shader_program = shader_program;
- v.options = options;
-
- add_uniforms_to_parameters_list(shader_program, shader, prog);
-
- /* Emit Mesa IR for main(). */
- visit_exec_list(shader->ir, &v);
- v.ir_to_mesa_emit_op0(NULL, OPCODE_END);
-
- /* Now emit bodies for any functions that were used. */
- do {
- progress = GL_FALSE;
-
- foreach_iter(exec_list_iterator, iter, v.function_signatures) {
- function_entry *entry = (function_entry *)iter.get();
-
- if (!entry->bgn_inst) {
- v.current_function = entry;
-
- entry->bgn_inst = v.ir_to_mesa_emit_op0(NULL, OPCODE_BGNSUB);
- entry->bgn_inst->function = entry;
-
- visit_exec_list(&entry->sig->body, &v);
-
- ir_to_mesa_instruction *last;
- last = (ir_to_mesa_instruction *)v.instructions.get_tail();
- if (last->op != OPCODE_RET)
- v.ir_to_mesa_emit_op0(NULL, OPCODE_RET);
-
- ir_to_mesa_instruction *end;
- end = v.ir_to_mesa_emit_op0(NULL, OPCODE_ENDSUB);
- end->function = entry;
-
- progress = GL_TRUE;
- }
- }
- } while (progress);
-
- prog->NumTemporaries = v.next_temp;
-
- int num_instructions = 0;
- foreach_iter(exec_list_iterator, iter, v.instructions) {
- num_instructions++;
- }
-
- mesa_instructions =
- (struct prog_instruction *)calloc(num_instructions,
- sizeof(*mesa_instructions));
- mesa_instruction_annotation = talloc_array(v.mem_ctx, ir_instruction *,
- num_instructions);
-
- v.copy_propagate();
-
- /* Convert ir_mesa_instructions into prog_instructions.
- */
- mesa_inst = mesa_instructions;
- i = 0;
- foreach_iter(exec_list_iterator, iter, v.instructions) {
- const ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
-
- mesa_inst->Opcode = inst->op;
- mesa_inst->CondUpdate = inst->cond_update;
- if (inst->saturate)
- mesa_inst->SaturateMode = SATURATE_ZERO_ONE;
- mesa_inst->DstReg.File = inst->dst_reg.file;
- mesa_inst->DstReg.Index = inst->dst_reg.index;
- mesa_inst->DstReg.CondMask = inst->dst_reg.cond_mask;
- mesa_inst->DstReg.WriteMask = inst->dst_reg.writemask;
- mesa_inst->DstReg.RelAddr = inst->dst_reg.reladdr != NULL;
- mesa_inst->SrcReg[0] = mesa_src_reg_from_ir_src_reg(inst->src_reg[0]);
- mesa_inst->SrcReg[1] = mesa_src_reg_from_ir_src_reg(inst->src_reg[1]);
- mesa_inst->SrcReg[2] = mesa_src_reg_from_ir_src_reg(inst->src_reg[2]);
- mesa_inst->TexSrcUnit = inst->sampler;
- mesa_inst->TexSrcTarget = inst->tex_target;
- mesa_inst->TexShadow = inst->tex_shadow;
- mesa_instruction_annotation[i] = inst->ir;
-
- /* Set IndirectRegisterFiles. */
- if (mesa_inst->DstReg.RelAddr)
- prog->IndirectRegisterFiles |= 1 << mesa_inst->DstReg.File;
-
- /* Update program's bitmask of indirectly accessed register files */
- for (unsigned src = 0; src < 3; src++)
- if (mesa_inst->SrcReg[src].RelAddr)
- prog->IndirectRegisterFiles |= 1 << mesa_inst->SrcReg[src].File;
-
- if (options->EmitNoIfs && mesa_inst->Opcode == OPCODE_IF) {
- fail_link(shader_program, "Couldn't flatten if statement\n");
- }
-
- switch (mesa_inst->Opcode) {
- case OPCODE_BGNSUB:
- inst->function->inst = i;
- mesa_inst->Comment = strdup(inst->function->sig->function_name());
- break;
- case OPCODE_ENDSUB:
- mesa_inst->Comment = strdup(inst->function->sig->function_name());
- break;
- case OPCODE_CAL:
- mesa_inst->BranchTarget = inst->function->sig_id; /* rewritten later */
- break;
- case OPCODE_ARL:
- prog->NumAddressRegs = 1;
- break;
- default:
- break;
- }
-
- mesa_inst++;
- i++;
-
- if (!shader_program->LinkStatus)
- break;
- }
-
- if (!shader_program->LinkStatus) {
- free(mesa_instructions);
- _mesa_reference_program(ctx, &shader->Program, NULL);
- return NULL;
- }
-
- set_branchtargets(&v, mesa_instructions, num_instructions);
-
- if (ctx->Shader.Flags & GLSL_DUMP) {
- printf("\n");
- printf("GLSL IR for linked %s program %d:\n", target_string,
- shader_program->Name);
- _mesa_print_ir(shader->ir, NULL);
- printf("\n");
- printf("\n");
- printf("Mesa IR for linked %s program %d:\n", target_string,
- shader_program->Name);
- print_program(mesa_instructions, mesa_instruction_annotation,
- num_instructions);
- }
-
- prog->Instructions = mesa_instructions;
- prog->NumInstructions = num_instructions;
-
- do_set_program_inouts(shader->ir, prog);
- count_resources(prog);
-
- _mesa_reference_program(ctx, &shader->Program, prog);
-
- if ((ctx->Shader.Flags & GLSL_NO_OPT) == 0) {
- _mesa_optimize_program(ctx, prog);
- }
-
- return prog;
-}
-
-extern "C" {
-
-/**
- * Called via ctx->Driver.CompilerShader().
- * This is a no-op.
- * XXX can we remove the ctx->Driver.CompileShader() hook?
- */
-GLboolean
-_mesa_ir_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
-{
- assert(shader->CompileStatus);
- (void) ctx;
-
- return GL_TRUE;
-}
-
-
-/**
- * Link a shader.
- * Called via ctx->Driver.LinkShader()
- * This actually involves converting GLSL IR into Mesa gl_programs with
- * code lowering and other optimizations.
- */
-GLboolean
-_mesa_ir_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
-{
- assert(prog->LinkStatus);
-
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- bool progress;
- exec_list *ir = prog->_LinkedShaders[i]->ir;
- const struct gl_shader_compiler_options *options =
- &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(prog->_LinkedShaders[i]->Type)];
-
- do {
- progress = false;
-
- /* Lowering */
- do_mat_op_to_vec(ir);
- lower_instructions(ir, (MOD_TO_FRACT | DIV_TO_MUL_RCP | EXP_TO_EXP2
- | LOG_TO_LOG2
- | ((options->EmitNoPow) ? POW_TO_EXP2 : 0)));
-
- progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
-
- progress = do_common_optimization(ir, true, options->MaxUnrollIterations) || progress;
-
- progress = lower_quadop_vector(ir, true) || progress;
-
- if (options->EmitNoIfs) {
- progress = lower_discard(ir) || progress;
- progress = lower_if_to_cond_assign(ir) || progress;
- }
-
- if (options->EmitNoNoise)
- progress = lower_noise(ir) || progress;
-
- /* If there are forms of indirect addressing that the driver
- * cannot handle, perform the lowering pass.
- */
- if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput
- || options->EmitNoIndirectTemp || options->EmitNoIndirectUniform)
- progress =
- lower_variable_index_to_cond_assign(ir,
- options->EmitNoIndirectInput,
- options->EmitNoIndirectOutput,
- options->EmitNoIndirectTemp,
- options->EmitNoIndirectUniform)
- || progress;
-
- progress = do_vec_index_to_cond_assign(ir) || progress;
- } while (progress);
-
- validate_ir_tree(ir);
- }
-
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
- struct gl_program *linked_prog;
-
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
-
- if (linked_prog) {
- bool ok = true;
-
- switch (prog->_LinkedShaders[i]->Type) {
- case GL_VERTEX_SHADER:
- _mesa_reference_vertprog(ctx, &prog->VertexProgram,
- (struct gl_vertex_program *)linked_prog);
- ok = ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
- linked_prog);
- break;
- case GL_FRAGMENT_SHADER:
- _mesa_reference_fragprog(ctx, &prog->FragmentProgram,
- (struct gl_fragment_program *)linked_prog);
- ok = ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
- linked_prog);
- break;
- case GL_GEOMETRY_SHADER:
- _mesa_reference_geomprog(ctx, &prog->GeometryProgram,
- (struct gl_geometry_program *)linked_prog);
- ok = ctx->Driver.ProgramStringNotify(ctx, GL_GEOMETRY_PROGRAM_NV,
- linked_prog);
- break;
- }
- if (!ok) {
- return GL_FALSE;
- }
- }
-
- _mesa_reference_program(ctx, &linked_prog, NULL);
- }
-
- return GL_TRUE;
-}
-
-
-/**
- * Compile a GLSL shader. Called via glCompileShader().
- */
-void
-_mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
-{
- struct _mesa_glsl_parse_state *state =
- new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
-
- const char *source = shader->Source;
- /* Check if the user called glCompileShader without first calling
- * glShaderSource. This should fail to compile, but not raise a GL_ERROR.
- */
- if (source == NULL) {
- shader->CompileStatus = GL_FALSE;
- return;
- }
-
- state->error = preprocess(state, &source, &state->info_log,
- &ctx->Extensions, ctx->API);
-
- if (ctx->Shader.Flags & GLSL_DUMP) {
- printf("GLSL source for shader %d:\n", shader->Name);
- printf("%s\n", shader->Source);
- }
-
- if (!state->error) {
- _mesa_glsl_lexer_ctor(state, source);
- _mesa_glsl_parse(state);
- _mesa_glsl_lexer_dtor(state);
- }
-
- talloc_free(shader->ir);
- shader->ir = new(shader) exec_list;
- if (!state->error && !state->translation_unit.is_empty())
- _mesa_ast_to_hir(shader->ir, state);
-
- if (!state->error && !shader->ir->is_empty()) {
- validate_ir_tree(shader->ir);
-
- /* Do some optimization at compile time to reduce shader IR size
- * and reduce later work if the same shader is linked multiple times
- */
- while (do_common_optimization(shader->ir, false, 32))
- ;
-
- validate_ir_tree(shader->ir);
- }
-
- shader->symbols = state->symbols;
-
- shader->CompileStatus = !state->error;
- shader->InfoLog = state->info_log;
- shader->Version = state->language_version;
- memcpy(shader->builtins_to_link, state->builtins_to_link,
- sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
- shader->num_builtins_to_link = state->num_builtins_to_link;
-
- if (ctx->Shader.Flags & GLSL_LOG) {
- _mesa_write_shader_to_file(shader);
- }
-
- if (ctx->Shader.Flags & GLSL_DUMP) {
- if (shader->CompileStatus) {
- printf("GLSL IR for shader %d:\n", shader->Name);
- _mesa_print_ir(shader->ir, NULL);
- printf("\n\n");
- } else {
- printf("GLSL shader %d failed to compile.\n", shader->Name);
- }
- if (shader->InfoLog && shader->InfoLog[0] != 0) {
- printf("GLSL shader %d info log:\n", shader->Name);
- printf("%s\n", shader->InfoLog);
- }
- }
-
- /* Retain any live IR, but trash the rest. */
- reparent_ir(shader->ir, shader->ir);
-
- talloc_free(state);
-
- if (shader->CompileStatus) {
- if (!ctx->Driver.CompileShader(ctx, shader))
- shader->CompileStatus = GL_FALSE;
- }
-}
-
-
-/**
- * Link a GLSL shader program. Called via glLinkProgram().
- */
-void
-_mesa_glsl_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
-{
- unsigned int i;
-
- _mesa_clear_shader_program_data(ctx, prog);
-
- prog->LinkStatus = GL_TRUE;
-
- for (i = 0; i < prog->NumShaders; i++) {
- if (!prog->Shaders[i]->CompileStatus) {
- fail_link(prog, "linking with uncompiled shader");
- prog->LinkStatus = GL_FALSE;
- }
- }
-
- prog->Varying = _mesa_new_parameter_list();
- _mesa_reference_vertprog(ctx, &prog->VertexProgram, NULL);
- _mesa_reference_fragprog(ctx, &prog->FragmentProgram, NULL);
- _mesa_reference_geomprog(ctx, &prog->GeometryProgram, NULL);
-
- if (prog->LinkStatus) {
- link_shaders(ctx, prog);
- }
-
- if (prog->LinkStatus) {
- if (!ctx->Driver.LinkShader(ctx, prog)) {
- prog->LinkStatus = GL_FALSE;
- }
- }
-
- set_uniform_initializers(ctx, prog);
-
- if (ctx->Shader.Flags & GLSL_DUMP) {
- if (!prog->LinkStatus) {
- printf("GLSL shader program %d failed to link\n", prog->Name);
- }
-
- if (prog->InfoLog && prog->InfoLog[0] != 0) {
- printf("GLSL shader program %d info log:\n", prog->Name);
- printf("%s\n", prog->InfoLog);
- }
- }
-}
-
-} /* extern "C" */
+/*
+ * Copyright (C) 2005-2007 Brian Paul All Rights Reserved.
+ * Copyright (C) 2008 VMware, Inc. All Rights Reserved.
+ * Copyright © 2010 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+/**
+ * \file ir_to_mesa.cpp
+ *
+ * Translate GLSL IR to Mesa's gl_program representation.
+ */
+
+#include <stdio.h>
+#include "main/compiler.h"
+#include "ir.h"
+#include "ir_visitor.h"
+#include "ir_print_visitor.h"
+#include "ir_expression_flattening.h"
+#include "glsl_types.h"
+#include "glsl_parser_extras.h"
+#include "../glsl/program.h"
+#include "ir_optimization.h"
+#include "ast.h"
+
+extern "C" {
+#include "main/mtypes.h"
+#include "main/shaderapi.h"
+#include "main/shaderobj.h"
+#include "main/uniforms.h"
+#include "program/hash_table.h"
+#include "program/prog_instruction.h"
+#include "program/prog_optimize.h"
+#include "program/prog_print.h"
+#include "program/program.h"
+#include "program/prog_uniform.h"
+#include "program/prog_parameter.h"
+#include "program/sampler.h"
+}
+
+static int swizzle_for_size(int size);
+
+/**
+ * This struct is a corresponding struct to Mesa prog_src_register, with
+ * wider fields.
+ */
+typedef struct ir_to_mesa_src_reg {
+ ir_to_mesa_src_reg(int file, int index, const glsl_type *type)
+ {
+ this->file = (gl_register_file) file;
+ this->index = index;
+ if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
+ this->swizzle = swizzle_for_size(type->vector_elements);
+ else
+ this->swizzle = SWIZZLE_XYZW;
+ this->negate = 0;
+ this->reladdr = NULL;
+ }
+
+ ir_to_mesa_src_reg()
+ {
+ this->file = PROGRAM_UNDEFINED;
+ this->index = 0;
+ this->swizzle = 0;
+ this->negate = 0;
+ this->reladdr = NULL;
+ }
+
+ gl_register_file file; /**< PROGRAM_* from Mesa */
+ int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
+ GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
+ int negate; /**< NEGATE_XYZW mask from mesa */
+ /** Register index should be offset by the integer in this reg. */
+ ir_to_mesa_src_reg *reladdr;
+} ir_to_mesa_src_reg;
+
+typedef struct ir_to_mesa_dst_reg {
+ int file; /**< PROGRAM_* from Mesa */
+ int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
+ int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
+ GLuint cond_mask:4;
+ /** Register index should be offset by the integer in this reg. */
+ ir_to_mesa_src_reg *reladdr;
+} ir_to_mesa_dst_reg;
+
+extern ir_to_mesa_src_reg ir_to_mesa_undef;
+
+class ir_to_mesa_instruction : public exec_node {
+public:
+ /* Callers of this talloc-based new need not call delete. It's
+ * easier to just talloc_free 'ctx' (or any of its ancestors). */
+ static void* operator new(size_t size, void *ctx)
+ {
+ void *node;
+
+ node = talloc_zero_size(ctx, size);
+ assert(node != NULL);
+
+ return node;
+ }
+
+ enum prog_opcode op;
+ ir_to_mesa_dst_reg dst_reg;
+ ir_to_mesa_src_reg src_reg[3];
+ /** Pointer to the ir source this tree came from for debugging */
+ ir_instruction *ir;
+ GLboolean cond_update;
+ bool saturate;
+ int sampler; /**< sampler index */
+ int tex_target; /**< One of TEXTURE_*_INDEX */
+ GLboolean tex_shadow;
+
+ class function_entry *function; /* Set on OPCODE_CAL or OPCODE_BGNSUB */
+};
+
+class variable_storage : public exec_node {
+public:
+ variable_storage(ir_variable *var, gl_register_file file, int index)
+ : file(file), index(index), var(var)
+ {
+ /* empty */
+ }
+
+ gl_register_file file;
+ int index;
+ ir_variable *var; /* variable that maps to this, if any */
+};
+
+class function_entry : public exec_node {
+public:
+ ir_function_signature *sig;
+
+ /**
+ * identifier of this function signature used by the program.
+ *
+ * At the point that Mesa instructions for function calls are
+ * generated, we don't know the address of the first instruction of
+ * the function body. So we make the BranchTarget that is called a
+ * small integer and rewrite them during set_branchtargets().
+ */
+ int sig_id;
+
+ /**
+ * Pointer to first instruction of the function body.
+ *
+ * Set during function body emits after main() is processed.
+ */
+ ir_to_mesa_instruction *bgn_inst;
+
+ /**
+ * Index of the first instruction of the function body in actual
+ * Mesa IR.
+ *
+ * Set after convertion from ir_to_mesa_instruction to prog_instruction.
+ */
+ int inst;
+
+ /** Storage for the return value. */
+ ir_to_mesa_src_reg return_reg;
+};
+
+class ir_to_mesa_visitor : public ir_visitor {
+public:
+ ir_to_mesa_visitor();
+ ~ir_to_mesa_visitor();
+
+ function_entry *current_function;
+
+ struct gl_context *ctx;
+ struct gl_program *prog;
+ struct gl_shader_program *shader_program;
+ struct gl_shader_compiler_options *options;
+
+ int next_temp;
+
+ variable_storage *find_variable_storage(ir_variable *var);
+
+ function_entry *get_function_signature(ir_function_signature *sig);
+
+ ir_to_mesa_src_reg get_temp(const glsl_type *type);
+ void reladdr_to_temp(ir_instruction *ir,
+ ir_to_mesa_src_reg *reg, int *num_reladdr);
+
+ struct ir_to_mesa_src_reg src_reg_for_float(float val);
+
+ /**
+ * \name Visit methods
+ *
+ * As typical for the visitor pattern, there must be one \c visit method for
+ * each concrete subclass of \c ir_instruction. Virtual base classes within
+ * the hierarchy should not have \c visit methods.
+ */
+ /*@{*/
+ virtual void visit(ir_variable *);
+ virtual void visit(ir_loop *);
+ virtual void visit(ir_loop_jump *);
+ virtual void visit(ir_function_signature *);
+ virtual void visit(ir_function *);
+ virtual void visit(ir_expression *);
+ virtual void visit(ir_swizzle *);
+ virtual void visit(ir_dereference_variable *);
+ virtual void visit(ir_dereference_array *);
+ virtual void visit(ir_dereference_record *);
+ virtual void visit(ir_assignment *);
+ virtual void visit(ir_constant *);
+ virtual void visit(ir_call *);
+ virtual void visit(ir_return *);
+ virtual void visit(ir_discard *);
+ virtual void visit(ir_texture *);
+ virtual void visit(ir_if *);
+ /*@}*/
+
+ struct ir_to_mesa_src_reg result;
+
+ /** List of variable_storage */
+ exec_list variables;
+
+ /** List of function_entry */
+ exec_list function_signatures;
+ int next_signature_id;
+
+ /** List of ir_to_mesa_instruction */
+ exec_list instructions;
+
+ ir_to_mesa_instruction *ir_to_mesa_emit_op0(ir_instruction *ir,
+ enum prog_opcode op);
+
+ ir_to_mesa_instruction *ir_to_mesa_emit_op1(ir_instruction *ir,
+ enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0);
+
+ ir_to_mesa_instruction *ir_to_mesa_emit_op2(ir_instruction *ir,
+ enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0,
+ ir_to_mesa_src_reg src1);
+
+ ir_to_mesa_instruction *ir_to_mesa_emit_op3(ir_instruction *ir,
+ enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0,
+ ir_to_mesa_src_reg src1,
+ ir_to_mesa_src_reg src2);
+
+ /**
+ * Emit the correct dot-product instruction for the type of arguments
+ *
+ * \sa ir_to_mesa_emit_op2
+ */
+ void ir_to_mesa_emit_dp(ir_instruction *ir,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0,
+ ir_to_mesa_src_reg src1,
+ unsigned elements);
+
+ void ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
+ enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0);
+
+ void ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
+ enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0,
+ ir_to_mesa_src_reg src1);
+
+ void emit_scs(ir_instruction *ir, enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ const ir_to_mesa_src_reg &src);
+
+ GLboolean try_emit_mad(ir_expression *ir,
+ int mul_operand);
+ GLboolean try_emit_sat(ir_expression *ir);
+
+ void emit_swz(ir_expression *ir);
+
+ bool process_move_condition(ir_rvalue *ir);
+
+ void copy_propagate(void);
+
+ void *mem_ctx;
+};
+
+ir_to_mesa_src_reg ir_to_mesa_undef = ir_to_mesa_src_reg(PROGRAM_UNDEFINED, 0, NULL);
+
+ir_to_mesa_dst_reg ir_to_mesa_undef_dst = {
+ PROGRAM_UNDEFINED, 0, SWIZZLE_NOOP, COND_TR, NULL,
+};
+
+ir_to_mesa_dst_reg ir_to_mesa_address_reg = {
+ PROGRAM_ADDRESS, 0, WRITEMASK_X, COND_TR, NULL
+};
+
+static void
+fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
+
+static void
+fail_link(struct gl_shader_program *prog, const char *fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, args);
+ va_end(args);
+
+ prog->LinkStatus = GL_FALSE;
+}
+
+static int
+swizzle_for_size(int size)
+{
+ int size_swizzles[4] = {
+ MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
+ MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
+ MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
+ MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
+ };
+
+ assert((size >= 1) && (size <= 4));
+ return size_swizzles[size - 1];
+}
+
+ir_to_mesa_instruction *
+ir_to_mesa_visitor::ir_to_mesa_emit_op3(ir_instruction *ir,
+ enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0,
+ ir_to_mesa_src_reg src1,
+ ir_to_mesa_src_reg src2)
+{
+ ir_to_mesa_instruction *inst = new(mem_ctx) ir_to_mesa_instruction();
+ int num_reladdr = 0;
+
+ /* If we have to do relative addressing, we want to load the ARL
+ * reg directly for one of the regs, and preload the other reladdr
+ * sources into temps.
+ */
+ num_reladdr += dst.reladdr != NULL;
+ num_reladdr += src0.reladdr != NULL;
+ num_reladdr += src1.reladdr != NULL;
+ num_reladdr += src2.reladdr != NULL;
+
+ reladdr_to_temp(ir, &src2, &num_reladdr);
+ reladdr_to_temp(ir, &src1, &num_reladdr);
+ reladdr_to_temp(ir, &src0, &num_reladdr);
+
+ if (dst.reladdr) {
+ ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg,
+ *dst.reladdr);
+
+ num_reladdr--;
+ }
+ assert(num_reladdr == 0);
+
+ inst->op = op;
+ inst->dst_reg = dst;
+ inst->src_reg[0] = src0;
+ inst->src_reg[1] = src1;
+ inst->src_reg[2] = src2;
+ inst->ir = ir;
+
+ inst->function = NULL;
+
+ this->instructions.push_tail(inst);
+
+ return inst;
+}
+
+
+ir_to_mesa_instruction *
+ir_to_mesa_visitor::ir_to_mesa_emit_op2(ir_instruction *ir,
+ enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0,
+ ir_to_mesa_src_reg src1)
+{
+ return ir_to_mesa_emit_op3(ir, op, dst, src0, src1, ir_to_mesa_undef);
+}
+
+ir_to_mesa_instruction *
+ir_to_mesa_visitor::ir_to_mesa_emit_op1(ir_instruction *ir,
+ enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0)
+{
+ assert(dst.writemask != 0);
+ return ir_to_mesa_emit_op3(ir, op, dst,
+ src0, ir_to_mesa_undef, ir_to_mesa_undef);
+}
+
+ir_to_mesa_instruction *
+ir_to_mesa_visitor::ir_to_mesa_emit_op0(ir_instruction *ir,
+ enum prog_opcode op)
+{
+ return ir_to_mesa_emit_op3(ir, op, ir_to_mesa_undef_dst,
+ ir_to_mesa_undef,
+ ir_to_mesa_undef,
+ ir_to_mesa_undef);
+}
+
+void
+ir_to_mesa_visitor::ir_to_mesa_emit_dp(ir_instruction *ir,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0,
+ ir_to_mesa_src_reg src1,
+ unsigned elements)
+{
+ static const gl_inst_opcode dot_opcodes[] = {
+ OPCODE_DP2, OPCODE_DP3, OPCODE_DP4
+ };
+
+ ir_to_mesa_emit_op3(ir, dot_opcodes[elements - 2],
+ dst, src0, src1, ir_to_mesa_undef);
+}
+
+inline ir_to_mesa_dst_reg
+ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg reg)
+{
+ ir_to_mesa_dst_reg dst_reg;
+
+ dst_reg.file = reg.file;
+ dst_reg.index = reg.index;
+ dst_reg.writemask = WRITEMASK_XYZW;
+ dst_reg.cond_mask = COND_TR;
+ dst_reg.reladdr = reg.reladdr;
+
+ return dst_reg;
+}
+
+inline ir_to_mesa_src_reg
+ir_to_mesa_src_reg_from_dst(ir_to_mesa_dst_reg reg)
+{
+ return ir_to_mesa_src_reg(reg.file, reg.index, NULL);
+}
+
+/**
+ * Emits Mesa scalar opcodes to produce unique answers across channels.
+ *
+ * Some Mesa opcodes are scalar-only, like ARB_fp/vp. The src X
+ * channel determines the result across all channels. So to do a vec4
+ * of this operation, we want to emit a scalar per source channel used
+ * to produce dest channels.
+ */
+void
+ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
+ enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg orig_src0,
+ ir_to_mesa_src_reg orig_src1)
+{
+ int i, j;
+ int done_mask = ~dst.writemask;
+
+ /* Mesa RCP is a scalar operation splatting results to all channels,
+ * like ARB_fp/vp. So emit as many RCPs as necessary to cover our
+ * dst channels.
+ */
+ for (i = 0; i < 4; i++) {
+ GLuint this_mask = (1 << i);
+ ir_to_mesa_instruction *inst;
+ ir_to_mesa_src_reg src0 = orig_src0;
+ ir_to_mesa_src_reg src1 = orig_src1;
+
+ if (done_mask & this_mask)
+ continue;
+
+ GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
+ GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
+ for (j = i + 1; j < 4; j++) {
+ /* If there is another enabled component in the destination that is
+ * derived from the same inputs, generate its value on this pass as
+ * well.
+ */
+ if (!(done_mask & (1 << j)) &&
+ GET_SWZ(src0.swizzle, j) == src0_swiz &&
+ GET_SWZ(src1.swizzle, j) == src1_swiz) {
+ this_mask |= (1 << j);
+ }
+ }
+ src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
+ src0_swiz, src0_swiz);
+ src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
+ src1_swiz, src1_swiz);
+
+ inst = ir_to_mesa_emit_op2(ir, op,
+ dst,
+ src0,
+ src1);
+ inst->dst_reg.writemask = this_mask;
+ done_mask |= this_mask;
+ }
+}
+
+void
+ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
+ enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ ir_to_mesa_src_reg src0)
+{
+ ir_to_mesa_src_reg undef = ir_to_mesa_undef;
+
+ undef.swizzle = SWIZZLE_XXXX;
+
+ ir_to_mesa_emit_scalar_op2(ir, op, dst, src0, undef);
+}
+
+/**
+ * Emit an OPCODE_SCS instruction
+ *
+ * The \c SCS opcode functions a bit differently than the other Mesa (or
+ * ARB_fragment_program) opcodes. Instead of splatting its result across all
+ * four components of the destination, it writes one value to the \c x
+ * component and another value to the \c y component.
+ *
+ * \param ir IR instruction being processed
+ * \param op Either \c OPCODE_SIN or \c OPCODE_COS depending on which
+ * value is desired.
+ * \param dst Destination register
+ * \param src Source register
+ */
+void
+ir_to_mesa_visitor::emit_scs(ir_instruction *ir, enum prog_opcode op,
+ ir_to_mesa_dst_reg dst,
+ const ir_to_mesa_src_reg &src)
+{
+ /* Vertex programs cannot use the SCS opcode.
+ */
+ if (this->prog->Target == GL_VERTEX_PROGRAM_ARB) {
+ ir_to_mesa_emit_scalar_op1(ir, op, dst, src);
+ return;
+ }
+
+ const unsigned component = (op == OPCODE_SIN) ? 0 : 1;
+ const unsigned scs_mask = (1U << component);
+ int done_mask = ~dst.writemask;
+ ir_to_mesa_src_reg tmp;
+
+ assert(op == OPCODE_SIN || op == OPCODE_COS);
+
+ /* If there are compnents in the destination that differ from the component
+ * that will be written by the SCS instrution, we'll need a temporary.
+ */
+ if (scs_mask != unsigned(dst.writemask)) {
+ tmp = get_temp(glsl_type::vec4_type);
+ }
+
+ for (unsigned i = 0; i < 4; i++) {
+ unsigned this_mask = (1U << i);
+ ir_to_mesa_src_reg src0 = src;
+
+ if ((done_mask & this_mask) != 0)
+ continue;
+
+ /* The source swizzle specified which component of the source generates
+ * sine / cosine for the current component in the destination. The SCS
+ * instruction requires that this value be swizzle to the X component.
+ * Replace the current swizzle with a swizzle that puts the source in
+ * the X component.
+ */
+ unsigned src0_swiz = GET_SWZ(src.swizzle, i);
+
+ src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
+ src0_swiz, src0_swiz);
+ for (unsigned j = i + 1; j < 4; j++) {
+ /* If there is another enabled component in the destination that is
+ * derived from the same inputs, generate its value on this pass as
+ * well.
+ */
+ if (!(done_mask & (1 << j)) &&
+ GET_SWZ(src0.swizzle, j) == src0_swiz) {
+ this_mask |= (1 << j);
+ }
+ }
+
+ if (this_mask != scs_mask) {
+ ir_to_mesa_instruction *inst;
+ ir_to_mesa_dst_reg tmp_dst = ir_to_mesa_dst_reg_from_src(tmp);
+
+ /* Emit the SCS instruction.
+ */
+ inst = ir_to_mesa_emit_op1(ir, OPCODE_SCS, tmp_dst, src0);
+ inst->dst_reg.writemask = scs_mask;
+
+ /* Move the result of the SCS instruction to the desired location in
+ * the destination.
+ */
+ tmp.swizzle = MAKE_SWIZZLE4(component, component,
+ component, component);
+ inst = ir_to_mesa_emit_op1(ir, OPCODE_SCS, dst, tmp);
+ inst->dst_reg.writemask = this_mask;
+ } else {
+ /* Emit the SCS instruction to write directly to the destination.
+ */
+ ir_to_mesa_instruction *inst =
+ ir_to_mesa_emit_op1(ir, OPCODE_SCS, dst, src0);
+ inst->dst_reg.writemask = scs_mask;
+ }
+
+ done_mask |= this_mask;
+ }
+}
+
+struct ir_to_mesa_src_reg
+ir_to_mesa_visitor::src_reg_for_float(float val)
+{
+ ir_to_mesa_src_reg src_reg(PROGRAM_CONSTANT, -1, NULL);
+
+ src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
+ &val, 1, &src_reg.swizzle);
+
+ return src_reg;
+}
+
+static int
+type_size(const struct glsl_type *type)
+{
+ unsigned int i;
+ int size;
+
+ switch (type->base_type) {
+ case GLSL_TYPE_UINT:
+ case GLSL_TYPE_INT:
+ case GLSL_TYPE_FLOAT:
+ case GLSL_TYPE_BOOL:
+ if (type->is_matrix()) {
+ return type->matrix_columns;
+ } else {
+ /* Regardless of size of vector, it gets a vec4. This is bad
+ * packing for things like floats, but otherwise arrays become a
+ * mess. Hopefully a later pass over the code can pack scalars
+ * down if appropriate.
+ */
+ return 1;
+ }
+ case GLSL_TYPE_ARRAY:
+ assert(type->length > 0);
+ return type_size(type->fields.array) * type->length;
+ case GLSL_TYPE_STRUCT:
+ size = 0;
+ for (i = 0; i < type->length; i++) {
+ size += type_size(type->fields.structure[i].type);
+ }
+ return size;
+ case GLSL_TYPE_SAMPLER:
+ /* Samplers take up one slot in UNIFORMS[], but they're baked in
+ * at link time.
+ */
+ return 1;
+ default:
+ assert(0);
+ return 0;
+ }
+}
+
+/**
+ * In the initial pass of codegen, we assign temporary numbers to
+ * intermediate results. (not SSA -- variable assignments will reuse
+ * storage). Actual register allocation for the Mesa VM occurs in a
+ * pass over the Mesa IR later.
+ */
+ir_to_mesa_src_reg
+ir_to_mesa_visitor::get_temp(const glsl_type *type)
+{
+ ir_to_mesa_src_reg src_reg;
+ int swizzle[4];
+ int i;
+
+ src_reg.file = PROGRAM_TEMPORARY;
+ src_reg.index = next_temp;
+ src_reg.reladdr = NULL;
+ next_temp += type_size(type);
+
+ if (type->is_array() || type->is_record()) {
+ src_reg.swizzle = SWIZZLE_NOOP;
+ } else {
+ for (i = 0; i < type->vector_elements; i++)
+ swizzle[i] = i;
+ for (; i < 4; i++)
+ swizzle[i] = type->vector_elements - 1;
+ src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1],
+ swizzle[2], swizzle[3]);
+ }
+ src_reg.negate = 0;
+
+ return src_reg;
+}
+
+variable_storage *
+ir_to_mesa_visitor::find_variable_storage(ir_variable *var)
+{
+
+ variable_storage *entry;
+
+ foreach_iter(exec_list_iterator, iter, this->variables) {
+ entry = (variable_storage *)iter.get();
+
+ if (entry->var == var)
+ return entry;
+ }
+
+ return NULL;
+}
+
+void
+ir_to_mesa_visitor::visit(ir_variable *ir)
+{
+ if (strcmp(ir->name, "gl_FragCoord") == 0) {
+ struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
+
+ fp->OriginUpperLeft = ir->origin_upper_left;
+ fp->PixelCenterInteger = ir->pixel_center_integer;
+ }
+
+ if (ir->mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
+ unsigned int i;
+ const struct gl_builtin_uniform_desc *statevar;
+
+ for (i = 0; _mesa_builtin_uniform_desc[i].name; i++) {
+ if (strcmp(ir->name, _mesa_builtin_uniform_desc[i].name) == 0)
+ break;
+ }
+
+ if (!_mesa_builtin_uniform_desc[i].name) {
+ fail_link(this->shader_program,
+ "Failed to find builtin uniform `%s'\n", ir->name);
+ return;
+ }
+
+ statevar = &_mesa_builtin_uniform_desc[i];
+
+ int array_count;
+ if (ir->type->is_array()) {
+ array_count = ir->type->length;
+ } else {
+ array_count = 1;
+ }
+
+ /* Check if this statevar's setup in the STATE file exactly
+ * matches how we'll want to reference it as a
+ * struct/array/whatever. If not, then we need to move it into
+ * temporary storage and hope that it'll get copy-propagated
+ * out.
+ */
+ for (i = 0; i < statevar->num_elements; i++) {
+ if (statevar->elements[i].swizzle != SWIZZLE_XYZW) {
+ break;
+ }
+ }
+
+ struct variable_storage *storage;
+ ir_to_mesa_dst_reg dst;
+ if (i == statevar->num_elements) {
+ /* We'll set the index later. */
+ storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
+ this->variables.push_tail(storage);
+
+ dst = ir_to_mesa_undef_dst;
+ } else {
+ storage = new(mem_ctx) variable_storage(ir, PROGRAM_TEMPORARY,
+ this->next_temp);
+ this->variables.push_tail(storage);
+ this->next_temp += type_size(ir->type);
+
+ dst = ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg(PROGRAM_TEMPORARY,
+ storage->index,
+ NULL));
+ }
+
+
+ for (int a = 0; a < array_count; a++) {
+ for (unsigned int i = 0; i < statevar->num_elements; i++) {
+ struct gl_builtin_uniform_element *element = &statevar->elements[i];
+ int tokens[STATE_LENGTH];
+
+ memcpy(tokens, element->tokens, sizeof(element->tokens));
+ if (ir->type->is_array()) {
+ tokens[1] = a;
+ }
+
+ int index = _mesa_add_state_reference(this->prog->Parameters,
+ (gl_state_index *)tokens);
+
+ if (storage->file == PROGRAM_STATE_VAR) {
+ if (storage->index == -1) {
+ storage->index = index;
+ } else {
+ assert(index ==
+ (int)(storage->index + a * statevar->num_elements + i));
+ }
+ } else {
+ ir_to_mesa_src_reg src(PROGRAM_STATE_VAR, index, NULL);
+ src.swizzle = element->swizzle;
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, dst, src);
+ /* even a float takes up a whole vec4 reg in a struct/array. */
+ dst.index++;
+ }
+ }
+ }
+ if (storage->file == PROGRAM_TEMPORARY &&
+ dst.index != storage->index + type_size(ir->type)) {
+ fail_link(this->shader_program,
+ "failed to load builtin uniform `%s' (%d/%d regs loaded)\n",
+ ir->name, dst.index - storage->index,
+ type_size(ir->type));
+ }
+ }
+}
+
+void
+ir_to_mesa_visitor::visit(ir_loop *ir)
+{
+ ir_dereference_variable *counter = NULL;
+
+ if (ir->counter != NULL)
+ counter = new(ir) ir_dereference_variable(ir->counter);
+
+ if (ir->from != NULL) {
+ assert(ir->counter != NULL);
+
+ ir_assignment *a = new(ir) ir_assignment(counter, ir->from, NULL);
+
+ a->accept(this);
+ delete a;
+ }
+
+ ir_to_mesa_emit_op0(NULL, OPCODE_BGNLOOP);
+
+ if (ir->to) {
+ ir_expression *e =
+ new(ir) ir_expression(ir->cmp, glsl_type::bool_type,
+ counter, ir->to);
+ ir_if *if_stmt = new(ir) ir_if(e);
+
+ ir_loop_jump *brk = new(ir) ir_loop_jump(ir_loop_jump::jump_break);
+
+ if_stmt->then_instructions.push_tail(brk);
+
+ if_stmt->accept(this);
+
+ delete if_stmt;
+ delete e;
+ delete brk;
+ }
+
+ visit_exec_list(&ir->body_instructions, this);
+
+ if (ir->increment) {
+ ir_expression *e =
+ new(ir) ir_expression(ir_binop_add, counter->type,
+ counter, ir->increment);
+
+ ir_assignment *a = new(ir) ir_assignment(counter, e, NULL);
+
+ a->accept(this);
+ delete a;
+ delete e;
+ }
+
+ ir_to_mesa_emit_op0(NULL, OPCODE_ENDLOOP);
+}
+
+void
+ir_to_mesa_visitor::visit(ir_loop_jump *ir)
+{
+ switch (ir->mode) {
+ case ir_loop_jump::jump_break:
+ ir_to_mesa_emit_op0(NULL, OPCODE_BRK);
+ break;
+ case ir_loop_jump::jump_continue:
+ ir_to_mesa_emit_op0(NULL, OPCODE_CONT);
+ break;
+ }
+}
+
+
+void
+ir_to_mesa_visitor::visit(ir_function_signature *ir)
+{
+ assert(0);
+ (void)ir;
+}
+
+void
+ir_to_mesa_visitor::visit(ir_function *ir)
+{
+ /* Ignore function bodies other than main() -- we shouldn't see calls to
+ * them since they should all be inlined before we get to ir_to_mesa.
+ */
+ if (strcmp(ir->name, "main") == 0) {
+ const ir_function_signature *sig;
+ exec_list empty;
+
+ sig = ir->matching_signature(&empty);
+
+ assert(sig);
+
+ foreach_iter(exec_list_iterator, iter, sig->body) {
+ ir_instruction *ir = (ir_instruction *)iter.get();
+
+ ir->accept(this);
+ }
+ }
+}
+
+GLboolean
+ir_to_mesa_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
+{
+ int nonmul_operand = 1 - mul_operand;
+ ir_to_mesa_src_reg a, b, c;
+
+ ir_expression *expr = ir->operands[mul_operand]->as_expression();
+ if (!expr || expr->operation != ir_binop_mul)
+ return false;
+
+ expr->operands[0]->accept(this);
+ a = this->result;
+ expr->operands[1]->accept(this);
+ b = this->result;
+ ir->operands[nonmul_operand]->accept(this);
+ c = this->result;
+
+ this->result = get_temp(ir->type);
+ ir_to_mesa_emit_op3(ir, OPCODE_MAD,
+ ir_to_mesa_dst_reg_from_src(this->result), a, b, c);
+
+ return true;
+}
+
+GLboolean
+ir_to_mesa_visitor::try_emit_sat(ir_expression *ir)
+{
+ /* Saturates were only introduced to vertex programs in
+ * NV_vertex_program3, so don't give them to drivers in the VP.
+ */
+ if (this->prog->Target == GL_VERTEX_PROGRAM_ARB)
+ return false;
+
+ ir_rvalue *sat_src = ir->as_rvalue_to_saturate();
+ if (!sat_src)
+ return false;
+
+ sat_src->accept(this);
+ ir_to_mesa_src_reg src = this->result;
+
+ this->result = get_temp(ir->type);
+ ir_to_mesa_instruction *inst;
+ inst = ir_to_mesa_emit_op1(ir, OPCODE_MOV,
+ ir_to_mesa_dst_reg_from_src(this->result),
+ src);
+ inst->saturate = true;
+
+ return true;
+}
+
+void
+ir_to_mesa_visitor::reladdr_to_temp(ir_instruction *ir,
+ ir_to_mesa_src_reg *reg, int *num_reladdr)
+{
+ if (!reg->reladdr)
+ return;
+
+ ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg, *reg->reladdr);
+
+ if (*num_reladdr != 1) {
+ ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
+
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV,
+ ir_to_mesa_dst_reg_from_src(temp), *reg);
+ *reg = temp;
+ }
+
+ (*num_reladdr)--;
+}
+
+void
+ir_to_mesa_visitor::emit_swz(ir_expression *ir)
+{
+ /* Assume that the vector operator is in a form compatible with OPCODE_SWZ.
+ * This means that each of the operands is either an immediate value of -1,
+ * 0, or 1, or is a component from one source register (possibly with
+ * negation).
+ */
+ uint8_t components[4] = { 0 };
+ bool negate[4] = { false };
+ ir_variable *var = NULL;
+
+ for (unsigned i = 0; i < ir->type->vector_elements; i++) {
+ ir_rvalue *op = ir->operands[i];
+
+ assert(op->type->is_scalar());
+
+ while (op != NULL) {
+ switch (op->ir_type) {
+ case ir_type_constant: {
+
+ assert(op->type->is_scalar());
+
+ const ir_constant *const c = op->as_constant();
+ if (c->is_one()) {
+ components[i] = SWIZZLE_ONE;
+ } else if (c->is_zero()) {
+ components[i] = SWIZZLE_ZERO;
+ } else if (c->is_negative_one()) {
+ components[i] = SWIZZLE_ONE;
+ negate[i] = true;
+ } else {
+ assert(!"SWZ constant must be 0.0 or 1.0.");
+ }
+
+ op = NULL;
+ break;
+ }
+
+ case ir_type_dereference_variable: {
+ ir_dereference_variable *const deref =
+ (ir_dereference_variable *) op;
+
+ assert((var == NULL) || (deref->var == var));
+ components[i] = SWIZZLE_X;
+ var = deref->var;
+ op = NULL;
+ break;
+ }
+
+ case ir_type_expression: {
+ ir_expression *const expr = (ir_expression *) op;
+
+ assert(expr->operation == ir_unop_neg);
+ negate[i] = true;
+
+ op = expr->operands[0];
+ break;
+ }
+
+ case ir_type_swizzle: {
+ ir_swizzle *const swiz = (ir_swizzle *) op;
+
+ components[i] = swiz->mask.x;
+ op = swiz->val;
+ break;
+ }
+
+ default:
+ assert(!"Should not get here.");
+ return;
+ }
+ }
+ }
+
+ assert(var != NULL);
+
+ ir_dereference_variable *const deref =
+ new(mem_ctx) ir_dereference_variable(var);
+
+ this->result.file = PROGRAM_UNDEFINED;
+ deref->accept(this);
+ if (this->result.file == PROGRAM_UNDEFINED) {
+ ir_print_visitor v;
+ printf("Failed to get tree for expression operand:\n");
+ deref->accept(&v);
+ exit(1);
+ }
+
+ ir_to_mesa_src_reg src;
+
+ src = this->result;
+ src.swizzle = MAKE_SWIZZLE4(components[0],
+ components[1],
+ components[2],
+ components[3]);
+ src.negate = ((unsigned(negate[0]) << 0)
+ | (unsigned(negate[1]) << 1)
+ | (unsigned(negate[2]) << 2)
+ | (unsigned(negate[3]) << 3));
+
+ /* Storage for our result. Ideally for an assignment we'd be using the
+ * actual storage for the result here, instead.
+ */
+ const ir_to_mesa_src_reg result_src = get_temp(ir->type);
+ ir_to_mesa_dst_reg result_dst = ir_to_mesa_dst_reg_from_src(result_src);
+
+ /* Limit writes to the channels that will be used by result_src later.
+ * This does limit this temp's use as a temporary for multi-instruction
+ * sequences.
+ */
+ result_dst.writemask = (1 << ir->type->vector_elements) - 1;
+
+ ir_to_mesa_emit_op1(ir, OPCODE_SWZ, result_dst, src);
+ this->result = result_src;
+}
+
+void
+ir_to_mesa_visitor::visit(ir_expression *ir)
+{
+ unsigned int operand;
+ struct ir_to_mesa_src_reg op[Elements(ir->operands)];
+ struct ir_to_mesa_src_reg result_src;
+ struct ir_to_mesa_dst_reg result_dst;
+
+ /* Quick peephole: Emit OPCODE_MAD(a, b, c) instead of ADD(MUL(a, b), c)
+ */
+ if (ir->operation == ir_binop_add) {
+ if (try_emit_mad(ir, 1))
+ return;
+ if (try_emit_mad(ir, 0))
+ return;
+ }
+ if (try_emit_sat(ir))
+ return;
+
+ if (ir->operation == ir_quadop_vector) {
+ this->emit_swz(ir);
+ return;
+ }
+
+ for (operand = 0; operand < ir->get_num_operands(); operand++) {
+ this->result.file = PROGRAM_UNDEFINED;
+ ir->operands[operand]->accept(this);
+ if (this->result.file == PROGRAM_UNDEFINED) {
+ ir_print_visitor v;
+ printf("Failed to get tree for expression operand:\n");
+ ir->operands[operand]->accept(&v);
+ exit(1);
+ }
+ op[operand] = this->result;
+
+ /* Matrix expression operands should have been broken down to vector
+ * operations already.
+ */
+ assert(!ir->operands[operand]->type->is_matrix());
+ }
+
+ int vector_elements = ir->operands[0]->type->vector_elements;
+ if (ir->operands[1]) {
+ vector_elements = MAX2(vector_elements,
+ ir->operands[1]->type->vector_elements);
+ }
+
+ this->result.file = PROGRAM_UNDEFINED;
+
+ /* Storage for our result. Ideally for an assignment we'd be using
+ * the actual storage for the result here, instead.
+ */
+ result_src = get_temp(ir->type);
+ /* convenience for the emit functions below. */
+ result_dst = ir_to_mesa_dst_reg_from_src(result_src);
+ /* Limit writes to the channels that will be used by result_src later.
+ * This does limit this temp's use as a temporary for multi-instruction
+ * sequences.
+ */
+ result_dst.writemask = (1 << ir->type->vector_elements) - 1;
+
+ switch (ir->operation) {
+ case ir_unop_logic_not:
+ ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst,
+ op[0], src_reg_for_float(0.0));
+ break;
+ case ir_unop_neg:
+ op[0].negate = ~op[0].negate;
+ result_src = op[0];
+ break;
+ case ir_unop_abs:
+ ir_to_mesa_emit_op1(ir, OPCODE_ABS, result_dst, op[0]);
+ break;
+ case ir_unop_sign:
+ ir_to_mesa_emit_op1(ir, OPCODE_SSG, result_dst, op[0]);
+ break;
+ case ir_unop_rcp:
+ ir_to_mesa_emit_scalar_op1(ir, OPCODE_RCP, result_dst, op[0]);
+ break;
+
+ case ir_unop_exp2:
+ ir_to_mesa_emit_scalar_op1(ir, OPCODE_EX2, result_dst, op[0]);
+ break;
+ case ir_unop_exp:
+ case ir_unop_log:
+ assert(!"not reached: should be handled by ir_explog_to_explog2");
+ break;
+ case ir_unop_log2:
+ ir_to_mesa_emit_scalar_op1(ir, OPCODE_LG2, result_dst, op[0]);
+ break;
+ case ir_unop_sin:
+ ir_to_mesa_emit_scalar_op1(ir, OPCODE_SIN, result_dst, op[0]);
+ break;
+ case ir_unop_cos:
+ ir_to_mesa_emit_scalar_op1(ir, OPCODE_COS, result_dst, op[0]);
+ break;
+ case ir_unop_sin_reduced:
+ emit_scs(ir, OPCODE_SIN, result_dst, op[0]);
+ break;
+ case ir_unop_cos_reduced:
+ emit_scs(ir, OPCODE_COS, result_dst, op[0]);
+ break;
+
+ case ir_unop_dFdx:
+ ir_to_mesa_emit_op1(ir, OPCODE_DDX, result_dst, op[0]);
+ break;
+ case ir_unop_dFdy:
+ ir_to_mesa_emit_op1(ir, OPCODE_DDY, result_dst, op[0]);
+ break;
+
+ case ir_unop_noise: {
+ const enum prog_opcode opcode =
+ prog_opcode(OPCODE_NOISE1
+ + (ir->operands[0]->type->vector_elements) - 1);
+ assert((opcode >= OPCODE_NOISE1) && (opcode <= OPCODE_NOISE4));
+
+ ir_to_mesa_emit_op1(ir, opcode, result_dst, op[0]);
+ break;
+ }
+
+ case ir_binop_add:
+ ir_to_mesa_emit_op2(ir, OPCODE_ADD, result_dst, op[0], op[1]);
+ break;
+ case ir_binop_sub:
+ ir_to_mesa_emit_op2(ir, OPCODE_SUB, result_dst, op[0], op[1]);
+ break;
+
+ case ir_binop_mul:
+ ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, op[0], op[1]);
+ break;
+ case ir_binop_div:
+ assert(!"not reached: should be handled by ir_div_to_mul_rcp");
+ case ir_binop_mod:
+ assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
+ break;
+
+ case ir_binop_less:
+ ir_to_mesa_emit_op2(ir, OPCODE_SLT, result_dst, op[0], op[1]);
+ break;
+ case ir_binop_greater:
+ ir_to_mesa_emit_op2(ir, OPCODE_SGT, result_dst, op[0], op[1]);
+ break;
+ case ir_binop_lequal:
+ ir_to_mesa_emit_op2(ir, OPCODE_SLE, result_dst, op[0], op[1]);
+ break;
+ case ir_binop_gequal:
+ ir_to_mesa_emit_op2(ir, OPCODE_SGE, result_dst, op[0], op[1]);
+ break;
+ case ir_binop_equal:
+ ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
+ break;
+ case ir_binop_nequal:
+ ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
+ break;
+ case ir_binop_all_equal:
+ /* "==" operator producing a scalar boolean. */
+ if (ir->operands[0]->type->is_vector() ||
+ ir->operands[1]->type->is_vector()) {
+ ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
+ ir_to_mesa_emit_op2(ir, OPCODE_SNE,
+ ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
+ ir_to_mesa_emit_dp(ir, result_dst, temp, temp, vector_elements);
+ ir_to_mesa_emit_op2(ir, OPCODE_SEQ,
+ result_dst, result_src, src_reg_for_float(0.0));
+ } else {
+ ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
+ }
+ break;
+ case ir_binop_any_nequal:
+ /* "!=" operator producing a scalar boolean. */
+ if (ir->operands[0]->type->is_vector() ||
+ ir->operands[1]->type->is_vector()) {
+ ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
+ ir_to_mesa_emit_op2(ir, OPCODE_SNE,
+ ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
+ ir_to_mesa_emit_dp(ir, result_dst, temp, temp, vector_elements);
+ ir_to_mesa_emit_op2(ir, OPCODE_SNE,
+ result_dst, result_src, src_reg_for_float(0.0));
+ } else {
+ ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
+ }
+ break;
+
+ case ir_unop_any:
+ assert(ir->operands[0]->type->is_vector());
+ ir_to_mesa_emit_dp(ir, result_dst, op[0], op[0],
+ ir->operands[0]->type->vector_elements);
+ ir_to_mesa_emit_op2(ir, OPCODE_SNE,
+ result_dst, result_src, src_reg_for_float(0.0));
+ break;
+
+ case ir_binop_logic_xor:
+ ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
+ break;
+
+ case ir_binop_logic_or:
+ /* This could be a saturated add and skip the SNE. */
+ ir_to_mesa_emit_op2(ir, OPCODE_ADD,
+ result_dst,
+ op[0], op[1]);
+
+ ir_to_mesa_emit_op2(ir, OPCODE_SNE,
+ result_dst,
+ result_src, src_reg_for_float(0.0));
+ break;
+
+ case ir_binop_logic_and:
+ /* the bool args are stored as float 0.0 or 1.0, so "mul" gives us "and". */
+ ir_to_mesa_emit_op2(ir, OPCODE_MUL,
+ result_dst,
+ op[0], op[1]);
+ break;
+
+ case ir_binop_dot:
+ assert(ir->operands[0]->type->is_vector());
+ assert(ir->operands[0]->type == ir->operands[1]->type);
+ ir_to_mesa_emit_dp(ir, result_dst, op[0], op[1],
+ ir->operands[0]->type->vector_elements);
+ break;
+
+ case ir_unop_sqrt:
+ /* sqrt(x) = x * rsq(x). */
+ ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
+ ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, result_src, op[0]);
+ /* For incoming channels <= 0, set the result to 0. */
+ op[0].negate = ~op[0].negate;
+ ir_to_mesa_emit_op3(ir, OPCODE_CMP, result_dst,
+ op[0], result_src, src_reg_for_float(0.0));
+ break;
+ case ir_unop_rsq:
+ ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
+ break;
+ case ir_unop_i2f:
+ case ir_unop_b2f:
+ case ir_unop_b2i:
+ /* Mesa IR lacks types, ints are stored as truncated floats. */
+ result_src = op[0];
+ break;
+ case ir_unop_f2i:
+ ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
+ break;
+ case ir_unop_f2b:
+ case ir_unop_i2b:
+ ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst,
+ op[0], src_reg_for_float(0.0));
+ break;
+ case ir_unop_trunc:
+ ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
+ break;
+ case ir_unop_ceil:
+ op[0].negate = ~op[0].negate;
+ ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
+ result_src.negate = ~result_src.negate;
+ break;
+ case ir_unop_floor:
+ ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
+ break;
+ case ir_unop_fract:
+ ir_to_mesa_emit_op1(ir, OPCODE_FRC, result_dst, op[0]);
+ break;
+
+ case ir_binop_min:
+ ir_to_mesa_emit_op2(ir, OPCODE_MIN, result_dst, op[0], op[1]);
+ break;
+ case ir_binop_max:
+ ir_to_mesa_emit_op2(ir, OPCODE_MAX, result_dst, op[0], op[1]);
+ break;
+ case ir_binop_pow:
+ ir_to_mesa_emit_scalar_op2(ir, OPCODE_POW, result_dst, op[0], op[1]);
+ break;
+
+ case ir_unop_bit_not:
+ case ir_unop_u2f:
+ case ir_binop_lshift:
+ case ir_binop_rshift:
+ case ir_binop_bit_and:
+ case ir_binop_bit_xor:
+ case ir_binop_bit_or:
+ case ir_unop_round_even:
+ assert(!"GLSL 1.30 features unsupported");
+ break;
+
+ case ir_quadop_vector:
+ /* This operation should have already been handled.
+ */
+ assert(!"Should not get here.");
+ break;
+ }
+
+ this->result = result_src;
+}
+
+
+void
+ir_to_mesa_visitor::visit(ir_swizzle *ir)
+{
+ ir_to_mesa_src_reg src_reg;
+ int i;
+ int swizzle[4];
+
+ /* Note that this is only swizzles in expressions, not those on the left
+ * hand side of an assignment, which do write masking. See ir_assignment
+ * for that.
+ */
+
+ ir->val->accept(this);
+ src_reg = this->result;
+ assert(src_reg.file != PROGRAM_UNDEFINED);
+
+ for (i = 0; i < 4; i++) {
+ if (i < ir->type->vector_elements) {
+ switch (i) {
+ case 0:
+ swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.x);
+ break;
+ case 1:
+ swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.y);
+ break;
+ case 2:
+ swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.z);
+ break;
+ case 3:
+ swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.w);
+ break;
+ }
+ } else {
+ /* If the type is smaller than a vec4, replicate the last
+ * channel out.
+ */
+ swizzle[i] = swizzle[ir->type->vector_elements - 1];
+ }
+ }
+
+ src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0],
+ swizzle[1],
+ swizzle[2],
+ swizzle[3]);
+
+ this->result = src_reg;
+}
+
+void
+ir_to_mesa_visitor::visit(ir_dereference_variable *ir)
+{
+ variable_storage *entry = find_variable_storage(ir->var);
+
+ if (!entry) {
+ switch (ir->var->mode) {
+ case ir_var_uniform:
+ entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_UNIFORM,
+ ir->var->location);
+ this->variables.push_tail(entry);
+ break;
+ case ir_var_in:
+ case ir_var_out:
+ case ir_var_inout:
+ case ir_var_system_value:
+ /* The linker assigns locations for varyings and attributes,
+ * including deprecated builtins (like gl_Color), user-assign
+ * generic attributes (glBindVertexLocation), and
+ * user-defined varyings.
+ *
+ * FINISHME: We would hit this path for function arguments. Fix!
+ */
+ assert(ir->var->location != -1);
+ if (ir->var->mode == ir_var_in ||
+ ir->var->mode == ir_var_inout) {
+ entry = new(mem_ctx) variable_storage(ir->var,
+ PROGRAM_INPUT,
+ ir->var->location);
+
+ if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
+ ir->var->location >= VERT_ATTRIB_GENERIC0) {
+ _mesa_add_attribute(prog->Attributes,
+ ir->var->name,
+ _mesa_sizeof_glsl_type(ir->var->type->gl_type),
+ ir->var->type->gl_type,
+ ir->var->location - VERT_ATTRIB_GENERIC0);
+ }
+ } else if (ir->var->mode == ir_var_system_value) {
+ entry = new(mem_ctx) variable_storage(ir->var,
+ PROGRAM_SYSTEM_VALUE,
+ ir->var->location);
+ } else {
+ entry = new(mem_ctx) variable_storage(ir->var,
+ PROGRAM_OUTPUT,
+ ir->var->location);
+ }
+
+ break;
+ case ir_var_auto:
+ case ir_var_temporary:
+ entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_TEMPORARY,
+ this->next_temp);
+ this->variables.push_tail(entry);
+
+ next_temp += type_size(ir->var->type);
+ break;
+ }
+
+ if (!entry) {
+ printf("Failed to make storage for %s\n", ir->var->name);
+ exit(1);
+ }
+ }
+
+ this->result = ir_to_mesa_src_reg(entry->file, entry->index, ir->var->type);
+}
+
+void
+ir_to_mesa_visitor::visit(ir_dereference_array *ir)
+{
+ ir_constant *index;
+ ir_to_mesa_src_reg src_reg;
+ int element_size = type_size(ir->type);
+
+ index = ir->array_index->constant_expression_value();
+
+ ir->array->accept(this);
+ src_reg = this->result;
+
+ if (index) {
+ src_reg.index += index->value.i[0] * element_size;
+ } else {
+ ir_to_mesa_src_reg array_base = this->result;
+ /* Variable index array dereference. It eats the "vec4" of the
+ * base of the array and an index that offsets the Mesa register
+ * index.
+ */
+ ir->array_index->accept(this);
+
+ ir_to_mesa_src_reg index_reg;
+
+ if (element_size == 1) {
+ index_reg = this->result;
+ } else {
+ index_reg = get_temp(glsl_type::float_type);
+
+ ir_to_mesa_emit_op2(ir, OPCODE_MUL,
+ ir_to_mesa_dst_reg_from_src(index_reg),
+ this->result, src_reg_for_float(element_size));
+ }
+
+ src_reg.reladdr = talloc(mem_ctx, ir_to_mesa_src_reg);
+ memcpy(src_reg.reladdr, &index_reg, sizeof(index_reg));
+ }
+
+ /* If the type is smaller than a vec4, replicate the last channel out. */
+ if (ir->type->is_scalar() || ir->type->is_vector())
+ src_reg.swizzle = swizzle_for_size(ir->type->vector_elements);
+ else
+ src_reg.swizzle = SWIZZLE_NOOP;
+
+ this->result = src_reg;
+}
+
+void
+ir_to_mesa_visitor::visit(ir_dereference_record *ir)
+{
+ unsigned int i;
+ const glsl_type *struct_type = ir->record->type;
+ int offset = 0;
+
+ ir->record->accept(this);
+
+ for (i = 0; i < struct_type->length; i++) {
+ if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
+ break;
+ offset += type_size(struct_type->fields.structure[i].type);
+ }
+
+ /* If the type is smaller than a vec4, replicate the last channel out. */
+ if (ir->type->is_scalar() || ir->type->is_vector())
+ this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
+ else
+ this->result.swizzle = SWIZZLE_NOOP;
+
+ this->result.index += offset;
+}
+
+/**
+ * We want to be careful in assignment setup to hit the actual storage
+ * instead of potentially using a temporary like we might with the
+ * ir_dereference handler.
+ */
+static struct ir_to_mesa_dst_reg
+get_assignment_lhs(ir_dereference *ir, ir_to_mesa_visitor *v)
+{
+ /* The LHS must be a dereference. If the LHS is a variable indexed array
+ * access of a vector, it must be separated into a series conditional moves
+ * before reaching this point (see ir_vec_index_to_cond_assign).
+ */
+ assert(ir->as_dereference());
+ ir_dereference_array *deref_array = ir->as_dereference_array();
+ if (deref_array) {
+ assert(!deref_array->array->type->is_vector());
+ }
+
+ /* Use the rvalue deref handler for the most part. We'll ignore
+ * swizzles in it and write swizzles using writemask, though.
+ */
+ ir->accept(v);
+ return ir_to_mesa_dst_reg_from_src(v->result);
+}
+
+/**
+ * Process the condition of a conditional assignment
+ *
+ * Examines the condition of a conditional assignment to generate the optimal
+ * first operand of a \c CMP instruction. If the condition is a relational
+ * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
+ * used as the source for the \c CMP instruction. Otherwise the comparison
+ * is processed to a boolean result, and the boolean result is used as the
+ * operand to the CMP instruction.
+ */
+bool
+ir_to_mesa_visitor::process_move_condition(ir_rvalue *ir)
+{
+ ir_rvalue *src_ir = ir;
+ bool negate = true;
+ bool switch_order = false;
+
+ ir_expression *const expr = ir->as_expression();
+ if ((expr != NULL) && (expr->get_num_operands() == 2)) {
+ bool zero_on_left = false;
+
+ if (expr->operands[0]->is_zero()) {
+ src_ir = expr->operands[1];
+ zero_on_left = true;
+ } else if (expr->operands[1]->is_zero()) {
+ src_ir = expr->operands[0];
+ zero_on_left = false;
+ }
+
+ /* a is - 0 + - 0 +
+ * (a < 0) T F F ( a < 0) T F F
+ * (0 < a) F F T (-a < 0) F F T
+ * (a <= 0) T T F (-a < 0) F F T (swap order of other operands)
+ * (0 <= a) F T T ( a < 0) T F F (swap order of other operands)
+ * (a > 0) F F T (-a < 0) F F T
+ * (0 > a) T F F ( a < 0) T F F
+ * (a >= 0) F T T ( a < 0) T F F (swap order of other operands)
+ * (0 >= a) T T F (-a < 0) F F T (swap order of other operands)
+ *
+ * Note that exchanging the order of 0 and 'a' in the comparison simply
+ * means that the value of 'a' should be negated.
+ */
+ if (src_ir != ir) {
+ switch (expr->operation) {
+ case ir_binop_less:
+ switch_order = false;
+ negate = zero_on_left;
+ break;
+
+ case ir_binop_greater:
+ switch_order = false;
+ negate = !zero_on_left;
+ break;
+
+ case ir_binop_lequal:
+ switch_order = true;
+ negate = !zero_on_left;
+ break;
+
+ case ir_binop_gequal:
+ switch_order = true;
+ negate = zero_on_left;
+ break;
+
+ default:
+ /* This isn't the right kind of comparison afterall, so make sure
+ * the whole condition is visited.
+ */
+ src_ir = ir;
+ break;
+ }
+ }
+ }
+
+ src_ir->accept(this);
+
+ /* We use the OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
+ * condition we produced is 0.0 or 1.0. By flipping the sign, we can
+ * choose which value OPCODE_CMP produces without an extra instruction
+ * computing the condition.
+ */
+ if (negate)
+ this->result.negate = ~this->result.negate;
+
+ return switch_order;
+}
+
+void
+ir_to_mesa_visitor::visit(ir_assignment *ir)
+{
+ struct ir_to_mesa_dst_reg l;
+ struct ir_to_mesa_src_reg r;
+ int i;
+
+ ir->rhs->accept(this);
+ r = this->result;
+
+ l = get_assignment_lhs(ir->lhs, this);
+
+ /* FINISHME: This should really set to the correct maximal writemask for each
+ * FINISHME: component written (in the loops below). This case can only
+ * FINISHME: occur for matrices, arrays, and structures.
+ */
+ if (ir->write_mask == 0) {
+ assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
+ l.writemask = WRITEMASK_XYZW;
+ } else if (ir->lhs->type->is_scalar()) {
+ /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
+ * FINISHME: W component of fragment shader output zero, work correctly.
+ */
+ l.writemask = WRITEMASK_XYZW;
+ } else {
+ int swizzles[4];
+ int first_enabled_chan = 0;
+ int rhs_chan = 0;
+
+ assert(ir->lhs->type->is_vector());
+ l.writemask = ir->write_mask;
+
+ for (int i = 0; i < 4; i++) {
+ if (l.writemask & (1 << i)) {
+ first_enabled_chan = GET_SWZ(r.swizzle, i);
+ break;
+ }
+ }
+
+ /* Swizzle a small RHS vector into the channels being written.
+ *
+ * glsl ir treats write_mask as dictating how many channels are
+ * present on the RHS while Mesa IR treats write_mask as just
+ * showing which channels of the vec4 RHS get written.
+ */
+ for (int i = 0; i < 4; i++) {
+ if (l.writemask & (1 << i))
+ swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
+ else
+ swizzles[i] = first_enabled_chan;
+ }
+ r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
+ swizzles[2], swizzles[3]);
+ }
+
+ assert(l.file != PROGRAM_UNDEFINED);
+ assert(r.file != PROGRAM_UNDEFINED);
+
+ if (ir->condition) {
+ const bool switch_order = this->process_move_condition(ir->condition);
+ ir_to_mesa_src_reg condition = this->result;
+
+ for (i = 0; i < type_size(ir->lhs->type); i++) {
+ if (switch_order) {
+ ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
+ condition, ir_to_mesa_src_reg_from_dst(l), r);
+ } else {
+ ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
+ condition, r, ir_to_mesa_src_reg_from_dst(l));
+ }
+
+ l.index++;
+ r.index++;
+ }
+ } else {
+ for (i = 0; i < type_size(ir->lhs->type); i++) {
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
+ l.index++;
+ r.index++;
+ }
+ }
+}
+
+
+void
+ir_to_mesa_visitor::visit(ir_constant *ir)
+{
+ ir_to_mesa_src_reg src_reg;
+ GLfloat stack_vals[4] = { 0 };
+ GLfloat *values = stack_vals;
+ unsigned int i;
+
+ /* Unfortunately, 4 floats is all we can get into
+ * _mesa_add_unnamed_constant. So, make a temp to store an
+ * aggregate constant and move each constant value into it. If we
+ * get lucky, copy propagation will eliminate the extra moves.
+ */
+
+ if (ir->type->base_type == GLSL_TYPE_STRUCT) {
+ ir_to_mesa_src_reg temp_base = get_temp(ir->type);
+ ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
+
+ foreach_iter(exec_list_iterator, iter, ir->components) {
+ ir_constant *field_value = (ir_constant *)iter.get();
+ int size = type_size(field_value->type);
+
+ assert(size > 0);
+
+ field_value->accept(this);
+ src_reg = this->result;
+
+ for (i = 0; i < (unsigned int)size; i++) {
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
+
+ src_reg.index++;
+ temp.index++;
+ }
+ }
+ this->result = temp_base;
+ return;
+ }
+
+ if (ir->type->is_array()) {
+ ir_to_mesa_src_reg temp_base = get_temp(ir->type);
+ ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
+ int size = type_size(ir->type->fields.array);
+
+ assert(size > 0);
+
+ for (i = 0; i < ir->type->length; i++) {
+ ir->array_elements[i]->accept(this);
+ src_reg = this->result;
+ for (int j = 0; j < size; j++) {
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
+
+ src_reg.index++;
+ temp.index++;
+ }
+ }
+ this->result = temp_base;
+ return;
+ }
+
+ if (ir->type->is_matrix()) {
+ ir_to_mesa_src_reg mat = get_temp(ir->type);
+ ir_to_mesa_dst_reg mat_column = ir_to_mesa_dst_reg_from_src(mat);
+
+ for (i = 0; i < ir->type->matrix_columns; i++) {
+ assert(ir->type->base_type == GLSL_TYPE_FLOAT);
+ values = &ir->value.f[i * ir->type->vector_elements];
+
+ src_reg = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, NULL);
+ src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
+ values,
+ ir->type->vector_elements,
+ &src_reg.swizzle);
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, mat_column, src_reg);
+
+ mat_column.index++;
+ }
+
+ this->result = mat;
+ return;
+ }
+
+ src_reg.file = PROGRAM_CONSTANT;
+ switch (ir->type->base_type) {
+ case GLSL_TYPE_FLOAT:
+ values = &ir->value.f[0];
+ break;
+ case GLSL_TYPE_UINT:
+ for (i = 0; i < ir->type->vector_elements; i++) {
+ values[i] = ir->value.u[i];
+ }
+ break;
+ case GLSL_TYPE_INT:
+ for (i = 0; i < ir->type->vector_elements; i++) {
+ values[i] = ir->value.i[i];
+ }
+ break;
+ case GLSL_TYPE_BOOL:
+ for (i = 0; i < ir->type->vector_elements; i++) {
+ values[i] = ir->value.b[i];
+ }
+ break;
+ default:
+ assert(!"Non-float/uint/int/bool constant");
+ }
+
+ this->result = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, ir->type);
+ this->result.index = _mesa_add_unnamed_constant(this->prog->Parameters,
+ values,
+ ir->type->vector_elements,
+ &this->result.swizzle);
+}
+
+function_entry *
+ir_to_mesa_visitor::get_function_signature(ir_function_signature *sig)
+{
+ function_entry *entry;
+
+ foreach_iter(exec_list_iterator, iter, this->function_signatures) {
+ entry = (function_entry *)iter.get();
+
+ if (entry->sig == sig)
+ return entry;
+ }
+
+ entry = talloc(mem_ctx, function_entry);
+ entry->sig = sig;
+ entry->sig_id = this->next_signature_id++;
+ entry->bgn_inst = NULL;
+
+ /* Allocate storage for all the parameters. */
+ foreach_iter(exec_list_iterator, iter, sig->parameters) {
+ ir_variable *param = (ir_variable *)iter.get();
+ variable_storage *storage;
+
+ storage = find_variable_storage(param);
+ assert(!storage);
+
+ storage = new(mem_ctx) variable_storage(param, PROGRAM_TEMPORARY,
+ this->next_temp);
+ this->variables.push_tail(storage);
+
+ this->next_temp += type_size(param->type);
+ }
+
+ if (!sig->return_type->is_void()) {
+ entry->return_reg = get_temp(sig->return_type);
+ } else {
+ entry->return_reg = ir_to_mesa_undef;
+ }
+
+ this->function_signatures.push_tail(entry);
+ return entry;
+}
+
+void
+ir_to_mesa_visitor::visit(ir_call *ir)
+{
+ ir_to_mesa_instruction *call_inst;
+ ir_function_signature *sig = ir->get_callee();
+ function_entry *entry = get_function_signature(sig);
+ int i;
+
+ /* Process in parameters. */
+ exec_list_iterator sig_iter = sig->parameters.iterator();
+ foreach_iter(exec_list_iterator, iter, *ir) {
+ ir_rvalue *param_rval = (ir_rvalue *)iter.get();
+ ir_variable *param = (ir_variable *)sig_iter.get();
+
+ if (param->mode == ir_var_in ||
+ param->mode == ir_var_inout) {
+ variable_storage *storage = find_variable_storage(param);
+ assert(storage);
+
+ param_rval->accept(this);
+ ir_to_mesa_src_reg r = this->result;
+
+ ir_to_mesa_dst_reg l;
+ l.file = storage->file;
+ l.index = storage->index;
+ l.reladdr = NULL;
+ l.writemask = WRITEMASK_XYZW;
+ l.cond_mask = COND_TR;
+
+ for (i = 0; i < type_size(param->type); i++) {
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
+ l.index++;
+ r.index++;
+ }
+ }
+
+ sig_iter.next();
+ }
+ assert(!sig_iter.has_next());
+
+ /* Emit call instruction */
+ call_inst = ir_to_mesa_emit_op1(ir, OPCODE_CAL,
+ ir_to_mesa_undef_dst, ir_to_mesa_undef);
+ call_inst->function = entry;
+
+ /* Process out parameters. */
+ sig_iter = sig->parameters.iterator();
+ foreach_iter(exec_list_iterator, iter, *ir) {
+ ir_rvalue *param_rval = (ir_rvalue *)iter.get();
+ ir_variable *param = (ir_variable *)sig_iter.get();
+
+ if (param->mode == ir_var_out ||
+ param->mode == ir_var_inout) {
+ variable_storage *storage = find_variable_storage(param);
+ assert(storage);
+
+ ir_to_mesa_src_reg r;
+ r.file = storage->file;
+ r.index = storage->index;
+ r.reladdr = NULL;
+ r.swizzle = SWIZZLE_NOOP;
+ r.negate = 0;
+
+ param_rval->accept(this);
+ ir_to_mesa_dst_reg l = ir_to_mesa_dst_reg_from_src(this->result);
+
+ for (i = 0; i < type_size(param->type); i++) {
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
+ l.index++;
+ r.index++;
+ }
+ }
+
+ sig_iter.next();
+ }
+ assert(!sig_iter.has_next());
+
+ /* Process return value. */
+ this->result = entry->return_reg;
+}
+
+void
+ir_to_mesa_visitor::visit(ir_texture *ir)
+{
+ ir_to_mesa_src_reg result_src, coord, lod_info, projector;
+ ir_to_mesa_dst_reg result_dst, coord_dst;
+ ir_to_mesa_instruction *inst = NULL;
+ prog_opcode opcode = OPCODE_NOP;
+
+ ir->coordinate->accept(this);
+
+ /* Put our coords in a temp. We'll need to modify them for shadow,
+ * projection, or LOD, so the only case we'd use it as is is if
+ * we're doing plain old texturing. Mesa IR optimization should
+ * handle cleaning up our mess in that case.
+ */
+ coord = get_temp(glsl_type::vec4_type);
+ coord_dst = ir_to_mesa_dst_reg_from_src(coord);
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst,
+ this->result);
+
+ if (ir->projector) {
+ ir->projector->accept(this);
+ projector = this->result;
+ }
+
+ /* Storage for our result. Ideally for an assignment we'd be using
+ * the actual storage for the result here, instead.
+ */
+ result_src = get_temp(glsl_type::vec4_type);
+ result_dst = ir_to_mesa_dst_reg_from_src(result_src);
+
+ switch (ir->op) {
+ case ir_tex:
+ opcode = OPCODE_TEX;
+ break;
+ case ir_txb:
+ opcode = OPCODE_TXB;
+ ir->lod_info.bias->accept(this);
+ lod_info = this->result;
+ break;
+ case ir_txl:
+ opcode = OPCODE_TXL;
+ ir->lod_info.lod->accept(this);
+ lod_info = this->result;
+ break;
+ case ir_txd:
+ case ir_txf:
+ assert(!"GLSL 1.30 features unsupported");
+ break;
+ }
+
+ if (ir->projector) {
+ if (opcode == OPCODE_TEX) {
+ /* Slot the projector in as the last component of the coord. */
+ coord_dst.writemask = WRITEMASK_W;
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, projector);
+ coord_dst.writemask = WRITEMASK_XYZW;
+ opcode = OPCODE_TXP;
+ } else {
+ ir_to_mesa_src_reg coord_w = coord;
+ coord_w.swizzle = SWIZZLE_WWWW;
+
+ /* For the other TEX opcodes there's no projective version
+ * since the last slot is taken up by lod info. Do the
+ * projective divide now.
+ */
+ coord_dst.writemask = WRITEMASK_W;
+ ir_to_mesa_emit_op1(ir, OPCODE_RCP, coord_dst, projector);
+
+ coord_dst.writemask = WRITEMASK_XYZ;
+ ir_to_mesa_emit_op2(ir, OPCODE_MUL, coord_dst, coord, coord_w);
+
+ coord_dst.writemask = WRITEMASK_XYZW;
+ coord.swizzle = SWIZZLE_XYZW;
+ }
+ }
+
+ if (ir->shadow_comparitor) {
+ /* Slot the shadow value in as the second to last component of the
+ * coord.
+ */
+ ir->shadow_comparitor->accept(this);
+ coord_dst.writemask = WRITEMASK_Z;
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, this->result);
+ coord_dst.writemask = WRITEMASK_XYZW;
+ }
+
+ if (opcode == OPCODE_TXL || opcode == OPCODE_TXB) {
+ /* Mesa IR stores lod or lod bias in the last channel of the coords. */
+ coord_dst.writemask = WRITEMASK_W;
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, lod_info);
+ coord_dst.writemask = WRITEMASK_XYZW;
+ }
+
+ inst = ir_to_mesa_emit_op1(ir, opcode, result_dst, coord);
+
+ if (ir->shadow_comparitor)
+ inst->tex_shadow = GL_TRUE;
+
+ inst->sampler = _mesa_get_sampler_uniform_value(ir->sampler,
+ this->shader_program,
+ this->prog);
+
+ const glsl_type *sampler_type = ir->sampler->type;
+
+ switch (sampler_type->sampler_dimensionality) {
+ case GLSL_SAMPLER_DIM_1D:
+ inst->tex_target = (sampler_type->sampler_array)
+ ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
+ break;
+ case GLSL_SAMPLER_DIM_2D:
+ inst->tex_target = (sampler_type->sampler_array)
+ ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
+ break;
+ case GLSL_SAMPLER_DIM_3D:
+ inst->tex_target = TEXTURE_3D_INDEX;
+ break;
+ case GLSL_SAMPLER_DIM_CUBE:
+ inst->tex_target = TEXTURE_CUBE_INDEX;
+ break;
+ case GLSL_SAMPLER_DIM_RECT:
+ inst->tex_target = TEXTURE_RECT_INDEX;
+ break;
+ case GLSL_SAMPLER_DIM_BUF:
+ assert(!"FINISHME: Implement ARB_texture_buffer_object");
+ break;
+ default:
+ assert(!"Should not get here.");
+ }
+
+ this->result = result_src;
+}
+
+void
+ir_to_mesa_visitor::visit(ir_return *ir)
+{
+ if (ir->get_value()) {
+ ir_to_mesa_dst_reg l;
+ int i;
+
+ assert(current_function);
+
+ ir->get_value()->accept(this);
+ ir_to_mesa_src_reg r = this->result;
+
+ l = ir_to_mesa_dst_reg_from_src(current_function->return_reg);
+
+ for (i = 0; i < type_size(current_function->sig->return_type); i++) {
+ ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
+ l.index++;
+ r.index++;
+ }
+ }
+
+ ir_to_mesa_emit_op0(ir, OPCODE_RET);
+}
+
+void
+ir_to_mesa_visitor::visit(ir_discard *ir)
+{
+ struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
+
+ if (ir->condition) {
+ ir->condition->accept(this);
+ this->result.negate = ~this->result.negate;
+ ir_to_mesa_emit_op1(ir, OPCODE_KIL, ir_to_mesa_undef_dst, this->result);
+ } else {
+ ir_to_mesa_emit_op0(ir, OPCODE_KIL_NV);
+ }
+
+ fp->UsesKill = GL_TRUE;
+}
+
+void
+ir_to_mesa_visitor::visit(ir_if *ir)
+{
+ ir_to_mesa_instruction *cond_inst, *if_inst, *else_inst = NULL;
+ ir_to_mesa_instruction *prev_inst;
+
+ prev_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
+
+ ir->condition->accept(this);
+ assert(this->result.file != PROGRAM_UNDEFINED);
+
+ if (this->options->EmitCondCodes) {
+ cond_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
+
+ /* See if we actually generated any instruction for generating
+ * the condition. If not, then cook up a move to a temp so we
+ * have something to set cond_update on.
+ */
+ if (cond_inst == prev_inst) {
+ ir_to_mesa_src_reg temp = get_temp(glsl_type::bool_type);
+ cond_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_MOV,
+ ir_to_mesa_dst_reg_from_src(temp),
+ result);
+ }
+ cond_inst->cond_update = GL_TRUE;
+
+ if_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_IF);
+ if_inst->dst_reg.cond_mask = COND_NE;
+ } else {
+ if_inst = ir_to_mesa_emit_op1(ir->condition,
+ OPCODE_IF, ir_to_mesa_undef_dst,
+ this->result);
+ }
+
+ this->instructions.push_tail(if_inst);
+
+ visit_exec_list(&ir->then_instructions, this);
+
+ if (!ir->else_instructions.is_empty()) {
+ else_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_ELSE);
+ visit_exec_list(&ir->else_instructions, this);
+ }
+
+ if_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_ENDIF,
+ ir_to_mesa_undef_dst, ir_to_mesa_undef);
+}
+
+ir_to_mesa_visitor::ir_to_mesa_visitor()
+{
+ result.file = PROGRAM_UNDEFINED;
+ next_temp = 1;
+ next_signature_id = 1;
+ current_function = NULL;
+ mem_ctx = talloc_new(NULL);
+}
+
+ir_to_mesa_visitor::~ir_to_mesa_visitor()
+{
+ talloc_free(mem_ctx);
+}
+
+static struct prog_src_register
+mesa_src_reg_from_ir_src_reg(ir_to_mesa_src_reg reg)
+{
+ struct prog_src_register mesa_reg;
+
+ mesa_reg.File = reg.file;
+ assert(reg.index < (1 << INST_INDEX_BITS));
+ mesa_reg.Index = reg.index;
+ mesa_reg.Swizzle = reg.swizzle;
+ mesa_reg.RelAddr = reg.reladdr != NULL;
+ mesa_reg.Negate = reg.negate;
+ mesa_reg.Abs = 0;
+ mesa_reg.HasIndex2 = GL_FALSE;
+ mesa_reg.RelAddr2 = 0;
+ mesa_reg.Index2 = 0;
+
+ return mesa_reg;
+}
+
+static void
+set_branchtargets(ir_to_mesa_visitor *v,
+ struct prog_instruction *mesa_instructions,
+ int num_instructions)
+{
+ int if_count = 0, loop_count = 0;
+ int *if_stack, *loop_stack;
+ int if_stack_pos = 0, loop_stack_pos = 0;
+ int i, j;
+
+ for (i = 0; i < num_instructions; i++) {
+ switch (mesa_instructions[i].Opcode) {
+ case OPCODE_IF:
+ if_count++;
+ break;
+ case OPCODE_BGNLOOP:
+ loop_count++;
+ break;
+ case OPCODE_BRK:
+ case OPCODE_CONT:
+ mesa_instructions[i].BranchTarget = -1;
+ break;
+ default:
+ break;
+ }
+ }
+
+ if_stack = talloc_zero_array(v->mem_ctx, int, if_count);
+ loop_stack = talloc_zero_array(v->mem_ctx, int, loop_count);
+
+ for (i = 0; i < num_instructions; i++) {
+ switch (mesa_instructions[i].Opcode) {
+ case OPCODE_IF:
+ if_stack[if_stack_pos] = i;
+ if_stack_pos++;
+ break;
+ case OPCODE_ELSE:
+ mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
+ if_stack[if_stack_pos - 1] = i;
+ break;
+ case OPCODE_ENDIF:
+ mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
+ if_stack_pos--;
+ break;
+ case OPCODE_BGNLOOP:
+ loop_stack[loop_stack_pos] = i;
+ loop_stack_pos++;
+ break;
+ case OPCODE_ENDLOOP:
+ loop_stack_pos--;
+ /* Rewrite any breaks/conts at this nesting level (haven't
+ * already had a BranchTarget assigned) to point to the end
+ * of the loop.
+ */
+ for (j = loop_stack[loop_stack_pos]; j < i; j++) {
+ if (mesa_instructions[j].Opcode == OPCODE_BRK ||
+ mesa_instructions[j].Opcode == OPCODE_CONT) {
+ if (mesa_instructions[j].BranchTarget == -1) {
+ mesa_instructions[j].BranchTarget = i;
+ }
+ }
+ }
+ /* The loop ends point at each other. */
+ mesa_instructions[i].BranchTarget = loop_stack[loop_stack_pos];
+ mesa_instructions[loop_stack[loop_stack_pos]].BranchTarget = i;
+ break;
+ case OPCODE_CAL:
+ foreach_iter(exec_list_iterator, iter, v->function_signatures) {
+ function_entry *entry = (function_entry *)iter.get();
+
+ if (entry->sig_id == mesa_instructions[i].BranchTarget) {
+ mesa_instructions[i].BranchTarget = entry->inst;
+ break;
+ }
+ }
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+static void
+print_program(struct prog_instruction *mesa_instructions,
+ ir_instruction **mesa_instruction_annotation,
+ int num_instructions)
+{
+ ir_instruction *last_ir = NULL;
+ int i;
+ int indent = 0;
+
+ for (i = 0; i < num_instructions; i++) {
+ struct prog_instruction *mesa_inst = mesa_instructions + i;
+ ir_instruction *ir = mesa_instruction_annotation[i];
+
+ fprintf(stdout, "%3d: ", i);
+
+ if (last_ir != ir && ir) {
+ int j;
+
+ for (j = 0; j < indent; j++) {
+ fprintf(stdout, " ");
+ }
+ ir->print();
+ printf("\n");
+ last_ir = ir;
+
+ fprintf(stdout, " "); /* line number spacing. */
+ }
+
+ indent = _mesa_fprint_instruction_opt(stdout, mesa_inst, indent,
+ PROG_PRINT_DEBUG, NULL);
+ }
+}
+
+static void
+count_resources(struct gl_program *prog)
+{
+ unsigned int i;
+
+ prog->SamplersUsed = 0;
+
+ for (i = 0; i < prog->NumInstructions; i++) {
+ struct prog_instruction *inst = &prog->Instructions[i];
+
+ if (_mesa_is_tex_instruction(inst->Opcode)) {
+ prog->SamplerTargets[inst->TexSrcUnit] =
+ (gl_texture_index)inst->TexSrcTarget;
+ prog->SamplersUsed |= 1 << inst->TexSrcUnit;
+ if (inst->TexShadow) {
+ prog->ShadowSamplers |= 1 << inst->TexSrcUnit;
+ }
+ }
+ }
+
+ _mesa_update_shader_textures_used(prog);
+}
+
+struct uniform_sort {
+ struct gl_uniform *u;
+ int pos;
+};
+
+/* The shader_program->Uniforms list is almost sorted in increasing
+ * uniform->{Frag,Vert}Pos locations, but not quite when there are
+ * uniforms shared between targets. We need to add parameters in
+ * increasing order for the targets.
+ */
+static int
+sort_uniforms(const void *a, const void *b)
+{
+ struct uniform_sort *u1 = (struct uniform_sort *)a;
+ struct uniform_sort *u2 = (struct uniform_sort *)b;
+
+ return u1->pos - u2->pos;
+}
+
+/* Add the uniforms to the parameters. The linker chose locations
+ * in our parameters lists (which weren't created yet), which the
+ * uniforms code will use to poke values into our parameters list
+ * when uniforms are updated.
+ */
+static void
+add_uniforms_to_parameters_list(struct gl_shader_program *shader_program,
+ struct gl_shader *shader,
+ struct gl_program *prog)
+{
+ unsigned int i;
+ unsigned int next_sampler = 0, num_uniforms = 0;
+ struct uniform_sort *sorted_uniforms;
+
+ sorted_uniforms = talloc_array(NULL, struct uniform_sort,
+ shader_program->Uniforms->NumUniforms);
+
+ for (i = 0; i < shader_program->Uniforms->NumUniforms; i++) {
+ struct gl_uniform *uniform = shader_program->Uniforms->Uniforms + i;
+ int parameter_index = -1;
+
+ switch (shader->Type) {
+ case GL_VERTEX_SHADER:
+ parameter_index = uniform->VertPos;
+ break;
+ case GL_FRAGMENT_SHADER:
+ parameter_index = uniform->FragPos;
+ break;
+ case GL_GEOMETRY_SHADER:
+ parameter_index = uniform->GeomPos;
+ break;
+ }
+
+ /* Only add uniforms used in our target. */
+ if (parameter_index != -1) {
+ sorted_uniforms[num_uniforms].pos = parameter_index;
+ sorted_uniforms[num_uniforms].u = uniform;
+ num_uniforms++;
+ }
+ }
+
+ qsort(sorted_uniforms, num_uniforms, sizeof(struct uniform_sort),
+ sort_uniforms);
+
+ for (i = 0; i < num_uniforms; i++) {
+ struct gl_uniform *uniform = sorted_uniforms[i].u;
+ int parameter_index = sorted_uniforms[i].pos;
+ const glsl_type *type = uniform->Type;
+ unsigned int size;
+
+ if (type->is_vector() ||
+ type->is_scalar()) {
+ size = type->vector_elements;
+ } else {
+ size = type_size(type) * 4;
+ }
+
+ gl_register_file file;
+ if (type->is_sampler() ||
+ (type->is_array() && type->fields.array->is_sampler())) {
+ file = PROGRAM_SAMPLER;
+ } else {
+ file = PROGRAM_UNIFORM;
+ }
+
+ GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
+ uniform->Name);
+
+ if (index < 0) {
+ index = _mesa_add_parameter(prog->Parameters, file,
+ uniform->Name, size, type->gl_type,
+ NULL, NULL, 0x0);
+
+ /* Sampler uniform values are stored in prog->SamplerUnits,
+ * and the entry in that array is selected by this index we
+ * store in ParameterValues[].
+ */
+ if (file == PROGRAM_SAMPLER) {
+ for (unsigned int j = 0; j < size / 4; j++)
+ prog->Parameters->ParameterValues[index + j][0] = next_sampler++;
+ }
+
+ /* The location chosen in the Parameters list here (returned
+ * from _mesa_add_uniform) has to match what the linker chose.
+ */
+ if (index != parameter_index) {
+ fail_link(shader_program, "Allocation of uniform `%s' to target "
+ "failed (%d vs %d)\n",
+ uniform->Name, index, parameter_index);
+ }
+ }
+ }
+
+ talloc_free(sorted_uniforms);
+}
+
+static void
+set_uniform_initializer(struct gl_context *ctx, void *mem_ctx,
+ struct gl_shader_program *shader_program,
+ const char *name, const glsl_type *type,
+ ir_constant *val)
+{
+ if (type->is_record()) {
+ ir_constant *field_constant;
+
+ field_constant = (ir_constant *)val->components.get_head();
+
+ for (unsigned int i = 0; i < type->length; i++) {
+ const glsl_type *field_type = type->fields.structure[i].type;
+ const char *field_name = talloc_asprintf(mem_ctx, "%s.%s", name,
+ type->fields.structure[i].name);
+ set_uniform_initializer(ctx, mem_ctx, shader_program, field_name,
+ field_type, field_constant);
+ field_constant = (ir_constant *)field_constant->next;
+ }
+ return;
+ }
+
+ int loc = _mesa_get_uniform_location(ctx, shader_program, name);
+
+ if (loc == -1) {
+ fail_link(shader_program,
+ "Couldn't find uniform for initializer %s\n", name);
+ return;
+ }
+
+ for (unsigned int i = 0; i < (type->is_array() ? type->length : 1); i++) {
+ ir_constant *element;
+ const glsl_type *element_type;
+ if (type->is_array()) {
+ element = val->array_elements[i];
+ element_type = type->fields.array;
+ } else {
+ element = val;
+ element_type = type;
+ }
+
+ void *values;
+
+ if (element_type->base_type == GLSL_TYPE_BOOL) {
+ int *conv = talloc_array(mem_ctx, int, element_type->components());
+ for (unsigned int j = 0; j < element_type->components(); j++) {
+ conv[j] = element->value.b[j];
+ }
+ values = (void *)conv;
+ element_type = glsl_type::get_instance(GLSL_TYPE_INT,
+ element_type->vector_elements,
+ 1);
+ } else {
+ values = &element->value;
+ }
+
+ if (element_type->is_matrix()) {
+ _mesa_uniform_matrix(ctx, shader_program,
+ element_type->matrix_columns,
+ element_type->vector_elements,
+ loc, 1, GL_FALSE, (GLfloat *)values);
+ loc += element_type->matrix_columns;
+ } else {
+ _mesa_uniform(ctx, shader_program, loc, element_type->matrix_columns,
+ values, element_type->gl_type);
+ loc += type_size(element_type);
+ }
+ }
+}
+
+static void
+set_uniform_initializers(struct gl_context *ctx,
+ struct gl_shader_program *shader_program)
+{
+ void *mem_ctx = NULL;
+
+ for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
+ struct gl_shader *shader = shader_program->_LinkedShaders[i];
+
+ if (shader == NULL)
+ continue;
+
+ foreach_iter(exec_list_iterator, iter, *shader->ir) {
+ ir_instruction *ir = (ir_instruction *)iter.get();
+ ir_variable *var = ir->as_variable();
+
+ if (!var || var->mode != ir_var_uniform || !var->constant_value)
+ continue;
+
+ if (!mem_ctx)
+ mem_ctx = talloc_new(NULL);
+
+ set_uniform_initializer(ctx, mem_ctx, shader_program, var->name,
+ var->type, var->constant_value);
+ }
+ }
+
+ talloc_free(mem_ctx);
+}
+
+/*
+ * On a basic block basis, tracks available PROGRAM_TEMPORARY register
+ * channels for copy propagation and updates following instructions to
+ * use the original versions.
+ *
+ * The ir_to_mesa_visitor lazily produces code assuming that this pass
+ * will occur. As an example, a TXP production before this pass:
+ *
+ * 0: MOV TEMP[1], INPUT[4].xyyy;
+ * 1: MOV TEMP[1].w, INPUT[4].wwww;
+ * 2: TXP TEMP[2], TEMP[1], texture[0], 2D;
+ *
+ * and after:
+ *
+ * 0: MOV TEMP[1], INPUT[4].xyyy;
+ * 1: MOV TEMP[1].w, INPUT[4].wwww;
+ * 2: TXP TEMP[2], INPUT[4].xyyw, texture[0], 2D;
+ *
+ * which allows for dead code elimination on TEMP[1]'s writes.
+ */
+void
+ir_to_mesa_visitor::copy_propagate(void)
+{
+ ir_to_mesa_instruction **acp = talloc_zero_array(mem_ctx,
+ ir_to_mesa_instruction *,
+ this->next_temp * 4);
+
+ foreach_iter(exec_list_iterator, iter, this->instructions) {
+ ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
+
+ assert(inst->dst_reg.file != PROGRAM_TEMPORARY
+ || inst->dst_reg.index < this->next_temp);
+
+ /* First, do any copy propagation possible into the src regs. */
+ for (int r = 0; r < 3; r++) {
+ ir_to_mesa_instruction *first = NULL;
+ bool good = true;
+ int acp_base = inst->src_reg[r].index * 4;
+
+ if (inst->src_reg[r].file != PROGRAM_TEMPORARY ||
+ inst->src_reg[r].reladdr)
+ continue;
+
+ /* See if we can find entries in the ACP consisting of MOVs
+ * from the same src register for all the swizzled channels
+ * of this src register reference.
+ */
+ for (int i = 0; i < 4; i++) {
+ int src_chan = GET_SWZ(inst->src_reg[r].swizzle, i);
+ ir_to_mesa_instruction *copy_chan = acp[acp_base + src_chan];
+
+ if (!copy_chan) {
+ good = false;
+ break;
+ }
+
+ if (!first) {
+ first = copy_chan;
+ } else {
+ if (first->src_reg[0].file != copy_chan->src_reg[0].file ||
+ first->src_reg[0].index != copy_chan->src_reg[0].index) {
+ good = false;
+ break;
+ }
+ }
+ }
+
+ if (good) {
+ /* We've now validated that we can copy-propagate to
+ * replace this src register reference. Do it.
+ */
+ inst->src_reg[r].file = first->src_reg[0].file;
+ inst->src_reg[r].index = first->src_reg[0].index;
+
+ int swizzle = 0;
+ for (int i = 0; i < 4; i++) {
+ int src_chan = GET_SWZ(inst->src_reg[r].swizzle, i);
+ ir_to_mesa_instruction *copy_inst = acp[acp_base + src_chan];
+ swizzle |= (GET_SWZ(copy_inst->src_reg[0].swizzle, src_chan) <<
+ (3 * i));
+ }
+ inst->src_reg[r].swizzle = swizzle;
+ }
+ }
+
+ switch (inst->op) {
+ case OPCODE_BGNLOOP:
+ case OPCODE_ENDLOOP:
+ case OPCODE_ELSE:
+ case OPCODE_ENDIF:
+ /* End of a basic block, clear the ACP entirely. */
+ memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
+ break;
+
+ default:
+ /* Continuing the block, clear any written channels from
+ * the ACP.
+ */
+ if (inst->dst_reg.file == PROGRAM_TEMPORARY) {
+ if (inst->dst_reg.reladdr) {
+ memset(acp, 0, sizeof(*acp) * this->next_temp * 4);
+ } else {
+ for (int i = 0; i < 4; i++) {
+ if (inst->dst_reg.writemask & (1 << i)) {
+ acp[4 * inst->dst_reg.index + i] = NULL;
+ }
+ }
+ }
+ }
+ break;
+ }
+
+ /* If this is a copy, add it to the ACP. */
+ if (inst->op == OPCODE_MOV &&
+ inst->dst_reg.file == PROGRAM_TEMPORARY &&
+ !inst->dst_reg.reladdr &&
+ !inst->saturate &&
+ !inst->src_reg[0].reladdr &&
+ !inst->src_reg[0].negate) {
+ for (int i = 0; i < 4; i++) {
+ if (inst->dst_reg.writemask & (1 << i)) {
+ acp[4 * inst->dst_reg.index + i] = inst;
+ }
+ }
+ }
+ }
+
+ talloc_free(acp);
+}
+
+
+/**
+ * Convert a shader's GLSL IR into a Mesa gl_program.
+ */
+static struct gl_program *
+get_mesa_program(struct gl_context *ctx,
+ struct gl_shader_program *shader_program,
+ struct gl_shader *shader)
+{
+ ir_to_mesa_visitor v;
+ struct prog_instruction *mesa_instructions, *mesa_inst;
+ ir_instruction **mesa_instruction_annotation;
+ int i;
+ struct gl_program *prog;
+ GLenum target;
+ const char *target_string;
+ GLboolean progress;
+ struct gl_shader_compiler_options *options =
+ &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(shader->Type)];
+
+ switch (shader->Type) {
+ case GL_VERTEX_SHADER:
+ target = GL_VERTEX_PROGRAM_ARB;
+ target_string = "vertex";
+ break;
+ case GL_FRAGMENT_SHADER:
+ target = GL_FRAGMENT_PROGRAM_ARB;
+ target_string = "fragment";
+ break;
+ case GL_GEOMETRY_SHADER:
+ target = GL_GEOMETRY_PROGRAM_NV;
+ target_string = "geometry";
+ break;
+ default:
+ assert(!"should not be reached");
+ return NULL;
+ }
+
+ validate_ir_tree(shader->ir);
+
+ prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
+ if (!prog)
+ return NULL;
+ prog->Parameters = _mesa_new_parameter_list();
+ prog->Varying = _mesa_new_parameter_list();
+ prog->Attributes = _mesa_new_parameter_list();
+ v.ctx = ctx;
+ v.prog = prog;
+ v.shader_program = shader_program;
+ v.options = options;
+
+ add_uniforms_to_parameters_list(shader_program, shader, prog);
+
+ /* Emit Mesa IR for main(). */
+ visit_exec_list(shader->ir, &v);
+ v.ir_to_mesa_emit_op0(NULL, OPCODE_END);
+
+ /* Now emit bodies for any functions that were used. */
+ do {
+ progress = GL_FALSE;
+
+ foreach_iter(exec_list_iterator, iter, v.function_signatures) {
+ function_entry *entry = (function_entry *)iter.get();
+
+ if (!entry->bgn_inst) {
+ v.current_function = entry;
+
+ entry->bgn_inst = v.ir_to_mesa_emit_op0(NULL, OPCODE_BGNSUB);
+ entry->bgn_inst->function = entry;
+
+ visit_exec_list(&entry->sig->body, &v);
+
+ ir_to_mesa_instruction *last;
+ last = (ir_to_mesa_instruction *)v.instructions.get_tail();
+ if (last->op != OPCODE_RET)
+ v.ir_to_mesa_emit_op0(NULL, OPCODE_RET);
+
+ ir_to_mesa_instruction *end;
+ end = v.ir_to_mesa_emit_op0(NULL, OPCODE_ENDSUB);
+ end->function = entry;
+
+ progress = GL_TRUE;
+ }
+ }
+ } while (progress);
+
+ prog->NumTemporaries = v.next_temp;
+
+ int num_instructions = 0;
+ foreach_iter(exec_list_iterator, iter, v.instructions) {
+ num_instructions++;
+ }
+
+ mesa_instructions =
+ (struct prog_instruction *)calloc(num_instructions,
+ sizeof(*mesa_instructions));
+ mesa_instruction_annotation = talloc_array(v.mem_ctx, ir_instruction *,
+ num_instructions);
+
+ v.copy_propagate();
+
+ /* Convert ir_mesa_instructions into prog_instructions.
+ */
+ mesa_inst = mesa_instructions;
+ i = 0;
+ foreach_iter(exec_list_iterator, iter, v.instructions) {
+ const ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
+
+ mesa_inst->Opcode = inst->op;
+ mesa_inst->CondUpdate = inst->cond_update;
+ if (inst->saturate)
+ mesa_inst->SaturateMode = SATURATE_ZERO_ONE;
+ mesa_inst->DstReg.File = inst->dst_reg.file;
+ mesa_inst->DstReg.Index = inst->dst_reg.index;
+ mesa_inst->DstReg.CondMask = inst->dst_reg.cond_mask;
+ mesa_inst->DstReg.WriteMask = inst->dst_reg.writemask;
+ mesa_inst->DstReg.RelAddr = inst->dst_reg.reladdr != NULL;
+ mesa_inst->SrcReg[0] = mesa_src_reg_from_ir_src_reg(inst->src_reg[0]);
+ mesa_inst->SrcReg[1] = mesa_src_reg_from_ir_src_reg(inst->src_reg[1]);
+ mesa_inst->SrcReg[2] = mesa_src_reg_from_ir_src_reg(inst->src_reg[2]);
+ mesa_inst->TexSrcUnit = inst->sampler;
+ mesa_inst->TexSrcTarget = inst->tex_target;
+ mesa_inst->TexShadow = inst->tex_shadow;
+ mesa_instruction_annotation[i] = inst->ir;
+
+ /* Set IndirectRegisterFiles. */
+ if (mesa_inst->DstReg.RelAddr)
+ prog->IndirectRegisterFiles |= 1 << mesa_inst->DstReg.File;
+
+ /* Update program's bitmask of indirectly accessed register files */
+ for (unsigned src = 0; src < 3; src++)
+ if (mesa_inst->SrcReg[src].RelAddr)
+ prog->IndirectRegisterFiles |= 1 << mesa_inst->SrcReg[src].File;
+
+ if (options->EmitNoIfs && mesa_inst->Opcode == OPCODE_IF) {
+ fail_link(shader_program, "Couldn't flatten if statement\n");
+ }
+
+ switch (mesa_inst->Opcode) {
+ case OPCODE_BGNSUB:
+ inst->function->inst = i;
+ mesa_inst->Comment = strdup(inst->function->sig->function_name());
+ break;
+ case OPCODE_ENDSUB:
+ mesa_inst->Comment = strdup(inst->function->sig->function_name());
+ break;
+ case OPCODE_CAL:
+ mesa_inst->BranchTarget = inst->function->sig_id; /* rewritten later */
+ break;
+ case OPCODE_ARL:
+ prog->NumAddressRegs = 1;
+ break;
+ default:
+ break;
+ }
+
+ mesa_inst++;
+ i++;
+
+ if (!shader_program->LinkStatus)
+ break;
+ }
+
+ if (!shader_program->LinkStatus) {
+ free(mesa_instructions);
+ _mesa_reference_program(ctx, &shader->Program, NULL);
+ return NULL;
+ }
+
+ set_branchtargets(&v, mesa_instructions, num_instructions);
+
+ if (ctx->Shader.Flags & GLSL_DUMP) {
+ printf("\n");
+ printf("GLSL IR for linked %s program %d:\n", target_string,
+ shader_program->Name);
+ _mesa_print_ir(shader->ir, NULL);
+ printf("\n");
+ printf("\n");
+ printf("Mesa IR for linked %s program %d:\n", target_string,
+ shader_program->Name);
+ print_program(mesa_instructions, mesa_instruction_annotation,
+ num_instructions);
+ }
+
+ prog->Instructions = mesa_instructions;
+ prog->NumInstructions = num_instructions;
+
+ do_set_program_inouts(shader->ir, prog);
+ count_resources(prog);
+
+ _mesa_reference_program(ctx, &shader->Program, prog);
+
+ if ((ctx->Shader.Flags & GLSL_NO_OPT) == 0) {
+ _mesa_optimize_program(ctx, prog);
+ }
+
+ return prog;
+}
+
+extern "C" {
+
+/**
+ * Called via ctx->Driver.CompilerShader().
+ * This is a no-op.
+ * XXX can we remove the ctx->Driver.CompileShader() hook?
+ */
+GLboolean
+_mesa_ir_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
+{
+ assert(shader->CompileStatus);
+ (void) ctx;
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Link a shader.
+ * Called via ctx->Driver.LinkShader()
+ * This actually involves converting GLSL IR into Mesa gl_programs with
+ * code lowering and other optimizations.
+ */
+GLboolean
+_mesa_ir_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
+{
+ assert(prog->LinkStatus);
+
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ bool progress;
+ exec_list *ir = prog->_LinkedShaders[i]->ir;
+ const struct gl_shader_compiler_options *options =
+ &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(prog->_LinkedShaders[i]->Type)];
+
+ do {
+ progress = false;
+
+ /* Lowering */
+ do_mat_op_to_vec(ir);
+ lower_instructions(ir, (MOD_TO_FRACT | DIV_TO_MUL_RCP | EXP_TO_EXP2
+ | LOG_TO_LOG2
+ | ((options->EmitNoPow) ? POW_TO_EXP2 : 0)));
+
+ progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
+
+ progress = do_common_optimization(ir, true, options->MaxUnrollIterations) || progress;
+
+ progress = lower_quadop_vector(ir, true) || progress;
+
+ if (options->EmitNoIfs) {
+ progress = lower_discard(ir) || progress;
+ progress = lower_if_to_cond_assign(ir) || progress;
+ }
+
+ if (options->EmitNoNoise)
+ progress = lower_noise(ir) || progress;
+
+ /* If there are forms of indirect addressing that the driver
+ * cannot handle, perform the lowering pass.
+ */
+ if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput
+ || options->EmitNoIndirectTemp || options->EmitNoIndirectUniform)
+ progress =
+ lower_variable_index_to_cond_assign(ir,
+ options->EmitNoIndirectInput,
+ options->EmitNoIndirectOutput,
+ options->EmitNoIndirectTemp,
+ options->EmitNoIndirectUniform)
+ || progress;
+
+ progress = do_vec_index_to_cond_assign(ir) || progress;
+ } while (progress);
+
+ validate_ir_tree(ir);
+ }
+
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
+ struct gl_program *linked_prog;
+
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
+
+ if (linked_prog) {
+ bool ok = true;
+
+ switch (prog->_LinkedShaders[i]->Type) {
+ case GL_VERTEX_SHADER:
+ _mesa_reference_vertprog(ctx, &prog->VertexProgram,
+ (struct gl_vertex_program *)linked_prog);
+ ok = ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
+ linked_prog);
+ break;
+ case GL_FRAGMENT_SHADER:
+ _mesa_reference_fragprog(ctx, &prog->FragmentProgram,
+ (struct gl_fragment_program *)linked_prog);
+ ok = ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
+ linked_prog);
+ break;
+ case GL_GEOMETRY_SHADER:
+ _mesa_reference_geomprog(ctx, &prog->GeometryProgram,
+ (struct gl_geometry_program *)linked_prog);
+ ok = ctx->Driver.ProgramStringNotify(ctx, GL_GEOMETRY_PROGRAM_NV,
+ linked_prog);
+ break;
+ }
+ if (!ok) {
+ return GL_FALSE;
+ }
+ }
+
+ _mesa_reference_program(ctx, &linked_prog, NULL);
+ }
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Compile a GLSL shader. Called via glCompileShader().
+ */
+void
+_mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
+{
+ struct _mesa_glsl_parse_state *state =
+ new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
+
+ const char *source = shader->Source;
+ /* Check if the user called glCompileShader without first calling
+ * glShaderSource. This should fail to compile, but not raise a GL_ERROR.
+ */
+ if (source == NULL) {
+ shader->CompileStatus = GL_FALSE;
+ return;
+ }
+
+ state->error = preprocess(state, &source, &state->info_log,
+ &ctx->Extensions, ctx->API);
+
+ if (ctx->Shader.Flags & GLSL_DUMP) {
+ printf("GLSL source for shader %d:\n", shader->Name);
+ printf("%s\n", shader->Source);
+ }
+
+ if (!state->error) {
+ _mesa_glsl_lexer_ctor(state, source);
+ _mesa_glsl_parse(state);
+ _mesa_glsl_lexer_dtor(state);
+ }
+
+ talloc_free(shader->ir);
+ shader->ir = new(shader) exec_list;
+ if (!state->error && !state->translation_unit.is_empty())
+ _mesa_ast_to_hir(shader->ir, state);
+
+ if (!state->error && !shader->ir->is_empty()) {
+ validate_ir_tree(shader->ir);
+
+ /* Do some optimization at compile time to reduce shader IR size
+ * and reduce later work if the same shader is linked multiple times
+ */
+ while (do_common_optimization(shader->ir, false, 32))
+ ;
+
+ validate_ir_tree(shader->ir);
+ }
+
+ shader->symbols = state->symbols;
+
+ shader->CompileStatus = !state->error;
+ shader->InfoLog = state->info_log;
+ shader->Version = state->language_version;
+ memcpy(shader->builtins_to_link, state->builtins_to_link,
+ sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
+ shader->num_builtins_to_link = state->num_builtins_to_link;
+
+ if (ctx->Shader.Flags & GLSL_LOG) {
+ _mesa_write_shader_to_file(shader);
+ }
+
+ if (ctx->Shader.Flags & GLSL_DUMP) {
+ if (shader->CompileStatus) {
+ printf("GLSL IR for shader %d:\n", shader->Name);
+ _mesa_print_ir(shader->ir, NULL);
+ printf("\n\n");
+ } else {
+ printf("GLSL shader %d failed to compile.\n", shader->Name);
+ }
+ if (shader->InfoLog && shader->InfoLog[0] != 0) {
+ printf("GLSL shader %d info log:\n", shader->Name);
+ printf("%s\n", shader->InfoLog);
+ }
+ }
+
+ /* Retain any live IR, but trash the rest. */
+ reparent_ir(shader->ir, shader->ir);
+
+ talloc_free(state);
+
+ if (shader->CompileStatus) {
+ if (!ctx->Driver.CompileShader(ctx, shader))
+ shader->CompileStatus = GL_FALSE;
+ }
+}
+
+
+/**
+ * Link a GLSL shader program. Called via glLinkProgram().
+ */
+void
+_mesa_glsl_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
+{
+ unsigned int i;
+
+ _mesa_clear_shader_program_data(ctx, prog);
+
+ prog->LinkStatus = GL_TRUE;
+
+ for (i = 0; i < prog->NumShaders; i++) {
+ if (!prog->Shaders[i]->CompileStatus) {
+ fail_link(prog, "linking with uncompiled shader");
+ prog->LinkStatus = GL_FALSE;
+ }
+ }
+
+ prog->Varying = _mesa_new_parameter_list();
+ _mesa_reference_vertprog(ctx, &prog->VertexProgram, NULL);
+ _mesa_reference_fragprog(ctx, &prog->FragmentProgram, NULL);
+ _mesa_reference_geomprog(ctx, &prog->GeometryProgram, NULL);
+
+ if (prog->LinkStatus) {
+ link_shaders(ctx, prog);
+ }
+
+ if (prog->LinkStatus) {
+ if (!ctx->Driver.LinkShader(ctx, prog)) {
+ prog->LinkStatus = GL_FALSE;
+ }
+ }
+
+ set_uniform_initializers(ctx, prog);
+
+ if (ctx->Shader.Flags & GLSL_DUMP) {
+ if (!prog->LinkStatus) {
+ printf("GLSL shader program %d failed to link\n", prog->Name);
+ }
+
+ if (prog->InfoLog && prog->InfoLog[0] != 0) {
+ printf("GLSL shader program %d info log:\n", prog->Name);
+ printf("%s\n", prog->InfoLog);
+ }
+ }
+}
+
+} /* extern "C" */
diff --git a/mesalib/src/mesa/state_tracker/st_cb_texture.c b/mesalib/src/mesa/state_tracker/st_cb_texture.c
index b60ac72e4..9653dcd65 100644
--- a/mesalib/src/mesa/state_tracker/st_cb_texture.c
+++ b/mesalib/src/mesa/state_tracker/st_cb_texture.c
@@ -1,2022 +1,2021 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sub license, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice (including the
- * next paragraph) shall be included in all copies or substantial portions
- * of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- **************************************************************************/
-
-#include "main/mfeatures.h"
-#include "main/bufferobj.h"
-#include "main/enums.h"
-#include "main/fbobject.h"
-#include "main/formats.h"
-#include "main/image.h"
-#include "main/imports.h"
-#include "main/macros.h"
-#include "main/mipmap.h"
-#include "main/pack.h"
-#include "main/pixeltransfer.h"
-#include "main/texcompress.h"
-#include "main/texfetch.h"
-#include "main/texgetimage.h"
-#include "main/teximage.h"
-#include "main/texobj.h"
-#include "main/texstore.h"
-
-#include "state_tracker/st_debug.h"
-#include "state_tracker/st_context.h"
-#include "state_tracker/st_cb_fbo.h"
-#include "state_tracker/st_cb_flush.h"
-#include "state_tracker/st_cb_texture.h"
-#include "state_tracker/st_format.h"
-#include "state_tracker/st_texture.h"
-#include "state_tracker/st_gen_mipmap.h"
-#include "state_tracker/st_atom.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "util/u_inlines.h"
-#include "pipe/p_shader_tokens.h"
-#include "util/u_tile.h"
-#include "util/u_blit.h"
-#include "util/u_format.h"
-#include "util/u_surface.h"
-#include "util/u_sampler.h"
-#include "util/u_math.h"
-#include "util/u_box.h"
-
-#define DBG if (0) printf
-
-
-static enum pipe_texture_target
-gl_target_to_pipe(GLenum target)
-{
- switch (target) {
- case GL_TEXTURE_1D:
- return PIPE_TEXTURE_1D;
-
- case GL_TEXTURE_2D:
- return PIPE_TEXTURE_2D;
-
- case GL_TEXTURE_RECTANGLE_NV:
- return PIPE_TEXTURE_RECT;
-
- case GL_TEXTURE_3D:
- return PIPE_TEXTURE_3D;
-
- case GL_TEXTURE_CUBE_MAP_ARB:
- return PIPE_TEXTURE_CUBE;
-
- default:
- assert(0);
- return 0;
- }
-}
-
-
-/** called via ctx->Driver.NewTextureImage() */
-static struct gl_texture_image *
-st_NewTextureImage(struct gl_context * ctx)
-{
- DBG("%s\n", __FUNCTION__);
- (void) ctx;
- return (struct gl_texture_image *) ST_CALLOC_STRUCT(st_texture_image);
-}
-
-
-/** called via ctx->Driver.NewTextureObject() */
-static struct gl_texture_object *
-st_NewTextureObject(struct gl_context * ctx, GLuint name, GLenum target)
-{
- struct st_texture_object *obj = ST_CALLOC_STRUCT(st_texture_object);
-
- DBG("%s\n", __FUNCTION__);
- _mesa_initialize_texture_object(&obj->base, name, target);
-
- return &obj->base;
-}
-
-/** called via ctx->Driver.DeleteTextureObject() */
-static void
-st_DeleteTextureObject(struct gl_context *ctx,
- struct gl_texture_object *texObj)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_object *stObj = st_texture_object(texObj);
- if (stObj->pt)
- pipe_resource_reference(&stObj->pt, NULL);
- if (stObj->sampler_view) {
- if (stObj->sampler_view->context != st->pipe) {
- /* Take "ownership" of this texture sampler view by setting
- * its context pointer to this context. This avoids potential
- * crashes when the texture object is shared among contexts
- * and the original/owner context has already been destroyed.
- */
- stObj->sampler_view->context = st->pipe;
- }
- pipe_sampler_view_reference(&stObj->sampler_view, NULL);
- }
- _mesa_delete_texture_object(ctx, texObj);
-}
-
-
-/** called via ctx->Driver.FreeTexImageData() */
-static void
-st_FreeTextureImageData(struct gl_context * ctx, struct gl_texture_image *texImage)
-{
- struct st_texture_image *stImage = st_texture_image(texImage);
-
- DBG("%s\n", __FUNCTION__);
-
- if (stImage->pt) {
- pipe_resource_reference(&stImage->pt, NULL);
- }
-
- if (texImage->Data) {
- _mesa_align_free(texImage->Data);
- texImage->Data = NULL;
- }
-}
-
-
-/**
- * From linux kernel i386 header files, copes with odd sizes better
- * than COPY_DWORDS would:
- * XXX Put this in src/mesa/main/imports.h ???
- */
-#if defined(PIPE_CC_GCC) && defined(PIPE_ARCH_X86)
-static INLINE void *
-__memcpy(void *to, const void *from, size_t n)
-{
- int d0, d1, d2;
- __asm__ __volatile__("rep ; movsl\n\t"
- "testb $2,%b4\n\t"
- "je 1f\n\t"
- "movsw\n"
- "1:\ttestb $1,%b4\n\t"
- "je 2f\n\t"
- "movsb\n" "2:":"=&c"(d0), "=&D"(d1), "=&S"(d2)
- :"0"(n / 4), "q"(n), "1"((long) to), "2"((long) from)
- :"memory");
- return (to);
-}
-#else
-#define __memcpy(a,b,c) memcpy(a,b,c)
-#endif
-
-
-/**
- * The system memcpy (at least on ubuntu 5.10) has problems copying
- * to agp (writecombined) memory from a source which isn't 64-byte
- * aligned - there is a 4x performance falloff.
- *
- * The x86 __memcpy is immune to this but is slightly slower
- * (10%-ish) than the system memcpy.
- *
- * The sse_memcpy seems to have a slight cliff at 64/32 bytes, but
- * isn't much faster than x86_memcpy for agp copies.
- *
- * TODO: switch dynamically.
- */
-static void *
-do_memcpy(void *dest, const void *src, size_t n)
-{
- if ((((unsigned long) src) & 63) || (((unsigned long) dest) & 63)) {
- return __memcpy(dest, src, n);
- }
- else
- return memcpy(dest, src, n);
-}
-
-
-/**
- * Return default texture resource binding bitmask for the given format.
- */
-static GLuint
-default_bindings(struct st_context *st, enum pipe_format format)
-{
- struct pipe_screen *screen = st->pipe->screen;
- const unsigned target = PIPE_TEXTURE_2D;
- const unsigned geom = 0x0;
- unsigned bindings;
-
- if (util_format_is_depth_or_stencil(format))
- bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_DEPTH_STENCIL;
- else
- bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_RENDER_TARGET;
-
- if (screen->is_format_supported(screen, format, target, 0, bindings, geom))
- return bindings;
- else
- return PIPE_BIND_SAMPLER_VIEW;
-}
-
-
-/** Return number of image dimensions (1, 2 or 3) for a texture target. */
-static GLuint
-get_texture_dims(GLenum target)
-{
- switch (target) {
- case GL_TEXTURE_1D:
- case GL_TEXTURE_1D_ARRAY_EXT:
- return 1;
- case GL_TEXTURE_2D:
- case GL_TEXTURE_CUBE_MAP_ARB:
- case GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB:
- case GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB:
- case GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB:
- case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB:
- case GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB:
- case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB:
- case GL_TEXTURE_RECTANGLE_NV:
- case GL_TEXTURE_2D_ARRAY_EXT:
- return 2;
- case GL_TEXTURE_3D:
- return 3;
- default:
- assert(0 && "invalid texture target in get_texture_dims()");
- return 1;
- }
-}
-
-
-/**
- * Try to allocate a pipe_resource object for the given st_texture_object.
- *
- * We use the given st_texture_image as a clue to determine the size of the
- * mipmap image at level=0.
- *
- * \return GL_TRUE for success, GL_FALSE if out of memory.
- */
-static GLboolean
-guess_and_alloc_texture(struct st_context *st,
- struct st_texture_object *stObj,
- const struct st_texture_image *stImage)
-{
- const GLuint dims = get_texture_dims(stObj->base.Target);
- GLuint level, lastLevel, width, height, depth;
- GLuint bindings;
- enum pipe_format fmt;
-
- DBG("%s\n", __FUNCTION__);
-
- assert(!stObj->pt);
-
- level = stImage->level;
- width = stImage->base.Width2; /* size w/out border */
- height = stImage->base.Height2;
- depth = stImage->base.Depth2;
-
- assert(width > 0);
- assert(height > 0);
- assert(depth > 0);
-
- /* Depending on the image's size, we can't always make a guess here.
- */
- if (level > 0) {
- if ( (dims >= 1 && width == 1) ||
- (dims >= 2 && height == 1) ||
- (dims >= 3 && depth == 1) ) {
- /* we can't determine the image size at level=0 */
- stObj->width0 = stObj->height0 = stObj->depth0 = 0;
- /* this is not an out of memory error */
- return GL_TRUE;
- }
- }
-
- /* grow the image size until we hit level = 0 */
- while (level > 0) {
- if (width != 1)
- width <<= 1;
- if (height != 1)
- height <<= 1;
- if (depth != 1)
- depth <<= 1;
- level--;
- }
-
- assert(level == 0);
-
- /* At this point, (width x height x depth) is the expected size of
- * the level=0 mipmap image.
- */
-
- /* Guess a reasonable value for lastLevel. With OpenGL we have no
- * idea how many mipmap levels will be in a texture until we start
- * to render with it. Make an educated guess here but be prepared
- * to re-allocating a texture buffer with space for more (or fewer)
- * mipmap levels later.
- */
- if ((stObj->base.MinFilter == GL_NEAREST ||
- stObj->base.MinFilter == GL_LINEAR ||
- stImage->base._BaseFormat == GL_DEPTH_COMPONENT ||
- stImage->base._BaseFormat == GL_DEPTH_STENCIL_EXT) &&
- !stObj->base.GenerateMipmap &&
- stImage->level == 0) {
- /* only alloc space for a single mipmap level */
- lastLevel = 0;
- }
- else {
- /* alloc space for a full mipmap */
- GLuint l2width = util_logbase2(width);
- GLuint l2height = util_logbase2(height);
- GLuint l2depth = util_logbase2(depth);
- lastLevel = MAX2(MAX2(l2width, l2height), l2depth);
- }
-
- /* Save the level=0 dimensions */
- stObj->width0 = width;
- stObj->height0 = height;
- stObj->depth0 = depth;
-
- fmt = st_mesa_format_to_pipe_format(stImage->base.TexFormat);
-
- bindings = default_bindings(st, fmt);
-
- stObj->pt = st_texture_create(st,
- gl_target_to_pipe(stObj->base.Target),
- fmt,
- lastLevel,
- width,
- height,
- depth,
- bindings);
-
- DBG("%s returning %d\n", __FUNCTION__, (stObj->pt != NULL));
-
- return stObj->pt != NULL;
-}
-
-
-/**
- * Adjust pixel unpack params and image dimensions to strip off the
- * texture border.
- * Gallium doesn't support texture borders. They've seldem been used
- * and seldom been implemented correctly anyway.
- * \param unpackNew returns the new pixel unpack parameters
- */
-static void
-strip_texture_border(GLint border,
- GLint *width, GLint *height, GLint *depth,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_pixelstore_attrib *unpackNew)
-{
- assert(border > 0); /* sanity check */
-
- *unpackNew = *unpack;
-
- if (unpackNew->RowLength == 0)
- unpackNew->RowLength = *width;
-
- if (depth && unpackNew->ImageHeight == 0)
- unpackNew->ImageHeight = *height;
-
- unpackNew->SkipPixels += border;
- if (height)
- unpackNew->SkipRows += border;
- if (depth)
- unpackNew->SkipImages += border;
-
- assert(*width >= 3);
- *width = *width - 2 * border;
- if (height && *height >= 3)
- *height = *height - 2 * border;
- if (depth && *depth >= 3)
- *depth = *depth - 2 * border;
-}
-
-
-/**
- * Try to do texture compression via rendering. If the Gallium driver
- * can render into a compressed surface this will allow us to do texture
- * compression.
- * \return GL_TRUE for success, GL_FALSE for failure
- */
-static GLboolean
-compress_with_blit(struct gl_context * ctx,
- GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLint width, GLint height, GLint depth,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_texture_image *texImage)
-{
- const GLuint dstImageOffsets[1] = {0};
- struct st_texture_image *stImage = st_texture_image(texImage);
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct pipe_screen *screen = pipe->screen;
- gl_format mesa_format;
- struct pipe_resource templ;
- struct pipe_resource *src_tex;
- struct pipe_sampler_view view_templ;
- struct pipe_sampler_view *src_view;
- struct pipe_surface *dst_surface, surf_tmpl;
- struct pipe_transfer *tex_xfer;
- void *map;
-
- if (!stImage->pt) {
- /* XXX: Can this happen? Should we assert? */
- return GL_FALSE;
- }
-
- /* get destination surface (in the compressed texture) */
- memset(&surf_tmpl, 0, sizeof(surf_tmpl));
- surf_tmpl.format = stImage->pt->format;
- surf_tmpl.usage = PIPE_BIND_RENDER_TARGET;
- surf_tmpl.u.tex.level = stImage->level;
- surf_tmpl.u.tex.first_layer = stImage->face;
- surf_tmpl.u.tex.last_layer = stImage->face;
- dst_surface = pipe->create_surface(pipe, stImage->pt, &surf_tmpl);
- if (!dst_surface) {
- /* can't render into this format (or other problem) */
- return GL_FALSE;
- }
-
- /* Choose format for the temporary RGBA texture image.
- */
- mesa_format = st_ChooseTextureFormat(ctx, GL_RGBA, format, type);
- assert(mesa_format);
- if (!mesa_format)
- return GL_FALSE;
-
- /* Create the temporary source texture
- */
- memset(&templ, 0, sizeof(templ));
- templ.target = st->internal_target;
- templ.format = st_mesa_format_to_pipe_format(mesa_format);
- templ.width0 = width;
- templ.height0 = height;
- templ.depth0 = 1;
- templ.array_size = 1;
- templ.last_level = 0;
- templ.usage = PIPE_USAGE_DEFAULT;
- templ.bind = PIPE_BIND_SAMPLER_VIEW;
- src_tex = screen->resource_create(screen, &templ);
-
- if (!src_tex)
- return GL_FALSE;
-
- /* Put user's tex data into the temporary texture
- */
- tex_xfer = pipe_get_transfer(st_context(ctx)->pipe, src_tex,
- 0, 0, /* layer, level are zero */
- PIPE_TRANSFER_WRITE,
- 0, 0, width, height); /* x, y, w, h */
- map = pipe_transfer_map(pipe, tex_xfer);
-
- _mesa_texstore(ctx, 2, GL_RGBA, mesa_format,
- map, /* dest ptr */
- 0, 0, 0, /* dest x/y/z offset */
- tex_xfer->stride, /* dest row stride (bytes) */
- dstImageOffsets, /* image offsets (for 3D only) */
- width, height, 1, /* size */
- format, type, /* source format/type */
- pixels, /* source data */
- unpack); /* source data packing */
-
- pipe_transfer_unmap(pipe, tex_xfer);
- pipe->transfer_destroy(pipe, tex_xfer);
-
- /* Create temporary sampler view */
- u_sampler_view_default_template(&view_templ,
- src_tex,
- src_tex->format);
- src_view = pipe->create_sampler_view(pipe, src_tex, &view_templ);
-
-
- /* copy / compress image */
- util_blit_pixels_tex(st->blit,
- src_view, /* sampler view (src) */
- 0, 0, /* src x0, y0 */
- width, height, /* src x1, y1 */
- dst_surface, /* pipe_surface (dst) */
- xoffset, yoffset, /* dst x0, y0 */
- xoffset + width, /* dst x1 */
- yoffset + height, /* dst y1 */
- 0.0, /* z */
- PIPE_TEX_MIPFILTER_NEAREST);
-
- pipe_surface_reference(&dst_surface, NULL);
- pipe_resource_reference(&src_tex, NULL);
- pipe_sampler_view_reference(&src_view, NULL);
-
- return GL_TRUE;
-}
-
-
-/**
- * Do glTexImage1/2/3D().
- */
-static void
-st_TexImage(struct gl_context * ctx,
- GLint dims,
- GLenum target, GLint level,
- GLint internalFormat,
- GLint width, GLint height, GLint depth,
- GLint border,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage,
- GLsizei imageSize, GLboolean compressed_src)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_screen *screen = st->pipe->screen;
- struct st_texture_object *stObj = st_texture_object(texObj);
- struct st_texture_image *stImage = st_texture_image(texImage);
- GLuint dstRowStride = 0;
- struct gl_pixelstore_attrib unpackNB;
- enum pipe_transfer_usage transfer_usage = 0;
-
- DBG("%s target %s level %d %dx%dx%d border %d\n", __FUNCTION__,
- _mesa_lookup_enum_by_nr(target), level, width, height, depth, border);
-
- /* switch to "normal" */
- if (stObj->surface_based) {
- gl_format texFormat;
-
- _mesa_clear_texture_object(ctx, texObj);
- pipe_resource_reference(&stObj->pt, NULL);
-
- /* oops, need to init this image again */
- texFormat = _mesa_choose_texture_format(ctx, texObj, target, level,
- internalFormat, format, type);
-
- _mesa_init_teximage_fields(ctx, target, texImage,
- width, height, depth, border,
- internalFormat, texFormat);
-
- stObj->surface_based = GL_FALSE;
- }
-
- /* gallium does not support texture borders, strip it off */
- if (border) {
- strip_texture_border(border, &width, &height, &depth, unpack, &unpackNB);
- unpack = &unpackNB;
- texImage->Width = width;
- texImage->Height = height;
- texImage->Depth = depth;
- texImage->Border = 0;
- border = 0;
- }
- else {
- assert(texImage->Width == width);
- assert(texImage->Height == height);
- assert(texImage->Depth == depth);
- }
-
- stImage->face = _mesa_tex_target_to_face(target);
- stImage->level = level;
-
- _mesa_set_fetch_functions(texImage, dims);
-
- /* Release the reference to a potentially orphaned buffer.
- * Release any old malloced memory.
- */
- if (stImage->pt) {
- pipe_resource_reference(&stImage->pt, NULL);
- assert(!texImage->Data);
- }
- else if (texImage->Data) {
- _mesa_align_free(texImage->Data);
- }
-
- /*
- * See if the new image is somehow incompatible with the existing
- * mipmap. If so, free the old mipmap.
- */
- if (stObj->pt) {
- if (level > (GLint) stObj->pt->last_level ||
- !st_texture_match_image(stObj->pt, &stImage->base,
- stImage->face, stImage->level)) {
- DBG("release it\n");
- pipe_resource_reference(&stObj->pt, NULL);
- assert(!stObj->pt);
- pipe_sampler_view_reference(&stObj->sampler_view, NULL);
- }
- }
-
- if (width == 0 || height == 0 || depth == 0) {
- /* stop after freeing old image */
- return;
- }
-
- if (!stObj->pt) {
- if (!guess_and_alloc_texture(st, stObj, stImage)) {
- /* Probably out of memory.
- * Try flushing any pending rendering, then retry.
- */
- st_finish(st);
- if (!guess_and_alloc_texture(st, stObj, stImage)) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
- return;
- }
- }
- }
-
- assert(!stImage->pt);
-
- /* Check if this texture image can live inside the texture object's buffer.
- * If so, store the image there. Otherwise the image will temporarily live
- * in its own buffer.
- */
- if (stObj->pt &&
- st_texture_match_image(stObj->pt, &stImage->base,
- stImage->face, stImage->level)) {
-
- pipe_resource_reference(&stImage->pt, stObj->pt);
- assert(stImage->pt);
- }
-
- if (!stImage->pt)
- DBG("XXX: Image did not fit into texture - storing in local memory!\n");
-
- /* Pixel data may come from regular user memory or a PBO. For the later,
- * do bounds checking and map the PBO to read pixels data from it.
- *
- * XXX we should try to use a GPU-accelerated path to copy the image data
- * from the PBO to the texture.
- */
- if (compressed_src) {
- pixels = _mesa_validate_pbo_compressed_teximage(ctx, imageSize, pixels,
- unpack,
- "glCompressedTexImage");
- }
- else {
- pixels = _mesa_validate_pbo_teximage(ctx, dims, width, height, 1,
- format, type,
- pixels, unpack, "glTexImage");
- }
-
- /* See if we can do texture compression with a blit/render.
- */
- if (!compressed_src &&
- !ctx->Mesa_DXTn &&
- _mesa_is_format_compressed(texImage->TexFormat) &&
- screen->is_format_supported(screen,
- stImage->pt->format,
- stImage->pt->target, 0,
- PIPE_BIND_RENDER_TARGET, 0)) {
- if (!pixels)
- goto done;
-
- if (compress_with_blit(ctx, target, level, 0, 0, 0, width, height, depth,
- format, type, pixels, unpack, texImage)) {
- goto done;
- }
- }
-
- /*
- * Prepare to store the texture data. Either map the gallium texture buffer
- * memory or malloc space for it.
- */
- if (stImage->pt) {
- /* Store the image in the gallium texture memory buffer */
- if (format == GL_DEPTH_COMPONENT &&
- util_format_is_depth_and_stencil(stImage->pt->format))
- transfer_usage = PIPE_TRANSFER_READ_WRITE;
- else
- transfer_usage = PIPE_TRANSFER_WRITE;
-
- texImage->Data = st_texture_image_map(st, stImage, 0,
- transfer_usage, 0, 0, width, height);
- if(stImage->transfer)
- dstRowStride = stImage->transfer->stride;
- }
- else {
- /* Allocate regular memory and store the image there temporarily. */
- GLuint imageSize = _mesa_format_image_size(texImage->TexFormat,
- width, height, depth);
- dstRowStride = _mesa_format_row_stride(texImage->TexFormat, width);
-
- texImage->Data = _mesa_align_malloc(imageSize, 16);
- }
-
- if (!texImage->Data) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
- return;
- }
-
- if (!pixels) {
- /* We've allocated texture memory, but have no pixel data - all done. */
- goto done;
- }
-
- DBG("Upload image %dx%dx%d row_len %x pitch %x\n",
- width, height, depth, width, dstRowStride);
-
- /* Copy user texture image into the texture buffer.
- */
- if (compressed_src) {
- const GLuint srcRowStride =
- _mesa_format_row_stride(texImage->TexFormat, width);
- if (dstRowStride == srcRowStride) {
- memcpy(texImage->Data, pixels, imageSize);
- }
- else {
- char *dst = texImage->Data;
- const char *src = pixels;
- GLuint i, bw, bh, lines;
- _mesa_get_format_block_size(texImage->TexFormat, &bw, &bh);
- lines = (height + bh - 1) / bh;
-
- for (i = 0; i < lines; ++i) {
- memcpy(dst, src, srcRowStride);
- dst += dstRowStride;
- src += srcRowStride;
- }
- }
- }
- else {
- const GLuint srcImageStride =
- _mesa_image_image_stride(unpack, width, height, format, type);
- GLint i;
- const GLubyte *src = (const GLubyte *) pixels;
-
- for (i = 0; i < depth; i++) {
- if (!_mesa_texstore(ctx, dims,
- texImage->_BaseFormat,
- texImage->TexFormat,
- texImage->Data,
- 0, 0, 0, /* dstX/Y/Zoffset */
- dstRowStride,
- texImage->ImageOffsets,
- width, height, 1,
- format, type, src, unpack)) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
- }
-
- if (stImage->pt && i + 1 < depth) {
- /* unmap this slice */
- st_texture_image_unmap(st, stImage);
- /* map next slice of 3D texture */
- texImage->Data = st_texture_image_map(st, stImage, i + 1,
- transfer_usage, 0, 0,
- width, height);
- src += srcImageStride;
- }
- }
- }
-
-done:
- _mesa_unmap_teximage_pbo(ctx, unpack);
-
- if (stImage->pt && texImage->Data) {
- st_texture_image_unmap(st, stImage);
- texImage->Data = NULL;
- }
-}
-
-
-static void
-st_TexImage3D(struct gl_context * ctx,
- GLenum target, GLint level,
- GLint internalFormat,
- GLint width, GLint height, GLint depth,
- GLint border,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexImage(ctx, 3, target, level, internalFormat, width, height, depth,
- border, format, type, pixels, unpack, texObj, texImage,
- 0, GL_FALSE);
-}
-
-
-static void
-st_TexImage2D(struct gl_context * ctx,
- GLenum target, GLint level,
- GLint internalFormat,
- GLint width, GLint height, GLint border,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
- format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
-}
-
-
-static void
-st_TexImage1D(struct gl_context * ctx,
- GLenum target, GLint level,
- GLint internalFormat,
- GLint width, GLint border,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexImage(ctx, 1, target, level, internalFormat, width, 1, 1, border,
- format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
-}
-
-
-static void
-st_CompressedTexImage2D(struct gl_context *ctx, GLenum target, GLint level,
- GLint internalFormat,
- GLint width, GLint height, GLint border,
- GLsizei imageSize, const GLvoid *data,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
- 0, 0, data, &ctx->Unpack, texObj, texImage, imageSize, GL_TRUE);
-}
-
-
-
-/**
- * glGetTexImage() helper: decompress a compressed texture by rendering
- * a textured quad. Store the results in the user's buffer.
- */
-static void
-decompress_with_blit(struct gl_context * ctx, GLenum target, GLint level,
- GLenum format, GLenum type, GLvoid *pixels,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct st_texture_image *stImage = st_texture_image(texImage);
- struct st_texture_object *stObj = st_texture_object(texObj);
- struct pipe_sampler_view *src_view =
- st_get_texture_sampler_view(stObj, pipe);
- const GLuint width = texImage->Width;
- const GLuint height = texImage->Height;
- struct pipe_surface *dst_surface;
- struct pipe_resource *dst_texture;
- struct pipe_transfer *tex_xfer;
- unsigned bind = (PIPE_BIND_RENDER_TARGET | /* util_blit may choose to render */
- PIPE_BIND_TRANSFER_READ);
-
- /* create temp / dest surface */
- if (!util_create_rgba_surface(pipe, width, height, bind,
- &dst_texture, &dst_surface)) {
- _mesa_problem(ctx, "util_create_rgba_surface() failed "
- "in decompress_with_blit()");
- return;
- }
-
- /* blit/render/decompress */
- util_blit_pixels_tex(st->blit,
- src_view, /* pipe_resource (src) */
- 0, 0, /* src x0, y0 */
- width, height, /* src x1, y1 */
- dst_surface, /* pipe_surface (dst) */
- 0, 0, /* dst x0, y0 */
- width, height, /* dst x1, y1 */
- 0.0, /* z */
- PIPE_TEX_MIPFILTER_NEAREST);
-
- /* map the dst_surface so we can read from it */
- tex_xfer = pipe_get_transfer(st_context(ctx)->pipe,
- dst_texture, 0, 0,
- PIPE_TRANSFER_READ,
- 0, 0, width, height);
-
- pixels = _mesa_map_pbo_dest(ctx, &ctx->Pack, pixels);
-
- /* copy/pack data into user buffer */
- if (st_equal_formats(stImage->pt->format, format, type)) {
- /* memcpy */
- const uint bytesPerRow = width * util_format_get_blocksize(stImage->pt->format);
- ubyte *map = pipe_transfer_map(pipe, tex_xfer);
- GLuint row;
- for (row = 0; row < height; row++) {
- GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
- height, format, type, row, 0);
- memcpy(dest, map, bytesPerRow);
- map += tex_xfer->stride;
- }
- pipe_transfer_unmap(pipe, tex_xfer);
- }
- else {
- /* format translation via floats */
- GLuint row;
- enum pipe_format format = util_format_linear(dst_texture->format);
- for (row = 0; row < height; row++) {
- const GLbitfield transferOps = 0x0; /* bypassed for glGetTexImage() */
- GLfloat rgba[4 * MAX_WIDTH];
- GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
- height, format, type, row, 0);
-
- if (ST_DEBUG & DEBUG_FALLBACK)
- debug_printf("%s: fallback format translation\n", __FUNCTION__);
-
- /* get float[4] rgba row from surface */
- pipe_get_tile_rgba_format(pipe, tex_xfer, 0, row, width, 1,
- format, rgba);
-
- _mesa_pack_rgba_span_float(ctx, width, (GLfloat (*)[4]) rgba, format,
- type, dest, &ctx->Pack, transferOps);
- }
- }
-
- _mesa_unmap_pbo_dest(ctx, &ctx->Pack);
-
- pipe->transfer_destroy(pipe, tex_xfer);
-
- /* destroy the temp / dest surface */
- util_destroy_rgba_surface(dst_texture, dst_surface);
-}
-
-
-
-/**
- * Need to map texture image into memory before copying image data,
- * then unmap it.
- */
-static void
-st_get_tex_image(struct gl_context * ctx, GLenum target, GLint level,
- GLenum format, GLenum type, GLvoid * pixels,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage, GLboolean compressed_dst)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_image *stImage = st_texture_image(texImage);
- const GLuint dstImageStride =
- _mesa_image_image_stride(&ctx->Pack, texImage->Width, texImage->Height,
- format, type);
- GLuint depth, i;
- GLubyte *dest;
-
- if (stImage->pt &&
- util_format_is_s3tc(stImage->pt->format) &&
- !compressed_dst) {
- /* Need to decompress the texture.
- * We'll do this by rendering a textured quad.
- * Note that we only expect RGBA formats (no Z/depth formats).
- */
- decompress_with_blit(ctx, target, level, format, type, pixels,
- texObj, texImage);
- return;
- }
-
- /* Map */
- if (stImage->pt) {
- /* Image is stored in hardware format in a buffer managed by the
- * kernel. Need to explicitly map and unmap it.
- */
- texImage->Data = st_texture_image_map(st, stImage, 0,
- PIPE_TRANSFER_READ, 0, 0,
- stImage->base.Width,
- stImage->base.Height);
- /* compute stride in texels from stride in bytes */
- texImage->RowStride = stImage->transfer->stride
- * util_format_get_blockwidth(stImage->pt->format)
- / util_format_get_blocksize(stImage->pt->format);
- }
- else {
- /* Otherwise, the image should actually be stored in
- * texImage->Data. This is pretty confusing for
- * everybody, I'd much prefer to separate the two functions of
- * texImage->Data - storage for texture images in main memory
- * and access (ie mappings) of images. In other words, we'd
- * create a new texImage->Map field and leave Data simply for
- * storage.
- */
- assert(texImage->Data);
- }
-
- depth = texImage->Depth;
- texImage->Depth = 1;
-
- dest = (GLubyte *) pixels;
-
- _mesa_set_fetch_functions(texImage, get_texture_dims(target));
-
- for (i = 0; i < depth; i++) {
- if (compressed_dst) {
- _mesa_get_compressed_teximage(ctx, target, level, dest,
- texObj, texImage);
- }
- else {
- _mesa_get_teximage(ctx, target, level, format, type, dest,
- texObj, texImage);
- }
-
- if (stImage->pt && i + 1 < depth) {
- /* unmap this slice */
- st_texture_image_unmap(st, stImage);
- /* map next slice of 3D texture */
- texImage->Data = st_texture_image_map(st, stImage, i + 1,
- PIPE_TRANSFER_READ, 0, 0,
- stImage->base.Width,
- stImage->base.Height);
- dest += dstImageStride;
- }
- }
-
- texImage->Depth = depth;
-
- /* Unmap */
- if (stImage->pt) {
- st_texture_image_unmap(st, stImage);
- texImage->Data = NULL;
- }
-}
-
-
-static void
-st_GetTexImage(struct gl_context * ctx, GLenum target, GLint level,
- GLenum format, GLenum type, GLvoid * pixels,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_get_tex_image(ctx, target, level, format, type, pixels, texObj, texImage,
- GL_FALSE);
-}
-
-
-static void
-st_GetCompressedTexImage(struct gl_context *ctx, GLenum target, GLint level,
- GLvoid *pixels,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_get_tex_image(ctx, target, level, 0, 0, pixels, texObj, texImage,
- GL_TRUE);
-}
-
-
-
-static void
-st_TexSubimage(struct gl_context *ctx, GLint dims, GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLint width, GLint height, GLint depth,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *packing,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_screen *screen = st->pipe->screen;
- struct st_texture_image *stImage = st_texture_image(texImage);
- GLuint dstRowStride;
- const GLuint srcImageStride =
- _mesa_image_image_stride(packing, width, height, format, type);
- GLint i;
- const GLubyte *src;
- /* init to silence warning only: */
- enum pipe_transfer_usage transfer_usage = PIPE_TRANSFER_WRITE;
-
- DBG("%s target %s level %d offset %d,%d %dx%d\n", __FUNCTION__,
- _mesa_lookup_enum_by_nr(target),
- level, xoffset, yoffset, width, height);
-
- pixels =
- _mesa_validate_pbo_teximage(ctx, dims, width, height, depth, format,
- type, pixels, packing, "glTexSubImage2D");
- if (!pixels)
- return;
-
- /* See if we can do texture compression with a blit/render.
- */
- if (!ctx->Mesa_DXTn &&
- _mesa_is_format_compressed(texImage->TexFormat) &&
- screen->is_format_supported(screen,
- stImage->pt->format,
- stImage->pt->target, 0,
- PIPE_BIND_RENDER_TARGET, 0)) {
- if (compress_with_blit(ctx, target, level,
- xoffset, yoffset, zoffset,
- width, height, depth,
- format, type, pixels, packing, texImage)) {
- goto done;
- }
- }
-
- /* Map buffer if necessary. Need to lock to prevent other contexts
- * from uploading the buffer under us.
- */
- if (stImage->pt) {
- if (format == GL_DEPTH_COMPONENT &&
- util_format_is_depth_and_stencil(stImage->pt->format))
- transfer_usage = PIPE_TRANSFER_READ_WRITE;
- else
- transfer_usage = PIPE_TRANSFER_WRITE;
-
- texImage->Data = st_texture_image_map(st, stImage, zoffset,
- transfer_usage,
- xoffset, yoffset,
- width, height);
- }
-
- if (!texImage->Data) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
- goto done;
- }
-
- src = (const GLubyte *) pixels;
- dstRowStride = stImage->transfer->stride;
-
- for (i = 0; i < depth; i++) {
- if (!_mesa_texstore(ctx, dims, texImage->_BaseFormat,
- texImage->TexFormat,
- texImage->Data,
- 0, 0, 0,
- dstRowStride,
- texImage->ImageOffsets,
- width, height, 1,
- format, type, src, packing)) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
- }
-
- if (stImage->pt && i + 1 < depth) {
- /* unmap this slice */
- st_texture_image_unmap(st, stImage);
- /* map next slice of 3D texture */
- texImage->Data = st_texture_image_map(st, stImage,
- zoffset + i + 1,
- transfer_usage,
- xoffset, yoffset,
- width, height);
- src += srcImageStride;
- }
- }
-
-done:
- _mesa_unmap_teximage_pbo(ctx, packing);
-
- if (stImage->pt && texImage->Data) {
- st_texture_image_unmap(st, stImage);
- texImage->Data = NULL;
- }
-}
-
-
-
-static void
-st_TexSubImage3D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLsizei width, GLsizei height, GLsizei depth,
- GLenum format, GLenum type, const GLvoid *pixels,
- const struct gl_pixelstore_attrib *packing,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexSubimage(ctx, 3, target, level, xoffset, yoffset, zoffset,
- width, height, depth, format, type,
- pixels, packing, texObj, texImage);
-}
-
-
-static void
-st_TexSubImage2D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset,
- GLsizei width, GLsizei height,
- GLenum format, GLenum type, const GLvoid * pixels,
- const struct gl_pixelstore_attrib *packing,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexSubimage(ctx, 2, target, level, xoffset, yoffset, 0,
- width, height, 1, format, type,
- pixels, packing, texObj, texImage);
-}
-
-
-static void
-st_TexSubImage1D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLsizei width, GLenum format, GLenum type,
- const GLvoid * pixels,
- const struct gl_pixelstore_attrib *packing,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexSubimage(ctx, 1, target, level, xoffset, 0, 0, width, 1, 1,
- format, type, pixels, packing, texObj, texImage);
-}
-
-
-static void
-st_CompressedTexSubImage1D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLsizei width,
- GLenum format,
- GLsizei imageSize, const GLvoid *data,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- assert(0);
-}
-
-
-static void
-st_CompressedTexSubImage2D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset,
- GLsizei width, GLint height,
- GLenum format,
- GLsizei imageSize, const GLvoid *data,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_image *stImage = st_texture_image(texImage);
- int srcBlockStride;
- int dstBlockStride;
- int y;
- enum pipe_format pformat;
-
- if (stImage->pt) {
- pformat = stImage->pt->format;
-
- texImage->Data = st_texture_image_map(st, stImage, 0,
- PIPE_TRANSFER_WRITE,
- xoffset, yoffset,
- width, height);
-
- srcBlockStride = util_format_get_stride(pformat, width);
- dstBlockStride = stImage->transfer->stride;
- } else {
- assert(stImage->pt);
- /* TODO find good values for block and strides */
- /* TODO also adjust texImage->data for yoffset/xoffset */
- return;
- }
-
- if (!texImage->Data) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage");
- return;
- }
-
- assert(xoffset % util_format_get_blockwidth(pformat) == 0);
- assert(yoffset % util_format_get_blockheight(pformat) == 0);
-
- for (y = 0; y < height; y += util_format_get_blockheight(pformat)) {
- /* don't need to adjust for xoffset and yoffset as st_texture_image_map does that */
- const char *src = (const char*)data + srcBlockStride * util_format_get_nblocksy(pformat, y);
- char *dst = (char*)texImage->Data + dstBlockStride * util_format_get_nblocksy(pformat, y);
- memcpy(dst, src, util_format_get_stride(pformat, width));
- }
-
- if (stImage->pt) {
- st_texture_image_unmap(st, stImage);
- texImage->Data = NULL;
- }
-}
-
-
-static void
-st_CompressedTexSubImage3D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLsizei width, GLint height, GLint depth,
- GLenum format,
- GLsizei imageSize, const GLvoid *data,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- assert(0);
-}
-
-
-
-/**
- * Do a CopyTexSubImage operation using a read transfer from the source,
- * a write transfer to the destination and get_tile()/put_tile() to access
- * the pixels/texels.
- *
- * Note: srcY=0=TOP of renderbuffer
- */
-static void
-fallback_copy_texsubimage(struct gl_context *ctx, GLenum target, GLint level,
- struct st_renderbuffer *strb,
- struct st_texture_image *stImage,
- GLenum baseFormat,
- GLint destX, GLint destY, GLint destZ,
- GLint srcX, GLint srcY,
- GLsizei width, GLsizei height)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct pipe_transfer *src_trans;
- GLvoid *texDest;
- enum pipe_transfer_usage transfer_usage;
-
- if (ST_DEBUG & DEBUG_FALLBACK)
- debug_printf("%s: fallback processing\n", __FUNCTION__);
-
- assert(width <= MAX_WIDTH);
-
- if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
- srcY = strb->Base.Height - srcY - height;
- }
-
- src_trans = pipe_get_transfer(st_context(ctx)->pipe,
- strb->texture,
- 0, 0,
- PIPE_TRANSFER_READ,
- srcX, srcY,
- width, height);
-
- if ((baseFormat == GL_DEPTH_COMPONENT ||
- baseFormat == GL_DEPTH_STENCIL) &&
- util_format_is_depth_and_stencil(stImage->pt->format))
- transfer_usage = PIPE_TRANSFER_READ_WRITE;
- else
- transfer_usage = PIPE_TRANSFER_WRITE;
-
- /* XXX this used to ignore destZ param */
- texDest = st_texture_image_map(st, stImage, destZ, transfer_usage,
- destX, destY, width, height);
-
- if (baseFormat == GL_DEPTH_COMPONENT ||
- baseFormat == GL_DEPTH_STENCIL) {
- const GLboolean scaleOrBias = (ctx->Pixel.DepthScale != 1.0F ||
- ctx->Pixel.DepthBias != 0.0F);
- GLint row, yStep;
-
- /* determine bottom-to-top vs. top-to-bottom order for src buffer */
- if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
- srcY = height - 1;
- yStep = -1;
- }
- else {
- srcY = 0;
- yStep = 1;
- }
-
- /* To avoid a large temp memory allocation, do copy row by row */
- for (row = 0; row < height; row++, srcY += yStep) {
- uint data[MAX_WIDTH];
- pipe_get_tile_z(pipe, src_trans, 0, srcY, width, 1, data);
- if (scaleOrBias) {
- _mesa_scale_and_bias_depth_uint(ctx, width, data);
- }
- pipe_put_tile_z(pipe, stImage->transfer, 0, row, width, 1, data);
- }
- }
- else {
- /* RGBA format */
- GLfloat *tempSrc =
- (GLfloat *) malloc(width * height * 4 * sizeof(GLfloat));
-
- if (tempSrc && texDest) {
- const GLint dims = 2;
- const GLint dstRowStride = stImage->transfer->stride;
- struct gl_texture_image *texImage = &stImage->base;
- struct gl_pixelstore_attrib unpack = ctx->DefaultPacking;
-
- if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
- unpack.Invert = GL_TRUE;
- }
-
- /* get float/RGBA image from framebuffer */
- /* XXX this usually involves a lot of int/float conversion.
- * try to avoid that someday.
- */
- pipe_get_tile_rgba_format(pipe, src_trans, 0, 0, width, height,
- util_format_linear(strb->texture->format),
- tempSrc);
-
- /* Store into texture memory.
- * Note that this does some special things such as pixel transfer
- * ops and format conversion. In particular, if the dest tex format
- * is actually RGBA but the user created the texture as GL_RGB we
- * need to fill-in/override the alpha channel with 1.0.
- */
- _mesa_texstore(ctx, dims,
- texImage->_BaseFormat,
- texImage->TexFormat,
- texDest,
- 0, 0, 0,
- dstRowStride,
- texImage->ImageOffsets,
- width, height, 1,
- GL_RGBA, GL_FLOAT, tempSrc, /* src */
- &unpack);
- }
- else {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
- }
-
- if (tempSrc)
- free(tempSrc);
- }
-
- st_texture_image_unmap(st, stImage);
- pipe->transfer_destroy(pipe, src_trans);
-}
-
-
-
-/**
- * If the format of the src renderbuffer and the format of the dest
- * texture are compatible (in terms of blitting), return a TGSI writemask
- * to be used during the blit.
- * If the src/dest are incompatible, return 0.
- */
-static unsigned
-compatible_src_dst_formats(struct gl_context *ctx,
- const struct gl_renderbuffer *src,
- const struct gl_texture_image *dst)
-{
- /* Get logical base formats for the src and dest.
- * That is, use the user-requested formats and not the actual, device-
- * chosen formats.
- * For example, the user may have requested an A8 texture but the
- * driver may actually be using an RGBA texture format. When we
- * copy/blit to that texture, we only want to copy the Alpha channel
- * and not the RGB channels.
- *
- * Similarly, when the src FBO was created an RGB format may have been
- * requested but the driver actually chose an RGBA format. In that case,
- * we don't want to copy the undefined Alpha channel to the dest texture
- * (it should be 1.0).
- */
- const GLenum srcFormat = _mesa_base_fbo_format(ctx, src->InternalFormat);
- const GLenum dstFormat = _mesa_base_tex_format(ctx, dst->InternalFormat);
-
- /**
- * XXX when we have red-only and red/green renderbuffers we'll need
- * to add more cases here (or implement a general-purpose routine that
- * queries the existance of the R,G,B,A channels in the src and dest).
- */
- if (srcFormat == dstFormat) {
- /* This is the same as matching_base_formats, which should
- * always pass, as it did previously.
- */
- return TGSI_WRITEMASK_XYZW;
- }
- else if (srcFormat == GL_RGB && dstFormat == GL_RGBA) {
- /* Make sure that A in the dest is 1. The actual src format
- * may be RGBA and have undefined A values.
- */
- return TGSI_WRITEMASK_XYZ;
- }
- else if (srcFormat == GL_RGBA && dstFormat == GL_RGB) {
- /* Make sure that A in the dest is 1. The actual dst format
- * may be RGBA and will need A=1 to provide proper alpha values
- * when sampled later.
- */
- return TGSI_WRITEMASK_XYZ;
- }
- else {
- if (ST_DEBUG & DEBUG_FALLBACK)
- debug_printf("%s failed for src %s, dst %s\n",
- __FUNCTION__,
- _mesa_lookup_enum_by_nr(srcFormat),
- _mesa_lookup_enum_by_nr(dstFormat));
-
- /* Otherwise fail.
- */
- return 0;
- }
-}
-
-
-
-/**
- * Do a CopyTex[Sub]Image1/2/3D() using a hardware (blit) path if possible.
- * Note that the region to copy has already been clipped so we know we
- * won't read from outside the source renderbuffer's bounds.
- *
- * Note: srcY=0=Bottom of renderbuffer (GL convention)
- */
-static void
-st_copy_texsubimage(struct gl_context *ctx,
- GLenum target, GLint level,
- GLint destX, GLint destY, GLint destZ,
- GLint srcX, GLint srcY,
- GLsizei width, GLsizei height)
-{
- struct gl_texture_unit *texUnit =
- &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
- struct gl_texture_object *texObj =
- _mesa_select_tex_object(ctx, texUnit, target);
- struct gl_texture_image *texImage =
- _mesa_select_tex_image(ctx, texObj, target, level);
- struct st_texture_image *stImage = st_texture_image(texImage);
- const GLenum texBaseFormat = texImage->_BaseFormat;
- struct gl_framebuffer *fb = ctx->ReadBuffer;
- struct st_renderbuffer *strb;
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct pipe_screen *screen = pipe->screen;
- enum pipe_format dest_format, src_format;
- GLboolean use_fallback = GL_TRUE;
- GLboolean matching_base_formats;
- GLuint format_writemask, sample_count;
- struct pipe_surface *dest_surface = NULL;
- GLboolean do_flip = (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP);
-
- /* make sure finalize_textures has been called?
- */
- if (0) st_validate_state(st);
-
- /* determine if copying depth or color data */
- if (texBaseFormat == GL_DEPTH_COMPONENT ||
- texBaseFormat == GL_DEPTH_STENCIL) {
- strb = st_renderbuffer(fb->_DepthBuffer);
- if (strb->Base.Wrapped) {
- strb = st_renderbuffer(strb->Base.Wrapped);
- }
- }
- else {
- /* texBaseFormat == GL_RGB, GL_RGBA, GL_ALPHA, etc */
- strb = st_renderbuffer(fb->_ColorReadBuffer);
- }
-
- if (!strb || !strb->surface || !stImage->pt) {
- debug_printf("%s: null strb or stImage\n", __FUNCTION__);
- return;
- }
-
- sample_count = strb->surface->texture->nr_samples;
- /* I believe this would be legal, presumably would need to do a resolve
- for color, and for depth/stencil spec says to just use one of the
- depth/stencil samples per pixel? Need some transfer clarifications. */
- assert(sample_count < 2);
-
- if (srcX < 0) {
- width -= -srcX;
- destX += -srcX;
- srcX = 0;
- }
-
- if (srcY < 0) {
- height -= -srcY;
- destY += -srcY;
- srcY = 0;
- }
-
- if (destX < 0) {
- width -= -destX;
- srcX += -destX;
- destX = 0;
- }
-
- if (destY < 0) {
- height -= -destY;
- srcY += -destY;
- destY = 0;
- }
-
- if (width < 0 || height < 0)
- return;
-
-
- assert(strb);
- assert(strb->surface);
- assert(stImage->pt);
-
- src_format = strb->surface->format;
- dest_format = stImage->pt->format;
-
- /*
- * Determine if the src framebuffer and dest texture have the same
- * base format. We need this to detect a case such as the framebuffer
- * being GL_RGBA but the texture being GL_RGB. If the actual hardware
- * texture format stores RGBA we need to set A=1 (overriding the
- * framebuffer's alpha values). We can't do that with the blit or
- * textured-quad paths.
- */
- matching_base_formats =
- (_mesa_get_format_base_format(strb->Base.Format) ==
- _mesa_get_format_base_format(texImage->TexFormat));
- format_writemask = compatible_src_dst_formats(ctx, &strb->Base, texImage);
-
- if (ctx->_ImageTransferState == 0x0) {
-
- if (matching_base_formats &&
- src_format == dest_format &&
- !do_flip)
- {
- /* use surface_copy() / blit */
- struct pipe_box src_box;
- u_box_2d_zslice(srcX, srcY, strb->surface->u.tex.first_layer,
- width, height, &src_box);
-
- /* for resource_copy_region(), y=0=top, always */
- pipe->resource_copy_region(pipe,
- /* dest */
- stImage->pt,
- stImage->level,
- destX, destY, destZ + stImage->face,
- /* src */
- strb->texture,
- strb->surface->u.tex.level,
- &src_box);
- use_fallback = GL_FALSE;
- }
- else if (format_writemask &&
- texBaseFormat != GL_DEPTH_COMPONENT &&
- texBaseFormat != GL_DEPTH_STENCIL &&
- screen->is_format_supported(screen, src_format,
- PIPE_TEXTURE_2D, sample_count,
- PIPE_BIND_SAMPLER_VIEW,
- 0) &&
- screen->is_format_supported(screen, dest_format,
- PIPE_TEXTURE_2D, 0,
- PIPE_BIND_RENDER_TARGET,
- 0)) {
- /* draw textured quad to do the copy */
- GLint srcY0, srcY1;
- struct pipe_surface surf_tmpl;
- memset(&surf_tmpl, 0, sizeof(surf_tmpl));
- surf_tmpl.format = stImage->pt->format;
- surf_tmpl.usage = PIPE_BIND_RENDER_TARGET;
- surf_tmpl.u.tex.level = stImage->level;
- surf_tmpl.u.tex.first_layer = stImage->face + destZ;
- surf_tmpl.u.tex.last_layer = stImage->face + destZ;
-
- dest_surface = pipe->create_surface(pipe, stImage->pt,
- &surf_tmpl);
-
- if (do_flip) {
- srcY1 = strb->Base.Height - srcY - height;
- srcY0 = srcY1 + height;
- }
- else {
- srcY0 = srcY;
- srcY1 = srcY0 + height;
- }
-
- util_blit_pixels_writemask(st->blit,
- strb->texture,
- strb->surface->u.tex.level,
- srcX, srcY0,
- srcX + width, srcY1,
- strb->surface->u.tex.first_layer,
- dest_surface,
- destX, destY,
- destX + width, destY + height,
- 0.0, PIPE_TEX_MIPFILTER_NEAREST,
- format_writemask);
- use_fallback = GL_FALSE;
- }
-
- if (dest_surface)
- pipe_surface_reference(&dest_surface, NULL);
- }
-
- if (use_fallback) {
- /* software fallback */
- fallback_copy_texsubimage(ctx, target, level,
- strb, stImage, texBaseFormat,
- destX, destY, destZ,
- srcX, srcY, width, height);
- }
-}
-
-
-
-static void
-st_CopyTexImage1D(struct gl_context * ctx, GLenum target, GLint level,
- GLenum internalFormat,
- GLint x, GLint y, GLsizei width, GLint border)
-{
- struct gl_texture_unit *texUnit =
- &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
- struct gl_texture_object *texObj =
- _mesa_select_tex_object(ctx, texUnit, target);
- struct gl_texture_image *texImage =
- _mesa_select_tex_image(ctx, texObj, target, level);
-
- /* Setup or redefine the texture object, texture and texture
- * image. Don't populate yet.
- */
- ctx->Driver.TexImage1D(ctx, target, level, internalFormat,
- width, border,
- GL_RGBA, CHAN_TYPE, NULL,
- &ctx->DefaultPacking, texObj, texImage);
-
- st_copy_texsubimage(ctx, target, level,
- 0, 0, 0, /* destX,Y,Z */
- x, y, width, 1); /* src X, Y, size */
-}
-
-
-static void
-st_CopyTexImage2D(struct gl_context * ctx, GLenum target, GLint level,
- GLenum internalFormat,
- GLint x, GLint y, GLsizei width, GLsizei height,
- GLint border)
-{
- struct gl_texture_unit *texUnit =
- &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
- struct gl_texture_object *texObj =
- _mesa_select_tex_object(ctx, texUnit, target);
- struct gl_texture_image *texImage =
- _mesa_select_tex_image(ctx, texObj, target, level);
-
- /* Setup or redefine the texture object, texture and texture
- * image. Don't populate yet.
- */
- ctx->Driver.TexImage2D(ctx, target, level, internalFormat,
- width, height, border,
- GL_RGBA, CHAN_TYPE, NULL,
- &ctx->DefaultPacking, texObj, texImage);
-
- st_copy_texsubimage(ctx, target, level,
- 0, 0, 0, /* destX,Y,Z */
- x, y, width, height); /* src X, Y, size */
-}
-
-
-static void
-st_CopyTexSubImage1D(struct gl_context * ctx, GLenum target, GLint level,
- GLint xoffset, GLint x, GLint y, GLsizei width)
-{
- const GLint yoffset = 0, zoffset = 0;
- const GLsizei height = 1;
- st_copy_texsubimage(ctx, target, level,
- xoffset, yoffset, zoffset, /* destX,Y,Z */
- x, y, width, height); /* src X, Y, size */
-}
-
-
-static void
-st_CopyTexSubImage2D(struct gl_context * ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset,
- GLint x, GLint y, GLsizei width, GLsizei height)
-{
- const GLint zoffset = 0;
- st_copy_texsubimage(ctx, target, level,
- xoffset, yoffset, zoffset, /* destX,Y,Z */
- x, y, width, height); /* src X, Y, size */
-}
-
-
-static void
-st_CopyTexSubImage3D(struct gl_context * ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLint x, GLint y, GLsizei width, GLsizei height)
-{
- st_copy_texsubimage(ctx, target, level,
- xoffset, yoffset, zoffset, /* destX,Y,Z */
- x, y, width, height); /* src X, Y, size */
-}
-
-
-/**
- * Copy image data from stImage into the texture object 'stObj' at level
- * 'dstLevel'.
- */
-static void
-copy_image_data_to_texture(struct st_context *st,
- struct st_texture_object *stObj,
- GLuint dstLevel,
- struct st_texture_image *stImage)
-{
- /* debug checks */
- {
- const struct gl_texture_image *dstImage =
- stObj->base.Image[stImage->face][stImage->level];
- assert(dstImage);
- assert(dstImage->Width == stImage->base.Width);
- assert(dstImage->Height == stImage->base.Height);
- assert(dstImage->Depth == stImage->base.Depth);
- }
-
- if (stImage->pt) {
- /* Copy potentially with the blitter:
- */
- st_texture_image_copy(st->pipe,
- stObj->pt, dstLevel, /* dest texture, level */
- stImage->pt, stImage->level, /* src texture, level */
- stImage->face);
-
- pipe_resource_reference(&stImage->pt, NULL);
- }
- else if (stImage->base.Data) {
- st_texture_image_data(st,
- stObj->pt,
- stImage->face,
- dstLevel,
- stImage->base.Data,
- stImage->base.RowStride *
- util_format_get_blocksize(stObj->pt->format),
- stImage->base.RowStride *
- stImage->base.Height *
- util_format_get_blocksize(stObj->pt->format));
- _mesa_align_free(stImage->base.Data);
- stImage->base.Data = NULL;
- }
-
- pipe_resource_reference(&stImage->pt, stObj->pt);
-}
-
-
-/**
- * Called during state validation. When this function is finished,
- * the texture object should be ready for rendering.
- * \return GL_TRUE for success, GL_FALSE for failure (out of mem)
- */
-GLboolean
-st_finalize_texture(struct gl_context *ctx,
- struct pipe_context *pipe,
- struct gl_texture_object *tObj)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_object *stObj = st_texture_object(tObj);
- const GLuint nr_faces = (stObj->base.Target == GL_TEXTURE_CUBE_MAP) ? 6 : 1;
- GLuint face;
- struct st_texture_image *firstImage;
- enum pipe_format firstImageFormat;
-
- if (stObj->base._Complete) {
- /* The texture is complete and we know exactly how many mipmap levels
- * are present/needed. This is conditional because we may be called
- * from the st_generate_mipmap() function when the texture object is
- * incomplete. In that case, we'll have set stObj->lastLevel before
- * we get here.
- */
- if (stObj->base.MinFilter == GL_LINEAR ||
- stObj->base.MinFilter == GL_NEAREST)
- stObj->lastLevel = stObj->base.BaseLevel;
- else
- stObj->lastLevel = stObj->base._MaxLevel;
- }
-
- firstImage = st_texture_image(stObj->base.Image[0][stObj->base.BaseLevel]);
- assert(firstImage);
-
- /* If both firstImage and stObj point to a texture which can contain
- * all active images, favour firstImage. Note that because of the
- * completeness requirement, we know that the image dimensions
- * will match.
- */
- if (firstImage->pt &&
- firstImage->pt != stObj->pt &&
- (!stObj->pt || firstImage->pt->last_level >= stObj->pt->last_level)) {
- pipe_resource_reference(&stObj->pt, firstImage->pt);
- pipe_sampler_view_reference(&stObj->sampler_view, NULL);
- }
-
- /* Find gallium format for the Mesa texture */
- firstImageFormat = st_mesa_format_to_pipe_format(firstImage->base.TexFormat);
-
- /* If we already have a gallium texture, check that it matches the texture
- * object's format, target, size, num_levels, etc.
- */
- if (stObj->pt) {
- if (stObj->pt->target != gl_target_to_pipe(stObj->base.Target) ||
- !st_sampler_compat_formats(stObj->pt->format, firstImageFormat) ||
- stObj->pt->last_level < stObj->lastLevel ||
- stObj->pt->width0 != stObj->width0 ||
- stObj->pt->height0 != stObj->height0 ||
- stObj->pt->depth0 != stObj->depth0)
- {
- /* The gallium texture does not match the Mesa texture so delete the
- * gallium texture now. We'll make a new one below.
- */
- pipe_resource_reference(&stObj->pt, NULL);
- pipe_sampler_view_reference(&stObj->sampler_view, NULL);
- st->dirty.st |= ST_NEW_FRAMEBUFFER;
- }
- }
-
- /* May need to create a new gallium texture:
- */
- if (!stObj->pt) {
- GLuint bindings = default_bindings(st, firstImageFormat);
-
- stObj->pt = st_texture_create(st,
- gl_target_to_pipe(stObj->base.Target),
- firstImageFormat,
- stObj->lastLevel,
- stObj->width0,
- stObj->height0,
- stObj->depth0,
- bindings);
-
- if (!stObj->pt) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
- return GL_FALSE;
- }
- }
-
- /* Pull in any images not in the object's texture:
- */
- for (face = 0; face < nr_faces; face++) {
- GLuint level;
- for (level = stObj->base.BaseLevel; level <= stObj->lastLevel; level++) {
- struct st_texture_image *stImage =
- st_texture_image(stObj->base.Image[face][level]);
-
- /* Need to import images in main memory or held in other textures.
- */
- if (stImage && stObj->pt != stImage->pt) {
- copy_image_data_to_texture(st, stObj, level, stImage);
- }
- }
- }
-
- return GL_TRUE;
-}
-
-
-/**
- * Returns pointer to a default/dummy texture.
- * This is typically used when the current shader has tex/sample instructions
- * but the user has not provided a (any) texture(s).
- */
-struct gl_texture_object *
-st_get_default_texture(struct st_context *st)
-{
- if (!st->default_texture) {
- static const GLenum target = GL_TEXTURE_2D;
- GLubyte pixels[16][16][4];
- struct gl_texture_object *texObj;
- struct gl_texture_image *texImg;
- GLuint i, j;
-
- /* The ARB_fragment_program spec says (0,0,0,1) should be returned
- * when attempting to sample incomplete textures.
- */
- for (i = 0; i < 16; i++) {
- for (j = 0; j < 16; j++) {
- pixels[i][j][0] = 0;
- pixels[i][j][1] = 0;
- pixels[i][j][2] = 0;
- pixels[i][j][3] = 255;
- }
- }
-
- texObj = st->ctx->Driver.NewTextureObject(st->ctx, 0, target);
-
- texImg = _mesa_get_tex_image(st->ctx, texObj, target, 0);
-
- _mesa_init_teximage_fields(st->ctx, target, texImg,
- 16, 16, 1, 0, /* w, h, d, border */
- GL_RGBA, MESA_FORMAT_RGBA8888);
-
- st_TexImage(st->ctx, 2, target,
- 0, GL_RGBA, /* level, intformat */
- 16, 16, 1, 0, /* w, h, d, border */
- GL_RGBA, GL_UNSIGNED_BYTE, pixels,
- &st->ctx->DefaultPacking,
- texObj, texImg,
- 0, 0);
-
- texObj->MinFilter = GL_NEAREST;
- texObj->MagFilter = GL_NEAREST;
- texObj->_Complete = GL_TRUE;
-
- st->default_texture = texObj;
- }
- return st->default_texture;
-}
-
-
-void
-st_init_texture_functions(struct dd_function_table *functions)
-{
- functions->ChooseTextureFormat = st_ChooseTextureFormat;
- functions->TexImage1D = st_TexImage1D;
- functions->TexImage2D = st_TexImage2D;
- functions->TexImage3D = st_TexImage3D;
- functions->TexSubImage1D = st_TexSubImage1D;
- functions->TexSubImage2D = st_TexSubImage2D;
- functions->TexSubImage3D = st_TexSubImage3D;
- functions->CompressedTexSubImage1D = st_CompressedTexSubImage1D;
- functions->CompressedTexSubImage2D = st_CompressedTexSubImage2D;
- functions->CompressedTexSubImage3D = st_CompressedTexSubImage3D;
- functions->CopyTexImage1D = st_CopyTexImage1D;
- functions->CopyTexImage2D = st_CopyTexImage2D;
- functions->CopyTexSubImage1D = st_CopyTexSubImage1D;
- functions->CopyTexSubImage2D = st_CopyTexSubImage2D;
- functions->CopyTexSubImage3D = st_CopyTexSubImage3D;
- functions->GenerateMipmap = st_generate_mipmap;
-
- functions->GetTexImage = st_GetTexImage;
-
- /* compressed texture functions */
- functions->CompressedTexImage2D = st_CompressedTexImage2D;
- functions->GetCompressedTexImage = st_GetCompressedTexImage;
-
- functions->NewTextureObject = st_NewTextureObject;
- functions->NewTextureImage = st_NewTextureImage;
- functions->DeleteTexture = st_DeleteTextureObject;
- functions->FreeTexImageData = st_FreeTextureImageData;
-
- functions->TextureMemCpy = do_memcpy;
-
- /* XXX Temporary until we can query pipe's texture sizes */
- functions->TestProxyTexImage = _mesa_test_proxy_teximage;
-}
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sub license, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial portions
+ * of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ **************************************************************************/
+
+#include "main/mfeatures.h"
+#include "main/bufferobj.h"
+#include "main/enums.h"
+#include "main/fbobject.h"
+#include "main/formats.h"
+#include "main/image.h"
+#include "main/imports.h"
+#include "main/macros.h"
+#include "main/mipmap.h"
+#include "main/pack.h"
+#include "main/pixeltransfer.h"
+#include "main/texcompress.h"
+#include "main/texfetch.h"
+#include "main/texgetimage.h"
+#include "main/teximage.h"
+#include "main/texobj.h"
+#include "main/texstore.h"
+
+#include "state_tracker/st_debug.h"
+#include "state_tracker/st_context.h"
+#include "state_tracker/st_cb_fbo.h"
+#include "state_tracker/st_cb_flush.h"
+#include "state_tracker/st_cb_texture.h"
+#include "state_tracker/st_format.h"
+#include "state_tracker/st_texture.h"
+#include "state_tracker/st_gen_mipmap.h"
+#include "state_tracker/st_atom.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "util/u_inlines.h"
+#include "pipe/p_shader_tokens.h"
+#include "util/u_tile.h"
+#include "util/u_blit.h"
+#include "util/u_format.h"
+#include "util/u_surface.h"
+#include "util/u_sampler.h"
+#include "util/u_math.h"
+#include "util/u_box.h"
+
+#define DBG if (0) printf
+
+
+static enum pipe_texture_target
+gl_target_to_pipe(GLenum target)
+{
+ switch (target) {
+ case GL_TEXTURE_1D:
+ return PIPE_TEXTURE_1D;
+ case GL_TEXTURE_2D:
+ return PIPE_TEXTURE_2D;
+ case GL_TEXTURE_RECTANGLE_NV:
+ return PIPE_TEXTURE_RECT;
+ case GL_TEXTURE_3D:
+ return PIPE_TEXTURE_3D;
+ case GL_TEXTURE_CUBE_MAP_ARB:
+ return PIPE_TEXTURE_CUBE;
+ case GL_TEXTURE_1D_ARRAY_EXT:
+ return PIPE_TEXTURE_1D_ARRAY;
+ case GL_TEXTURE_2D_ARRAY_EXT:
+ return PIPE_TEXTURE_2D_ARRAY;
+ default:
+ assert(0);
+ return 0;
+ }
+}
+
+
+/** called via ctx->Driver.NewTextureImage() */
+static struct gl_texture_image *
+st_NewTextureImage(struct gl_context * ctx)
+{
+ DBG("%s\n", __FUNCTION__);
+ (void) ctx;
+ return (struct gl_texture_image *) ST_CALLOC_STRUCT(st_texture_image);
+}
+
+
+/** called via ctx->Driver.NewTextureObject() */
+static struct gl_texture_object *
+st_NewTextureObject(struct gl_context * ctx, GLuint name, GLenum target)
+{
+ struct st_texture_object *obj = ST_CALLOC_STRUCT(st_texture_object);
+
+ DBG("%s\n", __FUNCTION__);
+ _mesa_initialize_texture_object(&obj->base, name, target);
+
+ return &obj->base;
+}
+
+/** called via ctx->Driver.DeleteTextureObject() */
+static void
+st_DeleteTextureObject(struct gl_context *ctx,
+ struct gl_texture_object *texObj)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_object *stObj = st_texture_object(texObj);
+ if (stObj->pt)
+ pipe_resource_reference(&stObj->pt, NULL);
+ if (stObj->sampler_view) {
+ if (stObj->sampler_view->context != st->pipe) {
+ /* Take "ownership" of this texture sampler view by setting
+ * its context pointer to this context. This avoids potential
+ * crashes when the texture object is shared among contexts
+ * and the original/owner context has already been destroyed.
+ */
+ stObj->sampler_view->context = st->pipe;
+ }
+ pipe_sampler_view_reference(&stObj->sampler_view, NULL);
+ }
+ _mesa_delete_texture_object(ctx, texObj);
+}
+
+
+/** called via ctx->Driver.FreeTexImageData() */
+static void
+st_FreeTextureImageData(struct gl_context * ctx, struct gl_texture_image *texImage)
+{
+ struct st_texture_image *stImage = st_texture_image(texImage);
+
+ DBG("%s\n", __FUNCTION__);
+
+ if (stImage->pt) {
+ pipe_resource_reference(&stImage->pt, NULL);
+ }
+
+ if (texImage->Data) {
+ _mesa_align_free(texImage->Data);
+ texImage->Data = NULL;
+ }
+}
+
+
+/**
+ * From linux kernel i386 header files, copes with odd sizes better
+ * than COPY_DWORDS would:
+ * XXX Put this in src/mesa/main/imports.h ???
+ */
+#if defined(PIPE_CC_GCC) && defined(PIPE_ARCH_X86)
+static INLINE void *
+__memcpy(void *to, const void *from, size_t n)
+{
+ int d0, d1, d2;
+ __asm__ __volatile__("rep ; movsl\n\t"
+ "testb $2,%b4\n\t"
+ "je 1f\n\t"
+ "movsw\n"
+ "1:\ttestb $1,%b4\n\t"
+ "je 2f\n\t"
+ "movsb\n" "2:":"=&c"(d0), "=&D"(d1), "=&S"(d2)
+ :"0"(n / 4), "q"(n), "1"((long) to), "2"((long) from)
+ :"memory");
+ return (to);
+}
+#else
+#define __memcpy(a,b,c) memcpy(a,b,c)
+#endif
+
+
+/**
+ * The system memcpy (at least on ubuntu 5.10) has problems copying
+ * to agp (writecombined) memory from a source which isn't 64-byte
+ * aligned - there is a 4x performance falloff.
+ *
+ * The x86 __memcpy is immune to this but is slightly slower
+ * (10%-ish) than the system memcpy.
+ *
+ * The sse_memcpy seems to have a slight cliff at 64/32 bytes, but
+ * isn't much faster than x86_memcpy for agp copies.
+ *
+ * TODO: switch dynamically.
+ */
+static void *
+do_memcpy(void *dest, const void *src, size_t n)
+{
+ if ((((unsigned long) src) & 63) || (((unsigned long) dest) & 63)) {
+ return __memcpy(dest, src, n);
+ }
+ else
+ return memcpy(dest, src, n);
+}
+
+
+/**
+ * Return default texture resource binding bitmask for the given format.
+ */
+static GLuint
+default_bindings(struct st_context *st, enum pipe_format format)
+{
+ struct pipe_screen *screen = st->pipe->screen;
+ const unsigned target = PIPE_TEXTURE_2D;
+ const unsigned geom = 0x0;
+ unsigned bindings;
+
+ if (util_format_is_depth_or_stencil(format))
+ bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_DEPTH_STENCIL;
+ else
+ bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_RENDER_TARGET;
+
+ if (screen->is_format_supported(screen, format, target, 0, bindings, geom))
+ return bindings;
+ else
+ return PIPE_BIND_SAMPLER_VIEW;
+}
+
+
+/** Return number of image dimensions (1, 2 or 3) for a texture target. */
+static GLuint
+get_texture_dims(GLenum target)
+{
+ switch (target) {
+ case GL_TEXTURE_1D:
+ case GL_TEXTURE_1D_ARRAY_EXT:
+ return 1;
+ case GL_TEXTURE_2D:
+ case GL_TEXTURE_CUBE_MAP_ARB:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB:
+ case GL_TEXTURE_RECTANGLE_NV:
+ case GL_TEXTURE_2D_ARRAY_EXT:
+ return 2;
+ case GL_TEXTURE_3D:
+ return 3;
+ default:
+ assert(0 && "invalid texture target in get_texture_dims()");
+ return 1;
+ }
+}
+
+
+/**
+ * Try to allocate a pipe_resource object for the given st_texture_object.
+ *
+ * We use the given st_texture_image as a clue to determine the size of the
+ * mipmap image at level=0.
+ *
+ * \return GL_TRUE for success, GL_FALSE if out of memory.
+ */
+static GLboolean
+guess_and_alloc_texture(struct st_context *st,
+ struct st_texture_object *stObj,
+ const struct st_texture_image *stImage)
+{
+ const GLuint dims = get_texture_dims(stObj->base.Target);
+ GLuint level, lastLevel, width, height, depth;
+ GLuint bindings;
+ enum pipe_format fmt;
+
+ DBG("%s\n", __FUNCTION__);
+
+ assert(!stObj->pt);
+
+ level = stImage->level;
+ width = stImage->base.Width2; /* size w/out border */
+ height = stImage->base.Height2;
+ depth = stImage->base.Depth2;
+
+ assert(width > 0);
+ assert(height > 0);
+ assert(depth > 0);
+
+ /* Depending on the image's size, we can't always make a guess here.
+ */
+ if (level > 0) {
+ if ( (dims >= 1 && width == 1) ||
+ (dims >= 2 && height == 1) ||
+ (dims >= 3 && depth == 1) ) {
+ /* we can't determine the image size at level=0 */
+ stObj->width0 = stObj->height0 = stObj->depth0 = 0;
+ /* this is not an out of memory error */
+ return GL_TRUE;
+ }
+ }
+
+ /* grow the image size until we hit level = 0 */
+ while (level > 0) {
+ if (width != 1)
+ width <<= 1;
+ if (height != 1)
+ height <<= 1;
+ if (depth != 1)
+ depth <<= 1;
+ level--;
+ }
+
+ assert(level == 0);
+
+ /* At this point, (width x height x depth) is the expected size of
+ * the level=0 mipmap image.
+ */
+
+ /* Guess a reasonable value for lastLevel. With OpenGL we have no
+ * idea how many mipmap levels will be in a texture until we start
+ * to render with it. Make an educated guess here but be prepared
+ * to re-allocating a texture buffer with space for more (or fewer)
+ * mipmap levels later.
+ */
+ if ((stObj->base.MinFilter == GL_NEAREST ||
+ stObj->base.MinFilter == GL_LINEAR ||
+ stImage->base._BaseFormat == GL_DEPTH_COMPONENT ||
+ stImage->base._BaseFormat == GL_DEPTH_STENCIL_EXT) &&
+ !stObj->base.GenerateMipmap &&
+ stImage->level == 0) {
+ /* only alloc space for a single mipmap level */
+ lastLevel = 0;
+ }
+ else {
+ /* alloc space for a full mipmap */
+ GLuint l2width = util_logbase2(width);
+ GLuint l2height = util_logbase2(height);
+ GLuint l2depth = util_logbase2(depth);
+ lastLevel = MAX2(MAX2(l2width, l2height), l2depth);
+ }
+
+ /* Save the level=0 dimensions */
+ stObj->width0 = width;
+ stObj->height0 = height;
+ stObj->depth0 = depth;
+
+ fmt = st_mesa_format_to_pipe_format(stImage->base.TexFormat);
+
+ bindings = default_bindings(st, fmt);
+
+ stObj->pt = st_texture_create(st,
+ gl_target_to_pipe(stObj->base.Target),
+ fmt,
+ lastLevel,
+ width,
+ height,
+ depth,
+ bindings);
+
+ DBG("%s returning %d\n", __FUNCTION__, (stObj->pt != NULL));
+
+ return stObj->pt != NULL;
+}
+
+
+/**
+ * Adjust pixel unpack params and image dimensions to strip off the
+ * texture border.
+ * Gallium doesn't support texture borders. They've seldem been used
+ * and seldom been implemented correctly anyway.
+ * \param unpackNew returns the new pixel unpack parameters
+ */
+static void
+strip_texture_border(GLint border,
+ GLint *width, GLint *height, GLint *depth,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_pixelstore_attrib *unpackNew)
+{
+ assert(border > 0); /* sanity check */
+
+ *unpackNew = *unpack;
+
+ if (unpackNew->RowLength == 0)
+ unpackNew->RowLength = *width;
+
+ if (depth && unpackNew->ImageHeight == 0)
+ unpackNew->ImageHeight = *height;
+
+ unpackNew->SkipPixels += border;
+ if (height)
+ unpackNew->SkipRows += border;
+ if (depth)
+ unpackNew->SkipImages += border;
+
+ assert(*width >= 3);
+ *width = *width - 2 * border;
+ if (height && *height >= 3)
+ *height = *height - 2 * border;
+ if (depth && *depth >= 3)
+ *depth = *depth - 2 * border;
+}
+
+
+/**
+ * Try to do texture compression via rendering. If the Gallium driver
+ * can render into a compressed surface this will allow us to do texture
+ * compression.
+ * \return GL_TRUE for success, GL_FALSE for failure
+ */
+static GLboolean
+compress_with_blit(struct gl_context * ctx,
+ GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLint width, GLint height, GLint depth,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_texture_image *texImage)
+{
+ const GLuint dstImageOffsets[1] = {0};
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_screen *screen = pipe->screen;
+ gl_format mesa_format;
+ struct pipe_resource templ;
+ struct pipe_resource *src_tex;
+ struct pipe_sampler_view view_templ;
+ struct pipe_sampler_view *src_view;
+ struct pipe_surface *dst_surface, surf_tmpl;
+ struct pipe_transfer *tex_xfer;
+ void *map;
+
+ if (!stImage->pt) {
+ /* XXX: Can this happen? Should we assert? */
+ return GL_FALSE;
+ }
+
+ /* get destination surface (in the compressed texture) */
+ memset(&surf_tmpl, 0, sizeof(surf_tmpl));
+ surf_tmpl.format = stImage->pt->format;
+ surf_tmpl.usage = PIPE_BIND_RENDER_TARGET;
+ surf_tmpl.u.tex.level = stImage->level;
+ surf_tmpl.u.tex.first_layer = stImage->face;
+ surf_tmpl.u.tex.last_layer = stImage->face;
+ dst_surface = pipe->create_surface(pipe, stImage->pt, &surf_tmpl);
+ if (!dst_surface) {
+ /* can't render into this format (or other problem) */
+ return GL_FALSE;
+ }
+
+ /* Choose format for the temporary RGBA texture image.
+ */
+ mesa_format = st_ChooseTextureFormat(ctx, GL_RGBA, format, type);
+ assert(mesa_format);
+ if (!mesa_format)
+ return GL_FALSE;
+
+ /* Create the temporary source texture
+ */
+ memset(&templ, 0, sizeof(templ));
+ templ.target = st->internal_target;
+ templ.format = st_mesa_format_to_pipe_format(mesa_format);
+ templ.width0 = width;
+ templ.height0 = height;
+ templ.depth0 = 1;
+ templ.array_size = 1;
+ templ.last_level = 0;
+ templ.usage = PIPE_USAGE_DEFAULT;
+ templ.bind = PIPE_BIND_SAMPLER_VIEW;
+ src_tex = screen->resource_create(screen, &templ);
+
+ if (!src_tex)
+ return GL_FALSE;
+
+ /* Put user's tex data into the temporary texture
+ */
+ tex_xfer = pipe_get_transfer(st_context(ctx)->pipe, src_tex,
+ 0, 0, /* layer, level are zero */
+ PIPE_TRANSFER_WRITE,
+ 0, 0, width, height); /* x, y, w, h */
+ map = pipe_transfer_map(pipe, tex_xfer);
+
+ _mesa_texstore(ctx, 2, GL_RGBA, mesa_format,
+ map, /* dest ptr */
+ 0, 0, 0, /* dest x/y/z offset */
+ tex_xfer->stride, /* dest row stride (bytes) */
+ dstImageOffsets, /* image offsets (for 3D only) */
+ width, height, 1, /* size */
+ format, type, /* source format/type */
+ pixels, /* source data */
+ unpack); /* source data packing */
+
+ pipe_transfer_unmap(pipe, tex_xfer);
+ pipe->transfer_destroy(pipe, tex_xfer);
+
+ /* Create temporary sampler view */
+ u_sampler_view_default_template(&view_templ,
+ src_tex,
+ src_tex->format);
+ src_view = pipe->create_sampler_view(pipe, src_tex, &view_templ);
+
+
+ /* copy / compress image */
+ util_blit_pixels_tex(st->blit,
+ src_view, /* sampler view (src) */
+ 0, 0, /* src x0, y0 */
+ width, height, /* src x1, y1 */
+ dst_surface, /* pipe_surface (dst) */
+ xoffset, yoffset, /* dst x0, y0 */
+ xoffset + width, /* dst x1 */
+ yoffset + height, /* dst y1 */
+ 0.0, /* z */
+ PIPE_TEX_MIPFILTER_NEAREST);
+
+ pipe_surface_reference(&dst_surface, NULL);
+ pipe_resource_reference(&src_tex, NULL);
+ pipe_sampler_view_reference(&src_view, NULL);
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Do glTexImage1/2/3D().
+ */
+static void
+st_TexImage(struct gl_context * ctx,
+ GLint dims,
+ GLenum target, GLint level,
+ GLint internalFormat,
+ GLint width, GLint height, GLint depth,
+ GLint border,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage,
+ GLsizei imageSize, GLboolean compressed_src)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_screen *screen = st->pipe->screen;
+ struct st_texture_object *stObj = st_texture_object(texObj);
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ GLuint dstRowStride = 0;
+ struct gl_pixelstore_attrib unpackNB;
+ enum pipe_transfer_usage transfer_usage = 0;
+
+ DBG("%s target %s level %d %dx%dx%d border %d\n", __FUNCTION__,
+ _mesa_lookup_enum_by_nr(target), level, width, height, depth, border);
+
+ /* switch to "normal" */
+ if (stObj->surface_based) {
+ gl_format texFormat;
+
+ _mesa_clear_texture_object(ctx, texObj);
+ pipe_resource_reference(&stObj->pt, NULL);
+
+ /* oops, need to init this image again */
+ texFormat = _mesa_choose_texture_format(ctx, texObj, target, level,
+ internalFormat, format, type);
+
+ _mesa_init_teximage_fields(ctx, target, texImage,
+ width, height, depth, border,
+ internalFormat, texFormat);
+
+ stObj->surface_based = GL_FALSE;
+ }
+
+ /* gallium does not support texture borders, strip it off */
+ if (border) {
+ strip_texture_border(border, &width, &height, &depth, unpack, &unpackNB);
+ unpack = &unpackNB;
+ texImage->Width = width;
+ texImage->Height = height;
+ texImage->Depth = depth;
+ texImage->Border = 0;
+ border = 0;
+ }
+ else {
+ assert(texImage->Width == width);
+ assert(texImage->Height == height);
+ assert(texImage->Depth == depth);
+ }
+
+ stImage->face = _mesa_tex_target_to_face(target);
+ stImage->level = level;
+
+ _mesa_set_fetch_functions(texImage, dims);
+
+ /* Release the reference to a potentially orphaned buffer.
+ * Release any old malloced memory.
+ */
+ if (stImage->pt) {
+ pipe_resource_reference(&stImage->pt, NULL);
+ assert(!texImage->Data);
+ }
+ else if (texImage->Data) {
+ _mesa_align_free(texImage->Data);
+ }
+
+ /*
+ * See if the new image is somehow incompatible with the existing
+ * mipmap. If so, free the old mipmap.
+ */
+ if (stObj->pt) {
+ if (level > (GLint) stObj->pt->last_level ||
+ !st_texture_match_image(stObj->pt, &stImage->base,
+ stImage->face, stImage->level)) {
+ DBG("release it\n");
+ pipe_resource_reference(&stObj->pt, NULL);
+ assert(!stObj->pt);
+ pipe_sampler_view_reference(&stObj->sampler_view, NULL);
+ }
+ }
+
+ if (width == 0 || height == 0 || depth == 0) {
+ /* stop after freeing old image */
+ return;
+ }
+
+ if (!stObj->pt) {
+ if (!guess_and_alloc_texture(st, stObj, stImage)) {
+ /* Probably out of memory.
+ * Try flushing any pending rendering, then retry.
+ */
+ st_finish(st);
+ if (!guess_and_alloc_texture(st, stObj, stImage)) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
+ return;
+ }
+ }
+ }
+
+ assert(!stImage->pt);
+
+ /* Check if this texture image can live inside the texture object's buffer.
+ * If so, store the image there. Otherwise the image will temporarily live
+ * in its own buffer.
+ */
+ if (stObj->pt &&
+ st_texture_match_image(stObj->pt, &stImage->base,
+ stImage->face, stImage->level)) {
+
+ pipe_resource_reference(&stImage->pt, stObj->pt);
+ assert(stImage->pt);
+ }
+
+ if (!stImage->pt)
+ DBG("XXX: Image did not fit into texture - storing in local memory!\n");
+
+ /* Pixel data may come from regular user memory or a PBO. For the later,
+ * do bounds checking and map the PBO to read pixels data from it.
+ *
+ * XXX we should try to use a GPU-accelerated path to copy the image data
+ * from the PBO to the texture.
+ */
+ if (compressed_src) {
+ pixels = _mesa_validate_pbo_compressed_teximage(ctx, imageSize, pixels,
+ unpack,
+ "glCompressedTexImage");
+ }
+ else {
+ pixels = _mesa_validate_pbo_teximage(ctx, dims, width, height, 1,
+ format, type,
+ pixels, unpack, "glTexImage");
+ }
+
+ /* See if we can do texture compression with a blit/render.
+ */
+ if (!compressed_src &&
+ !ctx->Mesa_DXTn &&
+ _mesa_is_format_compressed(texImage->TexFormat) &&
+ screen->is_format_supported(screen,
+ stImage->pt->format,
+ stImage->pt->target, 0,
+ PIPE_BIND_RENDER_TARGET, 0)) {
+ if (!pixels)
+ goto done;
+
+ if (compress_with_blit(ctx, target, level, 0, 0, 0, width, height, depth,
+ format, type, pixels, unpack, texImage)) {
+ goto done;
+ }
+ }
+
+ /*
+ * Prepare to store the texture data. Either map the gallium texture buffer
+ * memory or malloc space for it.
+ */
+ if (stImage->pt) {
+ /* Store the image in the gallium texture memory buffer */
+ if (format == GL_DEPTH_COMPONENT &&
+ util_format_is_depth_and_stencil(stImage->pt->format))
+ transfer_usage = PIPE_TRANSFER_READ_WRITE;
+ else
+ transfer_usage = PIPE_TRANSFER_WRITE;
+
+ texImage->Data = st_texture_image_map(st, stImage, 0,
+ transfer_usage, 0, 0, width, height);
+ if(stImage->transfer)
+ dstRowStride = stImage->transfer->stride;
+ }
+ else {
+ /* Allocate regular memory and store the image there temporarily. */
+ GLuint imageSize = _mesa_format_image_size(texImage->TexFormat,
+ width, height, depth);
+ dstRowStride = _mesa_format_row_stride(texImage->TexFormat, width);
+
+ texImage->Data = _mesa_align_malloc(imageSize, 16);
+ }
+
+ if (!texImage->Data) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
+ return;
+ }
+
+ if (!pixels) {
+ /* We've allocated texture memory, but have no pixel data - all done. */
+ goto done;
+ }
+
+ DBG("Upload image %dx%dx%d row_len %x pitch %x\n",
+ width, height, depth, width, dstRowStride);
+
+ /* Copy user texture image into the texture buffer.
+ */
+ if (compressed_src) {
+ const GLuint srcRowStride =
+ _mesa_format_row_stride(texImage->TexFormat, width);
+ if (dstRowStride == srcRowStride) {
+ memcpy(texImage->Data, pixels, imageSize);
+ }
+ else {
+ char *dst = texImage->Data;
+ const char *src = pixels;
+ GLuint i, bw, bh, lines;
+ _mesa_get_format_block_size(texImage->TexFormat, &bw, &bh);
+ lines = (height + bh - 1) / bh;
+
+ for (i = 0; i < lines; ++i) {
+ memcpy(dst, src, srcRowStride);
+ dst += dstRowStride;
+ src += srcRowStride;
+ }
+ }
+ }
+ else {
+ const GLuint srcImageStride =
+ _mesa_image_image_stride(unpack, width, height, format, type);
+ GLint i;
+ const GLubyte *src = (const GLubyte *) pixels;
+
+ for (i = 0; i < depth; i++) {
+ if (!_mesa_texstore(ctx, dims,
+ texImage->_BaseFormat,
+ texImage->TexFormat,
+ texImage->Data,
+ 0, 0, 0, /* dstX/Y/Zoffset */
+ dstRowStride,
+ texImage->ImageOffsets,
+ width, height, 1,
+ format, type, src, unpack)) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
+ }
+
+ if (stImage->pt && i + 1 < depth) {
+ /* unmap this slice */
+ st_texture_image_unmap(st, stImage);
+ /* map next slice of 3D texture */
+ texImage->Data = st_texture_image_map(st, stImage, i + 1,
+ transfer_usage, 0, 0,
+ width, height);
+ src += srcImageStride;
+ }
+ }
+ }
+
+done:
+ _mesa_unmap_teximage_pbo(ctx, unpack);
+
+ if (stImage->pt && texImage->Data) {
+ st_texture_image_unmap(st, stImage);
+ texImage->Data = NULL;
+ }
+}
+
+
+static void
+st_TexImage3D(struct gl_context * ctx,
+ GLenum target, GLint level,
+ GLint internalFormat,
+ GLint width, GLint height, GLint depth,
+ GLint border,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexImage(ctx, 3, target, level, internalFormat, width, height, depth,
+ border, format, type, pixels, unpack, texObj, texImage,
+ 0, GL_FALSE);
+}
+
+
+static void
+st_TexImage2D(struct gl_context * ctx,
+ GLenum target, GLint level,
+ GLint internalFormat,
+ GLint width, GLint height, GLint border,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
+ format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
+}
+
+
+static void
+st_TexImage1D(struct gl_context * ctx,
+ GLenum target, GLint level,
+ GLint internalFormat,
+ GLint width, GLint border,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexImage(ctx, 1, target, level, internalFormat, width, 1, 1, border,
+ format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
+}
+
+
+static void
+st_CompressedTexImage2D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint internalFormat,
+ GLint width, GLint height, GLint border,
+ GLsizei imageSize, const GLvoid *data,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
+ 0, 0, data, &ctx->Unpack, texObj, texImage, imageSize, GL_TRUE);
+}
+
+
+
+/**
+ * glGetTexImage() helper: decompress a compressed texture by rendering
+ * a textured quad. Store the results in the user's buffer.
+ */
+static void
+decompress_with_blit(struct gl_context * ctx, GLenum target, GLint level,
+ GLenum format, GLenum type, GLvoid *pixels,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ struct st_texture_object *stObj = st_texture_object(texObj);
+ struct pipe_sampler_view *src_view =
+ st_get_texture_sampler_view(stObj, pipe);
+ const GLuint width = texImage->Width;
+ const GLuint height = texImage->Height;
+ struct pipe_surface *dst_surface;
+ struct pipe_resource *dst_texture;
+ struct pipe_transfer *tex_xfer;
+ unsigned bind = (PIPE_BIND_RENDER_TARGET | /* util_blit may choose to render */
+ PIPE_BIND_TRANSFER_READ);
+
+ /* create temp / dest surface */
+ if (!util_create_rgba_surface(pipe, width, height, bind,
+ &dst_texture, &dst_surface)) {
+ _mesa_problem(ctx, "util_create_rgba_surface() failed "
+ "in decompress_with_blit()");
+ return;
+ }
+
+ /* blit/render/decompress */
+ util_blit_pixels_tex(st->blit,
+ src_view, /* pipe_resource (src) */
+ 0, 0, /* src x0, y0 */
+ width, height, /* src x1, y1 */
+ dst_surface, /* pipe_surface (dst) */
+ 0, 0, /* dst x0, y0 */
+ width, height, /* dst x1, y1 */
+ 0.0, /* z */
+ PIPE_TEX_MIPFILTER_NEAREST);
+
+ /* map the dst_surface so we can read from it */
+ tex_xfer = pipe_get_transfer(st_context(ctx)->pipe,
+ dst_texture, 0, 0,
+ PIPE_TRANSFER_READ,
+ 0, 0, width, height);
+
+ pixels = _mesa_map_pbo_dest(ctx, &ctx->Pack, pixels);
+
+ /* copy/pack data into user buffer */
+ if (st_equal_formats(stImage->pt->format, format, type)) {
+ /* memcpy */
+ const uint bytesPerRow = width * util_format_get_blocksize(stImage->pt->format);
+ ubyte *map = pipe_transfer_map(pipe, tex_xfer);
+ GLuint row;
+ for (row = 0; row < height; row++) {
+ GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
+ height, format, type, row, 0);
+ memcpy(dest, map, bytesPerRow);
+ map += tex_xfer->stride;
+ }
+ pipe_transfer_unmap(pipe, tex_xfer);
+ }
+ else {
+ /* format translation via floats */
+ GLuint row;
+ enum pipe_format format = util_format_linear(dst_texture->format);
+ for (row = 0; row < height; row++) {
+ const GLbitfield transferOps = 0x0; /* bypassed for glGetTexImage() */
+ GLfloat rgba[4 * MAX_WIDTH];
+ GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
+ height, format, type, row, 0);
+
+ if (ST_DEBUG & DEBUG_FALLBACK)
+ debug_printf("%s: fallback format translation\n", __FUNCTION__);
+
+ /* get float[4] rgba row from surface */
+ pipe_get_tile_rgba_format(pipe, tex_xfer, 0, row, width, 1,
+ format, rgba);
+
+ _mesa_pack_rgba_span_float(ctx, width, (GLfloat (*)[4]) rgba, format,
+ type, dest, &ctx->Pack, transferOps);
+ }
+ }
+
+ _mesa_unmap_pbo_dest(ctx, &ctx->Pack);
+
+ pipe->transfer_destroy(pipe, tex_xfer);
+
+ /* destroy the temp / dest surface */
+ util_destroy_rgba_surface(dst_texture, dst_surface);
+}
+
+
+
+/**
+ * Need to map texture image into memory before copying image data,
+ * then unmap it.
+ */
+static void
+st_get_tex_image(struct gl_context * ctx, GLenum target, GLint level,
+ GLenum format, GLenum type, GLvoid * pixels,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage, GLboolean compressed_dst)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ const GLuint dstImageStride =
+ _mesa_image_image_stride(&ctx->Pack, texImage->Width, texImage->Height,
+ format, type);
+ GLuint depth, i;
+ GLubyte *dest;
+
+ if (stImage->pt &&
+ util_format_is_s3tc(stImage->pt->format) &&
+ !compressed_dst) {
+ /* Need to decompress the texture.
+ * We'll do this by rendering a textured quad.
+ * Note that we only expect RGBA formats (no Z/depth formats).
+ */
+ decompress_with_blit(ctx, target, level, format, type, pixels,
+ texObj, texImage);
+ return;
+ }
+
+ /* Map */
+ if (stImage->pt) {
+ /* Image is stored in hardware format in a buffer managed by the
+ * kernel. Need to explicitly map and unmap it.
+ */
+ texImage->Data = st_texture_image_map(st, stImage, 0,
+ PIPE_TRANSFER_READ, 0, 0,
+ stImage->base.Width,
+ stImage->base.Height);
+ /* compute stride in texels from stride in bytes */
+ texImage->RowStride = stImage->transfer->stride
+ * util_format_get_blockwidth(stImage->pt->format)
+ / util_format_get_blocksize(stImage->pt->format);
+ }
+ else {
+ /* Otherwise, the image should actually be stored in
+ * texImage->Data. This is pretty confusing for
+ * everybody, I'd much prefer to separate the two functions of
+ * texImage->Data - storage for texture images in main memory
+ * and access (ie mappings) of images. In other words, we'd
+ * create a new texImage->Map field and leave Data simply for
+ * storage.
+ */
+ assert(texImage->Data);
+ }
+
+ depth = texImage->Depth;
+ texImage->Depth = 1;
+
+ dest = (GLubyte *) pixels;
+
+ _mesa_set_fetch_functions(texImage, get_texture_dims(target));
+
+ for (i = 0; i < depth; i++) {
+ if (compressed_dst) {
+ _mesa_get_compressed_teximage(ctx, target, level, dest,
+ texObj, texImage);
+ }
+ else {
+ _mesa_get_teximage(ctx, target, level, format, type, dest,
+ texObj, texImage);
+ }
+
+ if (stImage->pt && i + 1 < depth) {
+ /* unmap this slice */
+ st_texture_image_unmap(st, stImage);
+ /* map next slice of 3D texture */
+ texImage->Data = st_texture_image_map(st, stImage, i + 1,
+ PIPE_TRANSFER_READ, 0, 0,
+ stImage->base.Width,
+ stImage->base.Height);
+ dest += dstImageStride;
+ }
+ }
+
+ texImage->Depth = depth;
+
+ /* Unmap */
+ if (stImage->pt) {
+ st_texture_image_unmap(st, stImage);
+ texImage->Data = NULL;
+ }
+}
+
+
+static void
+st_GetTexImage(struct gl_context * ctx, GLenum target, GLint level,
+ GLenum format, GLenum type, GLvoid * pixels,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_get_tex_image(ctx, target, level, format, type, pixels, texObj, texImage,
+ GL_FALSE);
+}
+
+
+static void
+st_GetCompressedTexImage(struct gl_context *ctx, GLenum target, GLint level,
+ GLvoid *pixels,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_get_tex_image(ctx, target, level, 0, 0, pixels, texObj, texImage,
+ GL_TRUE);
+}
+
+
+
+static void
+st_TexSubimage(struct gl_context *ctx, GLint dims, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLint width, GLint height, GLint depth,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *packing,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_screen *screen = st->pipe->screen;
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ GLuint dstRowStride;
+ const GLuint srcImageStride =
+ _mesa_image_image_stride(packing, width, height, format, type);
+ GLint i;
+ const GLubyte *src;
+ /* init to silence warning only: */
+ enum pipe_transfer_usage transfer_usage = PIPE_TRANSFER_WRITE;
+
+ DBG("%s target %s level %d offset %d,%d %dx%d\n", __FUNCTION__,
+ _mesa_lookup_enum_by_nr(target),
+ level, xoffset, yoffset, width, height);
+
+ pixels =
+ _mesa_validate_pbo_teximage(ctx, dims, width, height, depth, format,
+ type, pixels, packing, "glTexSubImage2D");
+ if (!pixels)
+ return;
+
+ /* See if we can do texture compression with a blit/render.
+ */
+ if (!ctx->Mesa_DXTn &&
+ _mesa_is_format_compressed(texImage->TexFormat) &&
+ screen->is_format_supported(screen,
+ stImage->pt->format,
+ stImage->pt->target, 0,
+ PIPE_BIND_RENDER_TARGET, 0)) {
+ if (compress_with_blit(ctx, target, level,
+ xoffset, yoffset, zoffset,
+ width, height, depth,
+ format, type, pixels, packing, texImage)) {
+ goto done;
+ }
+ }
+
+ /* Map buffer if necessary. Need to lock to prevent other contexts
+ * from uploading the buffer under us.
+ */
+ if (stImage->pt) {
+ if (format == GL_DEPTH_COMPONENT &&
+ util_format_is_depth_and_stencil(stImage->pt->format))
+ transfer_usage = PIPE_TRANSFER_READ_WRITE;
+ else
+ transfer_usage = PIPE_TRANSFER_WRITE;
+
+ texImage->Data = st_texture_image_map(st, stImage, zoffset,
+ transfer_usage,
+ xoffset, yoffset,
+ width, height);
+ }
+
+ if (!texImage->Data) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
+ goto done;
+ }
+
+ src = (const GLubyte *) pixels;
+ dstRowStride = stImage->transfer->stride;
+
+ for (i = 0; i < depth; i++) {
+ if (!_mesa_texstore(ctx, dims, texImage->_BaseFormat,
+ texImage->TexFormat,
+ texImage->Data,
+ 0, 0, 0,
+ dstRowStride,
+ texImage->ImageOffsets,
+ width, height, 1,
+ format, type, src, packing)) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
+ }
+
+ if (stImage->pt && i + 1 < depth) {
+ /* unmap this slice */
+ st_texture_image_unmap(st, stImage);
+ /* map next slice of 3D texture */
+ texImage->Data = st_texture_image_map(st, stImage,
+ zoffset + i + 1,
+ transfer_usage,
+ xoffset, yoffset,
+ width, height);
+ src += srcImageStride;
+ }
+ }
+
+done:
+ _mesa_unmap_teximage_pbo(ctx, packing);
+
+ if (stImage->pt && texImage->Data) {
+ st_texture_image_unmap(st, stImage);
+ texImage->Data = NULL;
+ }
+}
+
+
+
+static void
+st_TexSubImage3D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLsizei width, GLsizei height, GLsizei depth,
+ GLenum format, GLenum type, const GLvoid *pixels,
+ const struct gl_pixelstore_attrib *packing,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexSubimage(ctx, 3, target, level, xoffset, yoffset, zoffset,
+ width, height, depth, format, type,
+ pixels, packing, texObj, texImage);
+}
+
+
+static void
+st_TexSubImage2D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset,
+ GLsizei width, GLsizei height,
+ GLenum format, GLenum type, const GLvoid * pixels,
+ const struct gl_pixelstore_attrib *packing,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexSubimage(ctx, 2, target, level, xoffset, yoffset, 0,
+ width, height, 1, format, type,
+ pixels, packing, texObj, texImage);
+}
+
+
+static void
+st_TexSubImage1D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLsizei width, GLenum format, GLenum type,
+ const GLvoid * pixels,
+ const struct gl_pixelstore_attrib *packing,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexSubimage(ctx, 1, target, level, xoffset, 0, 0, width, 1, 1,
+ format, type, pixels, packing, texObj, texImage);
+}
+
+
+static void
+st_CompressedTexSubImage1D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLsizei width,
+ GLenum format,
+ GLsizei imageSize, const GLvoid *data,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ assert(0);
+}
+
+
+static void
+st_CompressedTexSubImage2D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset,
+ GLsizei width, GLint height,
+ GLenum format,
+ GLsizei imageSize, const GLvoid *data,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ int srcBlockStride;
+ int dstBlockStride;
+ int y;
+ enum pipe_format pformat;
+
+ if (stImage->pt) {
+ pformat = stImage->pt->format;
+
+ texImage->Data = st_texture_image_map(st, stImage, 0,
+ PIPE_TRANSFER_WRITE,
+ xoffset, yoffset,
+ width, height);
+
+ srcBlockStride = util_format_get_stride(pformat, width);
+ dstBlockStride = stImage->transfer->stride;
+ } else {
+ assert(stImage->pt);
+ /* TODO find good values for block and strides */
+ /* TODO also adjust texImage->data for yoffset/xoffset */
+ return;
+ }
+
+ if (!texImage->Data) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage");
+ return;
+ }
+
+ assert(xoffset % util_format_get_blockwidth(pformat) == 0);
+ assert(yoffset % util_format_get_blockheight(pformat) == 0);
+
+ for (y = 0; y < height; y += util_format_get_blockheight(pformat)) {
+ /* don't need to adjust for xoffset and yoffset as st_texture_image_map does that */
+ const char *src = (const char*)data + srcBlockStride * util_format_get_nblocksy(pformat, y);
+ char *dst = (char*)texImage->Data + dstBlockStride * util_format_get_nblocksy(pformat, y);
+ memcpy(dst, src, util_format_get_stride(pformat, width));
+ }
+
+ if (stImage->pt) {
+ st_texture_image_unmap(st, stImage);
+ texImage->Data = NULL;
+ }
+}
+
+
+static void
+st_CompressedTexSubImage3D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLsizei width, GLint height, GLint depth,
+ GLenum format,
+ GLsizei imageSize, const GLvoid *data,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ assert(0);
+}
+
+
+
+/**
+ * Do a CopyTexSubImage operation using a read transfer from the source,
+ * a write transfer to the destination and get_tile()/put_tile() to access
+ * the pixels/texels.
+ *
+ * Note: srcY=0=TOP of renderbuffer
+ */
+static void
+fallback_copy_texsubimage(struct gl_context *ctx, GLenum target, GLint level,
+ struct st_renderbuffer *strb,
+ struct st_texture_image *stImage,
+ GLenum baseFormat,
+ GLint destX, GLint destY, GLint destZ,
+ GLint srcX, GLint srcY,
+ GLsizei width, GLsizei height)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_transfer *src_trans;
+ GLvoid *texDest;
+ enum pipe_transfer_usage transfer_usage;
+
+ if (ST_DEBUG & DEBUG_FALLBACK)
+ debug_printf("%s: fallback processing\n", __FUNCTION__);
+
+ assert(width <= MAX_WIDTH);
+
+ if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
+ srcY = strb->Base.Height - srcY - height;
+ }
+
+ src_trans = pipe_get_transfer(st_context(ctx)->pipe,
+ strb->texture,
+ 0, 0,
+ PIPE_TRANSFER_READ,
+ srcX, srcY,
+ width, height);
+
+ if ((baseFormat == GL_DEPTH_COMPONENT ||
+ baseFormat == GL_DEPTH_STENCIL) &&
+ util_format_is_depth_and_stencil(stImage->pt->format))
+ transfer_usage = PIPE_TRANSFER_READ_WRITE;
+ else
+ transfer_usage = PIPE_TRANSFER_WRITE;
+
+ /* XXX this used to ignore destZ param */
+ texDest = st_texture_image_map(st, stImage, destZ, transfer_usage,
+ destX, destY, width, height);
+
+ if (baseFormat == GL_DEPTH_COMPONENT ||
+ baseFormat == GL_DEPTH_STENCIL) {
+ const GLboolean scaleOrBias = (ctx->Pixel.DepthScale != 1.0F ||
+ ctx->Pixel.DepthBias != 0.0F);
+ GLint row, yStep;
+
+ /* determine bottom-to-top vs. top-to-bottom order for src buffer */
+ if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
+ srcY = height - 1;
+ yStep = -1;
+ }
+ else {
+ srcY = 0;
+ yStep = 1;
+ }
+
+ /* To avoid a large temp memory allocation, do copy row by row */
+ for (row = 0; row < height; row++, srcY += yStep) {
+ uint data[MAX_WIDTH];
+ pipe_get_tile_z(pipe, src_trans, 0, srcY, width, 1, data);
+ if (scaleOrBias) {
+ _mesa_scale_and_bias_depth_uint(ctx, width, data);
+ }
+ pipe_put_tile_z(pipe, stImage->transfer, 0, row, width, 1, data);
+ }
+ }
+ else {
+ /* RGBA format */
+ GLfloat *tempSrc =
+ (GLfloat *) malloc(width * height * 4 * sizeof(GLfloat));
+
+ if (tempSrc && texDest) {
+ const GLint dims = 2;
+ const GLint dstRowStride = stImage->transfer->stride;
+ struct gl_texture_image *texImage = &stImage->base;
+ struct gl_pixelstore_attrib unpack = ctx->DefaultPacking;
+
+ if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
+ unpack.Invert = GL_TRUE;
+ }
+
+ /* get float/RGBA image from framebuffer */
+ /* XXX this usually involves a lot of int/float conversion.
+ * try to avoid that someday.
+ */
+ pipe_get_tile_rgba_format(pipe, src_trans, 0, 0, width, height,
+ util_format_linear(strb->texture->format),
+ tempSrc);
+
+ /* Store into texture memory.
+ * Note that this does some special things such as pixel transfer
+ * ops and format conversion. In particular, if the dest tex format
+ * is actually RGBA but the user created the texture as GL_RGB we
+ * need to fill-in/override the alpha channel with 1.0.
+ */
+ _mesa_texstore(ctx, dims,
+ texImage->_BaseFormat,
+ texImage->TexFormat,
+ texDest,
+ 0, 0, 0,
+ dstRowStride,
+ texImage->ImageOffsets,
+ width, height, 1,
+ GL_RGBA, GL_FLOAT, tempSrc, /* src */
+ &unpack);
+ }
+ else {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
+ }
+
+ if (tempSrc)
+ free(tempSrc);
+ }
+
+ st_texture_image_unmap(st, stImage);
+ pipe->transfer_destroy(pipe, src_trans);
+}
+
+
+
+/**
+ * If the format of the src renderbuffer and the format of the dest
+ * texture are compatible (in terms of blitting), return a TGSI writemask
+ * to be used during the blit.
+ * If the src/dest are incompatible, return 0.
+ */
+static unsigned
+compatible_src_dst_formats(struct gl_context *ctx,
+ const struct gl_renderbuffer *src,
+ const struct gl_texture_image *dst)
+{
+ /* Get logical base formats for the src and dest.
+ * That is, use the user-requested formats and not the actual, device-
+ * chosen formats.
+ * For example, the user may have requested an A8 texture but the
+ * driver may actually be using an RGBA texture format. When we
+ * copy/blit to that texture, we only want to copy the Alpha channel
+ * and not the RGB channels.
+ *
+ * Similarly, when the src FBO was created an RGB format may have been
+ * requested but the driver actually chose an RGBA format. In that case,
+ * we don't want to copy the undefined Alpha channel to the dest texture
+ * (it should be 1.0).
+ */
+ const GLenum srcFormat = _mesa_base_fbo_format(ctx, src->InternalFormat);
+ const GLenum dstFormat = _mesa_base_tex_format(ctx, dst->InternalFormat);
+
+ /**
+ * XXX when we have red-only and red/green renderbuffers we'll need
+ * to add more cases here (or implement a general-purpose routine that
+ * queries the existance of the R,G,B,A channels in the src and dest).
+ */
+ if (srcFormat == dstFormat) {
+ /* This is the same as matching_base_formats, which should
+ * always pass, as it did previously.
+ */
+ return TGSI_WRITEMASK_XYZW;
+ }
+ else if (srcFormat == GL_RGB && dstFormat == GL_RGBA) {
+ /* Make sure that A in the dest is 1. The actual src format
+ * may be RGBA and have undefined A values.
+ */
+ return TGSI_WRITEMASK_XYZ;
+ }
+ else if (srcFormat == GL_RGBA && dstFormat == GL_RGB) {
+ /* Make sure that A in the dest is 1. The actual dst format
+ * may be RGBA and will need A=1 to provide proper alpha values
+ * when sampled later.
+ */
+ return TGSI_WRITEMASK_XYZ;
+ }
+ else {
+ if (ST_DEBUG & DEBUG_FALLBACK)
+ debug_printf("%s failed for src %s, dst %s\n",
+ __FUNCTION__,
+ _mesa_lookup_enum_by_nr(srcFormat),
+ _mesa_lookup_enum_by_nr(dstFormat));
+
+ /* Otherwise fail.
+ */
+ return 0;
+ }
+}
+
+
+
+/**
+ * Do a CopyTex[Sub]Image1/2/3D() using a hardware (blit) path if possible.
+ * Note that the region to copy has already been clipped so we know we
+ * won't read from outside the source renderbuffer's bounds.
+ *
+ * Note: srcY=0=Bottom of renderbuffer (GL convention)
+ */
+static void
+st_copy_texsubimage(struct gl_context *ctx,
+ GLenum target, GLint level,
+ GLint destX, GLint destY, GLint destZ,
+ GLint srcX, GLint srcY,
+ GLsizei width, GLsizei height)
+{
+ struct gl_texture_unit *texUnit =
+ &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
+ struct gl_texture_object *texObj =
+ _mesa_select_tex_object(ctx, texUnit, target);
+ struct gl_texture_image *texImage =
+ _mesa_select_tex_image(ctx, texObj, target, level);
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ const GLenum texBaseFormat = texImage->_BaseFormat;
+ struct gl_framebuffer *fb = ctx->ReadBuffer;
+ struct st_renderbuffer *strb;
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_screen *screen = pipe->screen;
+ enum pipe_format dest_format, src_format;
+ GLboolean use_fallback = GL_TRUE;
+ GLboolean matching_base_formats;
+ GLuint format_writemask, sample_count;
+ struct pipe_surface *dest_surface = NULL;
+ GLboolean do_flip = (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP);
+
+ /* make sure finalize_textures has been called?
+ */
+ if (0) st_validate_state(st);
+
+ /* determine if copying depth or color data */
+ if (texBaseFormat == GL_DEPTH_COMPONENT ||
+ texBaseFormat == GL_DEPTH_STENCIL) {
+ strb = st_renderbuffer(fb->_DepthBuffer);
+ if (strb->Base.Wrapped) {
+ strb = st_renderbuffer(strb->Base.Wrapped);
+ }
+ }
+ else {
+ /* texBaseFormat == GL_RGB, GL_RGBA, GL_ALPHA, etc */
+ strb = st_renderbuffer(fb->_ColorReadBuffer);
+ }
+
+ if (!strb || !strb->surface || !stImage->pt) {
+ debug_printf("%s: null strb or stImage\n", __FUNCTION__);
+ return;
+ }
+
+ sample_count = strb->surface->texture->nr_samples;
+ /* I believe this would be legal, presumably would need to do a resolve
+ for color, and for depth/stencil spec says to just use one of the
+ depth/stencil samples per pixel? Need some transfer clarifications. */
+ assert(sample_count < 2);
+
+ if (srcX < 0) {
+ width -= -srcX;
+ destX += -srcX;
+ srcX = 0;
+ }
+
+ if (srcY < 0) {
+ height -= -srcY;
+ destY += -srcY;
+ srcY = 0;
+ }
+
+ if (destX < 0) {
+ width -= -destX;
+ srcX += -destX;
+ destX = 0;
+ }
+
+ if (destY < 0) {
+ height -= -destY;
+ srcY += -destY;
+ destY = 0;
+ }
+
+ if (width < 0 || height < 0)
+ return;
+
+
+ assert(strb);
+ assert(strb->surface);
+ assert(stImage->pt);
+
+ src_format = strb->surface->format;
+ dest_format = stImage->pt->format;
+
+ /*
+ * Determine if the src framebuffer and dest texture have the same
+ * base format. We need this to detect a case such as the framebuffer
+ * being GL_RGBA but the texture being GL_RGB. If the actual hardware
+ * texture format stores RGBA we need to set A=1 (overriding the
+ * framebuffer's alpha values). We can't do that with the blit or
+ * textured-quad paths.
+ */
+ matching_base_formats =
+ (_mesa_get_format_base_format(strb->Base.Format) ==
+ _mesa_get_format_base_format(texImage->TexFormat));
+ format_writemask = compatible_src_dst_formats(ctx, &strb->Base, texImage);
+
+ if (ctx->_ImageTransferState == 0x0) {
+
+ if (matching_base_formats &&
+ src_format == dest_format &&
+ !do_flip)
+ {
+ /* use surface_copy() / blit */
+ struct pipe_box src_box;
+ u_box_2d_zslice(srcX, srcY, strb->surface->u.tex.first_layer,
+ width, height, &src_box);
+
+ /* for resource_copy_region(), y=0=top, always */
+ pipe->resource_copy_region(pipe,
+ /* dest */
+ stImage->pt,
+ stImage->level,
+ destX, destY, destZ + stImage->face,
+ /* src */
+ strb->texture,
+ strb->surface->u.tex.level,
+ &src_box);
+ use_fallback = GL_FALSE;
+ }
+ else if (format_writemask &&
+ texBaseFormat != GL_DEPTH_COMPONENT &&
+ texBaseFormat != GL_DEPTH_STENCIL &&
+ screen->is_format_supported(screen, src_format,
+ PIPE_TEXTURE_2D, sample_count,
+ PIPE_BIND_SAMPLER_VIEW,
+ 0) &&
+ screen->is_format_supported(screen, dest_format,
+ PIPE_TEXTURE_2D, 0,
+ PIPE_BIND_RENDER_TARGET,
+ 0)) {
+ /* draw textured quad to do the copy */
+ GLint srcY0, srcY1;
+ struct pipe_surface surf_tmpl;
+ memset(&surf_tmpl, 0, sizeof(surf_tmpl));
+ surf_tmpl.format = stImage->pt->format;
+ surf_tmpl.usage = PIPE_BIND_RENDER_TARGET;
+ surf_tmpl.u.tex.level = stImage->level;
+ surf_tmpl.u.tex.first_layer = stImage->face + destZ;
+ surf_tmpl.u.tex.last_layer = stImage->face + destZ;
+
+ dest_surface = pipe->create_surface(pipe, stImage->pt,
+ &surf_tmpl);
+
+ if (do_flip) {
+ srcY1 = strb->Base.Height - srcY - height;
+ srcY0 = srcY1 + height;
+ }
+ else {
+ srcY0 = srcY;
+ srcY1 = srcY0 + height;
+ }
+
+ util_blit_pixels_writemask(st->blit,
+ strb->texture,
+ strb->surface->u.tex.level,
+ srcX, srcY0,
+ srcX + width, srcY1,
+ strb->surface->u.tex.first_layer,
+ dest_surface,
+ destX, destY,
+ destX + width, destY + height,
+ 0.0, PIPE_TEX_MIPFILTER_NEAREST,
+ format_writemask);
+ use_fallback = GL_FALSE;
+ }
+
+ if (dest_surface)
+ pipe_surface_reference(&dest_surface, NULL);
+ }
+
+ if (use_fallback) {
+ /* software fallback */
+ fallback_copy_texsubimage(ctx, target, level,
+ strb, stImage, texBaseFormat,
+ destX, destY, destZ,
+ srcX, srcY, width, height);
+ }
+}
+
+
+
+static void
+st_CopyTexImage1D(struct gl_context * ctx, GLenum target, GLint level,
+ GLenum internalFormat,
+ GLint x, GLint y, GLsizei width, GLint border)
+{
+ struct gl_texture_unit *texUnit =
+ &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
+ struct gl_texture_object *texObj =
+ _mesa_select_tex_object(ctx, texUnit, target);
+ struct gl_texture_image *texImage =
+ _mesa_select_tex_image(ctx, texObj, target, level);
+
+ /* Setup or redefine the texture object, texture and texture
+ * image. Don't populate yet.
+ */
+ ctx->Driver.TexImage1D(ctx, target, level, internalFormat,
+ width, border,
+ GL_RGBA, CHAN_TYPE, NULL,
+ &ctx->DefaultPacking, texObj, texImage);
+
+ st_copy_texsubimage(ctx, target, level,
+ 0, 0, 0, /* destX,Y,Z */
+ x, y, width, 1); /* src X, Y, size */
+}
+
+
+static void
+st_CopyTexImage2D(struct gl_context * ctx, GLenum target, GLint level,
+ GLenum internalFormat,
+ GLint x, GLint y, GLsizei width, GLsizei height,
+ GLint border)
+{
+ struct gl_texture_unit *texUnit =
+ &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
+ struct gl_texture_object *texObj =
+ _mesa_select_tex_object(ctx, texUnit, target);
+ struct gl_texture_image *texImage =
+ _mesa_select_tex_image(ctx, texObj, target, level);
+
+ /* Setup or redefine the texture object, texture and texture
+ * image. Don't populate yet.
+ */
+ ctx->Driver.TexImage2D(ctx, target, level, internalFormat,
+ width, height, border,
+ GL_RGBA, CHAN_TYPE, NULL,
+ &ctx->DefaultPacking, texObj, texImage);
+
+ st_copy_texsubimage(ctx, target, level,
+ 0, 0, 0, /* destX,Y,Z */
+ x, y, width, height); /* src X, Y, size */
+}
+
+
+static void
+st_CopyTexSubImage1D(struct gl_context * ctx, GLenum target, GLint level,
+ GLint xoffset, GLint x, GLint y, GLsizei width)
+{
+ const GLint yoffset = 0, zoffset = 0;
+ const GLsizei height = 1;
+ st_copy_texsubimage(ctx, target, level,
+ xoffset, yoffset, zoffset, /* destX,Y,Z */
+ x, y, width, height); /* src X, Y, size */
+}
+
+
+static void
+st_CopyTexSubImage2D(struct gl_context * ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset,
+ GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ const GLint zoffset = 0;
+ st_copy_texsubimage(ctx, target, level,
+ xoffset, yoffset, zoffset, /* destX,Y,Z */
+ x, y, width, height); /* src X, Y, size */
+}
+
+
+static void
+st_CopyTexSubImage3D(struct gl_context * ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ st_copy_texsubimage(ctx, target, level,
+ xoffset, yoffset, zoffset, /* destX,Y,Z */
+ x, y, width, height); /* src X, Y, size */
+}
+
+
+/**
+ * Copy image data from stImage into the texture object 'stObj' at level
+ * 'dstLevel'.
+ */
+static void
+copy_image_data_to_texture(struct st_context *st,
+ struct st_texture_object *stObj,
+ GLuint dstLevel,
+ struct st_texture_image *stImage)
+{
+ /* debug checks */
+ {
+ const struct gl_texture_image *dstImage =
+ stObj->base.Image[stImage->face][stImage->level];
+ assert(dstImage);
+ assert(dstImage->Width == stImage->base.Width);
+ assert(dstImage->Height == stImage->base.Height);
+ assert(dstImage->Depth == stImage->base.Depth);
+ }
+
+ if (stImage->pt) {
+ /* Copy potentially with the blitter:
+ */
+ st_texture_image_copy(st->pipe,
+ stObj->pt, dstLevel, /* dest texture, level */
+ stImage->pt, stImage->level, /* src texture, level */
+ stImage->face);
+
+ pipe_resource_reference(&stImage->pt, NULL);
+ }
+ else if (stImage->base.Data) {
+ st_texture_image_data(st,
+ stObj->pt,
+ stImage->face,
+ dstLevel,
+ stImage->base.Data,
+ stImage->base.RowStride *
+ util_format_get_blocksize(stObj->pt->format),
+ stImage->base.RowStride *
+ stImage->base.Height *
+ util_format_get_blocksize(stObj->pt->format));
+ _mesa_align_free(stImage->base.Data);
+ stImage->base.Data = NULL;
+ }
+
+ pipe_resource_reference(&stImage->pt, stObj->pt);
+}
+
+
+/**
+ * Called during state validation. When this function is finished,
+ * the texture object should be ready for rendering.
+ * \return GL_TRUE for success, GL_FALSE for failure (out of mem)
+ */
+GLboolean
+st_finalize_texture(struct gl_context *ctx,
+ struct pipe_context *pipe,
+ struct gl_texture_object *tObj)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_object *stObj = st_texture_object(tObj);
+ const GLuint nr_faces = (stObj->base.Target == GL_TEXTURE_CUBE_MAP) ? 6 : 1;
+ GLuint face;
+ struct st_texture_image *firstImage;
+ enum pipe_format firstImageFormat;
+
+ if (stObj->base._Complete) {
+ /* The texture is complete and we know exactly how many mipmap levels
+ * are present/needed. This is conditional because we may be called
+ * from the st_generate_mipmap() function when the texture object is
+ * incomplete. In that case, we'll have set stObj->lastLevel before
+ * we get here.
+ */
+ if (stObj->base.MinFilter == GL_LINEAR ||
+ stObj->base.MinFilter == GL_NEAREST)
+ stObj->lastLevel = stObj->base.BaseLevel;
+ else
+ stObj->lastLevel = stObj->base._MaxLevel;
+ }
+
+ firstImage = st_texture_image(stObj->base.Image[0][stObj->base.BaseLevel]);
+ assert(firstImage);
+
+ /* If both firstImage and stObj point to a texture which can contain
+ * all active images, favour firstImage. Note that because of the
+ * completeness requirement, we know that the image dimensions
+ * will match.
+ */
+ if (firstImage->pt &&
+ firstImage->pt != stObj->pt &&
+ (!stObj->pt || firstImage->pt->last_level >= stObj->pt->last_level)) {
+ pipe_resource_reference(&stObj->pt, firstImage->pt);
+ pipe_sampler_view_reference(&stObj->sampler_view, NULL);
+ }
+
+ /* Find gallium format for the Mesa texture */
+ firstImageFormat = st_mesa_format_to_pipe_format(firstImage->base.TexFormat);
+
+ /* If we already have a gallium texture, check that it matches the texture
+ * object's format, target, size, num_levels, etc.
+ */
+ if (stObj->pt) {
+ if (stObj->pt->target != gl_target_to_pipe(stObj->base.Target) ||
+ !st_sampler_compat_formats(stObj->pt->format, firstImageFormat) ||
+ stObj->pt->last_level < stObj->lastLevel ||
+ stObj->pt->width0 != stObj->width0 ||
+ stObj->pt->height0 != stObj->height0 ||
+ stObj->pt->depth0 != stObj->depth0)
+ {
+ /* The gallium texture does not match the Mesa texture so delete the
+ * gallium texture now. We'll make a new one below.
+ */
+ pipe_resource_reference(&stObj->pt, NULL);
+ pipe_sampler_view_reference(&stObj->sampler_view, NULL);
+ st->dirty.st |= ST_NEW_FRAMEBUFFER;
+ }
+ }
+
+ /* May need to create a new gallium texture:
+ */
+ if (!stObj->pt) {
+ GLuint bindings = default_bindings(st, firstImageFormat);
+
+ stObj->pt = st_texture_create(st,
+ gl_target_to_pipe(stObj->base.Target),
+ firstImageFormat,
+ stObj->lastLevel,
+ stObj->width0,
+ stObj->height0,
+ stObj->depth0,
+ bindings);
+
+ if (!stObj->pt) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
+ return GL_FALSE;
+ }
+ }
+
+ /* Pull in any images not in the object's texture:
+ */
+ for (face = 0; face < nr_faces; face++) {
+ GLuint level;
+ for (level = stObj->base.BaseLevel; level <= stObj->lastLevel; level++) {
+ struct st_texture_image *stImage =
+ st_texture_image(stObj->base.Image[face][level]);
+
+ /* Need to import images in main memory or held in other textures.
+ */
+ if (stImage && stObj->pt != stImage->pt) {
+ copy_image_data_to_texture(st, stObj, level, stImage);
+ }
+ }
+ }
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Returns pointer to a default/dummy texture.
+ * This is typically used when the current shader has tex/sample instructions
+ * but the user has not provided a (any) texture(s).
+ */
+struct gl_texture_object *
+st_get_default_texture(struct st_context *st)
+{
+ if (!st->default_texture) {
+ static const GLenum target = GL_TEXTURE_2D;
+ GLubyte pixels[16][16][4];
+ struct gl_texture_object *texObj;
+ struct gl_texture_image *texImg;
+ GLuint i, j;
+
+ /* The ARB_fragment_program spec says (0,0,0,1) should be returned
+ * when attempting to sample incomplete textures.
+ */
+ for (i = 0; i < 16; i++) {
+ for (j = 0; j < 16; j++) {
+ pixels[i][j][0] = 0;
+ pixels[i][j][1] = 0;
+ pixels[i][j][2] = 0;
+ pixels[i][j][3] = 255;
+ }
+ }
+
+ texObj = st->ctx->Driver.NewTextureObject(st->ctx, 0, target);
+
+ texImg = _mesa_get_tex_image(st->ctx, texObj, target, 0);
+
+ _mesa_init_teximage_fields(st->ctx, target, texImg,
+ 16, 16, 1, 0, /* w, h, d, border */
+ GL_RGBA, MESA_FORMAT_RGBA8888);
+
+ st_TexImage(st->ctx, 2, target,
+ 0, GL_RGBA, /* level, intformat */
+ 16, 16, 1, 0, /* w, h, d, border */
+ GL_RGBA, GL_UNSIGNED_BYTE, pixels,
+ &st->ctx->DefaultPacking,
+ texObj, texImg,
+ 0, 0);
+
+ texObj->MinFilter = GL_NEAREST;
+ texObj->MagFilter = GL_NEAREST;
+ texObj->_Complete = GL_TRUE;
+
+ st->default_texture = texObj;
+ }
+ return st->default_texture;
+}
+
+
+void
+st_init_texture_functions(struct dd_function_table *functions)
+{
+ functions->ChooseTextureFormat = st_ChooseTextureFormat;
+ functions->TexImage1D = st_TexImage1D;
+ functions->TexImage2D = st_TexImage2D;
+ functions->TexImage3D = st_TexImage3D;
+ functions->TexSubImage1D = st_TexSubImage1D;
+ functions->TexSubImage2D = st_TexSubImage2D;
+ functions->TexSubImage3D = st_TexSubImage3D;
+ functions->CompressedTexSubImage1D = st_CompressedTexSubImage1D;
+ functions->CompressedTexSubImage2D = st_CompressedTexSubImage2D;
+ functions->CompressedTexSubImage3D = st_CompressedTexSubImage3D;
+ functions->CopyTexImage1D = st_CopyTexImage1D;
+ functions->CopyTexImage2D = st_CopyTexImage2D;
+ functions->CopyTexSubImage1D = st_CopyTexSubImage1D;
+ functions->CopyTexSubImage2D = st_CopyTexSubImage2D;
+ functions->CopyTexSubImage3D = st_CopyTexSubImage3D;
+ functions->GenerateMipmap = st_generate_mipmap;
+
+ functions->GetTexImage = st_GetTexImage;
+
+ /* compressed texture functions */
+ functions->CompressedTexImage2D = st_CompressedTexImage2D;
+ functions->GetCompressedTexImage = st_GetCompressedTexImage;
+
+ functions->NewTextureObject = st_NewTextureObject;
+ functions->NewTextureImage = st_NewTextureImage;
+ functions->DeleteTexture = st_DeleteTextureObject;
+ functions->FreeTexImageData = st_FreeTextureImageData;
+
+ functions->TextureMemCpy = do_memcpy;
+
+ /* XXX Temporary until we can query pipe's texture sizes */
+ functions->TestProxyTexImage = _mesa_test_proxy_teximage;
+}
diff --git a/mesalib/src/mesa/state_tracker/st_extensions.c b/mesalib/src/mesa/state_tracker/st_extensions.c
index d7ed7ea3a..a81cbe85d 100644
--- a/mesalib/src/mesa/state_tracker/st_extensions.c
+++ b/mesalib/src/mesa/state_tracker/st_extensions.c
@@ -420,6 +420,12 @@ void st_init_extensions(struct st_context *st)
ctx->Extensions.MESA_ycbcr_texture = GL_TRUE;
}
+ /* GL_EXT_texture_array */
+ if (screen->get_param(screen, PIPE_CAP_ARRAY_TEXTURES)) {
+ ctx->Extensions.EXT_texture_array = GL_TRUE;
+ ctx->Extensions.MESA_texture_array = GL_TRUE;
+ }
+
/* GL_ARB_framebuffer_object */
if (ctx->Extensions.EXT_packed_depth_stencil) {
/* we support always support GL_EXT_framebuffer_blit */
diff --git a/mesalib/src/mesa/state_tracker/st_mesa_to_tgsi.c b/mesalib/src/mesa/state_tracker/st_mesa_to_tgsi.c
index 87c69e4dd..5c68fd78c 100644
--- a/mesalib/src/mesa/state_tracker/st_mesa_to_tgsi.c
+++ b/mesalib/src/mesa/state_tracker/st_mesa_to_tgsi.c
@@ -1,1247 +1,1249 @@
-/**************************************************************************
- *
- * Copyright 2007-2008 Tungsten Graphics, Inc., Cedar Park, Texas.
- * All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sub license, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice (including the
- * next paragraph) shall be included in all copies or substantial portions
- * of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- **************************************************************************/
-
-/*
- * \author
- * Michal Krol,
- * Keith Whitwell
- */
-
-#include "pipe/p_compiler.h"
-#include "pipe/p_context.h"
-#include "pipe/p_screen.h"
-#include "pipe/p_shader_tokens.h"
-#include "pipe/p_state.h"
-#include "tgsi/tgsi_ureg.h"
-#include "st_mesa_to_tgsi.h"
-#include "st_context.h"
-#include "program/prog_instruction.h"
-#include "program/prog_parameter.h"
-#include "util/u_debug.h"
-#include "util/u_math.h"
-#include "util/u_memory.h"
-
-
-#define PROGRAM_ANY_CONST ((1 << PROGRAM_LOCAL_PARAM) | \
- (1 << PROGRAM_ENV_PARAM) | \
- (1 << PROGRAM_STATE_VAR) | \
- (1 << PROGRAM_NAMED_PARAM) | \
- (1 << PROGRAM_CONSTANT) | \
- (1 << PROGRAM_UNIFORM))
-
-
-struct label {
- unsigned branch_target;
- unsigned token;
-};
-
-
-/**
- * Intermediate state used during shader translation.
- */
-struct st_translate {
- struct ureg_program *ureg;
-
- struct ureg_dst temps[MAX_PROGRAM_TEMPS];
- struct ureg_src *constants;
- struct ureg_dst outputs[PIPE_MAX_SHADER_OUTPUTS];
- struct ureg_src inputs[PIPE_MAX_SHADER_INPUTS];
- struct ureg_dst address[1];
- struct ureg_src samplers[PIPE_MAX_SAMPLERS];
- struct ureg_src systemValues[SYSTEM_VALUE_MAX];
-
- /* Extra info for handling point size clamping in vertex shader */
- struct ureg_dst pointSizeResult; /**< Actual point size output register */
- struct ureg_src pointSizeConst; /**< Point size range constant register */
- GLint pointSizeOutIndex; /**< Temp point size output register */
- GLboolean prevInstWrotePointSize;
-
- const GLuint *inputMapping;
- const GLuint *outputMapping;
-
- /* For every instruction that contains a label (eg CALL), keep
- * details so that we can go back afterwards and emit the correct
- * tgsi instruction number for each label.
- */
- struct label *labels;
- unsigned labels_size;
- unsigned labels_count;
-
- /* Keep a record of the tgsi instruction number that each mesa
- * instruction starts at, will be used to fix up labels after
- * translation.
- */
- unsigned *insn;
- unsigned insn_size;
- unsigned insn_count;
-
- unsigned procType; /**< TGSI_PROCESSOR_VERTEX/FRAGMENT */
-
- boolean error;
-};
-
-
-/** Map Mesa's SYSTEM_VALUE_x to TGSI_SEMANTIC_x */
-static unsigned mesa_sysval_to_semantic[SYSTEM_VALUE_MAX] = {
- TGSI_SEMANTIC_FACE,
- TGSI_SEMANTIC_INSTANCEID
-};
-
-
-/**
- * Make note of a branch to a label in the TGSI code.
- * After we've emitted all instructions, we'll go over the list
- * of labels built here and patch the TGSI code with the actual
- * location of each label.
- */
-static unsigned *get_label( struct st_translate *t,
- unsigned branch_target )
-{
- unsigned i;
-
- if (t->labels_count + 1 >= t->labels_size) {
- unsigned old_size = t->labels_size;
- t->labels_size = 1 << (util_logbase2(t->labels_size) + 1);
- t->labels = REALLOC( t->labels,
- old_size * sizeof t->labels[0],
- t->labels_size * sizeof t->labels[0] );
- if (t->labels == NULL) {
- static unsigned dummy;
- t->error = TRUE;
- return &dummy;
- }
- }
-
- i = t->labels_count++;
- t->labels[i].branch_target = branch_target;
- return &t->labels[i].token;
-}
-
-
-/**
- * Called prior to emitting the TGSI code for each Mesa instruction.
- * Allocate additional space for instructions if needed.
- * Update the insn[] array so the next Mesa instruction points to
- * the next TGSI instruction.
- */
-static void set_insn_start( struct st_translate *t,
- unsigned start )
-{
- if (t->insn_count + 1 >= t->insn_size) {
- unsigned old_size = t->insn_size;
- t->insn_size = 1 << (util_logbase2(t->insn_size) + 1);
- t->insn = REALLOC( t->insn,
- old_size * sizeof t->insn[0],
- t->insn_size * sizeof t->insn[0] );
- if (t->insn == NULL) {
- t->error = TRUE;
- return;
- }
- }
-
- t->insn[t->insn_count++] = start;
-}
-
-
-/**
- * Map a Mesa dst register to a TGSI ureg_dst register.
- */
-static struct ureg_dst
-dst_register( struct st_translate *t,
- gl_register_file file,
- GLuint index )
-{
- switch( file ) {
- case PROGRAM_UNDEFINED:
- return ureg_dst_undef();
-
- case PROGRAM_TEMPORARY:
- if (ureg_dst_is_undef(t->temps[index]))
- t->temps[index] = ureg_DECL_temporary( t->ureg );
-
- return t->temps[index];
-
- case PROGRAM_OUTPUT:
- if (t->procType == TGSI_PROCESSOR_VERTEX && index == VERT_RESULT_PSIZ)
- t->prevInstWrotePointSize = GL_TRUE;
-
- if (t->procType == TGSI_PROCESSOR_VERTEX)
- assert(index < VERT_RESULT_MAX);
- else if (t->procType == TGSI_PROCESSOR_FRAGMENT)
- assert(index < FRAG_RESULT_MAX);
- else
- assert(index < GEOM_RESULT_MAX);
-
- assert(t->outputMapping[index] < Elements(t->outputs));
-
- return t->outputs[t->outputMapping[index]];
-
- case PROGRAM_ADDRESS:
- return t->address[index];
-
- default:
- debug_assert( 0 );
- return ureg_dst_undef();
- }
-}
-
-
-/**
- * Map a Mesa src register to a TGSI ureg_src register.
- */
-static struct ureg_src
-src_register( struct st_translate *t,
- gl_register_file file,
- GLint index )
-{
- switch( file ) {
- case PROGRAM_UNDEFINED:
- return ureg_src_undef();
-
- case PROGRAM_TEMPORARY:
- assert(index >= 0);
- if (ureg_dst_is_undef(t->temps[index]))
- t->temps[index] = ureg_DECL_temporary( t->ureg );
- assert(index < Elements(t->temps));
- return ureg_src(t->temps[index]);
-
- case PROGRAM_NAMED_PARAM:
- case PROGRAM_ENV_PARAM:
- case PROGRAM_LOCAL_PARAM:
- case PROGRAM_UNIFORM:
- assert(index >= 0);
- return t->constants[index];
- case PROGRAM_STATE_VAR:
- case PROGRAM_CONSTANT: /* ie, immediate */
- if (index < 0)
- return ureg_DECL_constant( t->ureg, 0 );
- else
- return t->constants[index];
-
- case PROGRAM_INPUT:
- assert(t->inputMapping[index] < Elements(t->inputs));
- return t->inputs[t->inputMapping[index]];
-
- case PROGRAM_OUTPUT:
- assert(t->outputMapping[index] < Elements(t->outputs));
- return ureg_src(t->outputs[t->outputMapping[index]]); /* not needed? */
-
- case PROGRAM_ADDRESS:
- return ureg_src(t->address[index]);
-
- case PROGRAM_SYSTEM_VALUE:
- assert(index < Elements(t->systemValues));
- return t->systemValues[index];
-
- default:
- debug_assert( 0 );
- return ureg_src_undef();
- }
-}
-
-
-/**
- * Map mesa texture target to TGSI texture target.
- */
-static unsigned
-translate_texture_target( GLuint textarget,
- GLboolean shadow )
-{
- if (shadow) {
- switch( textarget ) {
- case TEXTURE_1D_INDEX: return TGSI_TEXTURE_SHADOW1D;
- case TEXTURE_2D_INDEX: return TGSI_TEXTURE_SHADOW2D;
- case TEXTURE_RECT_INDEX: return TGSI_TEXTURE_SHADOWRECT;
- default: break;
- }
- }
-
- switch( textarget ) {
- case TEXTURE_1D_INDEX: return TGSI_TEXTURE_1D;
- case TEXTURE_2D_INDEX: return TGSI_TEXTURE_2D;
- case TEXTURE_3D_INDEX: return TGSI_TEXTURE_3D;
- case TEXTURE_CUBE_INDEX: return TGSI_TEXTURE_CUBE;
- case TEXTURE_RECT_INDEX: return TGSI_TEXTURE_RECT;
- default:
- debug_assert( 0 );
- return TGSI_TEXTURE_1D;
- }
-}
-
-
-/**
- * Create a TGSI ureg_dst register from a Mesa dest register.
- */
-static struct ureg_dst
-translate_dst( struct st_translate *t,
- const struct prog_dst_register *DstReg,
- boolean saturate )
-{
- struct ureg_dst dst = dst_register( t,
- DstReg->File,
- DstReg->Index );
-
- dst = ureg_writemask( dst,
- DstReg->WriteMask );
-
- if (saturate)
- dst = ureg_saturate( dst );
-
- if (DstReg->RelAddr)
- dst = ureg_dst_indirect( dst, ureg_src(t->address[0]) );
-
- return dst;
-}
-
-
-/**
- * Create a TGSI ureg_src register from a Mesa src register.
- */
-static struct ureg_src
-translate_src( struct st_translate *t,
- const struct prog_src_register *SrcReg )
-{
- struct ureg_src src = src_register( t, SrcReg->File, SrcReg->Index );
-
- if (t->procType == TGSI_PROCESSOR_GEOMETRY && SrcReg->HasIndex2) {
- src = src_register( t, SrcReg->File, SrcReg->Index2 );
- if (SrcReg->RelAddr2)
- src = ureg_src_dimension_indirect( src, ureg_src(t->address[0]),
- SrcReg->Index);
- else
- src = ureg_src_dimension( src, SrcReg->Index);
- }
-
- src = ureg_swizzle( src,
- GET_SWZ( SrcReg->Swizzle, 0 ) & 0x3,
- GET_SWZ( SrcReg->Swizzle, 1 ) & 0x3,
- GET_SWZ( SrcReg->Swizzle, 2 ) & 0x3,
- GET_SWZ( SrcReg->Swizzle, 3 ) & 0x3);
-
- if (SrcReg->Negate == NEGATE_XYZW)
- src = ureg_negate(src);
-
- if (SrcReg->Abs)
- src = ureg_abs(src);
-
- if (SrcReg->RelAddr) {
- src = ureg_src_indirect( src, ureg_src(t->address[0]));
- if (SrcReg->File != PROGRAM_INPUT &&
- SrcReg->File != PROGRAM_OUTPUT) {
- /* If SrcReg->Index was negative, it was set to zero in
- * src_register(). Reassign it now. But don't do this
- * for input/output regs since they get remapped while
- * const buffers don't.
- */
- src.Index = SrcReg->Index;
- }
- }
-
- return src;
-}
-
-
-static struct ureg_src swizzle_4v( struct ureg_src src,
- const unsigned *swz )
-{
- return ureg_swizzle( src, swz[0], swz[1], swz[2], swz[3] );
-}
-
-
-/**
- * Translate a SWZ instruction into a MOV, MUL or MAD instruction. EG:
- *
- * SWZ dst, src.x-y10
- *
- * becomes:
- *
- * MAD dst {1,-1,0,0}, src.xyxx, {0,0,1,0}
- */
-static void emit_swz( struct st_translate *t,
- struct ureg_dst dst,
- const struct prog_src_register *SrcReg )
-{
- struct ureg_program *ureg = t->ureg;
- struct ureg_src src = src_register( t, SrcReg->File, SrcReg->Index );
-
- unsigned negate_mask = SrcReg->Negate;
-
- unsigned one_mask = ((GET_SWZ(SrcReg->Swizzle, 0) == SWIZZLE_ONE) << 0 |
- (GET_SWZ(SrcReg->Swizzle, 1) == SWIZZLE_ONE) << 1 |
- (GET_SWZ(SrcReg->Swizzle, 2) == SWIZZLE_ONE) << 2 |
- (GET_SWZ(SrcReg->Swizzle, 3) == SWIZZLE_ONE) << 3);
-
- unsigned zero_mask = ((GET_SWZ(SrcReg->Swizzle, 0) == SWIZZLE_ZERO) << 0 |
- (GET_SWZ(SrcReg->Swizzle, 1) == SWIZZLE_ZERO) << 1 |
- (GET_SWZ(SrcReg->Swizzle, 2) == SWIZZLE_ZERO) << 2 |
- (GET_SWZ(SrcReg->Swizzle, 3) == SWIZZLE_ZERO) << 3);
-
- unsigned negative_one_mask = one_mask & negate_mask;
- unsigned positive_one_mask = one_mask & ~negate_mask;
-
- struct ureg_src imm;
- unsigned i;
- unsigned mul_swizzle[4] = {0,0,0,0};
- unsigned add_swizzle[4] = {0,0,0,0};
- unsigned src_swizzle[4] = {0,0,0,0};
- boolean need_add = FALSE;
- boolean need_mul = FALSE;
-
- if (dst.WriteMask == 0)
- return;
-
- /* Is this just a MOV?
- */
- if (zero_mask == 0 &&
- one_mask == 0 &&
- (negate_mask == 0 || negate_mask == TGSI_WRITEMASK_XYZW))
- {
- ureg_MOV( ureg, dst, translate_src( t, SrcReg ));
- return;
- }
-
-#define IMM_ZERO 0
-#define IMM_ONE 1
-#define IMM_NEG_ONE 2
-
- imm = ureg_imm3f( ureg, 0, 1, -1 );
-
- for (i = 0; i < 4; i++) {
- unsigned bit = 1 << i;
-
- if (dst.WriteMask & bit) {
- if (positive_one_mask & bit) {
- mul_swizzle[i] = IMM_ZERO;
- add_swizzle[i] = IMM_ONE;
- need_add = TRUE;
- }
- else if (negative_one_mask & bit) {
- mul_swizzle[i] = IMM_ZERO;
- add_swizzle[i] = IMM_NEG_ONE;
- need_add = TRUE;
- }
- else if (zero_mask & bit) {
- mul_swizzle[i] = IMM_ZERO;
- add_swizzle[i] = IMM_ZERO;
- need_add = TRUE;
- }
- else {
- add_swizzle[i] = IMM_ZERO;
- src_swizzle[i] = GET_SWZ(SrcReg->Swizzle, i);
- need_mul = TRUE;
- if (negate_mask & bit) {
- mul_swizzle[i] = IMM_NEG_ONE;
- }
- else {
- mul_swizzle[i] = IMM_ONE;
- }
- }
- }
- }
-
- if (need_mul && need_add) {
- ureg_MAD( ureg,
- dst,
- swizzle_4v( src, src_swizzle ),
- swizzle_4v( imm, mul_swizzle ),
- swizzle_4v( imm, add_swizzle ) );
- }
- else if (need_mul) {
- ureg_MUL( ureg,
- dst,
- swizzle_4v( src, src_swizzle ),
- swizzle_4v( imm, mul_swizzle ) );
- }
- else if (need_add) {
- ureg_MOV( ureg,
- dst,
- swizzle_4v( imm, add_swizzle ) );
- }
- else {
- debug_assert(0);
- }
-
-#undef IMM_ZERO
-#undef IMM_ONE
-#undef IMM_NEG_ONE
-}
-
-
-/**
- * Negate the value of DDY to match GL semantics where (0,0) is the
- * lower-left corner of the window.
- * Note that the GL_ARB_fragment_coord_conventions extension will
- * effect this someday.
- */
-static void emit_ddy( struct st_translate *t,
- struct ureg_dst dst,
- const struct prog_src_register *SrcReg )
-{
- struct ureg_program *ureg = t->ureg;
- struct ureg_src src = translate_src( t, SrcReg );
- src = ureg_negate( src );
- ureg_DDY( ureg, dst, src );
-}
-
-
-
-static unsigned
-translate_opcode( unsigned op )
-{
- switch( op ) {
- case OPCODE_ARL:
- return TGSI_OPCODE_ARL;
- case OPCODE_ABS:
- return TGSI_OPCODE_ABS;
- case OPCODE_ADD:
- return TGSI_OPCODE_ADD;
- case OPCODE_BGNLOOP:
- return TGSI_OPCODE_BGNLOOP;
- case OPCODE_BGNSUB:
- return TGSI_OPCODE_BGNSUB;
- case OPCODE_BRA:
- return TGSI_OPCODE_BRA;
- case OPCODE_BRK:
- return TGSI_OPCODE_BRK;
- case OPCODE_CAL:
- return TGSI_OPCODE_CAL;
- case OPCODE_CMP:
- return TGSI_OPCODE_CMP;
- case OPCODE_CONT:
- return TGSI_OPCODE_CONT;
- case OPCODE_COS:
- return TGSI_OPCODE_COS;
- case OPCODE_DDX:
- return TGSI_OPCODE_DDX;
- case OPCODE_DDY:
- return TGSI_OPCODE_DDY;
- case OPCODE_DP2:
- return TGSI_OPCODE_DP2;
- case OPCODE_DP2A:
- return TGSI_OPCODE_DP2A;
- case OPCODE_DP3:
- return TGSI_OPCODE_DP3;
- case OPCODE_DP4:
- return TGSI_OPCODE_DP4;
- case OPCODE_DPH:
- return TGSI_OPCODE_DPH;
- case OPCODE_DST:
- return TGSI_OPCODE_DST;
- case OPCODE_ELSE:
- return TGSI_OPCODE_ELSE;
- case OPCODE_EMIT_VERTEX:
- return TGSI_OPCODE_EMIT;
- case OPCODE_END_PRIMITIVE:
- return TGSI_OPCODE_ENDPRIM;
- case OPCODE_ENDIF:
- return TGSI_OPCODE_ENDIF;
- case OPCODE_ENDLOOP:
- return TGSI_OPCODE_ENDLOOP;
- case OPCODE_ENDSUB:
- return TGSI_OPCODE_ENDSUB;
- case OPCODE_EX2:
- return TGSI_OPCODE_EX2;
- case OPCODE_EXP:
- return TGSI_OPCODE_EXP;
- case OPCODE_FLR:
- return TGSI_OPCODE_FLR;
- case OPCODE_FRC:
- return TGSI_OPCODE_FRC;
- case OPCODE_IF:
- return TGSI_OPCODE_IF;
- case OPCODE_TRUNC:
- return TGSI_OPCODE_TRUNC;
- case OPCODE_KIL:
- return TGSI_OPCODE_KIL;
- case OPCODE_KIL_NV:
- return TGSI_OPCODE_KILP;
- case OPCODE_LG2:
- return TGSI_OPCODE_LG2;
- case OPCODE_LOG:
- return TGSI_OPCODE_LOG;
- case OPCODE_LIT:
- return TGSI_OPCODE_LIT;
- case OPCODE_LRP:
- return TGSI_OPCODE_LRP;
- case OPCODE_MAD:
- return TGSI_OPCODE_MAD;
- case OPCODE_MAX:
- return TGSI_OPCODE_MAX;
- case OPCODE_MIN:
- return TGSI_OPCODE_MIN;
- case OPCODE_MOV:
- return TGSI_OPCODE_MOV;
- case OPCODE_MUL:
- return TGSI_OPCODE_MUL;
- case OPCODE_NOP:
- return TGSI_OPCODE_NOP;
- case OPCODE_NRM3:
- return TGSI_OPCODE_NRM;
- case OPCODE_NRM4:
- return TGSI_OPCODE_NRM4;
- case OPCODE_POW:
- return TGSI_OPCODE_POW;
- case OPCODE_RCP:
- return TGSI_OPCODE_RCP;
- case OPCODE_RET:
- return TGSI_OPCODE_RET;
- case OPCODE_RSQ:
- return TGSI_OPCODE_RSQ;
- case OPCODE_SCS:
- return TGSI_OPCODE_SCS;
- case OPCODE_SEQ:
- return TGSI_OPCODE_SEQ;
- case OPCODE_SGE:
- return TGSI_OPCODE_SGE;
- case OPCODE_SGT:
- return TGSI_OPCODE_SGT;
- case OPCODE_SIN:
- return TGSI_OPCODE_SIN;
- case OPCODE_SLE:
- return TGSI_OPCODE_SLE;
- case OPCODE_SLT:
- return TGSI_OPCODE_SLT;
- case OPCODE_SNE:
- return TGSI_OPCODE_SNE;
- case OPCODE_SSG:
- return TGSI_OPCODE_SSG;
- case OPCODE_SUB:
- return TGSI_OPCODE_SUB;
- case OPCODE_TEX:
- return TGSI_OPCODE_TEX;
- case OPCODE_TXB:
- return TGSI_OPCODE_TXB;
- case OPCODE_TXD:
- return TGSI_OPCODE_TXD;
- case OPCODE_TXL:
- return TGSI_OPCODE_TXL;
- case OPCODE_TXP:
- return TGSI_OPCODE_TXP;
- case OPCODE_XPD:
- return TGSI_OPCODE_XPD;
- case OPCODE_END:
- return TGSI_OPCODE_END;
- default:
- debug_assert( 0 );
- return TGSI_OPCODE_NOP;
- }
-}
-
-
-static void
-compile_instruction(
- struct st_translate *t,
- const struct prog_instruction *inst )
-{
- struct ureg_program *ureg = t->ureg;
- GLuint i;
- struct ureg_dst dst[1];
- struct ureg_src src[4];
- unsigned num_dst;
- unsigned num_src;
-
- num_dst = _mesa_num_inst_dst_regs( inst->Opcode );
- num_src = _mesa_num_inst_src_regs( inst->Opcode );
-
- if (num_dst)
- dst[0] = translate_dst( t,
- &inst->DstReg,
- inst->SaturateMode );
-
- for (i = 0; i < num_src; i++)
- src[i] = translate_src( t, &inst->SrcReg[i] );
-
- switch( inst->Opcode ) {
- case OPCODE_SWZ:
- emit_swz( t, dst[0], &inst->SrcReg[0] );
- return;
-
- case OPCODE_BGNLOOP:
- case OPCODE_CAL:
- case OPCODE_ELSE:
- case OPCODE_ENDLOOP:
- case OPCODE_IF:
- debug_assert(num_dst == 0);
- ureg_label_insn( ureg,
- translate_opcode( inst->Opcode ),
- src, num_src,
- get_label( t, inst->BranchTarget ));
- return;
-
- case OPCODE_TEX:
- case OPCODE_TXB:
- case OPCODE_TXD:
- case OPCODE_TXL:
- case OPCODE_TXP:
- src[num_src++] = t->samplers[inst->TexSrcUnit];
- ureg_tex_insn( ureg,
- translate_opcode( inst->Opcode ),
- dst, num_dst,
- translate_texture_target( inst->TexSrcTarget,
- inst->TexShadow ),
- src, num_src );
- return;
-
- case OPCODE_SCS:
- dst[0] = ureg_writemask(dst[0], TGSI_WRITEMASK_XY );
- ureg_insn( ureg,
- translate_opcode( inst->Opcode ),
- dst, num_dst,
- src, num_src );
- break;
-
- case OPCODE_XPD:
- dst[0] = ureg_writemask(dst[0], TGSI_WRITEMASK_XYZ );
- ureg_insn( ureg,
- translate_opcode( inst->Opcode ),
- dst, num_dst,
- src, num_src );
- break;
-
- case OPCODE_NOISE1:
- case OPCODE_NOISE2:
- case OPCODE_NOISE3:
- case OPCODE_NOISE4:
- /* At some point, a motivated person could add a better
- * implementation of noise. Currently not even the nvidia
- * binary drivers do anything more than this. In any case, the
- * place to do this is in the GL state tracker, not the poor
- * driver.
- */
- ureg_MOV( ureg, dst[0], ureg_imm1f(ureg, 0.5) );
- break;
-
- case OPCODE_DDY:
- emit_ddy( t, dst[0], &inst->SrcReg[0] );
- break;
-
- default:
- ureg_insn( ureg,
- translate_opcode( inst->Opcode ),
- dst, num_dst,
- src, num_src );
- break;
- }
-}
-
-
-/**
- * Emit the TGSI instructions to adjust the WPOS pixel center convention
- * Basically, add (adjX, adjY) to the fragment position.
- */
-static void
-emit_adjusted_wpos( struct st_translate *t,
- const struct gl_program *program,
- GLfloat adjX, GLfloat adjY)
-{
- struct ureg_program *ureg = t->ureg;
- struct ureg_dst wpos_temp = ureg_DECL_temporary(ureg);
- struct ureg_src wpos_input = t->inputs[t->inputMapping[FRAG_ATTRIB_WPOS]];
-
- /* Note that we bias X and Y and pass Z and W through unchanged.
- * The shader might also use gl_FragCoord.w and .z.
- */
- ureg_ADD(ureg, wpos_temp, wpos_input,
- ureg_imm4f(ureg, adjX, adjY, 0.0f, 0.0f));
-
- t->inputs[t->inputMapping[FRAG_ATTRIB_WPOS]] = ureg_src(wpos_temp);
-}
-
-
-/**
- * Emit the TGSI instructions for inverting the WPOS y coordinate.
- * This code is unavoidable because it also depends on whether
- * a FBO is bound (STATE_FB_WPOS_Y_TRANSFORM).
- */
-static void
-emit_wpos_inversion( struct st_translate *t,
- const struct gl_program *program,
- boolean invert)
-{
- struct ureg_program *ureg = t->ureg;
-
- /* Fragment program uses fragment position input.
- * Need to replace instances of INPUT[WPOS] with temp T
- * where T = INPUT[WPOS] by y is inverted.
- */
- static const gl_state_index wposTransformState[STATE_LENGTH]
- = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM, 0, 0, 0 };
-
- /* XXX: note we are modifying the incoming shader here! Need to
- * do this before emitting the constant decls below, or this
- * will be missed:
- */
- unsigned wposTransConst = _mesa_add_state_reference(program->Parameters,
- wposTransformState);
-
- struct ureg_src wpostrans = ureg_DECL_constant( ureg, wposTransConst );
- struct ureg_dst wpos_temp;
- struct ureg_src wpos_input = t->inputs[t->inputMapping[FRAG_ATTRIB_WPOS]];
-
- /* MOV wpos_temp, input[wpos]
- */
- if (wpos_input.File == TGSI_FILE_TEMPORARY)
- wpos_temp = ureg_dst(wpos_input);
- else {
- wpos_temp = ureg_DECL_temporary( ureg );
- ureg_MOV( ureg, wpos_temp, wpos_input );
- }
-
- if (invert) {
- /* MAD wpos_temp.y, wpos_input, wpostrans.xxxx, wpostrans.yyyy
- */
- ureg_MAD( ureg,
- ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
- wpos_input,
- ureg_scalar(wpostrans, 0),
- ureg_scalar(wpostrans, 1));
- } else {
- /* MAD wpos_temp.y, wpos_input, wpostrans.zzzz, wpostrans.wwww
- */
- ureg_MAD( ureg,
- ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
- wpos_input,
- ureg_scalar(wpostrans, 2),
- ureg_scalar(wpostrans, 3));
- }
-
- /* Use wpos_temp as position input from here on:
- */
- t->inputs[t->inputMapping[FRAG_ATTRIB_WPOS]] = ureg_src(wpos_temp);
-}
-
-
-/**
- * Emit fragment position/ooordinate code.
- */
-static void
-emit_wpos(struct st_context *st,
- struct st_translate *t,
- const struct gl_program *program,
- struct ureg_program *ureg)
-{
- const struct gl_fragment_program *fp =
- (const struct gl_fragment_program *) program;
- struct pipe_screen *pscreen = st->pipe->screen;
- boolean invert = FALSE;
-
- if (fp->OriginUpperLeft) {
- /* Fragment shader wants origin in upper-left */
- if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT)) {
- /* the driver supports upper-left origin */
- }
- else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT)) {
- /* the driver supports lower-left origin, need to invert Y */
- ureg_property_fs_coord_origin(ureg, TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
- invert = TRUE;
- }
- else
- assert(0);
- }
- else {
- /* Fragment shader wants origin in lower-left */
- if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT))
- /* the driver supports lower-left origin */
- ureg_property_fs_coord_origin(ureg, TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
- else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT))
- /* the driver supports upper-left origin, need to invert Y */
- invert = TRUE;
- else
- assert(0);
- }
-
- if (fp->PixelCenterInteger) {
- /* Fragment shader wants pixel center integer */
- if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER))
- /* the driver supports pixel center integer */
- ureg_property_fs_coord_pixel_center(ureg, TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
- else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER))
- /* the driver supports pixel center half integer, need to bias X,Y */
- emit_adjusted_wpos(t, program, 0.5f, invert ? 0.5f : -0.5f);
- else
- assert(0);
- }
- else {
- /* Fragment shader wants pixel center half integer */
- if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
- /* the driver supports pixel center half integer */
- }
- else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
- /* the driver supports pixel center integer, need to bias X,Y */
- ureg_property_fs_coord_pixel_center(ureg, TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
- emit_adjusted_wpos(t, program, 0.5f, invert ? -0.5f : 0.5f);
- }
- else
- assert(0);
- }
-
- /* we invert after adjustment so that we avoid the MOV to temporary,
- * and reuse the adjustment ADD instead */
- emit_wpos_inversion(t, program, invert);
-}
-
-
-/**
- * OpenGL's fragment gl_FrontFace input is 1 for front-facing, 0 for back.
- * TGSI uses +1 for front, -1 for back.
- * This function converts the TGSI value to the GL value. Simply clamping/
- * saturating the value to [0,1] does the job.
- */
-static void
-emit_face_var( struct st_translate *t,
- const struct gl_program *program )
-{
- struct ureg_program *ureg = t->ureg;
- struct ureg_dst face_temp = ureg_DECL_temporary( ureg );
- struct ureg_src face_input = t->inputs[t->inputMapping[FRAG_ATTRIB_FACE]];
-
- /* MOV_SAT face_temp, input[face]
- */
- face_temp = ureg_saturate( face_temp );
- ureg_MOV( ureg, face_temp, face_input );
-
- /* Use face_temp as face input from here on:
- */
- t->inputs[t->inputMapping[FRAG_ATTRIB_FACE]] = ureg_src(face_temp);
-}
-
-
-static void
-emit_edgeflags( struct st_translate *t,
- const struct gl_program *program )
-{
- struct ureg_program *ureg = t->ureg;
- struct ureg_dst edge_dst = t->outputs[t->outputMapping[VERT_RESULT_EDGE]];
- struct ureg_src edge_src = t->inputs[t->inputMapping[VERT_ATTRIB_EDGEFLAG]];
-
- ureg_MOV( ureg, edge_dst, edge_src );
-}
-
-
-/**
- * Translate Mesa program to TGSI format.
- * \param program the program to translate
- * \param numInputs number of input registers used
- * \param inputMapping maps Mesa fragment program inputs to TGSI generic
- * input indexes
- * \param inputSemanticName the TGSI_SEMANTIC flag for each input
- * \param inputSemanticIndex the semantic index (ex: which texcoord) for
- * each input
- * \param interpMode the TGSI_INTERPOLATE_LINEAR/PERSP mode for each input
- * \param numOutputs number of output registers used
- * \param outputMapping maps Mesa fragment program outputs to TGSI
- * generic outputs
- * \param outputSemanticName the TGSI_SEMANTIC flag for each output
- * \param outputSemanticIndex the semantic index (ex: which texcoord) for
- * each output
- *
- * \return PIPE_OK or PIPE_ERROR_OUT_OF_MEMORY
- */
-enum pipe_error
-st_translate_mesa_program(
- struct gl_context *ctx,
- uint procType,
- struct ureg_program *ureg,
- const struct gl_program *program,
- GLuint numInputs,
- const GLuint inputMapping[],
- const ubyte inputSemanticName[],
- const ubyte inputSemanticIndex[],
- const GLuint interpMode[],
- GLuint numOutputs,
- const GLuint outputMapping[],
- const ubyte outputSemanticName[],
- const ubyte outputSemanticIndex[],
- boolean passthrough_edgeflags )
-{
- struct st_translate translate, *t;
- unsigned i;
- enum pipe_error ret = PIPE_OK;
-
- assert(numInputs <= Elements(t->inputs));
- assert(numOutputs <= Elements(t->outputs));
-
- t = &translate;
- memset(t, 0, sizeof *t);
-
- t->procType = procType;
- t->inputMapping = inputMapping;
- t->outputMapping = outputMapping;
- t->ureg = ureg;
- t->pointSizeOutIndex = -1;
- t->prevInstWrotePointSize = GL_FALSE;
-
- /*_mesa_print_program(program);*/
-
- /*
- * Declare input attributes.
- */
- if (procType == TGSI_PROCESSOR_FRAGMENT) {
- for (i = 0; i < numInputs; i++) {
- if (program->InputFlags[0] & PROG_PARAM_BIT_CYL_WRAP) {
- t->inputs[i] = ureg_DECL_fs_input_cyl(ureg,
- inputSemanticName[i],
- inputSemanticIndex[i],
- interpMode[i],
- TGSI_CYLINDRICAL_WRAP_X);
- }
- else {
- t->inputs[i] = ureg_DECL_fs_input(ureg,
- inputSemanticName[i],
- inputSemanticIndex[i],
- interpMode[i]);
- }
- }
-
- if (program->InputsRead & FRAG_BIT_WPOS) {
- /* Must do this after setting up t->inputs, and before
- * emitting constant references, below:
- */
- emit_wpos(st_context(ctx), t, program, ureg);
- }
-
- if (program->InputsRead & FRAG_BIT_FACE) {
- emit_face_var( t, program );
- }
-
- /*
- * Declare output attributes.
- */
- for (i = 0; i < numOutputs; i++) {
- switch (outputSemanticName[i]) {
- case TGSI_SEMANTIC_POSITION:
- t->outputs[i] = ureg_DECL_output( ureg,
- TGSI_SEMANTIC_POSITION, /* Z / Depth */
- outputSemanticIndex[i] );
-
- t->outputs[i] = ureg_writemask( t->outputs[i],
- TGSI_WRITEMASK_Z );
- break;
- case TGSI_SEMANTIC_STENCIL:
- t->outputs[i] = ureg_DECL_output( ureg,
- TGSI_SEMANTIC_STENCIL, /* Stencil */
- outputSemanticIndex[i] );
- t->outputs[i] = ureg_writemask( t->outputs[i],
- TGSI_WRITEMASK_Y );
- break;
- case TGSI_SEMANTIC_COLOR:
- t->outputs[i] = ureg_DECL_output( ureg,
- TGSI_SEMANTIC_COLOR,
- outputSemanticIndex[i] );
- break;
- default:
- debug_assert(0);
- return 0;
- }
- }
- }
- else if (procType == TGSI_PROCESSOR_GEOMETRY) {
- for (i = 0; i < numInputs; i++) {
- t->inputs[i] = ureg_DECL_gs_input(ureg,
- i,
- inputSemanticName[i],
- inputSemanticIndex[i]);
- }
-
- for (i = 0; i < numOutputs; i++) {
- t->outputs[i] = ureg_DECL_output( ureg,
- outputSemanticName[i],
- outputSemanticIndex[i] );
- }
- }
- else {
- assert(procType == TGSI_PROCESSOR_VERTEX);
-
- for (i = 0; i < numInputs; i++) {
- t->inputs[i] = ureg_DECL_vs_input(ureg, i);
- }
-
- for (i = 0; i < numOutputs; i++) {
- t->outputs[i] = ureg_DECL_output( ureg,
- outputSemanticName[i],
- outputSemanticIndex[i] );
- if ((outputSemanticName[i] == TGSI_SEMANTIC_PSIZE) && program->Id) {
- /* Writing to the point size result register requires special
- * handling to implement clamping.
- */
- static const gl_state_index pointSizeClampState[STATE_LENGTH]
- = { STATE_INTERNAL, STATE_POINT_SIZE_IMPL_CLAMP, 0, 0, 0 };
- /* XXX: note we are modifying the incoming shader here! Need to
- * do this before emitting the constant decls below, or this
- * will be missed:
- */
- unsigned pointSizeClampConst =
- _mesa_add_state_reference(program->Parameters,
- pointSizeClampState);
- struct ureg_dst psizregtemp = ureg_DECL_temporary( ureg );
- t->pointSizeConst = ureg_DECL_constant( ureg, pointSizeClampConst );
- t->pointSizeResult = t->outputs[i];
- t->pointSizeOutIndex = i;
- t->outputs[i] = psizregtemp;
- }
- }
- if (passthrough_edgeflags)
- emit_edgeflags( t, program );
- }
-
- /* Declare address register.
- */
- if (program->NumAddressRegs > 0) {
- debug_assert( program->NumAddressRegs == 1 );
- t->address[0] = ureg_DECL_address( ureg );
- }
-
- /* Declare misc input registers
- */
- {
- GLbitfield sysInputs = program->SystemValuesRead;
- unsigned numSys = 0;
- for (i = 0; sysInputs; i++) {
- if (sysInputs & (1 << i)) {
- unsigned semName = mesa_sysval_to_semantic[i];
- t->systemValues[i] = ureg_DECL_system_value(ureg, numSys, semName, 0);
- numSys++;
- sysInputs &= ~(1 << i);
- }
- }
- }
-
- if (program->IndirectRegisterFiles & (1 << PROGRAM_TEMPORARY)) {
- /* If temps are accessed with indirect addressing, declare temporaries
- * in sequential order. Else, we declare them on demand elsewhere.
- */
- for (i = 0; i < program->NumTemporaries; i++) {
- /* XXX use TGSI_FILE_TEMPORARY_ARRAY when it's supported by ureg */
- t->temps[i] = ureg_DECL_temporary( t->ureg );
- }
- }
-
- /* Emit constants and immediates. Mesa uses a single index space
- * for these, so we put all the translated regs in t->constants.
- */
- if (program->Parameters) {
- t->constants = CALLOC( program->Parameters->NumParameters,
- sizeof t->constants[0] );
- if (t->constants == NULL) {
- ret = PIPE_ERROR_OUT_OF_MEMORY;
- goto out;
- }
-
- for (i = 0; i < program->Parameters->NumParameters; i++) {
- switch (program->Parameters->Parameters[i].Type) {
- case PROGRAM_ENV_PARAM:
- case PROGRAM_LOCAL_PARAM:
- case PROGRAM_STATE_VAR:
- case PROGRAM_NAMED_PARAM:
- case PROGRAM_UNIFORM:
- t->constants[i] = ureg_DECL_constant( ureg, i );
- break;
-
- /* Emit immediates only when there's no indirect addressing of
- * the const buffer.
- * FIXME: Be smarter and recognize param arrays:
- * indirect addressing is only valid within the referenced
- * array.
- */
- case PROGRAM_CONSTANT:
- if (program->IndirectRegisterFiles & PROGRAM_ANY_CONST)
- t->constants[i] = ureg_DECL_constant( ureg, i );
- else
- t->constants[i] =
- ureg_DECL_immediate( ureg,
- program->Parameters->ParameterValues[i],
- 4 );
- break;
- default:
- break;
- }
- }
- }
-
- /* texture samplers */
- for (i = 0; i < ctx->Const.MaxTextureImageUnits; i++) {
- if (program->SamplersUsed & (1 << i)) {
- t->samplers[i] = ureg_DECL_sampler( ureg, i );
- }
- }
-
- /* Emit each instruction in turn:
- */
- for (i = 0; i < program->NumInstructions; i++) {
- set_insn_start( t, ureg_get_instruction_number( ureg ));
- compile_instruction( t, &program->Instructions[i] );
-
- if (t->prevInstWrotePointSize && program->Id) {
- /* The previous instruction wrote to the (fake) vertex point size
- * result register. Now we need to clamp that value to the min/max
- * point size range, putting the result into the real point size
- * register.
- * Note that we can't do this easily at the end of program due to
- * possible early return.
- */
- set_insn_start( t, ureg_get_instruction_number( ureg ));
- ureg_MAX( t->ureg,
- ureg_writemask(t->outputs[t->pointSizeOutIndex], WRITEMASK_X),
- ureg_src(t->outputs[t->pointSizeOutIndex]),
- ureg_swizzle(t->pointSizeConst, 1,1,1,1));
- ureg_MIN( t->ureg, ureg_writemask(t->pointSizeResult, WRITEMASK_X),
- ureg_src(t->outputs[t->pointSizeOutIndex]),
- ureg_swizzle(t->pointSizeConst, 2,2,2,2));
- }
- t->prevInstWrotePointSize = GL_FALSE;
- }
-
- /* Fix up all emitted labels:
- */
- for (i = 0; i < t->labels_count; i++) {
- ureg_fixup_label( ureg,
- t->labels[i].token,
- t->insn[t->labels[i].branch_target] );
- }
-
-out:
- FREE(t->insn);
- FREE(t->labels);
- FREE(t->constants);
-
- if (t->error) {
- debug_printf("%s: translate error flag set\n", __FUNCTION__);
- }
-
- return ret;
-}
-
-
-/**
- * Tokens cannot be free with free otherwise the builtin gallium
- * malloc debugging will get confused.
- */
-void
-st_free_tokens(const struct tgsi_token *tokens)
-{
- FREE((void *)tokens);
-}
+/**************************************************************************
+ *
+ * Copyright 2007-2008 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sub license, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial portions
+ * of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ **************************************************************************/
+
+/*
+ * \author
+ * Michal Krol,
+ * Keith Whitwell
+ */
+
+#include "pipe/p_compiler.h"
+#include "pipe/p_context.h"
+#include "pipe/p_screen.h"
+#include "pipe/p_shader_tokens.h"
+#include "pipe/p_state.h"
+#include "tgsi/tgsi_ureg.h"
+#include "st_mesa_to_tgsi.h"
+#include "st_context.h"
+#include "program/prog_instruction.h"
+#include "program/prog_parameter.h"
+#include "util/u_debug.h"
+#include "util/u_math.h"
+#include "util/u_memory.h"
+
+
+#define PROGRAM_ANY_CONST ((1 << PROGRAM_LOCAL_PARAM) | \
+ (1 << PROGRAM_ENV_PARAM) | \
+ (1 << PROGRAM_STATE_VAR) | \
+ (1 << PROGRAM_NAMED_PARAM) | \
+ (1 << PROGRAM_CONSTANT) | \
+ (1 << PROGRAM_UNIFORM))
+
+
+struct label {
+ unsigned branch_target;
+ unsigned token;
+};
+
+
+/**
+ * Intermediate state used during shader translation.
+ */
+struct st_translate {
+ struct ureg_program *ureg;
+
+ struct ureg_dst temps[MAX_PROGRAM_TEMPS];
+ struct ureg_src *constants;
+ struct ureg_dst outputs[PIPE_MAX_SHADER_OUTPUTS];
+ struct ureg_src inputs[PIPE_MAX_SHADER_INPUTS];
+ struct ureg_dst address[1];
+ struct ureg_src samplers[PIPE_MAX_SAMPLERS];
+ struct ureg_src systemValues[SYSTEM_VALUE_MAX];
+
+ /* Extra info for handling point size clamping in vertex shader */
+ struct ureg_dst pointSizeResult; /**< Actual point size output register */
+ struct ureg_src pointSizeConst; /**< Point size range constant register */
+ GLint pointSizeOutIndex; /**< Temp point size output register */
+ GLboolean prevInstWrotePointSize;
+
+ const GLuint *inputMapping;
+ const GLuint *outputMapping;
+
+ /* For every instruction that contains a label (eg CALL), keep
+ * details so that we can go back afterwards and emit the correct
+ * tgsi instruction number for each label.
+ */
+ struct label *labels;
+ unsigned labels_size;
+ unsigned labels_count;
+
+ /* Keep a record of the tgsi instruction number that each mesa
+ * instruction starts at, will be used to fix up labels after
+ * translation.
+ */
+ unsigned *insn;
+ unsigned insn_size;
+ unsigned insn_count;
+
+ unsigned procType; /**< TGSI_PROCESSOR_VERTEX/FRAGMENT */
+
+ boolean error;
+};
+
+
+/** Map Mesa's SYSTEM_VALUE_x to TGSI_SEMANTIC_x */
+static unsigned mesa_sysval_to_semantic[SYSTEM_VALUE_MAX] = {
+ TGSI_SEMANTIC_FACE,
+ TGSI_SEMANTIC_INSTANCEID
+};
+
+
+/**
+ * Make note of a branch to a label in the TGSI code.
+ * After we've emitted all instructions, we'll go over the list
+ * of labels built here and patch the TGSI code with the actual
+ * location of each label.
+ */
+static unsigned *get_label( struct st_translate *t,
+ unsigned branch_target )
+{
+ unsigned i;
+
+ if (t->labels_count + 1 >= t->labels_size) {
+ unsigned old_size = t->labels_size;
+ t->labels_size = 1 << (util_logbase2(t->labels_size) + 1);
+ t->labels = REALLOC( t->labels,
+ old_size * sizeof t->labels[0],
+ t->labels_size * sizeof t->labels[0] );
+ if (t->labels == NULL) {
+ static unsigned dummy;
+ t->error = TRUE;
+ return &dummy;
+ }
+ }
+
+ i = t->labels_count++;
+ t->labels[i].branch_target = branch_target;
+ return &t->labels[i].token;
+}
+
+
+/**
+ * Called prior to emitting the TGSI code for each Mesa instruction.
+ * Allocate additional space for instructions if needed.
+ * Update the insn[] array so the next Mesa instruction points to
+ * the next TGSI instruction.
+ */
+static void set_insn_start( struct st_translate *t,
+ unsigned start )
+{
+ if (t->insn_count + 1 >= t->insn_size) {
+ unsigned old_size = t->insn_size;
+ t->insn_size = 1 << (util_logbase2(t->insn_size) + 1);
+ t->insn = REALLOC( t->insn,
+ old_size * sizeof t->insn[0],
+ t->insn_size * sizeof t->insn[0] );
+ if (t->insn == NULL) {
+ t->error = TRUE;
+ return;
+ }
+ }
+
+ t->insn[t->insn_count++] = start;
+}
+
+
+/**
+ * Map a Mesa dst register to a TGSI ureg_dst register.
+ */
+static struct ureg_dst
+dst_register( struct st_translate *t,
+ gl_register_file file,
+ GLuint index )
+{
+ switch( file ) {
+ case PROGRAM_UNDEFINED:
+ return ureg_dst_undef();
+
+ case PROGRAM_TEMPORARY:
+ if (ureg_dst_is_undef(t->temps[index]))
+ t->temps[index] = ureg_DECL_temporary( t->ureg );
+
+ return t->temps[index];
+
+ case PROGRAM_OUTPUT:
+ if (t->procType == TGSI_PROCESSOR_VERTEX && index == VERT_RESULT_PSIZ)
+ t->prevInstWrotePointSize = GL_TRUE;
+
+ if (t->procType == TGSI_PROCESSOR_VERTEX)
+ assert(index < VERT_RESULT_MAX);
+ else if (t->procType == TGSI_PROCESSOR_FRAGMENT)
+ assert(index < FRAG_RESULT_MAX);
+ else
+ assert(index < GEOM_RESULT_MAX);
+
+ assert(t->outputMapping[index] < Elements(t->outputs));
+
+ return t->outputs[t->outputMapping[index]];
+
+ case PROGRAM_ADDRESS:
+ return t->address[index];
+
+ default:
+ debug_assert( 0 );
+ return ureg_dst_undef();
+ }
+}
+
+
+/**
+ * Map a Mesa src register to a TGSI ureg_src register.
+ */
+static struct ureg_src
+src_register( struct st_translate *t,
+ gl_register_file file,
+ GLint index )
+{
+ switch( file ) {
+ case PROGRAM_UNDEFINED:
+ return ureg_src_undef();
+
+ case PROGRAM_TEMPORARY:
+ assert(index >= 0);
+ if (ureg_dst_is_undef(t->temps[index]))
+ t->temps[index] = ureg_DECL_temporary( t->ureg );
+ assert(index < Elements(t->temps));
+ return ureg_src(t->temps[index]);
+
+ case PROGRAM_NAMED_PARAM:
+ case PROGRAM_ENV_PARAM:
+ case PROGRAM_LOCAL_PARAM:
+ case PROGRAM_UNIFORM:
+ assert(index >= 0);
+ return t->constants[index];
+ case PROGRAM_STATE_VAR:
+ case PROGRAM_CONSTANT: /* ie, immediate */
+ if (index < 0)
+ return ureg_DECL_constant( t->ureg, 0 );
+ else
+ return t->constants[index];
+
+ case PROGRAM_INPUT:
+ assert(t->inputMapping[index] < Elements(t->inputs));
+ return t->inputs[t->inputMapping[index]];
+
+ case PROGRAM_OUTPUT:
+ assert(t->outputMapping[index] < Elements(t->outputs));
+ return ureg_src(t->outputs[t->outputMapping[index]]); /* not needed? */
+
+ case PROGRAM_ADDRESS:
+ return ureg_src(t->address[index]);
+
+ case PROGRAM_SYSTEM_VALUE:
+ assert(index < Elements(t->systemValues));
+ return t->systemValues[index];
+
+ default:
+ debug_assert( 0 );
+ return ureg_src_undef();
+ }
+}
+
+
+/**
+ * Map mesa texture target to TGSI texture target.
+ */
+static unsigned
+translate_texture_target( GLuint textarget,
+ GLboolean shadow )
+{
+ if (shadow) {
+ switch( textarget ) {
+ case TEXTURE_1D_INDEX: return TGSI_TEXTURE_SHADOW1D;
+ case TEXTURE_2D_INDEX: return TGSI_TEXTURE_SHADOW2D;
+ case TEXTURE_RECT_INDEX: return TGSI_TEXTURE_SHADOWRECT;
+ default: break;
+ }
+ }
+
+ switch( textarget ) {
+ case TEXTURE_1D_INDEX: return TGSI_TEXTURE_1D;
+ case TEXTURE_2D_INDEX: return TGSI_TEXTURE_2D;
+ case TEXTURE_3D_INDEX: return TGSI_TEXTURE_3D;
+ case TEXTURE_CUBE_INDEX: return TGSI_TEXTURE_CUBE;
+ case TEXTURE_RECT_INDEX: return TGSI_TEXTURE_RECT;
+ case TEXTURE_1D_ARRAY_INDEX: return TGSI_TEXTURE_1D_ARRAY;
+ case TEXTURE_2D_ARRAY_INDEX: return TGSI_TEXTURE_2D_ARRAY;
+ default:
+ debug_assert( 0 );
+ return TGSI_TEXTURE_1D;
+ }
+}
+
+
+/**
+ * Create a TGSI ureg_dst register from a Mesa dest register.
+ */
+static struct ureg_dst
+translate_dst( struct st_translate *t,
+ const struct prog_dst_register *DstReg,
+ boolean saturate )
+{
+ struct ureg_dst dst = dst_register( t,
+ DstReg->File,
+ DstReg->Index );
+
+ dst = ureg_writemask( dst,
+ DstReg->WriteMask );
+
+ if (saturate)
+ dst = ureg_saturate( dst );
+
+ if (DstReg->RelAddr)
+ dst = ureg_dst_indirect( dst, ureg_src(t->address[0]) );
+
+ return dst;
+}
+
+
+/**
+ * Create a TGSI ureg_src register from a Mesa src register.
+ */
+static struct ureg_src
+translate_src( struct st_translate *t,
+ const struct prog_src_register *SrcReg )
+{
+ struct ureg_src src = src_register( t, SrcReg->File, SrcReg->Index );
+
+ if (t->procType == TGSI_PROCESSOR_GEOMETRY && SrcReg->HasIndex2) {
+ src = src_register( t, SrcReg->File, SrcReg->Index2 );
+ if (SrcReg->RelAddr2)
+ src = ureg_src_dimension_indirect( src, ureg_src(t->address[0]),
+ SrcReg->Index);
+ else
+ src = ureg_src_dimension( src, SrcReg->Index);
+ }
+
+ src = ureg_swizzle( src,
+ GET_SWZ( SrcReg->Swizzle, 0 ) & 0x3,
+ GET_SWZ( SrcReg->Swizzle, 1 ) & 0x3,
+ GET_SWZ( SrcReg->Swizzle, 2 ) & 0x3,
+ GET_SWZ( SrcReg->Swizzle, 3 ) & 0x3);
+
+ if (SrcReg->Negate == NEGATE_XYZW)
+ src = ureg_negate(src);
+
+ if (SrcReg->Abs)
+ src = ureg_abs(src);
+
+ if (SrcReg->RelAddr) {
+ src = ureg_src_indirect( src, ureg_src(t->address[0]));
+ if (SrcReg->File != PROGRAM_INPUT &&
+ SrcReg->File != PROGRAM_OUTPUT) {
+ /* If SrcReg->Index was negative, it was set to zero in
+ * src_register(). Reassign it now. But don't do this
+ * for input/output regs since they get remapped while
+ * const buffers don't.
+ */
+ src.Index = SrcReg->Index;
+ }
+ }
+
+ return src;
+}
+
+
+static struct ureg_src swizzle_4v( struct ureg_src src,
+ const unsigned *swz )
+{
+ return ureg_swizzle( src, swz[0], swz[1], swz[2], swz[3] );
+}
+
+
+/**
+ * Translate a SWZ instruction into a MOV, MUL or MAD instruction. EG:
+ *
+ * SWZ dst, src.x-y10
+ *
+ * becomes:
+ *
+ * MAD dst {1,-1,0,0}, src.xyxx, {0,0,1,0}
+ */
+static void emit_swz( struct st_translate *t,
+ struct ureg_dst dst,
+ const struct prog_src_register *SrcReg )
+{
+ struct ureg_program *ureg = t->ureg;
+ struct ureg_src src = src_register( t, SrcReg->File, SrcReg->Index );
+
+ unsigned negate_mask = SrcReg->Negate;
+
+ unsigned one_mask = ((GET_SWZ(SrcReg->Swizzle, 0) == SWIZZLE_ONE) << 0 |
+ (GET_SWZ(SrcReg->Swizzle, 1) == SWIZZLE_ONE) << 1 |
+ (GET_SWZ(SrcReg->Swizzle, 2) == SWIZZLE_ONE) << 2 |
+ (GET_SWZ(SrcReg->Swizzle, 3) == SWIZZLE_ONE) << 3);
+
+ unsigned zero_mask = ((GET_SWZ(SrcReg->Swizzle, 0) == SWIZZLE_ZERO) << 0 |
+ (GET_SWZ(SrcReg->Swizzle, 1) == SWIZZLE_ZERO) << 1 |
+ (GET_SWZ(SrcReg->Swizzle, 2) == SWIZZLE_ZERO) << 2 |
+ (GET_SWZ(SrcReg->Swizzle, 3) == SWIZZLE_ZERO) << 3);
+
+ unsigned negative_one_mask = one_mask & negate_mask;
+ unsigned positive_one_mask = one_mask & ~negate_mask;
+
+ struct ureg_src imm;
+ unsigned i;
+ unsigned mul_swizzle[4] = {0,0,0,0};
+ unsigned add_swizzle[4] = {0,0,0,0};
+ unsigned src_swizzle[4] = {0,0,0,0};
+ boolean need_add = FALSE;
+ boolean need_mul = FALSE;
+
+ if (dst.WriteMask == 0)
+ return;
+
+ /* Is this just a MOV?
+ */
+ if (zero_mask == 0 &&
+ one_mask == 0 &&
+ (negate_mask == 0 || negate_mask == TGSI_WRITEMASK_XYZW))
+ {
+ ureg_MOV( ureg, dst, translate_src( t, SrcReg ));
+ return;
+ }
+
+#define IMM_ZERO 0
+#define IMM_ONE 1
+#define IMM_NEG_ONE 2
+
+ imm = ureg_imm3f( ureg, 0, 1, -1 );
+
+ for (i = 0; i < 4; i++) {
+ unsigned bit = 1 << i;
+
+ if (dst.WriteMask & bit) {
+ if (positive_one_mask & bit) {
+ mul_swizzle[i] = IMM_ZERO;
+ add_swizzle[i] = IMM_ONE;
+ need_add = TRUE;
+ }
+ else if (negative_one_mask & bit) {
+ mul_swizzle[i] = IMM_ZERO;
+ add_swizzle[i] = IMM_NEG_ONE;
+ need_add = TRUE;
+ }
+ else if (zero_mask & bit) {
+ mul_swizzle[i] = IMM_ZERO;
+ add_swizzle[i] = IMM_ZERO;
+ need_add = TRUE;
+ }
+ else {
+ add_swizzle[i] = IMM_ZERO;
+ src_swizzle[i] = GET_SWZ(SrcReg->Swizzle, i);
+ need_mul = TRUE;
+ if (negate_mask & bit) {
+ mul_swizzle[i] = IMM_NEG_ONE;
+ }
+ else {
+ mul_swizzle[i] = IMM_ONE;
+ }
+ }
+ }
+ }
+
+ if (need_mul && need_add) {
+ ureg_MAD( ureg,
+ dst,
+ swizzle_4v( src, src_swizzle ),
+ swizzle_4v( imm, mul_swizzle ),
+ swizzle_4v( imm, add_swizzle ) );
+ }
+ else if (need_mul) {
+ ureg_MUL( ureg,
+ dst,
+ swizzle_4v( src, src_swizzle ),
+ swizzle_4v( imm, mul_swizzle ) );
+ }
+ else if (need_add) {
+ ureg_MOV( ureg,
+ dst,
+ swizzle_4v( imm, add_swizzle ) );
+ }
+ else {
+ debug_assert(0);
+ }
+
+#undef IMM_ZERO
+#undef IMM_ONE
+#undef IMM_NEG_ONE
+}
+
+
+/**
+ * Negate the value of DDY to match GL semantics where (0,0) is the
+ * lower-left corner of the window.
+ * Note that the GL_ARB_fragment_coord_conventions extension will
+ * effect this someday.
+ */
+static void emit_ddy( struct st_translate *t,
+ struct ureg_dst dst,
+ const struct prog_src_register *SrcReg )
+{
+ struct ureg_program *ureg = t->ureg;
+ struct ureg_src src = translate_src( t, SrcReg );
+ src = ureg_negate( src );
+ ureg_DDY( ureg, dst, src );
+}
+
+
+
+static unsigned
+translate_opcode( unsigned op )
+{
+ switch( op ) {
+ case OPCODE_ARL:
+ return TGSI_OPCODE_ARL;
+ case OPCODE_ABS:
+ return TGSI_OPCODE_ABS;
+ case OPCODE_ADD:
+ return TGSI_OPCODE_ADD;
+ case OPCODE_BGNLOOP:
+ return TGSI_OPCODE_BGNLOOP;
+ case OPCODE_BGNSUB:
+ return TGSI_OPCODE_BGNSUB;
+ case OPCODE_BRA:
+ return TGSI_OPCODE_BRA;
+ case OPCODE_BRK:
+ return TGSI_OPCODE_BRK;
+ case OPCODE_CAL:
+ return TGSI_OPCODE_CAL;
+ case OPCODE_CMP:
+ return TGSI_OPCODE_CMP;
+ case OPCODE_CONT:
+ return TGSI_OPCODE_CONT;
+ case OPCODE_COS:
+ return TGSI_OPCODE_COS;
+ case OPCODE_DDX:
+ return TGSI_OPCODE_DDX;
+ case OPCODE_DDY:
+ return TGSI_OPCODE_DDY;
+ case OPCODE_DP2:
+ return TGSI_OPCODE_DP2;
+ case OPCODE_DP2A:
+ return TGSI_OPCODE_DP2A;
+ case OPCODE_DP3:
+ return TGSI_OPCODE_DP3;
+ case OPCODE_DP4:
+ return TGSI_OPCODE_DP4;
+ case OPCODE_DPH:
+ return TGSI_OPCODE_DPH;
+ case OPCODE_DST:
+ return TGSI_OPCODE_DST;
+ case OPCODE_ELSE:
+ return TGSI_OPCODE_ELSE;
+ case OPCODE_EMIT_VERTEX:
+ return TGSI_OPCODE_EMIT;
+ case OPCODE_END_PRIMITIVE:
+ return TGSI_OPCODE_ENDPRIM;
+ case OPCODE_ENDIF:
+ return TGSI_OPCODE_ENDIF;
+ case OPCODE_ENDLOOP:
+ return TGSI_OPCODE_ENDLOOP;
+ case OPCODE_ENDSUB:
+ return TGSI_OPCODE_ENDSUB;
+ case OPCODE_EX2:
+ return TGSI_OPCODE_EX2;
+ case OPCODE_EXP:
+ return TGSI_OPCODE_EXP;
+ case OPCODE_FLR:
+ return TGSI_OPCODE_FLR;
+ case OPCODE_FRC:
+ return TGSI_OPCODE_FRC;
+ case OPCODE_IF:
+ return TGSI_OPCODE_IF;
+ case OPCODE_TRUNC:
+ return TGSI_OPCODE_TRUNC;
+ case OPCODE_KIL:
+ return TGSI_OPCODE_KIL;
+ case OPCODE_KIL_NV:
+ return TGSI_OPCODE_KILP;
+ case OPCODE_LG2:
+ return TGSI_OPCODE_LG2;
+ case OPCODE_LOG:
+ return TGSI_OPCODE_LOG;
+ case OPCODE_LIT:
+ return TGSI_OPCODE_LIT;
+ case OPCODE_LRP:
+ return TGSI_OPCODE_LRP;
+ case OPCODE_MAD:
+ return TGSI_OPCODE_MAD;
+ case OPCODE_MAX:
+ return TGSI_OPCODE_MAX;
+ case OPCODE_MIN:
+ return TGSI_OPCODE_MIN;
+ case OPCODE_MOV:
+ return TGSI_OPCODE_MOV;
+ case OPCODE_MUL:
+ return TGSI_OPCODE_MUL;
+ case OPCODE_NOP:
+ return TGSI_OPCODE_NOP;
+ case OPCODE_NRM3:
+ return TGSI_OPCODE_NRM;
+ case OPCODE_NRM4:
+ return TGSI_OPCODE_NRM4;
+ case OPCODE_POW:
+ return TGSI_OPCODE_POW;
+ case OPCODE_RCP:
+ return TGSI_OPCODE_RCP;
+ case OPCODE_RET:
+ return TGSI_OPCODE_RET;
+ case OPCODE_RSQ:
+ return TGSI_OPCODE_RSQ;
+ case OPCODE_SCS:
+ return TGSI_OPCODE_SCS;
+ case OPCODE_SEQ:
+ return TGSI_OPCODE_SEQ;
+ case OPCODE_SGE:
+ return TGSI_OPCODE_SGE;
+ case OPCODE_SGT:
+ return TGSI_OPCODE_SGT;
+ case OPCODE_SIN:
+ return TGSI_OPCODE_SIN;
+ case OPCODE_SLE:
+ return TGSI_OPCODE_SLE;
+ case OPCODE_SLT:
+ return TGSI_OPCODE_SLT;
+ case OPCODE_SNE:
+ return TGSI_OPCODE_SNE;
+ case OPCODE_SSG:
+ return TGSI_OPCODE_SSG;
+ case OPCODE_SUB:
+ return TGSI_OPCODE_SUB;
+ case OPCODE_TEX:
+ return TGSI_OPCODE_TEX;
+ case OPCODE_TXB:
+ return TGSI_OPCODE_TXB;
+ case OPCODE_TXD:
+ return TGSI_OPCODE_TXD;
+ case OPCODE_TXL:
+ return TGSI_OPCODE_TXL;
+ case OPCODE_TXP:
+ return TGSI_OPCODE_TXP;
+ case OPCODE_XPD:
+ return TGSI_OPCODE_XPD;
+ case OPCODE_END:
+ return TGSI_OPCODE_END;
+ default:
+ debug_assert( 0 );
+ return TGSI_OPCODE_NOP;
+ }
+}
+
+
+static void
+compile_instruction(
+ struct st_translate *t,
+ const struct prog_instruction *inst )
+{
+ struct ureg_program *ureg = t->ureg;
+ GLuint i;
+ struct ureg_dst dst[1];
+ struct ureg_src src[4];
+ unsigned num_dst;
+ unsigned num_src;
+
+ num_dst = _mesa_num_inst_dst_regs( inst->Opcode );
+ num_src = _mesa_num_inst_src_regs( inst->Opcode );
+
+ if (num_dst)
+ dst[0] = translate_dst( t,
+ &inst->DstReg,
+ inst->SaturateMode );
+
+ for (i = 0; i < num_src; i++)
+ src[i] = translate_src( t, &inst->SrcReg[i] );
+
+ switch( inst->Opcode ) {
+ case OPCODE_SWZ:
+ emit_swz( t, dst[0], &inst->SrcReg[0] );
+ return;
+
+ case OPCODE_BGNLOOP:
+ case OPCODE_CAL:
+ case OPCODE_ELSE:
+ case OPCODE_ENDLOOP:
+ case OPCODE_IF:
+ debug_assert(num_dst == 0);
+ ureg_label_insn( ureg,
+ translate_opcode( inst->Opcode ),
+ src, num_src,
+ get_label( t, inst->BranchTarget ));
+ return;
+
+ case OPCODE_TEX:
+ case OPCODE_TXB:
+ case OPCODE_TXD:
+ case OPCODE_TXL:
+ case OPCODE_TXP:
+ src[num_src++] = t->samplers[inst->TexSrcUnit];
+ ureg_tex_insn( ureg,
+ translate_opcode( inst->Opcode ),
+ dst, num_dst,
+ translate_texture_target( inst->TexSrcTarget,
+ inst->TexShadow ),
+ src, num_src );
+ return;
+
+ case OPCODE_SCS:
+ dst[0] = ureg_writemask(dst[0], TGSI_WRITEMASK_XY );
+ ureg_insn( ureg,
+ translate_opcode( inst->Opcode ),
+ dst, num_dst,
+ src, num_src );
+ break;
+
+ case OPCODE_XPD:
+ dst[0] = ureg_writemask(dst[0], TGSI_WRITEMASK_XYZ );
+ ureg_insn( ureg,
+ translate_opcode( inst->Opcode ),
+ dst, num_dst,
+ src, num_src );
+ break;
+
+ case OPCODE_NOISE1:
+ case OPCODE_NOISE2:
+ case OPCODE_NOISE3:
+ case OPCODE_NOISE4:
+ /* At some point, a motivated person could add a better
+ * implementation of noise. Currently not even the nvidia
+ * binary drivers do anything more than this. In any case, the
+ * place to do this is in the GL state tracker, not the poor
+ * driver.
+ */
+ ureg_MOV( ureg, dst[0], ureg_imm1f(ureg, 0.5) );
+ break;
+
+ case OPCODE_DDY:
+ emit_ddy( t, dst[0], &inst->SrcReg[0] );
+ break;
+
+ default:
+ ureg_insn( ureg,
+ translate_opcode( inst->Opcode ),
+ dst, num_dst,
+ src, num_src );
+ break;
+ }
+}
+
+
+/**
+ * Emit the TGSI instructions to adjust the WPOS pixel center convention
+ * Basically, add (adjX, adjY) to the fragment position.
+ */
+static void
+emit_adjusted_wpos( struct st_translate *t,
+ const struct gl_program *program,
+ GLfloat adjX, GLfloat adjY)
+{
+ struct ureg_program *ureg = t->ureg;
+ struct ureg_dst wpos_temp = ureg_DECL_temporary(ureg);
+ struct ureg_src wpos_input = t->inputs[t->inputMapping[FRAG_ATTRIB_WPOS]];
+
+ /* Note that we bias X and Y and pass Z and W through unchanged.
+ * The shader might also use gl_FragCoord.w and .z.
+ */
+ ureg_ADD(ureg, wpos_temp, wpos_input,
+ ureg_imm4f(ureg, adjX, adjY, 0.0f, 0.0f));
+
+ t->inputs[t->inputMapping[FRAG_ATTRIB_WPOS]] = ureg_src(wpos_temp);
+}
+
+
+/**
+ * Emit the TGSI instructions for inverting the WPOS y coordinate.
+ * This code is unavoidable because it also depends on whether
+ * a FBO is bound (STATE_FB_WPOS_Y_TRANSFORM).
+ */
+static void
+emit_wpos_inversion( struct st_translate *t,
+ const struct gl_program *program,
+ boolean invert)
+{
+ struct ureg_program *ureg = t->ureg;
+
+ /* Fragment program uses fragment position input.
+ * Need to replace instances of INPUT[WPOS] with temp T
+ * where T = INPUT[WPOS] by y is inverted.
+ */
+ static const gl_state_index wposTransformState[STATE_LENGTH]
+ = { STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM, 0, 0, 0 };
+
+ /* XXX: note we are modifying the incoming shader here! Need to
+ * do this before emitting the constant decls below, or this
+ * will be missed:
+ */
+ unsigned wposTransConst = _mesa_add_state_reference(program->Parameters,
+ wposTransformState);
+
+ struct ureg_src wpostrans = ureg_DECL_constant( ureg, wposTransConst );
+ struct ureg_dst wpos_temp;
+ struct ureg_src wpos_input = t->inputs[t->inputMapping[FRAG_ATTRIB_WPOS]];
+
+ /* MOV wpos_temp, input[wpos]
+ */
+ if (wpos_input.File == TGSI_FILE_TEMPORARY)
+ wpos_temp = ureg_dst(wpos_input);
+ else {
+ wpos_temp = ureg_DECL_temporary( ureg );
+ ureg_MOV( ureg, wpos_temp, wpos_input );
+ }
+
+ if (invert) {
+ /* MAD wpos_temp.y, wpos_input, wpostrans.xxxx, wpostrans.yyyy
+ */
+ ureg_MAD( ureg,
+ ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
+ wpos_input,
+ ureg_scalar(wpostrans, 0),
+ ureg_scalar(wpostrans, 1));
+ } else {
+ /* MAD wpos_temp.y, wpos_input, wpostrans.zzzz, wpostrans.wwww
+ */
+ ureg_MAD( ureg,
+ ureg_writemask(wpos_temp, TGSI_WRITEMASK_Y ),
+ wpos_input,
+ ureg_scalar(wpostrans, 2),
+ ureg_scalar(wpostrans, 3));
+ }
+
+ /* Use wpos_temp as position input from here on:
+ */
+ t->inputs[t->inputMapping[FRAG_ATTRIB_WPOS]] = ureg_src(wpos_temp);
+}
+
+
+/**
+ * Emit fragment position/ooordinate code.
+ */
+static void
+emit_wpos(struct st_context *st,
+ struct st_translate *t,
+ const struct gl_program *program,
+ struct ureg_program *ureg)
+{
+ const struct gl_fragment_program *fp =
+ (const struct gl_fragment_program *) program;
+ struct pipe_screen *pscreen = st->pipe->screen;
+ boolean invert = FALSE;
+
+ if (fp->OriginUpperLeft) {
+ /* Fragment shader wants origin in upper-left */
+ if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT)) {
+ /* the driver supports upper-left origin */
+ }
+ else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT)) {
+ /* the driver supports lower-left origin, need to invert Y */
+ ureg_property_fs_coord_origin(ureg, TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
+ invert = TRUE;
+ }
+ else
+ assert(0);
+ }
+ else {
+ /* Fragment shader wants origin in lower-left */
+ if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT))
+ /* the driver supports lower-left origin */
+ ureg_property_fs_coord_origin(ureg, TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
+ else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT))
+ /* the driver supports upper-left origin, need to invert Y */
+ invert = TRUE;
+ else
+ assert(0);
+ }
+
+ if (fp->PixelCenterInteger) {
+ /* Fragment shader wants pixel center integer */
+ if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER))
+ /* the driver supports pixel center integer */
+ ureg_property_fs_coord_pixel_center(ureg, TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
+ else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER))
+ /* the driver supports pixel center half integer, need to bias X,Y */
+ emit_adjusted_wpos(t, program, 0.5f, invert ? 0.5f : -0.5f);
+ else
+ assert(0);
+ }
+ else {
+ /* Fragment shader wants pixel center half integer */
+ if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER)) {
+ /* the driver supports pixel center half integer */
+ }
+ else if (pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER)) {
+ /* the driver supports pixel center integer, need to bias X,Y */
+ ureg_property_fs_coord_pixel_center(ureg, TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
+ emit_adjusted_wpos(t, program, 0.5f, invert ? -0.5f : 0.5f);
+ }
+ else
+ assert(0);
+ }
+
+ /* we invert after adjustment so that we avoid the MOV to temporary,
+ * and reuse the adjustment ADD instead */
+ emit_wpos_inversion(t, program, invert);
+}
+
+
+/**
+ * OpenGL's fragment gl_FrontFace input is 1 for front-facing, 0 for back.
+ * TGSI uses +1 for front, -1 for back.
+ * This function converts the TGSI value to the GL value. Simply clamping/
+ * saturating the value to [0,1] does the job.
+ */
+static void
+emit_face_var( struct st_translate *t,
+ const struct gl_program *program )
+{
+ struct ureg_program *ureg = t->ureg;
+ struct ureg_dst face_temp = ureg_DECL_temporary( ureg );
+ struct ureg_src face_input = t->inputs[t->inputMapping[FRAG_ATTRIB_FACE]];
+
+ /* MOV_SAT face_temp, input[face]
+ */
+ face_temp = ureg_saturate( face_temp );
+ ureg_MOV( ureg, face_temp, face_input );
+
+ /* Use face_temp as face input from here on:
+ */
+ t->inputs[t->inputMapping[FRAG_ATTRIB_FACE]] = ureg_src(face_temp);
+}
+
+
+static void
+emit_edgeflags( struct st_translate *t,
+ const struct gl_program *program )
+{
+ struct ureg_program *ureg = t->ureg;
+ struct ureg_dst edge_dst = t->outputs[t->outputMapping[VERT_RESULT_EDGE]];
+ struct ureg_src edge_src = t->inputs[t->inputMapping[VERT_ATTRIB_EDGEFLAG]];
+
+ ureg_MOV( ureg, edge_dst, edge_src );
+}
+
+
+/**
+ * Translate Mesa program to TGSI format.
+ * \param program the program to translate
+ * \param numInputs number of input registers used
+ * \param inputMapping maps Mesa fragment program inputs to TGSI generic
+ * input indexes
+ * \param inputSemanticName the TGSI_SEMANTIC flag for each input
+ * \param inputSemanticIndex the semantic index (ex: which texcoord) for
+ * each input
+ * \param interpMode the TGSI_INTERPOLATE_LINEAR/PERSP mode for each input
+ * \param numOutputs number of output registers used
+ * \param outputMapping maps Mesa fragment program outputs to TGSI
+ * generic outputs
+ * \param outputSemanticName the TGSI_SEMANTIC flag for each output
+ * \param outputSemanticIndex the semantic index (ex: which texcoord) for
+ * each output
+ *
+ * \return PIPE_OK or PIPE_ERROR_OUT_OF_MEMORY
+ */
+enum pipe_error
+st_translate_mesa_program(
+ struct gl_context *ctx,
+ uint procType,
+ struct ureg_program *ureg,
+ const struct gl_program *program,
+ GLuint numInputs,
+ const GLuint inputMapping[],
+ const ubyte inputSemanticName[],
+ const ubyte inputSemanticIndex[],
+ const GLuint interpMode[],
+ GLuint numOutputs,
+ const GLuint outputMapping[],
+ const ubyte outputSemanticName[],
+ const ubyte outputSemanticIndex[],
+ boolean passthrough_edgeflags )
+{
+ struct st_translate translate, *t;
+ unsigned i;
+ enum pipe_error ret = PIPE_OK;
+
+ assert(numInputs <= Elements(t->inputs));
+ assert(numOutputs <= Elements(t->outputs));
+
+ t = &translate;
+ memset(t, 0, sizeof *t);
+
+ t->procType = procType;
+ t->inputMapping = inputMapping;
+ t->outputMapping = outputMapping;
+ t->ureg = ureg;
+ t->pointSizeOutIndex = -1;
+ t->prevInstWrotePointSize = GL_FALSE;
+
+ /*_mesa_print_program(program);*/
+
+ /*
+ * Declare input attributes.
+ */
+ if (procType == TGSI_PROCESSOR_FRAGMENT) {
+ for (i = 0; i < numInputs; i++) {
+ if (program->InputFlags[0] & PROG_PARAM_BIT_CYL_WRAP) {
+ t->inputs[i] = ureg_DECL_fs_input_cyl(ureg,
+ inputSemanticName[i],
+ inputSemanticIndex[i],
+ interpMode[i],
+ TGSI_CYLINDRICAL_WRAP_X);
+ }
+ else {
+ t->inputs[i] = ureg_DECL_fs_input(ureg,
+ inputSemanticName[i],
+ inputSemanticIndex[i],
+ interpMode[i]);
+ }
+ }
+
+ if (program->InputsRead & FRAG_BIT_WPOS) {
+ /* Must do this after setting up t->inputs, and before
+ * emitting constant references, below:
+ */
+ emit_wpos(st_context(ctx), t, program, ureg);
+ }
+
+ if (program->InputsRead & FRAG_BIT_FACE) {
+ emit_face_var( t, program );
+ }
+
+ /*
+ * Declare output attributes.
+ */
+ for (i = 0; i < numOutputs; i++) {
+ switch (outputSemanticName[i]) {
+ case TGSI_SEMANTIC_POSITION:
+ t->outputs[i] = ureg_DECL_output( ureg,
+ TGSI_SEMANTIC_POSITION, /* Z / Depth */
+ outputSemanticIndex[i] );
+
+ t->outputs[i] = ureg_writemask( t->outputs[i],
+ TGSI_WRITEMASK_Z );
+ break;
+ case TGSI_SEMANTIC_STENCIL:
+ t->outputs[i] = ureg_DECL_output( ureg,
+ TGSI_SEMANTIC_STENCIL, /* Stencil */
+ outputSemanticIndex[i] );
+ t->outputs[i] = ureg_writemask( t->outputs[i],
+ TGSI_WRITEMASK_Y );
+ break;
+ case TGSI_SEMANTIC_COLOR:
+ t->outputs[i] = ureg_DECL_output( ureg,
+ TGSI_SEMANTIC_COLOR,
+ outputSemanticIndex[i] );
+ break;
+ default:
+ debug_assert(0);
+ return 0;
+ }
+ }
+ }
+ else if (procType == TGSI_PROCESSOR_GEOMETRY) {
+ for (i = 0; i < numInputs; i++) {
+ t->inputs[i] = ureg_DECL_gs_input(ureg,
+ i,
+ inputSemanticName[i],
+ inputSemanticIndex[i]);
+ }
+
+ for (i = 0; i < numOutputs; i++) {
+ t->outputs[i] = ureg_DECL_output( ureg,
+ outputSemanticName[i],
+ outputSemanticIndex[i] );
+ }
+ }
+ else {
+ assert(procType == TGSI_PROCESSOR_VERTEX);
+
+ for (i = 0; i < numInputs; i++) {
+ t->inputs[i] = ureg_DECL_vs_input(ureg, i);
+ }
+
+ for (i = 0; i < numOutputs; i++) {
+ t->outputs[i] = ureg_DECL_output( ureg,
+ outputSemanticName[i],
+ outputSemanticIndex[i] );
+ if ((outputSemanticName[i] == TGSI_SEMANTIC_PSIZE) && program->Id) {
+ /* Writing to the point size result register requires special
+ * handling to implement clamping.
+ */
+ static const gl_state_index pointSizeClampState[STATE_LENGTH]
+ = { STATE_INTERNAL, STATE_POINT_SIZE_IMPL_CLAMP, 0, 0, 0 };
+ /* XXX: note we are modifying the incoming shader here! Need to
+ * do this before emitting the constant decls below, or this
+ * will be missed:
+ */
+ unsigned pointSizeClampConst =
+ _mesa_add_state_reference(program->Parameters,
+ pointSizeClampState);
+ struct ureg_dst psizregtemp = ureg_DECL_temporary( ureg );
+ t->pointSizeConst = ureg_DECL_constant( ureg, pointSizeClampConst );
+ t->pointSizeResult = t->outputs[i];
+ t->pointSizeOutIndex = i;
+ t->outputs[i] = psizregtemp;
+ }
+ }
+ if (passthrough_edgeflags)
+ emit_edgeflags( t, program );
+ }
+
+ /* Declare address register.
+ */
+ if (program->NumAddressRegs > 0) {
+ debug_assert( program->NumAddressRegs == 1 );
+ t->address[0] = ureg_DECL_address( ureg );
+ }
+
+ /* Declare misc input registers
+ */
+ {
+ GLbitfield sysInputs = program->SystemValuesRead;
+ unsigned numSys = 0;
+ for (i = 0; sysInputs; i++) {
+ if (sysInputs & (1 << i)) {
+ unsigned semName = mesa_sysval_to_semantic[i];
+ t->systemValues[i] = ureg_DECL_system_value(ureg, numSys, semName, 0);
+ numSys++;
+ sysInputs &= ~(1 << i);
+ }
+ }
+ }
+
+ if (program->IndirectRegisterFiles & (1 << PROGRAM_TEMPORARY)) {
+ /* If temps are accessed with indirect addressing, declare temporaries
+ * in sequential order. Else, we declare them on demand elsewhere.
+ */
+ for (i = 0; i < program->NumTemporaries; i++) {
+ /* XXX use TGSI_FILE_TEMPORARY_ARRAY when it's supported by ureg */
+ t->temps[i] = ureg_DECL_temporary( t->ureg );
+ }
+ }
+
+ /* Emit constants and immediates. Mesa uses a single index space
+ * for these, so we put all the translated regs in t->constants.
+ */
+ if (program->Parameters) {
+ t->constants = CALLOC( program->Parameters->NumParameters,
+ sizeof t->constants[0] );
+ if (t->constants == NULL) {
+ ret = PIPE_ERROR_OUT_OF_MEMORY;
+ goto out;
+ }
+
+ for (i = 0; i < program->Parameters->NumParameters; i++) {
+ switch (program->Parameters->Parameters[i].Type) {
+ case PROGRAM_ENV_PARAM:
+ case PROGRAM_LOCAL_PARAM:
+ case PROGRAM_STATE_VAR:
+ case PROGRAM_NAMED_PARAM:
+ case PROGRAM_UNIFORM:
+ t->constants[i] = ureg_DECL_constant( ureg, i );
+ break;
+
+ /* Emit immediates only when there's no indirect addressing of
+ * the const buffer.
+ * FIXME: Be smarter and recognize param arrays:
+ * indirect addressing is only valid within the referenced
+ * array.
+ */
+ case PROGRAM_CONSTANT:
+ if (program->IndirectRegisterFiles & PROGRAM_ANY_CONST)
+ t->constants[i] = ureg_DECL_constant( ureg, i );
+ else
+ t->constants[i] =
+ ureg_DECL_immediate( ureg,
+ program->Parameters->ParameterValues[i],
+ 4 );
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ /* texture samplers */
+ for (i = 0; i < ctx->Const.MaxTextureImageUnits; i++) {
+ if (program->SamplersUsed & (1 << i)) {
+ t->samplers[i] = ureg_DECL_sampler( ureg, i );
+ }
+ }
+
+ /* Emit each instruction in turn:
+ */
+ for (i = 0; i < program->NumInstructions; i++) {
+ set_insn_start( t, ureg_get_instruction_number( ureg ));
+ compile_instruction( t, &program->Instructions[i] );
+
+ if (t->prevInstWrotePointSize && program->Id) {
+ /* The previous instruction wrote to the (fake) vertex point size
+ * result register. Now we need to clamp that value to the min/max
+ * point size range, putting the result into the real point size
+ * register.
+ * Note that we can't do this easily at the end of program due to
+ * possible early return.
+ */
+ set_insn_start( t, ureg_get_instruction_number( ureg ));
+ ureg_MAX( t->ureg,
+ ureg_writemask(t->outputs[t->pointSizeOutIndex], WRITEMASK_X),
+ ureg_src(t->outputs[t->pointSizeOutIndex]),
+ ureg_swizzle(t->pointSizeConst, 1,1,1,1));
+ ureg_MIN( t->ureg, ureg_writemask(t->pointSizeResult, WRITEMASK_X),
+ ureg_src(t->outputs[t->pointSizeOutIndex]),
+ ureg_swizzle(t->pointSizeConst, 2,2,2,2));
+ }
+ t->prevInstWrotePointSize = GL_FALSE;
+ }
+
+ /* Fix up all emitted labels:
+ */
+ for (i = 0; i < t->labels_count; i++) {
+ ureg_fixup_label( ureg,
+ t->labels[i].token,
+ t->insn[t->labels[i].branch_target] );
+ }
+
+out:
+ FREE(t->insn);
+ FREE(t->labels);
+ FREE(t->constants);
+
+ if (t->error) {
+ debug_printf("%s: translate error flag set\n", __FUNCTION__);
+ }
+
+ return ret;
+}
+
+
+/**
+ * Tokens cannot be free with free otherwise the builtin gallium
+ * malloc debugging will get confused.
+ */
+void
+st_free_tokens(const struct tgsi_token *tokens)
+{
+ FREE((void *)tokens);
+}