Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Blame | Last modification | View Log | Download | RSS feed

  1. /*
  2.  * Copyright (C) 2005-2007  Brian Paul   All Rights Reserved.
  3.  * Copyright (C) 2008  VMware, Inc.   All Rights Reserved.
  4.  * Copyright © 2010 Intel Corporation
  5.  *
  6.  * Permission is hereby granted, free of charge, to any person obtaining a
  7.  * copy of this software and associated documentation files (the "Software"),
  8.  * to deal in the Software without restriction, including without limitation
  9.  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  10.  * and/or sell copies of the Software, and to permit persons to whom the
  11.  * Software is furnished to do so, subject to the following conditions:
  12.  *
  13.  * The above copyright notice and this permission notice (including the next
  14.  * paragraph) shall be included in all copies or substantial portions of the
  15.  * Software.
  16.  *
  17.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18.  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19.  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  20.  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21.  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22.  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23.  * DEALINGS IN THE SOFTWARE.
  24.  */
  25.  
  26. /**
  27.  * \file ir_to_mesa.cpp
  28.  *
  29.  * Translate GLSL IR to Mesa's gl_program representation.
  30.  */
  31.  
  32. #include <stdio.h>
  33. #include "main/compiler.h"
  34. #include "ir.h"
  35. #include "ir_visitor.h"
  36. #include "ir_print_visitor.h"
  37. #include "ir_expression_flattening.h"
  38. #include "glsl_types.h"
  39. #include "glsl_parser_extras.h"
  40. #include "../glsl/program.h"
  41. #include "ir_optimization.h"
  42. #include "ast.h"
  43.  
  44. extern "C" {
  45. #include "main/mtypes.h"
  46. #include "main/shaderapi.h"
  47. #include "main/shaderobj.h"
  48. #include "main/uniforms.h"
  49. #include "program/hash_table.h"
  50. #include "program/prog_instruction.h"
  51. #include "program/prog_optimize.h"
  52. #include "program/prog_print.h"
  53. #include "program/program.h"
  54. #include "program/prog_uniform.h"
  55. #include "program/prog_parameter.h"
  56. #include "program/sampler.h"
  57. }
  58.  
  59. static int swizzle_for_size(int size);
  60.  
  61. /**
  62.  * This struct is a corresponding struct to Mesa prog_src_register, with
  63.  * wider fields.
  64.  */
  65. typedef struct ir_to_mesa_src_reg {
  66.    ir_to_mesa_src_reg(int file, int index, const glsl_type *type)
  67.    {
  68.       this->file = (gl_register_file) file;
  69.       this->index = index;
  70.       if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
  71.          this->swizzle = swizzle_for_size(type->vector_elements);
  72.       else
  73.          this->swizzle = SWIZZLE_XYZW;
  74.       this->negate = 0;
  75.       this->reladdr = NULL;
  76.    }
  77.  
  78.    ir_to_mesa_src_reg()
  79.    {
  80.       this->file = PROGRAM_UNDEFINED;
  81.       this->index = 0;
  82.       this->swizzle = 0;
  83.       this->negate = 0;
  84.       this->reladdr = NULL;
  85.    }
  86.  
  87.    gl_register_file file; /**< PROGRAM_* from Mesa */
  88.    int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
  89.    GLuint swizzle; /**< SWIZZLE_XYZWONEZERO swizzles from Mesa. */
  90.    int negate; /**< NEGATE_XYZW mask from mesa */
  91.    /** Register index should be offset by the integer in this reg. */
  92.    ir_to_mesa_src_reg *reladdr;
  93. } ir_to_mesa_src_reg;
  94.  
  95. typedef struct ir_to_mesa_dst_reg {
  96.    int file; /**< PROGRAM_* from Mesa */
  97.    int index; /**< temporary index, VERT_ATTRIB_*, FRAG_ATTRIB_*, etc. */
  98.    int writemask; /**< Bitfield of WRITEMASK_[XYZW] */
  99.    GLuint cond_mask:4;
  100.    /** Register index should be offset by the integer in this reg. */
  101.    ir_to_mesa_src_reg *reladdr;
  102. } ir_to_mesa_dst_reg;
  103.  
  104. extern ir_to_mesa_src_reg ir_to_mesa_undef;
  105.  
  106. class ir_to_mesa_instruction : public exec_node {
  107. public:
  108.    /* Callers of this ralloc-based new need not call delete. It's
  109.     * easier to just ralloc_free 'ctx' (or any of its ancestors). */
  110.    static void* operator new(size_t size, void *ctx)
  111.    {
  112.       void *node;
  113.  
  114.       node = rzalloc_size(ctx, size);
  115.       assert(node != NULL);
  116.  
  117.       return node;
  118.    }
  119.  
  120.    enum prog_opcode op;
  121.    ir_to_mesa_dst_reg dst_reg;
  122.    ir_to_mesa_src_reg src_reg[3];
  123.    /** Pointer to the ir source this tree came from for debugging */
  124.    ir_instruction *ir;
  125.    GLboolean cond_update;
  126.    bool saturate;
  127.    int sampler; /**< sampler index */
  128.    int tex_target; /**< One of TEXTURE_*_INDEX */
  129.    GLboolean tex_shadow;
  130.  
  131.    class function_entry *function; /* Set on OPCODE_CAL or OPCODE_BGNSUB */
  132. };
  133.  
  134. class variable_storage : public exec_node {
  135. public:
  136.    variable_storage(ir_variable *var, gl_register_file file, int index)
  137.       : file(file), index(index), var(var)
  138.    {
  139.       /* empty */
  140.    }
  141.  
  142.    gl_register_file file;
  143.    int index;
  144.    ir_variable *var; /* variable that maps to this, if any */
  145. };
  146.  
  147. class function_entry : public exec_node {
  148. public:
  149.    ir_function_signature *sig;
  150.  
  151.    /**
  152.     * identifier of this function signature used by the program.
  153.     *
  154.     * At the point that Mesa instructions for function calls are
  155.     * generated, we don't know the address of the first instruction of
  156.     * the function body.  So we make the BranchTarget that is called a
  157.     * small integer and rewrite them during set_branchtargets().
  158.     */
  159.    int sig_id;
  160.  
  161.    /**
  162.     * Pointer to first instruction of the function body.
  163.     *
  164.     * Set during function body emits after main() is processed.
  165.     */
  166.    ir_to_mesa_instruction *bgn_inst;
  167.  
  168.    /**
  169.     * Index of the first instruction of the function body in actual
  170.     * Mesa IR.
  171.     *
  172.     * Set after convertion from ir_to_mesa_instruction to prog_instruction.
  173.     */
  174.    int inst;
  175.  
  176.    /** Storage for the return value. */
  177.    ir_to_mesa_src_reg return_reg;
  178. };
  179.  
  180. class ir_to_mesa_visitor : public ir_visitor {
  181. public:
  182.    ir_to_mesa_visitor();
  183.    ~ir_to_mesa_visitor();
  184.  
  185.    function_entry *current_function;
  186.  
  187.    struct gl_context *ctx;
  188.    struct gl_program *prog;
  189.    struct gl_shader_program *shader_program;
  190.    struct gl_shader_compiler_options *options;
  191.  
  192.    int next_temp;
  193.  
  194.    variable_storage *find_variable_storage(ir_variable *var);
  195.  
  196.    function_entry *get_function_signature(ir_function_signature *sig);
  197.  
  198.    ir_to_mesa_src_reg get_temp(const glsl_type *type);
  199.    void reladdr_to_temp(ir_instruction *ir,
  200.                         ir_to_mesa_src_reg *reg, int *num_reladdr);
  201.  
  202.    struct ir_to_mesa_src_reg src_reg_for_float(float val);
  203.  
  204.    /**
  205.     * \name Visit methods
  206.     *
  207.     * As typical for the visitor pattern, there must be one \c visit method for
  208.     * each concrete subclass of \c ir_instruction.  Virtual base classes within
  209.     * the hierarchy should not have \c visit methods.
  210.     */
  211.    /*@{*/
  212.    virtual void visit(ir_variable *);
  213.    virtual void visit(ir_loop *);
  214.    virtual void visit(ir_loop_jump *);
  215.    virtual void visit(ir_function_signature *);
  216.    virtual void visit(ir_function *);
  217.    virtual void visit(ir_expression *);
  218.    virtual void visit(ir_swizzle *);
  219.    virtual void visit(ir_dereference_variable  *);
  220.    virtual void visit(ir_dereference_array *);
  221.    virtual void visit(ir_dereference_record *);
  222.    virtual void visit(ir_assignment *);
  223.    virtual void visit(ir_constant *);
  224.    virtual void visit(ir_call *);
  225.    virtual void visit(ir_return *);
  226.    virtual void visit(ir_discard *);
  227.    virtual void visit(ir_texture *);
  228.    virtual void visit(ir_if *);
  229.    /*@}*/
  230.  
  231.    struct ir_to_mesa_src_reg result;
  232.  
  233.    /** List of variable_storage */
  234.    exec_list variables;
  235.  
  236.    /** List of function_entry */
  237.    exec_list function_signatures;
  238.    int next_signature_id;
  239.  
  240.    /** List of ir_to_mesa_instruction */
  241.    exec_list instructions;
  242.  
  243.    ir_to_mesa_instruction *ir_to_mesa_emit_op0(ir_instruction *ir,
  244.                                                enum prog_opcode op);
  245.  
  246.    ir_to_mesa_instruction *ir_to_mesa_emit_op1(ir_instruction *ir,
  247.                                                enum prog_opcode op,
  248.                                                ir_to_mesa_dst_reg dst,
  249.                                                ir_to_mesa_src_reg src0);
  250.  
  251.    ir_to_mesa_instruction *ir_to_mesa_emit_op2(ir_instruction *ir,
  252.                                                enum prog_opcode op,
  253.                                                ir_to_mesa_dst_reg dst,
  254.                                                ir_to_mesa_src_reg src0,
  255.                                                ir_to_mesa_src_reg src1);
  256.  
  257.    ir_to_mesa_instruction *ir_to_mesa_emit_op3(ir_instruction *ir,
  258.                                                enum prog_opcode op,
  259.                                                ir_to_mesa_dst_reg dst,
  260.                                                ir_to_mesa_src_reg src0,
  261.                                                ir_to_mesa_src_reg src1,
  262.                                                ir_to_mesa_src_reg src2);
  263.  
  264.    /**
  265.     * Emit the correct dot-product instruction for the type of arguments
  266.     *
  267.     * \sa ir_to_mesa_emit_op2
  268.     */
  269.    void ir_to_mesa_emit_dp(ir_instruction *ir,
  270.                            ir_to_mesa_dst_reg dst,
  271.                            ir_to_mesa_src_reg src0,
  272.                            ir_to_mesa_src_reg src1,
  273.                            unsigned elements);
  274.  
  275.    void ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
  276.                                    enum prog_opcode op,
  277.                                    ir_to_mesa_dst_reg dst,
  278.                                    ir_to_mesa_src_reg src0);
  279.  
  280.    void ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
  281.                                    enum prog_opcode op,
  282.                                    ir_to_mesa_dst_reg dst,
  283.                                    ir_to_mesa_src_reg src0,
  284.                                    ir_to_mesa_src_reg src1);
  285.  
  286.    void emit_scs(ir_instruction *ir, enum prog_opcode op,
  287.                  ir_to_mesa_dst_reg dst,
  288.                  const ir_to_mesa_src_reg &src);
  289.  
  290.    GLboolean try_emit_mad(ir_expression *ir,
  291.                           int mul_operand);
  292.    GLboolean try_emit_sat(ir_expression *ir);
  293.  
  294.    void emit_swz(ir_expression *ir);
  295.  
  296.    bool process_move_condition(ir_rvalue *ir);
  297.  
  298.    void *mem_ctx;
  299. };
  300.  
  301. ir_to_mesa_src_reg ir_to_mesa_undef = ir_to_mesa_src_reg(PROGRAM_UNDEFINED, 0, NULL);
  302.  
  303. ir_to_mesa_dst_reg ir_to_mesa_undef_dst = {
  304.    PROGRAM_UNDEFINED, 0, SWIZZLE_NOOP, COND_TR, NULL,
  305. };
  306.  
  307. ir_to_mesa_dst_reg ir_to_mesa_address_reg = {
  308.    PROGRAM_ADDRESS, 0, WRITEMASK_X, COND_TR, NULL
  309. };
  310.  
  311. static void
  312. fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
  313.  
  314. static void
  315. fail_link(struct gl_shader_program *prog, const char *fmt, ...)
  316. {
  317.    va_list args;
  318.    va_start(args, fmt);
  319.    ralloc_vasprintf_append(&prog->InfoLog, fmt, args);
  320.    va_end(args);
  321.  
  322.    prog->LinkStatus = GL_FALSE;
  323. }
  324.  
  325. static int
  326. swizzle_for_size(int size)
  327. {
  328.    int size_swizzles[4] = {
  329.       MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_X, SWIZZLE_X, SWIZZLE_X),
  330.       MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Y, SWIZZLE_Y),
  331.       MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z),
  332.       MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W),
  333.    };
  334.  
  335.    assert((size >= 1) && (size <= 4));
  336.    return size_swizzles[size - 1];
  337. }
  338.  
  339. ir_to_mesa_instruction *
  340. ir_to_mesa_visitor::ir_to_mesa_emit_op3(ir_instruction *ir,
  341.                                         enum prog_opcode op,
  342.                                         ir_to_mesa_dst_reg dst,
  343.                                         ir_to_mesa_src_reg src0,
  344.                                         ir_to_mesa_src_reg src1,
  345.                                         ir_to_mesa_src_reg src2)
  346. {
  347.    ir_to_mesa_instruction *inst = new(mem_ctx) ir_to_mesa_instruction();
  348.    int num_reladdr = 0;
  349.  
  350.    /* If we have to do relative addressing, we want to load the ARL
  351.     * reg directly for one of the regs, and preload the other reladdr
  352.     * sources into temps.
  353.     */
  354.    num_reladdr += dst.reladdr != NULL;
  355.    num_reladdr += src0.reladdr != NULL;
  356.    num_reladdr += src1.reladdr != NULL;
  357.    num_reladdr += src2.reladdr != NULL;
  358.  
  359.    reladdr_to_temp(ir, &src2, &num_reladdr);
  360.    reladdr_to_temp(ir, &src1, &num_reladdr);
  361.    reladdr_to_temp(ir, &src0, &num_reladdr);
  362.  
  363.    if (dst.reladdr) {
  364.       ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg,
  365.                           *dst.reladdr);
  366.  
  367.       num_reladdr--;
  368.    }
  369.    assert(num_reladdr == 0);
  370.  
  371.    inst->op = op;
  372.    inst->dst_reg = dst;
  373.    inst->src_reg[0] = src0;
  374.    inst->src_reg[1] = src1;
  375.    inst->src_reg[2] = src2;
  376.    inst->ir = ir;
  377.  
  378.    inst->function = NULL;
  379.  
  380.    this->instructions.push_tail(inst);
  381.  
  382.    return inst;
  383. }
  384.  
  385.  
  386. ir_to_mesa_instruction *
  387. ir_to_mesa_visitor::ir_to_mesa_emit_op2(ir_instruction *ir,
  388.                                         enum prog_opcode op,
  389.                                         ir_to_mesa_dst_reg dst,
  390.                                         ir_to_mesa_src_reg src0,
  391.                                         ir_to_mesa_src_reg src1)
  392. {
  393.    return ir_to_mesa_emit_op3(ir, op, dst, src0, src1, ir_to_mesa_undef);
  394. }
  395.  
  396. ir_to_mesa_instruction *
  397. ir_to_mesa_visitor::ir_to_mesa_emit_op1(ir_instruction *ir,
  398.                                         enum prog_opcode op,
  399.                                         ir_to_mesa_dst_reg dst,
  400.                                         ir_to_mesa_src_reg src0)
  401. {
  402.    assert(dst.writemask != 0);
  403.    return ir_to_mesa_emit_op3(ir, op, dst,
  404.                               src0, ir_to_mesa_undef, ir_to_mesa_undef);
  405. }
  406.  
  407. ir_to_mesa_instruction *
  408. ir_to_mesa_visitor::ir_to_mesa_emit_op0(ir_instruction *ir,
  409.                                         enum prog_opcode op)
  410. {
  411.    return ir_to_mesa_emit_op3(ir, op, ir_to_mesa_undef_dst,
  412.                               ir_to_mesa_undef,
  413.                               ir_to_mesa_undef,
  414.                               ir_to_mesa_undef);
  415. }
  416.  
  417. void
  418. ir_to_mesa_visitor::ir_to_mesa_emit_dp(ir_instruction *ir,
  419.                                        ir_to_mesa_dst_reg dst,
  420.                                        ir_to_mesa_src_reg src0,
  421.                                        ir_to_mesa_src_reg src1,
  422.                                        unsigned elements)
  423. {
  424.    static const gl_inst_opcode dot_opcodes[] = {
  425.       OPCODE_DP2, OPCODE_DP3, OPCODE_DP4
  426.    };
  427.  
  428.    ir_to_mesa_emit_op3(ir, dot_opcodes[elements - 2],
  429.                        dst, src0, src1, ir_to_mesa_undef);
  430. }
  431.  
  432. inline ir_to_mesa_dst_reg
  433. ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg reg)
  434. {
  435.    ir_to_mesa_dst_reg dst_reg;
  436.  
  437.    dst_reg.file = reg.file;
  438.    dst_reg.index = reg.index;
  439.    dst_reg.writemask = WRITEMASK_XYZW;
  440.    dst_reg.cond_mask = COND_TR;
  441.    dst_reg.reladdr = reg.reladdr;
  442.  
  443.    return dst_reg;
  444. }
  445.  
  446. inline ir_to_mesa_src_reg
  447. ir_to_mesa_src_reg_from_dst(ir_to_mesa_dst_reg reg)
  448. {
  449.    return ir_to_mesa_src_reg(reg.file, reg.index, NULL);
  450. }
  451.  
  452. /**
  453.  * Emits Mesa scalar opcodes to produce unique answers across channels.
  454.  *
  455.  * Some Mesa opcodes are scalar-only, like ARB_fp/vp.  The src X
  456.  * channel determines the result across all channels.  So to do a vec4
  457.  * of this operation, we want to emit a scalar per source channel used
  458.  * to produce dest channels.
  459.  */
  460. void
  461. ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op2(ir_instruction *ir,
  462.                                                enum prog_opcode op,
  463.                                                ir_to_mesa_dst_reg dst,
  464.                                                ir_to_mesa_src_reg orig_src0,
  465.                                                ir_to_mesa_src_reg orig_src1)
  466. {
  467.    int i, j;
  468.    int done_mask = ~dst.writemask;
  469.  
  470.    /* Mesa RCP is a scalar operation splatting results to all channels,
  471.     * like ARB_fp/vp.  So emit as many RCPs as necessary to cover our
  472.     * dst channels.
  473.     */
  474.    for (i = 0; i < 4; i++) {
  475.       GLuint this_mask = (1 << i);
  476.       ir_to_mesa_instruction *inst;
  477.       ir_to_mesa_src_reg src0 = orig_src0;
  478.       ir_to_mesa_src_reg src1 = orig_src1;
  479.  
  480.       if (done_mask & this_mask)
  481.          continue;
  482.  
  483.       GLuint src0_swiz = GET_SWZ(src0.swizzle, i);
  484.       GLuint src1_swiz = GET_SWZ(src1.swizzle, i);
  485.       for (j = i + 1; j < 4; j++) {
  486.          /* If there is another enabled component in the destination that is
  487.           * derived from the same inputs, generate its value on this pass as
  488.           * well.
  489.           */
  490.          if (!(done_mask & (1 << j)) &&
  491.              GET_SWZ(src0.swizzle, j) == src0_swiz &&
  492.              GET_SWZ(src1.swizzle, j) == src1_swiz) {
  493.             this_mask |= (1 << j);
  494.          }
  495.       }
  496.       src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
  497.                                    src0_swiz, src0_swiz);
  498.       src1.swizzle = MAKE_SWIZZLE4(src1_swiz, src1_swiz,
  499.                                   src1_swiz, src1_swiz);
  500.  
  501.       inst = ir_to_mesa_emit_op2(ir, op,
  502.                                  dst,
  503.                                  src0,
  504.                                  src1);
  505.       inst->dst_reg.writemask = this_mask;
  506.       done_mask |= this_mask;
  507.    }
  508. }
  509.  
  510. void
  511. ir_to_mesa_visitor::ir_to_mesa_emit_scalar_op1(ir_instruction *ir,
  512.                                                enum prog_opcode op,
  513.                                                ir_to_mesa_dst_reg dst,
  514.                                                ir_to_mesa_src_reg src0)
  515. {
  516.    ir_to_mesa_src_reg undef = ir_to_mesa_undef;
  517.  
  518.    undef.swizzle = SWIZZLE_XXXX;
  519.  
  520.    ir_to_mesa_emit_scalar_op2(ir, op, dst, src0, undef);
  521. }
  522.  
  523. /**
  524.  * Emit an OPCODE_SCS instruction
  525.  *
  526.  * The \c SCS opcode functions a bit differently than the other Mesa (or
  527.  * ARB_fragment_program) opcodes.  Instead of splatting its result across all
  528.  * four components of the destination, it writes one value to the \c x
  529.  * component and another value to the \c y component.
  530.  *
  531.  * \param ir        IR instruction being processed
  532.  * \param op        Either \c OPCODE_SIN or \c OPCODE_COS depending on which
  533.  *                  value is desired.
  534.  * \param dst       Destination register
  535.  * \param src       Source register
  536.  */
  537. void
  538. ir_to_mesa_visitor::emit_scs(ir_instruction *ir, enum prog_opcode op,
  539.                              ir_to_mesa_dst_reg dst,
  540.                              const ir_to_mesa_src_reg &src)
  541. {
  542.    /* Vertex programs cannot use the SCS opcode.
  543.     */
  544.    if (this->prog->Target == GL_VERTEX_PROGRAM_ARB) {
  545.       ir_to_mesa_emit_scalar_op1(ir, op, dst, src);
  546.       return;
  547.    }
  548.  
  549.    const unsigned component = (op == OPCODE_SIN) ? 0 : 1;
  550.    const unsigned scs_mask = (1U << component);
  551.    int done_mask = ~dst.writemask;
  552.    ir_to_mesa_src_reg tmp;
  553.  
  554.    assert(op == OPCODE_SIN || op == OPCODE_COS);
  555.  
  556.    /* If there are compnents in the destination that differ from the component
  557.     * that will be written by the SCS instrution, we'll need a temporary.
  558.     */
  559.    if (scs_mask != unsigned(dst.writemask)) {
  560.       tmp = get_temp(glsl_type::vec4_type);
  561.    }
  562.  
  563.    for (unsigned i = 0; i < 4; i++) {
  564.       unsigned this_mask = (1U << i);
  565.       ir_to_mesa_src_reg src0 = src;
  566.  
  567.       if ((done_mask & this_mask) != 0)
  568.          continue;
  569.  
  570.       /* The source swizzle specified which component of the source generates
  571.        * sine / cosine for the current component in the destination.  The SCS
  572.        * instruction requires that this value be swizzle to the X component.
  573.        * Replace the current swizzle with a swizzle that puts the source in
  574.        * the X component.
  575.        */
  576.       unsigned src0_swiz = GET_SWZ(src.swizzle, i);
  577.  
  578.       src0.swizzle = MAKE_SWIZZLE4(src0_swiz, src0_swiz,
  579.                                    src0_swiz, src0_swiz);
  580.       for (unsigned j = i + 1; j < 4; j++) {
  581.          /* If there is another enabled component in the destination that is
  582.           * derived from the same inputs, generate its value on this pass as
  583.           * well.
  584.           */
  585.          if (!(done_mask & (1 << j)) &&
  586.              GET_SWZ(src0.swizzle, j) == src0_swiz) {
  587.             this_mask |= (1 << j);
  588.          }
  589.       }
  590.  
  591.       if (this_mask != scs_mask) {
  592.          ir_to_mesa_instruction *inst;
  593.          ir_to_mesa_dst_reg tmp_dst = ir_to_mesa_dst_reg_from_src(tmp);
  594.  
  595.          /* Emit the SCS instruction.
  596.           */
  597.          inst = ir_to_mesa_emit_op1(ir, OPCODE_SCS, tmp_dst, src0);
  598.          inst->dst_reg.writemask = scs_mask;
  599.  
  600.          /* Move the result of the SCS instruction to the desired location in
  601.           * the destination.
  602.           */
  603.          tmp.swizzle = MAKE_SWIZZLE4(component, component,
  604.                                      component, component);
  605.          inst = ir_to_mesa_emit_op1(ir, OPCODE_SCS, dst, tmp);
  606.          inst->dst_reg.writemask = this_mask;
  607.       } else {
  608.          /* Emit the SCS instruction to write directly to the destination.
  609.           */
  610.          ir_to_mesa_instruction *inst =
  611.             ir_to_mesa_emit_op1(ir, OPCODE_SCS, dst, src0);
  612.          inst->dst_reg.writemask = scs_mask;
  613.       }
  614.  
  615.       done_mask |= this_mask;
  616.    }
  617. }
  618.  
  619. struct ir_to_mesa_src_reg
  620. ir_to_mesa_visitor::src_reg_for_float(float val)
  621. {
  622.    ir_to_mesa_src_reg src_reg(PROGRAM_CONSTANT, -1, NULL);
  623.  
  624.    src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
  625.                                               &val, 1, &src_reg.swizzle);
  626.  
  627.    return src_reg;
  628. }
  629.  
  630. static int
  631. type_size(const struct glsl_type *type)
  632. {
  633.    unsigned int i;
  634.    int size;
  635.  
  636.    switch (type->base_type) {
  637.    case GLSL_TYPE_UINT:
  638.    case GLSL_TYPE_INT:
  639.    case GLSL_TYPE_FLOAT:
  640.    case GLSL_TYPE_BOOL:
  641.       if (type->is_matrix()) {
  642.          return type->matrix_columns;
  643.       } else {
  644.          /* Regardless of size of vector, it gets a vec4. This is bad
  645.           * packing for things like floats, but otherwise arrays become a
  646.           * mess.  Hopefully a later pass over the code can pack scalars
  647.           * down if appropriate.
  648.           */
  649.          return 1;
  650.       }
  651.    case GLSL_TYPE_ARRAY:
  652.       return type_size(type->fields.array) * type->length;
  653.    case GLSL_TYPE_STRUCT:
  654.       size = 0;
  655.       for (i = 0; i < type->length; i++) {
  656.          size += type_size(type->fields.structure[i].type);
  657.       }
  658.       return size;
  659.    case GLSL_TYPE_SAMPLER:
  660.       /* Samplers take up one slot in UNIFORMS[], but they're baked in
  661.        * at link time.
  662.        */
  663.       return 1;
  664.    default:
  665.       assert(0);
  666.       return 0;
  667.    }
  668. }
  669.  
  670. /**
  671.  * In the initial pass of codegen, we assign temporary numbers to
  672.  * intermediate results.  (not SSA -- variable assignments will reuse
  673.  * storage).  Actual register allocation for the Mesa VM occurs in a
  674.  * pass over the Mesa IR later.
  675.  */
  676. ir_to_mesa_src_reg
  677. ir_to_mesa_visitor::get_temp(const glsl_type *type)
  678. {
  679.    ir_to_mesa_src_reg src_reg;
  680.    int swizzle[4];
  681.    int i;
  682.  
  683.    src_reg.file = PROGRAM_TEMPORARY;
  684.    src_reg.index = next_temp;
  685.    src_reg.reladdr = NULL;
  686.    next_temp += type_size(type);
  687.  
  688.    if (type->is_array() || type->is_record()) {
  689.       src_reg.swizzle = SWIZZLE_NOOP;
  690.    } else {
  691.       for (i = 0; i < type->vector_elements; i++)
  692.          swizzle[i] = i;
  693.       for (; i < 4; i++)
  694.          swizzle[i] = type->vector_elements - 1;
  695.       src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0], swizzle[1],
  696.                                       swizzle[2], swizzle[3]);
  697.    }
  698.    src_reg.negate = 0;
  699.  
  700.    return src_reg;
  701. }
  702.  
  703. variable_storage *
  704. ir_to_mesa_visitor::find_variable_storage(ir_variable *var)
  705. {
  706.    
  707.    variable_storage *entry;
  708.  
  709.    foreach_iter(exec_list_iterator, iter, this->variables) {
  710.       entry = (variable_storage *)iter.get();
  711.  
  712.       if (entry->var == var)
  713.          return entry;
  714.    }
  715.  
  716.    return NULL;
  717. }
  718.  
  719. void
  720. ir_to_mesa_visitor::visit(ir_variable *ir)
  721. {
  722.    if (strcmp(ir->name, "gl_FragCoord") == 0) {
  723.       struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
  724.  
  725.       fp->OriginUpperLeft = ir->origin_upper_left;
  726.       fp->PixelCenterInteger = ir->pixel_center_integer;
  727.    }
  728.  
  729.    if (ir->mode == ir_var_uniform && strncmp(ir->name, "gl_", 3) == 0) {
  730.       unsigned int i;
  731.       const struct gl_builtin_uniform_desc *statevar;
  732.  
  733.       for (i = 0; _mesa_builtin_uniform_desc[i].name; i++) {
  734.          if (strcmp(ir->name, _mesa_builtin_uniform_desc[i].name) == 0)
  735.             break;
  736.       }
  737.  
  738.       if (!_mesa_builtin_uniform_desc[i].name) {
  739.          fail_link(this->shader_program,
  740.                    "Failed to find builtin uniform `%s'\n", ir->name);
  741.          return;
  742.       }
  743.  
  744.       statevar = &_mesa_builtin_uniform_desc[i];
  745.  
  746.       int array_count;
  747.       if (ir->type->is_array()) {
  748.          array_count = ir->type->length;
  749.       } else {
  750.          array_count = 1;
  751.       }
  752.  
  753.       /* Check if this statevar's setup in the STATE file exactly
  754.        * matches how we'll want to reference it as a
  755.        * struct/array/whatever.  If not, then we need to move it into
  756.        * temporary storage and hope that it'll get copy-propagated
  757.        * out.
  758.        */
  759.       for (i = 0; i < statevar->num_elements; i++) {
  760.          if (statevar->elements[i].swizzle != SWIZZLE_XYZW) {
  761.             break;
  762.          }
  763.       }
  764.  
  765.       struct variable_storage *storage;
  766.       ir_to_mesa_dst_reg dst;
  767.       if (i == statevar->num_elements) {
  768.          /* We'll set the index later. */
  769.          storage = new(mem_ctx) variable_storage(ir, PROGRAM_STATE_VAR, -1);
  770.          this->variables.push_tail(storage);
  771.  
  772.          dst = ir_to_mesa_undef_dst;
  773.       } else {
  774.          storage = new(mem_ctx) variable_storage(ir, PROGRAM_TEMPORARY,
  775.                                                  this->next_temp);
  776.          this->variables.push_tail(storage);
  777.          this->next_temp += type_size(ir->type);
  778.  
  779.          dst = ir_to_mesa_dst_reg_from_src(ir_to_mesa_src_reg(PROGRAM_TEMPORARY,
  780.                                                               storage->index,
  781.                                                               NULL));
  782.       }
  783.  
  784.  
  785.       for (int a = 0; a < array_count; a++) {
  786.          for (unsigned int i = 0; i < statevar->num_elements; i++) {
  787.             struct gl_builtin_uniform_element *element = &statevar->elements[i];
  788.             int tokens[STATE_LENGTH];
  789.  
  790.             memcpy(tokens, element->tokens, sizeof(element->tokens));
  791.             if (ir->type->is_array()) {
  792.                tokens[1] = a;
  793.             }
  794.  
  795.             int index = _mesa_add_state_reference(this->prog->Parameters,
  796.                                                   (gl_state_index *)tokens);
  797.  
  798.             if (storage->file == PROGRAM_STATE_VAR) {
  799.                if (storage->index == -1) {
  800.                   storage->index = index;
  801.                } else {
  802.                   assert(index ==
  803.                          (int)(storage->index + a * statevar->num_elements + i));
  804.                }
  805.             } else {
  806.                ir_to_mesa_src_reg src(PROGRAM_STATE_VAR, index, NULL);
  807.                src.swizzle = element->swizzle;
  808.                ir_to_mesa_emit_op1(ir, OPCODE_MOV, dst, src);
  809.                /* even a float takes up a whole vec4 reg in a struct/array. */
  810.                dst.index++;
  811.             }
  812.          }
  813.       }
  814.       if (storage->file == PROGRAM_TEMPORARY &&
  815.           dst.index != storage->index + type_size(ir->type)) {
  816.          fail_link(this->shader_program,
  817.                    "failed to load builtin uniform `%s'  (%d/%d regs loaded)\n",
  818.                    ir->name, dst.index - storage->index,
  819.                    type_size(ir->type));
  820.       }
  821.    }
  822. }
  823.  
  824. void
  825. ir_to_mesa_visitor::visit(ir_loop *ir)
  826. {
  827.    ir_dereference_variable *counter = NULL;
  828.  
  829.    if (ir->counter != NULL)
  830.       counter = new(ir) ir_dereference_variable(ir->counter);
  831.  
  832.    if (ir->from != NULL) {
  833.       assert(ir->counter != NULL);
  834.  
  835.       ir_assignment *a = new(ir) ir_assignment(counter, ir->from, NULL);
  836.  
  837.       a->accept(this);
  838.       delete a;
  839.    }
  840.  
  841.    ir_to_mesa_emit_op0(NULL, OPCODE_BGNLOOP);
  842.  
  843.    if (ir->to) {
  844.       ir_expression *e =
  845.          new(ir) ir_expression(ir->cmp, glsl_type::bool_type,
  846.                                counter, ir->to);
  847.       ir_if *if_stmt =  new(ir) ir_if(e);
  848.  
  849.       ir_loop_jump *brk = new(ir) ir_loop_jump(ir_loop_jump::jump_break);
  850.  
  851.       if_stmt->then_instructions.push_tail(brk);
  852.  
  853.       if_stmt->accept(this);
  854.  
  855.       delete if_stmt;
  856.       delete e;
  857.       delete brk;
  858.    }
  859.  
  860.    visit_exec_list(&ir->body_instructions, this);
  861.  
  862.    if (ir->increment) {
  863.       ir_expression *e =
  864.          new(ir) ir_expression(ir_binop_add, counter->type,
  865.                                counter, ir->increment);
  866.  
  867.       ir_assignment *a = new(ir) ir_assignment(counter, e, NULL);
  868.  
  869.       a->accept(this);
  870.       delete a;
  871.       delete e;
  872.    }
  873.  
  874.    ir_to_mesa_emit_op0(NULL, OPCODE_ENDLOOP);
  875. }
  876.  
  877. void
  878. ir_to_mesa_visitor::visit(ir_loop_jump *ir)
  879. {
  880.    switch (ir->mode) {
  881.    case ir_loop_jump::jump_break:
  882.       ir_to_mesa_emit_op0(NULL, OPCODE_BRK);
  883.       break;
  884.    case ir_loop_jump::jump_continue:
  885.       ir_to_mesa_emit_op0(NULL, OPCODE_CONT);
  886.       break;
  887.    }
  888. }
  889.  
  890.  
  891. void
  892. ir_to_mesa_visitor::visit(ir_function_signature *ir)
  893. {
  894.    assert(0);
  895.    (void)ir;
  896. }
  897.  
  898. void
  899. ir_to_mesa_visitor::visit(ir_function *ir)
  900. {
  901.    /* Ignore function bodies other than main() -- we shouldn't see calls to
  902.     * them since they should all be inlined before we get to ir_to_mesa.
  903.     */
  904.    if (strcmp(ir->name, "main") == 0) {
  905.       const ir_function_signature *sig;
  906.       exec_list empty;
  907.  
  908.       sig = ir->matching_signature(&empty);
  909.  
  910.       assert(sig);
  911.  
  912.       foreach_iter(exec_list_iterator, iter, sig->body) {
  913.          ir_instruction *ir = (ir_instruction *)iter.get();
  914.  
  915.          ir->accept(this);
  916.       }
  917.    }
  918. }
  919.  
  920. GLboolean
  921. ir_to_mesa_visitor::try_emit_mad(ir_expression *ir, int mul_operand)
  922. {
  923.    int nonmul_operand = 1 - mul_operand;
  924.    ir_to_mesa_src_reg a, b, c;
  925.  
  926.    ir_expression *expr = ir->operands[mul_operand]->as_expression();
  927.    if (!expr || expr->operation != ir_binop_mul)
  928.       return false;
  929.  
  930.    expr->operands[0]->accept(this);
  931.    a = this->result;
  932.    expr->operands[1]->accept(this);
  933.    b = this->result;
  934.    ir->operands[nonmul_operand]->accept(this);
  935.    c = this->result;
  936.  
  937.    this->result = get_temp(ir->type);
  938.    ir_to_mesa_emit_op3(ir, OPCODE_MAD,
  939.                        ir_to_mesa_dst_reg_from_src(this->result), a, b, c);
  940.  
  941.    return true;
  942. }
  943.  
  944. GLboolean
  945. ir_to_mesa_visitor::try_emit_sat(ir_expression *ir)
  946. {
  947.    /* Saturates were only introduced to vertex programs in
  948.     * NV_vertex_program3, so don't give them to drivers in the VP.
  949.     */
  950.    if (this->prog->Target == GL_VERTEX_PROGRAM_ARB)
  951.       return false;
  952.  
  953.    ir_rvalue *sat_src = ir->as_rvalue_to_saturate();
  954.    if (!sat_src)
  955.       return false;
  956.  
  957.    sat_src->accept(this);
  958.    ir_to_mesa_src_reg src = this->result;
  959.  
  960.    this->result = get_temp(ir->type);
  961.    ir_to_mesa_instruction *inst;
  962.    inst = ir_to_mesa_emit_op1(ir, OPCODE_MOV,
  963.                               ir_to_mesa_dst_reg_from_src(this->result),
  964.                               src);
  965.    inst->saturate = true;
  966.  
  967.    return true;
  968. }
  969.  
  970. void
  971. ir_to_mesa_visitor::reladdr_to_temp(ir_instruction *ir,
  972.                                     ir_to_mesa_src_reg *reg, int *num_reladdr)
  973. {
  974.    if (!reg->reladdr)
  975.       return;
  976.  
  977.    ir_to_mesa_emit_op1(ir, OPCODE_ARL, ir_to_mesa_address_reg, *reg->reladdr);
  978.  
  979.    if (*num_reladdr != 1) {
  980.       ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
  981.  
  982.       ir_to_mesa_emit_op1(ir, OPCODE_MOV,
  983.                           ir_to_mesa_dst_reg_from_src(temp), *reg);
  984.       *reg = temp;
  985.    }
  986.  
  987.    (*num_reladdr)--;
  988. }
  989.  
  990. void
  991. ir_to_mesa_visitor::emit_swz(ir_expression *ir)
  992. {
  993.    /* Assume that the vector operator is in a form compatible with OPCODE_SWZ.
  994.     * This means that each of the operands is either an immediate value of -1,
  995.     * 0, or 1, or is a component from one source register (possibly with
  996.     * negation).
  997.     */
  998.    uint8_t components[4] = { 0 };
  999.    bool negate[4] = { false };
  1000.    ir_variable *var = NULL;
  1001.  
  1002.    for (unsigned i = 0; i < ir->type->vector_elements; i++) {
  1003.       ir_rvalue *op = ir->operands[i];
  1004.  
  1005.       assert(op->type->is_scalar());
  1006.  
  1007.       while (op != NULL) {
  1008.          switch (op->ir_type) {
  1009.          case ir_type_constant: {
  1010.  
  1011.             assert(op->type->is_scalar());
  1012.  
  1013.             const ir_constant *const c = op->as_constant();
  1014.             if (c->is_one()) {
  1015.                components[i] = SWIZZLE_ONE;
  1016.             } else if (c->is_zero()) {
  1017.                components[i] = SWIZZLE_ZERO;
  1018.             } else if (c->is_negative_one()) {
  1019.                components[i] = SWIZZLE_ONE;
  1020.                negate[i] = true;
  1021.             } else {
  1022.                assert(!"SWZ constant must be 0.0 or 1.0.");
  1023.             }
  1024.  
  1025.             op = NULL;
  1026.             break;
  1027.          }
  1028.  
  1029.          case ir_type_dereference_variable: {
  1030.             ir_dereference_variable *const deref =
  1031.                (ir_dereference_variable *) op;
  1032.  
  1033.             assert((var == NULL) || (deref->var == var));
  1034.             components[i] = SWIZZLE_X;
  1035.             var = deref->var;
  1036.             op = NULL;
  1037.             break;
  1038.          }
  1039.  
  1040.          case ir_type_expression: {
  1041.             ir_expression *const expr = (ir_expression *) op;
  1042.  
  1043.             assert(expr->operation == ir_unop_neg);
  1044.             negate[i] = true;
  1045.  
  1046.             op = expr->operands[0];
  1047.             break;
  1048.          }
  1049.  
  1050.          case ir_type_swizzle: {
  1051.             ir_swizzle *const swiz = (ir_swizzle *) op;
  1052.  
  1053.             components[i] = swiz->mask.x;
  1054.             op = swiz->val;
  1055.             break;
  1056.          }
  1057.  
  1058.          default:
  1059.             assert(!"Should not get here.");
  1060.             return;
  1061.          }
  1062.       }
  1063.    }
  1064.  
  1065.    assert(var != NULL);
  1066.  
  1067.    ir_dereference_variable *const deref =
  1068.       new(mem_ctx) ir_dereference_variable(var);
  1069.  
  1070.    this->result.file = PROGRAM_UNDEFINED;
  1071.    deref->accept(this);
  1072.    if (this->result.file == PROGRAM_UNDEFINED) {
  1073.       ir_print_visitor v;
  1074.       printf("Failed to get tree for expression operand:\n");
  1075.       deref->accept(&v);
  1076.       exit(1);
  1077.    }
  1078.  
  1079.    ir_to_mesa_src_reg src;
  1080.  
  1081.    src = this->result;
  1082.    src.swizzle = MAKE_SWIZZLE4(components[0],
  1083.                                components[1],
  1084.                                components[2],
  1085.                                components[3]);
  1086.    src.negate = ((unsigned(negate[0]) << 0)
  1087.                  | (unsigned(negate[1]) << 1)
  1088.                  | (unsigned(negate[2]) << 2)
  1089.                  | (unsigned(negate[3]) << 3));
  1090.  
  1091.    /* Storage for our result.  Ideally for an assignment we'd be using the
  1092.     * actual storage for the result here, instead.
  1093.     */
  1094.    const ir_to_mesa_src_reg result_src = get_temp(ir->type);
  1095.    ir_to_mesa_dst_reg result_dst = ir_to_mesa_dst_reg_from_src(result_src);
  1096.  
  1097.    /* Limit writes to the channels that will be used by result_src later.
  1098.     * This does limit this temp's use as a temporary for multi-instruction
  1099.     * sequences.
  1100.     */
  1101.    result_dst.writemask = (1 << ir->type->vector_elements) - 1;
  1102.  
  1103.    ir_to_mesa_emit_op1(ir, OPCODE_SWZ, result_dst, src);
  1104.    this->result = result_src;
  1105. }
  1106.  
  1107. void
  1108. ir_to_mesa_visitor::visit(ir_expression *ir)
  1109. {
  1110.    unsigned int operand;
  1111.    struct ir_to_mesa_src_reg op[Elements(ir->operands)];
  1112.    struct ir_to_mesa_src_reg result_src;
  1113.    struct ir_to_mesa_dst_reg result_dst;
  1114.  
  1115.    /* Quick peephole: Emit OPCODE_MAD(a, b, c) instead of ADD(MUL(a, b), c)
  1116.     */
  1117.    if (ir->operation == ir_binop_add) {
  1118.       if (try_emit_mad(ir, 1))
  1119.          return;
  1120.       if (try_emit_mad(ir, 0))
  1121.          return;
  1122.    }
  1123.    if (try_emit_sat(ir))
  1124.       return;
  1125.  
  1126.    if (ir->operation == ir_quadop_vector) {
  1127.       this->emit_swz(ir);
  1128.       return;
  1129.    }
  1130.  
  1131.    for (operand = 0; operand < ir->get_num_operands(); operand++) {
  1132.       this->result.file = PROGRAM_UNDEFINED;
  1133.       ir->operands[operand]->accept(this);
  1134.       if (this->result.file == PROGRAM_UNDEFINED) {
  1135.          ir_print_visitor v;
  1136.          printf("Failed to get tree for expression operand:\n");
  1137.          ir->operands[operand]->accept(&v);
  1138.          exit(1);
  1139.       }
  1140.       op[operand] = this->result;
  1141.  
  1142.       /* Matrix expression operands should have been broken down to vector
  1143.        * operations already.
  1144.        */
  1145.       assert(!ir->operands[operand]->type->is_matrix());
  1146.    }
  1147.  
  1148.    int vector_elements = ir->operands[0]->type->vector_elements;
  1149.    if (ir->operands[1]) {
  1150.       vector_elements = MAX2(vector_elements,
  1151.                              ir->operands[1]->type->vector_elements);
  1152.    }
  1153.  
  1154.    this->result.file = PROGRAM_UNDEFINED;
  1155.  
  1156.    /* Storage for our result.  Ideally for an assignment we'd be using
  1157.     * the actual storage for the result here, instead.
  1158.     */
  1159.    result_src = get_temp(ir->type);
  1160.    /* convenience for the emit functions below. */
  1161.    result_dst = ir_to_mesa_dst_reg_from_src(result_src);
  1162.    /* Limit writes to the channels that will be used by result_src later.
  1163.     * This does limit this temp's use as a temporary for multi-instruction
  1164.     * sequences.
  1165.     */
  1166.    result_dst.writemask = (1 << ir->type->vector_elements) - 1;
  1167.  
  1168.    switch (ir->operation) {
  1169.    case ir_unop_logic_not:
  1170.       ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst,
  1171.                           op[0], src_reg_for_float(0.0));
  1172.       break;
  1173.    case ir_unop_neg:
  1174.       op[0].negate = ~op[0].negate;
  1175.       result_src = op[0];
  1176.       break;
  1177.    case ir_unop_abs:
  1178.       ir_to_mesa_emit_op1(ir, OPCODE_ABS, result_dst, op[0]);
  1179.       break;
  1180.    case ir_unop_sign:
  1181.       ir_to_mesa_emit_op1(ir, OPCODE_SSG, result_dst, op[0]);
  1182.       break;
  1183.    case ir_unop_rcp:
  1184.       ir_to_mesa_emit_scalar_op1(ir, OPCODE_RCP, result_dst, op[0]);
  1185.       break;
  1186.  
  1187.    case ir_unop_exp2:
  1188.       ir_to_mesa_emit_scalar_op1(ir, OPCODE_EX2, result_dst, op[0]);
  1189.       break;
  1190.    case ir_unop_exp:
  1191.    case ir_unop_log:
  1192.       assert(!"not reached: should be handled by ir_explog_to_explog2");
  1193.       break;
  1194.    case ir_unop_log2:
  1195.       ir_to_mesa_emit_scalar_op1(ir, OPCODE_LG2, result_dst, op[0]);
  1196.       break;
  1197.    case ir_unop_sin:
  1198.       ir_to_mesa_emit_scalar_op1(ir, OPCODE_SIN, result_dst, op[0]);
  1199.       break;
  1200.    case ir_unop_cos:
  1201.       ir_to_mesa_emit_scalar_op1(ir, OPCODE_COS, result_dst, op[0]);
  1202.       break;
  1203.    case ir_unop_sin_reduced:
  1204.       emit_scs(ir, OPCODE_SIN, result_dst, op[0]);
  1205.       break;
  1206.    case ir_unop_cos_reduced:
  1207.       emit_scs(ir, OPCODE_COS, result_dst, op[0]);
  1208.       break;
  1209.  
  1210.    case ir_unop_dFdx:
  1211.       ir_to_mesa_emit_op1(ir, OPCODE_DDX, result_dst, op[0]);
  1212.       break;
  1213.    case ir_unop_dFdy:
  1214.       ir_to_mesa_emit_op1(ir, OPCODE_DDY, result_dst, op[0]);
  1215.       break;
  1216.  
  1217.    case ir_unop_noise: {
  1218.       const enum prog_opcode opcode =
  1219.          prog_opcode(OPCODE_NOISE1
  1220.                      + (ir->operands[0]->type->vector_elements) - 1);
  1221.       assert((opcode >= OPCODE_NOISE1) && (opcode <= OPCODE_NOISE4));
  1222.  
  1223.       ir_to_mesa_emit_op1(ir, opcode, result_dst, op[0]);
  1224.       break;
  1225.    }
  1226.  
  1227.    case ir_binop_add:
  1228.       ir_to_mesa_emit_op2(ir, OPCODE_ADD, result_dst, op[0], op[1]);
  1229.       break;
  1230.    case ir_binop_sub:
  1231.       ir_to_mesa_emit_op2(ir, OPCODE_SUB, result_dst, op[0], op[1]);
  1232.       break;
  1233.  
  1234.    case ir_binop_mul:
  1235.       ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, op[0], op[1]);
  1236.       break;
  1237.    case ir_binop_div:
  1238.       assert(!"not reached: should be handled by ir_div_to_mul_rcp");
  1239.    case ir_binop_mod:
  1240.       assert(!"ir_binop_mod should have been converted to b * fract(a/b)");
  1241.       break;
  1242.  
  1243.    case ir_binop_less:
  1244.       ir_to_mesa_emit_op2(ir, OPCODE_SLT, result_dst, op[0], op[1]);
  1245.       break;
  1246.    case ir_binop_greater:
  1247.       ir_to_mesa_emit_op2(ir, OPCODE_SGT, result_dst, op[0], op[1]);
  1248.       break;
  1249.    case ir_binop_lequal:
  1250.       ir_to_mesa_emit_op2(ir, OPCODE_SLE, result_dst, op[0], op[1]);
  1251.       break;
  1252.    case ir_binop_gequal:
  1253.       ir_to_mesa_emit_op2(ir, OPCODE_SGE, result_dst, op[0], op[1]);
  1254.       break;
  1255.    case ir_binop_equal:
  1256.       ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
  1257.       break;
  1258.    case ir_binop_nequal:
  1259.       ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
  1260.       break;
  1261.    case ir_binop_all_equal:
  1262.       /* "==" operator producing a scalar boolean. */
  1263.       if (ir->operands[0]->type->is_vector() ||
  1264.           ir->operands[1]->type->is_vector()) {
  1265.          ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
  1266.          ir_to_mesa_emit_op2(ir, OPCODE_SNE,
  1267.                              ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
  1268.          ir_to_mesa_emit_dp(ir, result_dst, temp, temp, vector_elements);
  1269.          ir_to_mesa_emit_op2(ir, OPCODE_SEQ,
  1270.                              result_dst, result_src, src_reg_for_float(0.0));
  1271.       } else {
  1272.          ir_to_mesa_emit_op2(ir, OPCODE_SEQ, result_dst, op[0], op[1]);
  1273.       }
  1274.       break;
  1275.    case ir_binop_any_nequal:
  1276.       /* "!=" operator producing a scalar boolean. */
  1277.       if (ir->operands[0]->type->is_vector() ||
  1278.           ir->operands[1]->type->is_vector()) {
  1279.          ir_to_mesa_src_reg temp = get_temp(glsl_type::vec4_type);
  1280.          ir_to_mesa_emit_op2(ir, OPCODE_SNE,
  1281.                              ir_to_mesa_dst_reg_from_src(temp), op[0], op[1]);
  1282.          ir_to_mesa_emit_dp(ir, result_dst, temp, temp, vector_elements);
  1283.          ir_to_mesa_emit_op2(ir, OPCODE_SNE,
  1284.                              result_dst, result_src, src_reg_for_float(0.0));
  1285.       } else {
  1286.          ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
  1287.       }
  1288.       break;
  1289.  
  1290.    case ir_unop_any:
  1291.       assert(ir->operands[0]->type->is_vector());
  1292.       ir_to_mesa_emit_dp(ir, result_dst, op[0], op[0],
  1293.                          ir->operands[0]->type->vector_elements);
  1294.       ir_to_mesa_emit_op2(ir, OPCODE_SNE,
  1295.                           result_dst, result_src, src_reg_for_float(0.0));
  1296.       break;
  1297.  
  1298.    case ir_binop_logic_xor:
  1299.       ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst, op[0], op[1]);
  1300.       break;
  1301.  
  1302.    case ir_binop_logic_or:
  1303.       /* This could be a saturated add and skip the SNE. */
  1304.       ir_to_mesa_emit_op2(ir, OPCODE_ADD,
  1305.                           result_dst,
  1306.                           op[0], op[1]);
  1307.  
  1308.       ir_to_mesa_emit_op2(ir, OPCODE_SNE,
  1309.                           result_dst,
  1310.                           result_src, src_reg_for_float(0.0));
  1311.       break;
  1312.  
  1313.    case ir_binop_logic_and:
  1314.       /* the bool args are stored as float 0.0 or 1.0, so "mul" gives us "and". */
  1315.       ir_to_mesa_emit_op2(ir, OPCODE_MUL,
  1316.                           result_dst,
  1317.                           op[0], op[1]);
  1318.       break;
  1319.  
  1320.    case ir_binop_dot:
  1321.       assert(ir->operands[0]->type->is_vector());
  1322.       assert(ir->operands[0]->type == ir->operands[1]->type);
  1323.       ir_to_mesa_emit_dp(ir, result_dst, op[0], op[1],
  1324.                          ir->operands[0]->type->vector_elements);
  1325.       break;
  1326.  
  1327.    case ir_unop_sqrt:
  1328.       /* sqrt(x) = x * rsq(x). */
  1329.       ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
  1330.       ir_to_mesa_emit_op2(ir, OPCODE_MUL, result_dst, result_src, op[0]);
  1331.       /* For incoming channels <= 0, set the result to 0. */
  1332.       op[0].negate = ~op[0].negate;
  1333.       ir_to_mesa_emit_op3(ir, OPCODE_CMP, result_dst,
  1334.                           op[0], result_src, src_reg_for_float(0.0));
  1335.       break;
  1336.    case ir_unop_rsq:
  1337.       ir_to_mesa_emit_scalar_op1(ir, OPCODE_RSQ, result_dst, op[0]);
  1338.       break;
  1339.    case ir_unop_i2f:
  1340.    case ir_unop_b2f:
  1341.    case ir_unop_b2i:
  1342.       /* Mesa IR lacks types, ints are stored as truncated floats. */
  1343.       result_src = op[0];
  1344.       break;
  1345.    case ir_unop_f2i:
  1346.       ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
  1347.       break;
  1348.    case ir_unop_f2b:
  1349.    case ir_unop_i2b:
  1350.       ir_to_mesa_emit_op2(ir, OPCODE_SNE, result_dst,
  1351.                           op[0], src_reg_for_float(0.0));
  1352.       break;
  1353.    case ir_unop_trunc:
  1354.       ir_to_mesa_emit_op1(ir, OPCODE_TRUNC, result_dst, op[0]);
  1355.       break;
  1356.    case ir_unop_ceil:
  1357.       op[0].negate = ~op[0].negate;
  1358.       ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
  1359.       result_src.negate = ~result_src.negate;
  1360.       break;
  1361.    case ir_unop_floor:
  1362.       ir_to_mesa_emit_op1(ir, OPCODE_FLR, result_dst, op[0]);
  1363.       break;
  1364.    case ir_unop_fract:
  1365.       ir_to_mesa_emit_op1(ir, OPCODE_FRC, result_dst, op[0]);
  1366.       break;
  1367.  
  1368.    case ir_binop_min:
  1369.       ir_to_mesa_emit_op2(ir, OPCODE_MIN, result_dst, op[0], op[1]);
  1370.       break;
  1371.    case ir_binop_max:
  1372.       ir_to_mesa_emit_op2(ir, OPCODE_MAX, result_dst, op[0], op[1]);
  1373.       break;
  1374.    case ir_binop_pow:
  1375.       ir_to_mesa_emit_scalar_op2(ir, OPCODE_POW, result_dst, op[0], op[1]);
  1376.       break;
  1377.  
  1378.    case ir_unop_bit_not:
  1379.    case ir_unop_u2f:
  1380.    case ir_binop_lshift:
  1381.    case ir_binop_rshift:
  1382.    case ir_binop_bit_and:
  1383.    case ir_binop_bit_xor:
  1384.    case ir_binop_bit_or:
  1385.    case ir_unop_round_even:
  1386.       assert(!"GLSL 1.30 features unsupported");
  1387.       break;
  1388.  
  1389.    case ir_quadop_vector:
  1390.       /* This operation should have already been handled.
  1391.        */
  1392.       assert(!"Should not get here.");
  1393.       break;
  1394.    }
  1395.  
  1396.    this->result = result_src;
  1397. }
  1398.  
  1399.  
  1400. void
  1401. ir_to_mesa_visitor::visit(ir_swizzle *ir)
  1402. {
  1403.    ir_to_mesa_src_reg src_reg;
  1404.    int i;
  1405.    int swizzle[4];
  1406.  
  1407.    /* Note that this is only swizzles in expressions, not those on the left
  1408.     * hand side of an assignment, which do write masking.  See ir_assignment
  1409.     * for that.
  1410.     */
  1411.  
  1412.    ir->val->accept(this);
  1413.    src_reg = this->result;
  1414.    assert(src_reg.file != PROGRAM_UNDEFINED);
  1415.  
  1416.    for (i = 0; i < 4; i++) {
  1417.       if (i < ir->type->vector_elements) {
  1418.          switch (i) {
  1419.          case 0:
  1420.             swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.x);
  1421.             break;
  1422.          case 1:
  1423.             swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.y);
  1424.             break;
  1425.          case 2:
  1426.             swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.z);
  1427.             break;
  1428.          case 3:
  1429.             swizzle[i] = GET_SWZ(src_reg.swizzle, ir->mask.w);
  1430.             break;
  1431.          }
  1432.       } else {
  1433.          /* If the type is smaller than a vec4, replicate the last
  1434.           * channel out.
  1435.           */
  1436.          swizzle[i] = swizzle[ir->type->vector_elements - 1];
  1437.       }
  1438.    }
  1439.  
  1440.    src_reg.swizzle = MAKE_SWIZZLE4(swizzle[0],
  1441.                                    swizzle[1],
  1442.                                    swizzle[2],
  1443.                                    swizzle[3]);
  1444.  
  1445.    this->result = src_reg;
  1446. }
  1447.  
  1448. void
  1449. ir_to_mesa_visitor::visit(ir_dereference_variable *ir)
  1450. {
  1451.    variable_storage *entry = find_variable_storage(ir->var);
  1452.  
  1453.    if (!entry) {
  1454.       switch (ir->var->mode) {
  1455.       case ir_var_uniform:
  1456.          entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_UNIFORM,
  1457.                                                ir->var->location);
  1458.          this->variables.push_tail(entry);
  1459.          break;
  1460.       case ir_var_in:
  1461.       case ir_var_out:
  1462.       case ir_var_inout:
  1463.          /* The linker assigns locations for varyings and attributes,
  1464.           * including deprecated builtins (like gl_Color), user-assign
  1465.           * generic attributes (glBindVertexLocation), and
  1466.           * user-defined varyings.
  1467.           *
  1468.           * FINISHME: We would hit this path for function arguments.  Fix!
  1469.           */
  1470.          assert(ir->var->location != -1);
  1471.          if (ir->var->mode == ir_var_in ||
  1472.              ir->var->mode == ir_var_inout) {
  1473.             entry = new(mem_ctx) variable_storage(ir->var,
  1474.                                                   PROGRAM_INPUT,
  1475.                                                   ir->var->location);
  1476.  
  1477.             if (this->prog->Target == GL_VERTEX_PROGRAM_ARB &&
  1478.                 ir->var->location >= VERT_ATTRIB_GENERIC0) {
  1479.                _mesa_add_attribute(prog->Attributes,
  1480.                                    ir->var->name,
  1481.                                    _mesa_sizeof_glsl_type(ir->var->type->gl_type),
  1482.                                    ir->var->type->gl_type,
  1483.                                    ir->var->location - VERT_ATTRIB_GENERIC0);
  1484.             }
  1485.          } else {
  1486.             entry = new(mem_ctx) variable_storage(ir->var,
  1487.                                                   PROGRAM_OUTPUT,
  1488.                                                   ir->var->location);
  1489.          }
  1490.  
  1491.          break;
  1492.       case ir_var_auto:
  1493.       case ir_var_temporary:
  1494.          entry = new(mem_ctx) variable_storage(ir->var, PROGRAM_TEMPORARY,
  1495.                                                this->next_temp);
  1496.          this->variables.push_tail(entry);
  1497.  
  1498.          next_temp += type_size(ir->var->type);
  1499.          break;
  1500.       }
  1501.  
  1502.       if (!entry) {
  1503.          printf("Failed to make storage for %s\n", ir->var->name);
  1504.          exit(1);
  1505.       }
  1506.    }
  1507.  
  1508.    this->result = ir_to_mesa_src_reg(entry->file, entry->index, ir->var->type);
  1509. }
  1510.  
  1511. void
  1512. ir_to_mesa_visitor::visit(ir_dereference_array *ir)
  1513. {
  1514.    ir_constant *index;
  1515.    ir_to_mesa_src_reg src_reg;
  1516.    int element_size = type_size(ir->type);
  1517.  
  1518.    index = ir->array_index->constant_expression_value();
  1519.  
  1520.    ir->array->accept(this);
  1521.    src_reg = this->result;
  1522.  
  1523.    if (index) {
  1524.       src_reg.index += index->value.i[0] * element_size;
  1525.    } else {
  1526.       ir_to_mesa_src_reg array_base = this->result;
  1527.       /* Variable index array dereference.  It eats the "vec4" of the
  1528.        * base of the array and an index that offsets the Mesa register
  1529.        * index.
  1530.        */
  1531.       ir->array_index->accept(this);
  1532.  
  1533.       ir_to_mesa_src_reg index_reg;
  1534.  
  1535.       if (element_size == 1) {
  1536.          index_reg = this->result;
  1537.       } else {
  1538.          index_reg = get_temp(glsl_type::float_type);
  1539.  
  1540.          ir_to_mesa_emit_op2(ir, OPCODE_MUL,
  1541.                              ir_to_mesa_dst_reg_from_src(index_reg),
  1542.                              this->result, src_reg_for_float(element_size));
  1543.       }
  1544.  
  1545.       src_reg.reladdr = ralloc(mem_ctx, ir_to_mesa_src_reg);
  1546.       memcpy(src_reg.reladdr, &index_reg, sizeof(index_reg));
  1547.    }
  1548.  
  1549.    /* If the type is smaller than a vec4, replicate the last channel out. */
  1550.    if (ir->type->is_scalar() || ir->type->is_vector())
  1551.       src_reg.swizzle = swizzle_for_size(ir->type->vector_elements);
  1552.    else
  1553.       src_reg.swizzle = SWIZZLE_NOOP;
  1554.  
  1555.    this->result = src_reg;
  1556. }
  1557.  
  1558. void
  1559. ir_to_mesa_visitor::visit(ir_dereference_record *ir)
  1560. {
  1561.    unsigned int i;
  1562.    const glsl_type *struct_type = ir->record->type;
  1563.    int offset = 0;
  1564.  
  1565.    ir->record->accept(this);
  1566.  
  1567.    for (i = 0; i < struct_type->length; i++) {
  1568.       if (strcmp(struct_type->fields.structure[i].name, ir->field) == 0)
  1569.          break;
  1570.       offset += type_size(struct_type->fields.structure[i].type);
  1571.    }
  1572.  
  1573.    /* If the type is smaller than a vec4, replicate the last channel out. */
  1574.    if (ir->type->is_scalar() || ir->type->is_vector())
  1575.       this->result.swizzle = swizzle_for_size(ir->type->vector_elements);
  1576.    else
  1577.       this->result.swizzle = SWIZZLE_NOOP;
  1578.  
  1579.    this->result.index += offset;
  1580. }
  1581.  
  1582. /**
  1583.  * We want to be careful in assignment setup to hit the actual storage
  1584.  * instead of potentially using a temporary like we might with the
  1585.  * ir_dereference handler.
  1586.  */
  1587. static struct ir_to_mesa_dst_reg
  1588. get_assignment_lhs(ir_dereference *ir, ir_to_mesa_visitor *v)
  1589. {
  1590.    /* The LHS must be a dereference.  If the LHS is a variable indexed array
  1591.     * access of a vector, it must be separated into a series conditional moves
  1592.     * before reaching this point (see ir_vec_index_to_cond_assign).
  1593.     */
  1594.    assert(ir->as_dereference());
  1595.    ir_dereference_array *deref_array = ir->as_dereference_array();
  1596.    if (deref_array) {
  1597.       assert(!deref_array->array->type->is_vector());
  1598.    }
  1599.  
  1600.    /* Use the rvalue deref handler for the most part.  We'll ignore
  1601.     * swizzles in it and write swizzles using writemask, though.
  1602.     */
  1603.    ir->accept(v);
  1604.    return ir_to_mesa_dst_reg_from_src(v->result);
  1605. }
  1606.  
  1607. /**
  1608.  * Process the condition of a conditional assignment
  1609.  *
  1610.  * Examines the condition of a conditional assignment to generate the optimal
  1611.  * first operand of a \c CMP instruction.  If the condition is a relational
  1612.  * operator with 0 (e.g., \c ir_binop_less), the value being compared will be
  1613.  * used as the source for the \c CMP instruction.  Otherwise the comparison
  1614.  * is processed to a boolean result, and the boolean result is used as the
  1615.  * operand to the CMP instruction.
  1616.  */
  1617. bool
  1618. ir_to_mesa_visitor::process_move_condition(ir_rvalue *ir)
  1619. {
  1620.    ir_rvalue *src_ir = ir;
  1621.    bool negate = true;
  1622.    bool switch_order = false;
  1623.  
  1624.    ir_expression *const expr = ir->as_expression();
  1625.    if ((expr != NULL) && (expr->get_num_operands() == 2)) {
  1626.       bool zero_on_left = false;
  1627.  
  1628.       if (expr->operands[0]->is_zero()) {
  1629.          src_ir = expr->operands[1];
  1630.          zero_on_left = true;
  1631.       } else if (expr->operands[1]->is_zero()) {
  1632.          src_ir = expr->operands[0];
  1633.          zero_on_left = false;
  1634.       }
  1635.  
  1636.       /*      a is -  0  +            -  0  +
  1637.        * (a <  0)  T  F  F  ( a < 0)  T  F  F
  1638.        * (0 <  a)  F  F  T  (-a < 0)  F  F  T
  1639.        * (a <= 0)  T  T  F  (-a < 0)  F  F  T  (swap order of other operands)
  1640.        * (0 <= a)  F  T  T  ( a < 0)  T  F  F  (swap order of other operands)
  1641.        * (a >  0)  F  F  T  (-a < 0)  F  F  T
  1642.        * (0 >  a)  T  F  F  ( a < 0)  T  F  F
  1643.        * (a >= 0)  F  T  T  ( a < 0)  T  F  F  (swap order of other operands)
  1644.        * (0 >= a)  T  T  F  (-a < 0)  F  F  T  (swap order of other operands)
  1645.        *
  1646.        * Note that exchanging the order of 0 and 'a' in the comparison simply
  1647.        * means that the value of 'a' should be negated.
  1648.        */
  1649.       if (src_ir != ir) {
  1650.          switch (expr->operation) {
  1651.          case ir_binop_less:
  1652.             switch_order = false;
  1653.             negate = zero_on_left;
  1654.             break;
  1655.  
  1656.          case ir_binop_greater:
  1657.             switch_order = false;
  1658.             negate = !zero_on_left;
  1659.             break;
  1660.  
  1661.          case ir_binop_lequal:
  1662.             switch_order = true;
  1663.             negate = !zero_on_left;
  1664.             break;
  1665.  
  1666.          case ir_binop_gequal:
  1667.             switch_order = true;
  1668.             negate = zero_on_left;
  1669.             break;
  1670.  
  1671.          default:
  1672.             /* This isn't the right kind of comparison afterall, so make sure
  1673.              * the whole condition is visited.
  1674.              */
  1675.             src_ir = ir;
  1676.             break;
  1677.          }
  1678.       }
  1679.    }
  1680.  
  1681.    src_ir->accept(this);
  1682.  
  1683.    /* We use the OPCODE_CMP (a < 0 ? b : c) for conditional moves, and the
  1684.     * condition we produced is 0.0 or 1.0.  By flipping the sign, we can
  1685.     * choose which value OPCODE_CMP produces without an extra instruction
  1686.     * computing the condition.
  1687.     */
  1688.    if (negate)
  1689.       this->result.negate = ~this->result.negate;
  1690.  
  1691.    return switch_order;
  1692. }
  1693.  
  1694. void
  1695. ir_to_mesa_visitor::visit(ir_assignment *ir)
  1696. {
  1697.    struct ir_to_mesa_dst_reg l;
  1698.    struct ir_to_mesa_src_reg r;
  1699.    int i;
  1700.  
  1701.    ir->rhs->accept(this);
  1702.    r = this->result;
  1703.  
  1704.    l = get_assignment_lhs(ir->lhs, this);
  1705.  
  1706.    /* FINISHME: This should really set to the correct maximal writemask for each
  1707.     * FINISHME: component written (in the loops below).  This case can only
  1708.     * FINISHME: occur for matrices, arrays, and structures.
  1709.     */
  1710.    if (ir->write_mask == 0) {
  1711.       assert(!ir->lhs->type->is_scalar() && !ir->lhs->type->is_vector());
  1712.       l.writemask = WRITEMASK_XYZW;
  1713.    } else if (ir->lhs->type->is_scalar()) {
  1714.       /* FINISHME: This hack makes writing to gl_FragDepth, which lives in the
  1715.        * FINISHME: W component of fragment shader output zero, work correctly.
  1716.        */
  1717.       l.writemask = WRITEMASK_XYZW;
  1718.    } else {
  1719.       int swizzles[4];
  1720.       int first_enabled_chan = 0;
  1721.       int rhs_chan = 0;
  1722.  
  1723.       assert(ir->lhs->type->is_vector());
  1724.       l.writemask = ir->write_mask;
  1725.  
  1726.       for (int i = 0; i < 4; i++) {
  1727.          if (l.writemask & (1 << i)) {
  1728.             first_enabled_chan = GET_SWZ(r.swizzle, i);
  1729.             break;
  1730.          }
  1731.       }
  1732.  
  1733.       /* Swizzle a small RHS vector into the channels being written.
  1734.        *
  1735.        * glsl ir treats write_mask as dictating how many channels are
  1736.        * present on the RHS while Mesa IR treats write_mask as just
  1737.        * showing which channels of the vec4 RHS get written.
  1738.        */
  1739.       for (int i = 0; i < 4; i++) {
  1740.          if (l.writemask & (1 << i))
  1741.             swizzles[i] = GET_SWZ(r.swizzle, rhs_chan++);
  1742.          else
  1743.             swizzles[i] = first_enabled_chan;
  1744.       }
  1745.       r.swizzle = MAKE_SWIZZLE4(swizzles[0], swizzles[1],
  1746.                                 swizzles[2], swizzles[3]);
  1747.    }
  1748.  
  1749.    assert(l.file != PROGRAM_UNDEFINED);
  1750.    assert(r.file != PROGRAM_UNDEFINED);
  1751.  
  1752.    if (ir->condition) {
  1753.       const bool switch_order = this->process_move_condition(ir->condition);
  1754.       ir_to_mesa_src_reg condition = this->result;
  1755.  
  1756.       for (i = 0; i < type_size(ir->lhs->type); i++) {
  1757.          if (switch_order) {
  1758.             ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
  1759.                                 condition, ir_to_mesa_src_reg_from_dst(l), r);
  1760.          } else {
  1761.             ir_to_mesa_emit_op3(ir, OPCODE_CMP, l,
  1762.                                 condition, r, ir_to_mesa_src_reg_from_dst(l));
  1763.          }
  1764.  
  1765.          l.index++;
  1766.          r.index++;
  1767.       }
  1768.    } else {
  1769.       for (i = 0; i < type_size(ir->lhs->type); i++) {
  1770.          ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
  1771.          l.index++;
  1772.          r.index++;
  1773.       }
  1774.    }
  1775. }
  1776.  
  1777.  
  1778. void
  1779. ir_to_mesa_visitor::visit(ir_constant *ir)
  1780. {
  1781.    ir_to_mesa_src_reg src_reg;
  1782.    GLfloat stack_vals[4] = { 0 };
  1783.    GLfloat *values = stack_vals;
  1784.    unsigned int i;
  1785.  
  1786.    /* Unfortunately, 4 floats is all we can get into
  1787.     * _mesa_add_unnamed_constant.  So, make a temp to store an
  1788.     * aggregate constant and move each constant value into it.  If we
  1789.     * get lucky, copy propagation will eliminate the extra moves.
  1790.     */
  1791.  
  1792.    if (ir->type->base_type == GLSL_TYPE_STRUCT) {
  1793.       ir_to_mesa_src_reg temp_base = get_temp(ir->type);
  1794.       ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
  1795.  
  1796.       foreach_iter(exec_list_iterator, iter, ir->components) {
  1797.          ir_constant *field_value = (ir_constant *)iter.get();
  1798.          int size = type_size(field_value->type);
  1799.  
  1800.          assert(size > 0);
  1801.  
  1802.          field_value->accept(this);
  1803.          src_reg = this->result;
  1804.  
  1805.          for (i = 0; i < (unsigned int)size; i++) {
  1806.             ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
  1807.  
  1808.             src_reg.index++;
  1809.             temp.index++;
  1810.          }
  1811.       }
  1812.       this->result = temp_base;
  1813.       return;
  1814.    }
  1815.  
  1816.    if (ir->type->is_array()) {
  1817.       ir_to_mesa_src_reg temp_base = get_temp(ir->type);
  1818.       ir_to_mesa_dst_reg temp = ir_to_mesa_dst_reg_from_src(temp_base);
  1819.       int size = type_size(ir->type->fields.array);
  1820.  
  1821.       assert(size > 0);
  1822.  
  1823.       for (i = 0; i < ir->type->length; i++) {
  1824.          ir->array_elements[i]->accept(this);
  1825.          src_reg = this->result;
  1826.          for (int j = 0; j < size; j++) {
  1827.             ir_to_mesa_emit_op1(ir, OPCODE_MOV, temp, src_reg);
  1828.  
  1829.             src_reg.index++;
  1830.             temp.index++;
  1831.          }
  1832.       }
  1833.       this->result = temp_base;
  1834.       return;
  1835.    }
  1836.  
  1837.    if (ir->type->is_matrix()) {
  1838.       ir_to_mesa_src_reg mat = get_temp(ir->type);
  1839.       ir_to_mesa_dst_reg mat_column = ir_to_mesa_dst_reg_from_src(mat);
  1840.  
  1841.       for (i = 0; i < ir->type->matrix_columns; i++) {
  1842.          assert(ir->type->base_type == GLSL_TYPE_FLOAT);
  1843.          values = &ir->value.f[i * ir->type->vector_elements];
  1844.  
  1845.          src_reg = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, NULL);
  1846.          src_reg.index = _mesa_add_unnamed_constant(this->prog->Parameters,
  1847.                                                 values,
  1848.                                                 ir->type->vector_elements,
  1849.                                                 &src_reg.swizzle);
  1850.          ir_to_mesa_emit_op1(ir, OPCODE_MOV, mat_column, src_reg);
  1851.  
  1852.          mat_column.index++;
  1853.       }
  1854.  
  1855.       this->result = mat;
  1856.       return;
  1857.    }
  1858.  
  1859.    src_reg.file = PROGRAM_CONSTANT;
  1860.    switch (ir->type->base_type) {
  1861.    case GLSL_TYPE_FLOAT:
  1862.       values = &ir->value.f[0];
  1863.       break;
  1864.    case GLSL_TYPE_UINT:
  1865.       for (i = 0; i < ir->type->vector_elements; i++) {
  1866.          values[i] = ir->value.u[i];
  1867.       }
  1868.       break;
  1869.    case GLSL_TYPE_INT:
  1870.       for (i = 0; i < ir->type->vector_elements; i++) {
  1871.          values[i] = ir->value.i[i];
  1872.       }
  1873.       break;
  1874.    case GLSL_TYPE_BOOL:
  1875.       for (i = 0; i < ir->type->vector_elements; i++) {
  1876.          values[i] = ir->value.b[i];
  1877.       }
  1878.       break;
  1879.    default:
  1880.       assert(!"Non-float/uint/int/bool constant");
  1881.    }
  1882.  
  1883.    this->result = ir_to_mesa_src_reg(PROGRAM_CONSTANT, -1, ir->type);
  1884.    this->result.index = _mesa_add_unnamed_constant(this->prog->Parameters,
  1885.                                                    values,
  1886.                                                    ir->type->vector_elements,
  1887.                                                    &this->result.swizzle);
  1888. }
  1889.  
  1890. function_entry *
  1891. ir_to_mesa_visitor::get_function_signature(ir_function_signature *sig)
  1892. {
  1893.    function_entry *entry;
  1894.  
  1895.    foreach_iter(exec_list_iterator, iter, this->function_signatures) {
  1896.       entry = (function_entry *)iter.get();
  1897.  
  1898.       if (entry->sig == sig)
  1899.          return entry;
  1900.    }
  1901.  
  1902.    entry = ralloc(mem_ctx, function_entry);
  1903.    entry->sig = sig;
  1904.    entry->sig_id = this->next_signature_id++;
  1905.    entry->bgn_inst = NULL;
  1906.  
  1907.    /* Allocate storage for all the parameters. */
  1908.    foreach_iter(exec_list_iterator, iter, sig->parameters) {
  1909.       ir_variable *param = (ir_variable *)iter.get();
  1910.       variable_storage *storage;
  1911.  
  1912.       storage = find_variable_storage(param);
  1913.       assert(!storage);
  1914.  
  1915.       storage = new(mem_ctx) variable_storage(param, PROGRAM_TEMPORARY,
  1916.                                               this->next_temp);
  1917.       this->variables.push_tail(storage);
  1918.  
  1919.       this->next_temp += type_size(param->type);
  1920.    }
  1921.  
  1922.    if (!sig->return_type->is_void()) {
  1923.       entry->return_reg = get_temp(sig->return_type);
  1924.    } else {
  1925.       entry->return_reg = ir_to_mesa_undef;
  1926.    }
  1927.  
  1928.    this->function_signatures.push_tail(entry);
  1929.    return entry;
  1930. }
  1931.  
  1932. void
  1933. ir_to_mesa_visitor::visit(ir_call *ir)
  1934. {
  1935.    ir_to_mesa_instruction *call_inst;
  1936.    ir_function_signature *sig = ir->get_callee();
  1937.    function_entry *entry = get_function_signature(sig);
  1938.    int i;
  1939.  
  1940.    /* Process in parameters. */
  1941.    exec_list_iterator sig_iter = sig->parameters.iterator();
  1942.    foreach_iter(exec_list_iterator, iter, *ir) {
  1943.       ir_rvalue *param_rval = (ir_rvalue *)iter.get();
  1944.       ir_variable *param = (ir_variable *)sig_iter.get();
  1945.  
  1946.       if (param->mode == ir_var_in ||
  1947.           param->mode == ir_var_inout) {
  1948.          variable_storage *storage = find_variable_storage(param);
  1949.          assert(storage);
  1950.  
  1951.          param_rval->accept(this);
  1952.          ir_to_mesa_src_reg r = this->result;
  1953.  
  1954.          ir_to_mesa_dst_reg l;
  1955.          l.file = storage->file;
  1956.          l.index = storage->index;
  1957.          l.reladdr = NULL;
  1958.          l.writemask = WRITEMASK_XYZW;
  1959.          l.cond_mask = COND_TR;
  1960.  
  1961.          for (i = 0; i < type_size(param->type); i++) {
  1962.             ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
  1963.             l.index++;
  1964.             r.index++;
  1965.          }
  1966.       }
  1967.  
  1968.       sig_iter.next();
  1969.    }
  1970.    assert(!sig_iter.has_next());
  1971.  
  1972.    /* Emit call instruction */
  1973.    call_inst = ir_to_mesa_emit_op1(ir, OPCODE_CAL,
  1974.                                    ir_to_mesa_undef_dst, ir_to_mesa_undef);
  1975.    call_inst->function = entry;
  1976.  
  1977.    /* Process out parameters. */
  1978.    sig_iter = sig->parameters.iterator();
  1979.    foreach_iter(exec_list_iterator, iter, *ir) {
  1980.       ir_rvalue *param_rval = (ir_rvalue *)iter.get();
  1981.       ir_variable *param = (ir_variable *)sig_iter.get();
  1982.  
  1983.       if (param->mode == ir_var_out ||
  1984.           param->mode == ir_var_inout) {
  1985.          variable_storage *storage = find_variable_storage(param);
  1986.          assert(storage);
  1987.  
  1988.          ir_to_mesa_src_reg r;
  1989.          r.file = storage->file;
  1990.          r.index = storage->index;
  1991.          r.reladdr = NULL;
  1992.          r.swizzle = SWIZZLE_NOOP;
  1993.          r.negate = 0;
  1994.  
  1995.          param_rval->accept(this);
  1996.          ir_to_mesa_dst_reg l = ir_to_mesa_dst_reg_from_src(this->result);
  1997.  
  1998.          for (i = 0; i < type_size(param->type); i++) {
  1999.             ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
  2000.             l.index++;
  2001.             r.index++;
  2002.          }
  2003.       }
  2004.  
  2005.       sig_iter.next();
  2006.    }
  2007.    assert(!sig_iter.has_next());
  2008.  
  2009.    /* Process return value. */
  2010.    this->result = entry->return_reg;
  2011. }
  2012.  
  2013. void
  2014. ir_to_mesa_visitor::visit(ir_texture *ir)
  2015. {
  2016.    ir_to_mesa_src_reg result_src, coord, lod_info, projector;
  2017.    ir_to_mesa_dst_reg result_dst, coord_dst;
  2018.    ir_to_mesa_instruction *inst = NULL;
  2019.    prog_opcode opcode = OPCODE_NOP;
  2020.  
  2021.    ir->coordinate->accept(this);
  2022.  
  2023.    /* Put our coords in a temp.  We'll need to modify them for shadow,
  2024.     * projection, or LOD, so the only case we'd use it as is is if
  2025.     * we're doing plain old texturing.  Mesa IR optimization should
  2026.     * handle cleaning up our mess in that case.
  2027.     */
  2028.    coord = get_temp(glsl_type::vec4_type);
  2029.    coord_dst = ir_to_mesa_dst_reg_from_src(coord);
  2030.    ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst,
  2031.                        this->result);
  2032.  
  2033.    if (ir->projector) {
  2034.       ir->projector->accept(this);
  2035.       projector = this->result;
  2036.    }
  2037.  
  2038.    /* Storage for our result.  Ideally for an assignment we'd be using
  2039.     * the actual storage for the result here, instead.
  2040.     */
  2041.    result_src = get_temp(glsl_type::vec4_type);
  2042.    result_dst = ir_to_mesa_dst_reg_from_src(result_src);
  2043.  
  2044.    switch (ir->op) {
  2045.    case ir_tex:
  2046.       opcode = OPCODE_TEX;
  2047.       break;
  2048.    case ir_txb:
  2049.       opcode = OPCODE_TXB;
  2050.       ir->lod_info.bias->accept(this);
  2051.       lod_info = this->result;
  2052.       break;
  2053.    case ir_txl:
  2054.       opcode = OPCODE_TXL;
  2055.       ir->lod_info.lod->accept(this);
  2056.       lod_info = this->result;
  2057.       break;
  2058.    case ir_txd:
  2059.    case ir_txf:
  2060.       assert(!"GLSL 1.30 features unsupported");
  2061.       break;
  2062.    }
  2063.  
  2064.    if (ir->projector) {
  2065.       if (opcode == OPCODE_TEX) {
  2066.          /* Slot the projector in as the last component of the coord. */
  2067.          coord_dst.writemask = WRITEMASK_W;
  2068.          ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, projector);
  2069.          coord_dst.writemask = WRITEMASK_XYZW;
  2070.          opcode = OPCODE_TXP;
  2071.       } else {
  2072.          ir_to_mesa_src_reg coord_w = coord;
  2073.          coord_w.swizzle = SWIZZLE_WWWW;
  2074.  
  2075.          /* For the other TEX opcodes there's no projective version
  2076.           * since the last slot is taken up by lod info.  Do the
  2077.           * projective divide now.
  2078.           */
  2079.          coord_dst.writemask = WRITEMASK_W;
  2080.          ir_to_mesa_emit_op1(ir, OPCODE_RCP, coord_dst, projector);
  2081.  
  2082.          coord_dst.writemask = WRITEMASK_XYZ;
  2083.          ir_to_mesa_emit_op2(ir, OPCODE_MUL, coord_dst, coord, coord_w);
  2084.  
  2085.          coord_dst.writemask = WRITEMASK_XYZW;
  2086.          coord.swizzle = SWIZZLE_XYZW;
  2087.       }
  2088.    }
  2089.  
  2090.    if (ir->shadow_comparitor) {
  2091.       /* Slot the shadow value in as the second to last component of the
  2092.        * coord.
  2093.        */
  2094.       ir->shadow_comparitor->accept(this);
  2095.       coord_dst.writemask = WRITEMASK_Z;
  2096.       ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, this->result);
  2097.       coord_dst.writemask = WRITEMASK_XYZW;
  2098.    }
  2099.  
  2100.    if (opcode == OPCODE_TXL || opcode == OPCODE_TXB) {
  2101.       /* Mesa IR stores lod or lod bias in the last channel of the coords. */
  2102.       coord_dst.writemask = WRITEMASK_W;
  2103.       ir_to_mesa_emit_op1(ir, OPCODE_MOV, coord_dst, lod_info);
  2104.       coord_dst.writemask = WRITEMASK_XYZW;
  2105.    }
  2106.  
  2107.    inst = ir_to_mesa_emit_op1(ir, opcode, result_dst, coord);
  2108.  
  2109.    if (ir->shadow_comparitor)
  2110.       inst->tex_shadow = GL_TRUE;
  2111.  
  2112.    inst->sampler = _mesa_get_sampler_uniform_value(ir->sampler,
  2113.                                                    this->shader_program,
  2114.                                                    this->prog);
  2115.  
  2116.    const glsl_type *sampler_type = ir->sampler->type;
  2117.  
  2118.    switch (sampler_type->sampler_dimensionality) {
  2119.    case GLSL_SAMPLER_DIM_1D:
  2120.       inst->tex_target = (sampler_type->sampler_array)
  2121.          ? TEXTURE_1D_ARRAY_INDEX : TEXTURE_1D_INDEX;
  2122.       break;
  2123.    case GLSL_SAMPLER_DIM_2D:
  2124.       inst->tex_target = (sampler_type->sampler_array)
  2125.          ? TEXTURE_2D_ARRAY_INDEX : TEXTURE_2D_INDEX;
  2126.       break;
  2127.    case GLSL_SAMPLER_DIM_3D:
  2128.       inst->tex_target = TEXTURE_3D_INDEX;
  2129.       break;
  2130.    case GLSL_SAMPLER_DIM_CUBE:
  2131.       inst->tex_target = TEXTURE_CUBE_INDEX;
  2132.       break;
  2133.    case GLSL_SAMPLER_DIM_RECT:
  2134.       inst->tex_target = TEXTURE_RECT_INDEX;
  2135.       break;
  2136.    case GLSL_SAMPLER_DIM_BUF:
  2137.       assert(!"FINISHME: Implement ARB_texture_buffer_object");
  2138.       break;
  2139.    default:
  2140.       assert(!"Should not get here.");
  2141.    }
  2142.  
  2143.    this->result = result_src;
  2144. }
  2145.  
  2146. void
  2147. ir_to_mesa_visitor::visit(ir_return *ir)
  2148. {
  2149.    if (ir->get_value()) {
  2150.       ir_to_mesa_dst_reg l;
  2151.       int i;
  2152.  
  2153.       assert(current_function);
  2154.  
  2155.       ir->get_value()->accept(this);
  2156.       ir_to_mesa_src_reg r = this->result;
  2157.  
  2158.       l = ir_to_mesa_dst_reg_from_src(current_function->return_reg);
  2159.  
  2160.       for (i = 0; i < type_size(current_function->sig->return_type); i++) {
  2161.          ir_to_mesa_emit_op1(ir, OPCODE_MOV, l, r);
  2162.          l.index++;
  2163.          r.index++;
  2164.       }
  2165.    }
  2166.  
  2167.    ir_to_mesa_emit_op0(ir, OPCODE_RET);
  2168. }
  2169.  
  2170. void
  2171. ir_to_mesa_visitor::visit(ir_discard *ir)
  2172. {
  2173.    struct gl_fragment_program *fp = (struct gl_fragment_program *)this->prog;
  2174.  
  2175.    if (ir->condition) {
  2176.       ir->condition->accept(this);
  2177.       this->result.negate = ~this->result.negate;
  2178.       ir_to_mesa_emit_op1(ir, OPCODE_KIL, ir_to_mesa_undef_dst, this->result);
  2179.    } else {
  2180.       ir_to_mesa_emit_op0(ir, OPCODE_KIL_NV);
  2181.    }
  2182.  
  2183.    fp->UsesKill = GL_TRUE;
  2184. }
  2185.  
  2186. void
  2187. ir_to_mesa_visitor::visit(ir_if *ir)
  2188. {
  2189.    ir_to_mesa_instruction *cond_inst, *if_inst, *else_inst = NULL;
  2190.    ir_to_mesa_instruction *prev_inst;
  2191.  
  2192.    prev_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
  2193.  
  2194.    ir->condition->accept(this);
  2195.    assert(this->result.file != PROGRAM_UNDEFINED);
  2196.  
  2197.    if (this->options->EmitCondCodes) {
  2198.       cond_inst = (ir_to_mesa_instruction *)this->instructions.get_tail();
  2199.  
  2200.       /* See if we actually generated any instruction for generating
  2201.        * the condition.  If not, then cook up a move to a temp so we
  2202.        * have something to set cond_update on.
  2203.        */
  2204.       if (cond_inst == prev_inst) {
  2205.          ir_to_mesa_src_reg temp = get_temp(glsl_type::bool_type);
  2206.          cond_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_MOV,
  2207.                                          ir_to_mesa_dst_reg_from_src(temp),
  2208.                                          result);
  2209.       }
  2210.       cond_inst->cond_update = GL_TRUE;
  2211.  
  2212.       if_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_IF);
  2213.       if_inst->dst_reg.cond_mask = COND_NE;
  2214.    } else {
  2215.       if_inst = ir_to_mesa_emit_op1(ir->condition,
  2216.                                     OPCODE_IF, ir_to_mesa_undef_dst,
  2217.                                     this->result);
  2218.    }
  2219.  
  2220.    this->instructions.push_tail(if_inst);
  2221.  
  2222.    visit_exec_list(&ir->then_instructions, this);
  2223.  
  2224.    if (!ir->else_instructions.is_empty()) {
  2225.       else_inst = ir_to_mesa_emit_op0(ir->condition, OPCODE_ELSE);
  2226.       visit_exec_list(&ir->else_instructions, this);
  2227.    }
  2228.  
  2229.    if_inst = ir_to_mesa_emit_op1(ir->condition, OPCODE_ENDIF,
  2230.                                  ir_to_mesa_undef_dst, ir_to_mesa_undef);
  2231. }
  2232.  
  2233. ir_to_mesa_visitor::ir_to_mesa_visitor()
  2234. {
  2235.    result.file = PROGRAM_UNDEFINED;
  2236.    next_temp = 1;
  2237.    next_signature_id = 1;
  2238.    current_function = NULL;
  2239.    mem_ctx = ralloc_context(NULL);
  2240. }
  2241.  
  2242. ir_to_mesa_visitor::~ir_to_mesa_visitor()
  2243. {
  2244.    ralloc_free(mem_ctx);
  2245. }
  2246.  
  2247. static struct prog_src_register
  2248. mesa_src_reg_from_ir_src_reg(ir_to_mesa_src_reg reg)
  2249. {
  2250.    struct prog_src_register mesa_reg;
  2251.  
  2252.    mesa_reg.File = reg.file;
  2253.    assert(reg.index < (1 << INST_INDEX_BITS));
  2254.    mesa_reg.Index = reg.index;
  2255.    mesa_reg.Swizzle = reg.swizzle;
  2256.    mesa_reg.RelAddr = reg.reladdr != NULL;
  2257.    mesa_reg.Negate = reg.negate;
  2258.    mesa_reg.Abs = 0;
  2259.    mesa_reg.HasIndex2 = GL_FALSE;
  2260.    mesa_reg.RelAddr2 = 0;
  2261.    mesa_reg.Index2 = 0;
  2262.  
  2263.    return mesa_reg;
  2264. }
  2265.  
  2266. static void
  2267. set_branchtargets(ir_to_mesa_visitor *v,
  2268.                   struct prog_instruction *mesa_instructions,
  2269.                   int num_instructions)
  2270. {
  2271.    int if_count = 0, loop_count = 0;
  2272.    int *if_stack, *loop_stack;
  2273.    int if_stack_pos = 0, loop_stack_pos = 0;
  2274.    int i, j;
  2275.  
  2276.    for (i = 0; i < num_instructions; i++) {
  2277.       switch (mesa_instructions[i].Opcode) {
  2278.       case OPCODE_IF:
  2279.          if_count++;
  2280.          break;
  2281.       case OPCODE_BGNLOOP:
  2282.          loop_count++;
  2283.          break;
  2284.       case OPCODE_BRK:
  2285.       case OPCODE_CONT:
  2286.          mesa_instructions[i].BranchTarget = -1;
  2287.          break;
  2288.       default:
  2289.          break;
  2290.       }
  2291.    }
  2292.  
  2293.    if_stack = rzalloc_array(v->mem_ctx, int, if_count);
  2294.    loop_stack = rzalloc_array(v->mem_ctx, int, loop_count);
  2295.  
  2296.    for (i = 0; i < num_instructions; i++) {
  2297.       switch (mesa_instructions[i].Opcode) {
  2298.       case OPCODE_IF:
  2299.          if_stack[if_stack_pos] = i;
  2300.          if_stack_pos++;
  2301.          break;
  2302.       case OPCODE_ELSE:
  2303.          mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
  2304.          if_stack[if_stack_pos - 1] = i;
  2305.          break;
  2306.       case OPCODE_ENDIF:
  2307.          mesa_instructions[if_stack[if_stack_pos - 1]].BranchTarget = i;
  2308.          if_stack_pos--;
  2309.          break;
  2310.       case OPCODE_BGNLOOP:
  2311.          loop_stack[loop_stack_pos] = i;
  2312.          loop_stack_pos++;
  2313.          break;
  2314.       case OPCODE_ENDLOOP:
  2315.          loop_stack_pos--;
  2316.          /* Rewrite any breaks/conts at this nesting level (haven't
  2317.           * already had a BranchTarget assigned) to point to the end
  2318.           * of the loop.
  2319.           */
  2320.          for (j = loop_stack[loop_stack_pos]; j < i; j++) {
  2321.             if (mesa_instructions[j].Opcode == OPCODE_BRK ||
  2322.                 mesa_instructions[j].Opcode == OPCODE_CONT) {
  2323.                if (mesa_instructions[j].BranchTarget == -1) {
  2324.                   mesa_instructions[j].BranchTarget = i;
  2325.                }
  2326.             }
  2327.          }
  2328.          /* The loop ends point at each other. */
  2329.          mesa_instructions[i].BranchTarget = loop_stack[loop_stack_pos];
  2330.          mesa_instructions[loop_stack[loop_stack_pos]].BranchTarget = i;
  2331.          break;
  2332.       case OPCODE_CAL:
  2333.          foreach_iter(exec_list_iterator, iter, v->function_signatures) {
  2334.             function_entry *entry = (function_entry *)iter.get();
  2335.  
  2336.             if (entry->sig_id == mesa_instructions[i].BranchTarget) {
  2337.                mesa_instructions[i].BranchTarget = entry->inst;
  2338.                break;
  2339.             }
  2340.          }
  2341.          break;
  2342.       default:
  2343.          break;
  2344.       }
  2345.    }
  2346. }
  2347.  
  2348. static void
  2349. print_program(struct prog_instruction *mesa_instructions,
  2350.               ir_instruction **mesa_instruction_annotation,
  2351.               int num_instructions)
  2352. {
  2353.    ir_instruction *last_ir = NULL;
  2354.    int i;
  2355.    int indent = 0;
  2356.  
  2357.    for (i = 0; i < num_instructions; i++) {
  2358.       struct prog_instruction *mesa_inst = mesa_instructions + i;
  2359.       ir_instruction *ir = mesa_instruction_annotation[i];
  2360.  
  2361.       fprintf(stdout, "%3d: ", i);
  2362.  
  2363.       if (last_ir != ir && ir) {
  2364.          int j;
  2365.  
  2366.          for (j = 0; j < indent; j++) {
  2367.             fprintf(stdout, " ");
  2368.          }
  2369.          ir->print();
  2370.          printf("\n");
  2371.          last_ir = ir;
  2372.  
  2373.          fprintf(stdout, "     "); /* line number spacing. */
  2374.       }
  2375.  
  2376.       indent = _mesa_fprint_instruction_opt(stdout, mesa_inst, indent,
  2377.                                             PROG_PRINT_DEBUG, NULL);
  2378.    }
  2379. }
  2380.  
  2381. static void
  2382. count_resources(struct gl_program *prog)
  2383. {
  2384.    unsigned int i;
  2385.  
  2386.    prog->SamplersUsed = 0;
  2387.  
  2388.    for (i = 0; i < prog->NumInstructions; i++) {
  2389.       struct prog_instruction *inst = &prog->Instructions[i];
  2390.  
  2391.       if (_mesa_is_tex_instruction(inst->Opcode)) {
  2392.          prog->SamplerTargets[inst->TexSrcUnit] =
  2393.             (gl_texture_index)inst->TexSrcTarget;
  2394.          prog->SamplersUsed |= 1 << inst->TexSrcUnit;
  2395.          if (inst->TexShadow) {
  2396.             prog->ShadowSamplers |= 1 << inst->TexSrcUnit;
  2397.          }
  2398.       }
  2399.    }
  2400.  
  2401.    _mesa_update_shader_textures_used(prog);
  2402. }
  2403.  
  2404. struct uniform_sort {
  2405.    struct gl_uniform *u;
  2406.    int pos;
  2407. };
  2408.  
  2409. /* The shader_program->Uniforms list is almost sorted in increasing
  2410.  * uniform->{Frag,Vert}Pos locations, but not quite when there are
  2411.  * uniforms shared between targets.  We need to add parameters in
  2412.  * increasing order for the targets.
  2413.  */
  2414. static int
  2415. sort_uniforms(const void *a, const void *b)
  2416. {
  2417.    struct uniform_sort *u1 = (struct uniform_sort *)a;
  2418.    struct uniform_sort *u2 = (struct uniform_sort *)b;
  2419.  
  2420.    return u1->pos - u2->pos;
  2421. }
  2422.  
  2423. /* Add the uniforms to the parameters.  The linker chose locations
  2424.  * in our parameters lists (which weren't created yet), which the
  2425.  * uniforms code will use to poke values into our parameters list
  2426.  * when uniforms are updated.
  2427.  */
  2428. static void
  2429. add_uniforms_to_parameters_list(struct gl_shader_program *shader_program,
  2430.                                 struct gl_shader *shader,
  2431.                                 struct gl_program *prog)
  2432. {
  2433.    unsigned int i;
  2434.    unsigned int next_sampler = 0, num_uniforms = 0;
  2435.    struct uniform_sort *sorted_uniforms;
  2436.  
  2437.    sorted_uniforms = ralloc_array(NULL, struct uniform_sort,
  2438.                                   shader_program->Uniforms->NumUniforms);
  2439.  
  2440.    for (i = 0; i < shader_program->Uniforms->NumUniforms; i++) {
  2441.       struct gl_uniform *uniform = shader_program->Uniforms->Uniforms + i;
  2442.       int parameter_index = -1;
  2443.  
  2444.       switch (shader->Type) {
  2445.       case GL_VERTEX_SHADER:
  2446.          parameter_index = uniform->VertPos;
  2447.          break;
  2448.       case GL_FRAGMENT_SHADER:
  2449.          parameter_index = uniform->FragPos;
  2450.          break;
  2451.       case GL_GEOMETRY_SHADER:
  2452.          parameter_index = uniform->GeomPos;
  2453.          break;
  2454.       }
  2455.  
  2456.       /* Only add uniforms used in our target. */
  2457.       if (parameter_index != -1) {
  2458.          sorted_uniforms[num_uniforms].pos = parameter_index;
  2459.          sorted_uniforms[num_uniforms].u = uniform;
  2460.          num_uniforms++;
  2461.       }
  2462.    }
  2463.  
  2464.    qsort(sorted_uniforms, num_uniforms, sizeof(struct uniform_sort),
  2465.          sort_uniforms);
  2466.  
  2467.    for (i = 0; i < num_uniforms; i++) {
  2468.       struct gl_uniform *uniform = sorted_uniforms[i].u;
  2469.       int parameter_index = sorted_uniforms[i].pos;
  2470.       const glsl_type *type = uniform->Type;
  2471.       unsigned int size;
  2472.  
  2473.       if (type->is_vector() ||
  2474.           type->is_scalar()) {
  2475.          size = type->vector_elements;
  2476.       } else {
  2477.          size = type_size(type) * 4;
  2478.       }
  2479.  
  2480.       gl_register_file file;
  2481.       if (type->is_sampler() ||
  2482.           (type->is_array() && type->fields.array->is_sampler())) {
  2483.          file = PROGRAM_SAMPLER;
  2484.       } else {
  2485.          file = PROGRAM_UNIFORM;
  2486.       }
  2487.  
  2488.       GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
  2489.                                                  uniform->Name);
  2490.  
  2491.       if (index < 0) {
  2492.          index = _mesa_add_parameter(prog->Parameters, file,
  2493.                                      uniform->Name, size, type->gl_type,
  2494.                                      NULL, NULL, 0x0);
  2495.  
  2496.          /* Sampler uniform values are stored in prog->SamplerUnits,
  2497.           * and the entry in that array is selected by this index we
  2498.           * store in ParameterValues[].
  2499.           */
  2500.          if (file == PROGRAM_SAMPLER) {
  2501.             for (unsigned int j = 0; j < size / 4; j++)
  2502.                prog->Parameters->ParameterValues[index + j][0] = next_sampler++;
  2503.          }
  2504.  
  2505.          /* The location chosen in the Parameters list here (returned
  2506.           * from _mesa_add_uniform) has to match what the linker chose.
  2507.           */
  2508.          if (index != parameter_index) {
  2509.             fail_link(shader_program, "Allocation of uniform `%s' to target "
  2510.                       "failed (%d vs %d)\n",
  2511.                       uniform->Name, index, parameter_index);
  2512.          }
  2513.       }
  2514.    }
  2515.  
  2516.    ralloc_free(sorted_uniforms);
  2517. }
  2518.  
  2519. static void
  2520. set_uniform_initializer(struct gl_context *ctx, void *mem_ctx,
  2521.                         struct gl_shader_program *shader_program,
  2522.                         const char *name, const glsl_type *type,
  2523.                         ir_constant *val)
  2524. {
  2525.    if (type->is_record()) {
  2526.       ir_constant *field_constant;
  2527.  
  2528.       field_constant = (ir_constant *)val->components.get_head();
  2529.  
  2530.       for (unsigned int i = 0; i < type->length; i++) {
  2531.          const glsl_type *field_type = type->fields.structure[i].type;
  2532.          const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
  2533.                                             type->fields.structure[i].name);
  2534.          set_uniform_initializer(ctx, mem_ctx, shader_program, field_name,
  2535.                                  field_type, field_constant);
  2536.          field_constant = (ir_constant *)field_constant->next;
  2537.       }
  2538.       return;
  2539.    }
  2540.  
  2541.    int loc = _mesa_get_uniform_location(ctx, shader_program, name);
  2542.  
  2543.    if (loc == -1) {
  2544.       fail_link(shader_program,
  2545.                 "Couldn't find uniform for initializer %s\n", name);
  2546.       return;
  2547.    }
  2548.  
  2549.    for (unsigned int i = 0; i < (type->is_array() ? type->length : 1); i++) {
  2550.       ir_constant *element;
  2551.       const glsl_type *element_type;
  2552.       if (type->is_array()) {
  2553.          element = val->array_elements[i];
  2554.          element_type = type->fields.array;
  2555.       } else {
  2556.          element = val;
  2557.          element_type = type;
  2558.       }
  2559.  
  2560.       void *values;
  2561.  
  2562.       if (element_type->base_type == GLSL_TYPE_BOOL) {
  2563.          int *conv = ralloc_array(mem_ctx, int, element_type->components());
  2564.          for (unsigned int j = 0; j < element_type->components(); j++) {
  2565.             conv[j] = element->value.b[j];
  2566.          }
  2567.          values = (void *)conv;
  2568.          element_type = glsl_type::get_instance(GLSL_TYPE_INT,
  2569.                                                 element_type->vector_elements,
  2570.                                                 1);
  2571.       } else {
  2572.          values = &element->value;
  2573.       }
  2574.  
  2575.       if (element_type->is_matrix()) {
  2576.          _mesa_uniform_matrix(ctx, shader_program,
  2577.                               element_type->matrix_columns,
  2578.                               element_type->vector_elements,
  2579.                               loc, 1, GL_FALSE, (GLfloat *)values);
  2580.          loc += element_type->matrix_columns;
  2581.       } else {
  2582.          _mesa_uniform(ctx, shader_program, loc, element_type->matrix_columns,
  2583.                        values, element_type->gl_type);
  2584.          loc += type_size(element_type);
  2585.       }
  2586.    }
  2587. }
  2588.  
  2589. static void
  2590. set_uniform_initializers(struct gl_context *ctx,
  2591.                          struct gl_shader_program *shader_program)
  2592. {
  2593.    void *mem_ctx = NULL;
  2594.  
  2595.    for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
  2596.       struct gl_shader *shader = shader_program->_LinkedShaders[i];
  2597.  
  2598.       if (shader == NULL)
  2599.          continue;
  2600.  
  2601.       foreach_iter(exec_list_iterator, iter, *shader->ir) {
  2602.          ir_instruction *ir = (ir_instruction *)iter.get();
  2603.          ir_variable *var = ir->as_variable();
  2604.  
  2605.          if (!var || var->mode != ir_var_uniform || !var->constant_value)
  2606.             continue;
  2607.  
  2608.          if (!mem_ctx)
  2609.             mem_ctx = ralloc_context(NULL);
  2610.  
  2611.          set_uniform_initializer(ctx, mem_ctx, shader_program, var->name,
  2612.                                  var->type, var->constant_value);
  2613.       }
  2614.    }
  2615.  
  2616.    ralloc_free(mem_ctx);
  2617. }
  2618.  
  2619.  
  2620. /**
  2621.  * Convert a shader's GLSL IR into a Mesa gl_program.
  2622.  */
  2623. static struct gl_program *
  2624. get_mesa_program(struct gl_context *ctx,
  2625.                  struct gl_shader_program *shader_program,
  2626.                  struct gl_shader *shader)
  2627. {
  2628.    ir_to_mesa_visitor v;
  2629.    struct prog_instruction *mesa_instructions, *mesa_inst;
  2630.    ir_instruction **mesa_instruction_annotation;
  2631.    int i;
  2632.    struct gl_program *prog;
  2633.    GLenum target;
  2634.    const char *target_string;
  2635.    GLboolean progress;
  2636.    struct gl_shader_compiler_options *options =
  2637.          &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(shader->Type)];
  2638.  
  2639.    switch (shader->Type) {
  2640.    case GL_VERTEX_SHADER:
  2641.       target = GL_VERTEX_PROGRAM_ARB;
  2642.       target_string = "vertex";
  2643.       break;
  2644.    case GL_FRAGMENT_SHADER:
  2645.       target = GL_FRAGMENT_PROGRAM_ARB;
  2646.       target_string = "fragment";
  2647.       break;
  2648.    case GL_GEOMETRY_SHADER:
  2649.       target = GL_GEOMETRY_PROGRAM_NV;
  2650.       target_string = "geometry";
  2651.       break;
  2652.    default:
  2653.       assert(!"should not be reached");
  2654.       return NULL;
  2655.    }
  2656.  
  2657.    validate_ir_tree(shader->ir);
  2658.  
  2659.    prog = ctx->Driver.NewProgram(ctx, target, shader_program->Name);
  2660.    if (!prog)
  2661.       return NULL;
  2662.    prog->Parameters = _mesa_new_parameter_list();
  2663.    prog->Varying = _mesa_new_parameter_list();
  2664.    prog->Attributes = _mesa_new_parameter_list();
  2665.    v.ctx = ctx;
  2666.    v.prog = prog;
  2667.    v.shader_program = shader_program;
  2668.    v.options = options;
  2669.  
  2670.    add_uniforms_to_parameters_list(shader_program, shader, prog);
  2671.  
  2672.    /* Emit Mesa IR for main(). */
  2673.    visit_exec_list(shader->ir, &v);
  2674.    v.ir_to_mesa_emit_op0(NULL, OPCODE_END);
  2675.  
  2676.    /* Now emit bodies for any functions that were used. */
  2677.    do {
  2678.       progress = GL_FALSE;
  2679.  
  2680.       foreach_iter(exec_list_iterator, iter, v.function_signatures) {
  2681.          function_entry *entry = (function_entry *)iter.get();
  2682.  
  2683.          if (!entry->bgn_inst) {
  2684.             v.current_function = entry;
  2685.  
  2686.             entry->bgn_inst = v.ir_to_mesa_emit_op0(NULL, OPCODE_BGNSUB);
  2687.             entry->bgn_inst->function = entry;
  2688.  
  2689.             visit_exec_list(&entry->sig->body, &v);
  2690.  
  2691.             ir_to_mesa_instruction *last;
  2692.             last = (ir_to_mesa_instruction *)v.instructions.get_tail();
  2693.             if (last->op != OPCODE_RET)
  2694.                v.ir_to_mesa_emit_op0(NULL, OPCODE_RET);
  2695.  
  2696.             ir_to_mesa_instruction *end;
  2697.             end = v.ir_to_mesa_emit_op0(NULL, OPCODE_ENDSUB);
  2698.             end->function = entry;
  2699.  
  2700.             progress = GL_TRUE;
  2701.          }
  2702.       }
  2703.    } while (progress);
  2704.  
  2705.    prog->NumTemporaries = v.next_temp;
  2706.  
  2707.    int num_instructions = 0;
  2708.    foreach_iter(exec_list_iterator, iter, v.instructions) {
  2709.       num_instructions++;
  2710.    }
  2711.  
  2712.    mesa_instructions =
  2713.       (struct prog_instruction *)calloc(num_instructions,
  2714.                                         sizeof(*mesa_instructions));
  2715.    mesa_instruction_annotation = ralloc_array(v.mem_ctx, ir_instruction *,
  2716.                                               num_instructions);
  2717.  
  2718.    /* Convert ir_mesa_instructions into prog_instructions.
  2719.     */
  2720.    mesa_inst = mesa_instructions;
  2721.    i = 0;
  2722.    foreach_iter(exec_list_iterator, iter, v.instructions) {
  2723.       const ir_to_mesa_instruction *inst = (ir_to_mesa_instruction *)iter.get();
  2724.  
  2725.       mesa_inst->Opcode = inst->op;
  2726.       mesa_inst->CondUpdate = inst->cond_update;
  2727.       if (inst->saturate)
  2728.          mesa_inst->SaturateMode = SATURATE_ZERO_ONE;
  2729.       mesa_inst->DstReg.File = inst->dst_reg.file;
  2730.       mesa_inst->DstReg.Index = inst->dst_reg.index;
  2731.       mesa_inst->DstReg.CondMask = inst->dst_reg.cond_mask;
  2732.       mesa_inst->DstReg.WriteMask = inst->dst_reg.writemask;
  2733.       mesa_inst->DstReg.RelAddr = inst->dst_reg.reladdr != NULL;
  2734.       mesa_inst->SrcReg[0] = mesa_src_reg_from_ir_src_reg(inst->src_reg[0]);
  2735.       mesa_inst->SrcReg[1] = mesa_src_reg_from_ir_src_reg(inst->src_reg[1]);
  2736.       mesa_inst->SrcReg[2] = mesa_src_reg_from_ir_src_reg(inst->src_reg[2]);
  2737.       mesa_inst->TexSrcUnit = inst->sampler;
  2738.       mesa_inst->TexSrcTarget = inst->tex_target;
  2739.       mesa_inst->TexShadow = inst->tex_shadow;
  2740.       mesa_instruction_annotation[i] = inst->ir;
  2741.  
  2742.       /* Set IndirectRegisterFiles. */
  2743.       if (mesa_inst->DstReg.RelAddr)
  2744.          prog->IndirectRegisterFiles |= 1 << mesa_inst->DstReg.File;
  2745.  
  2746.       /* Update program's bitmask of indirectly accessed register files */
  2747.       for (unsigned src = 0; src < 3; src++)
  2748.          if (mesa_inst->SrcReg[src].RelAddr)
  2749.             prog->IndirectRegisterFiles |= 1 << mesa_inst->SrcReg[src].File;
  2750.  
  2751.       if (options->EmitNoIfs && mesa_inst->Opcode == OPCODE_IF) {
  2752.          fail_link(shader_program, "Couldn't flatten if statement\n");
  2753.       }
  2754.  
  2755.       switch (mesa_inst->Opcode) {
  2756.       case OPCODE_BGNSUB:
  2757.          inst->function->inst = i;
  2758.          mesa_inst->Comment = strdup(inst->function->sig->function_name());
  2759.          break;
  2760.       case OPCODE_ENDSUB:
  2761.          mesa_inst->Comment = strdup(inst->function->sig->function_name());
  2762.          break;
  2763.       case OPCODE_CAL:
  2764.          mesa_inst->BranchTarget = inst->function->sig_id; /* rewritten later */
  2765.          break;
  2766.       case OPCODE_ARL:
  2767.          prog->NumAddressRegs = 1;
  2768.          break;
  2769.       default:
  2770.          break;
  2771.       }
  2772.  
  2773.       mesa_inst++;
  2774.       i++;
  2775.  
  2776.       if (!shader_program->LinkStatus)
  2777.          break;
  2778.    }
  2779.  
  2780.    if (!shader_program->LinkStatus) {
  2781.       free(mesa_instructions);
  2782.       _mesa_reference_program(ctx, &shader->Program, NULL);
  2783.       return NULL;
  2784.    }
  2785.  
  2786.    set_branchtargets(&v, mesa_instructions, num_instructions);
  2787.  
  2788.    if (ctx->Shader.Flags & GLSL_DUMP) {
  2789.       printf("\n");
  2790.       printf("GLSL IR for linked %s program %d:\n", target_string,
  2791.              shader_program->Name);
  2792.       _mesa_print_ir(shader->ir, NULL);
  2793.       printf("\n");
  2794.       printf("\n");
  2795.       printf("Mesa IR for linked %s program %d:\n", target_string,
  2796.              shader_program->Name);
  2797.       print_program(mesa_instructions, mesa_instruction_annotation,
  2798.                     num_instructions);
  2799.    }
  2800.  
  2801.    prog->Instructions = mesa_instructions;
  2802.    prog->NumInstructions = num_instructions;
  2803.  
  2804.    do_set_program_inouts(shader->ir, prog);
  2805.    count_resources(prog);
  2806.  
  2807.    _mesa_reference_program(ctx, &shader->Program, prog);
  2808.  
  2809.    if ((ctx->Shader.Flags & GLSL_NO_OPT) == 0) {
  2810.       _mesa_optimize_program(ctx, prog);
  2811.    }
  2812.  
  2813.    return prog;
  2814. }
  2815.  
  2816. extern "C" {
  2817.  
  2818. /**
  2819.  * Called via ctx->Driver.CompilerShader().
  2820.  * This is a no-op.
  2821.  * XXX can we remove the ctx->Driver.CompileShader() hook?
  2822.  */
  2823. GLboolean
  2824. _mesa_ir_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
  2825. {
  2826.    assert(shader->CompileStatus);
  2827.    (void) ctx;
  2828.  
  2829.    return GL_TRUE;
  2830. }
  2831.  
  2832.  
  2833. /**
  2834.  * Link a shader.
  2835.  * Called via ctx->Driver.LinkShader()
  2836.  * This actually involves converting GLSL IR into Mesa gl_programs with
  2837.  * code lowering and other optimizations.
  2838.  */
  2839. GLboolean
  2840. _mesa_ir_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
  2841. {
  2842.    assert(prog->LinkStatus);
  2843.  
  2844.    for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
  2845.       if (prog->_LinkedShaders[i] == NULL)
  2846.          continue;
  2847.  
  2848.       bool progress;
  2849.       exec_list *ir = prog->_LinkedShaders[i]->ir;
  2850.       const struct gl_shader_compiler_options *options =
  2851.             &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(prog->_LinkedShaders[i]->Type)];
  2852.  
  2853.       do {
  2854.          progress = false;
  2855.  
  2856.          /* Lowering */
  2857.          do_mat_op_to_vec(ir);
  2858.          lower_instructions(ir, (MOD_TO_FRACT | DIV_TO_MUL_RCP | EXP_TO_EXP2
  2859.                                  | LOG_TO_LOG2
  2860.                                  | ((options->EmitNoPow) ? POW_TO_EXP2 : 0)));
  2861.  
  2862.          progress = do_lower_jumps(ir, true, true, options->EmitNoMainReturn, options->EmitNoCont, options->EmitNoLoops) || progress;
  2863.  
  2864.          progress = do_common_optimization(ir, true, options->MaxUnrollIterations) || progress;
  2865.  
  2866.          progress = lower_quadop_vector(ir, true) || progress;
  2867.  
  2868.          if (options->EmitNoIfs) {
  2869.             progress = lower_discard(ir) || progress;
  2870.             progress = lower_if_to_cond_assign(ir) || progress;
  2871.          }
  2872.  
  2873.          if (options->EmitNoNoise)
  2874.             progress = lower_noise(ir) || progress;
  2875.  
  2876.          /* If there are forms of indirect addressing that the driver
  2877.           * cannot handle, perform the lowering pass.
  2878.           */
  2879.          if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput
  2880.              || options->EmitNoIndirectTemp || options->EmitNoIndirectUniform)
  2881.            progress =
  2882.              lower_variable_index_to_cond_assign(ir,
  2883.                                                  options->EmitNoIndirectInput,
  2884.                                                  options->EmitNoIndirectOutput,
  2885.                                                  options->EmitNoIndirectTemp,
  2886.                                                  options->EmitNoIndirectUniform)
  2887.              || progress;
  2888.  
  2889.          progress = do_vec_index_to_cond_assign(ir) || progress;
  2890.       } while (progress);
  2891.  
  2892.       validate_ir_tree(ir);
  2893.    }
  2894.  
  2895.    for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
  2896.       struct gl_program *linked_prog;
  2897.  
  2898.       if (prog->_LinkedShaders[i] == NULL)
  2899.          continue;
  2900.  
  2901.       linked_prog = get_mesa_program(ctx, prog, prog->_LinkedShaders[i]);
  2902.  
  2903.       if (linked_prog) {
  2904.          bool ok = true;
  2905.  
  2906.          switch (prog->_LinkedShaders[i]->Type) {
  2907.          case GL_VERTEX_SHADER:
  2908.             _mesa_reference_vertprog(ctx, &prog->VertexProgram,
  2909.                                      (struct gl_vertex_program *)linked_prog);
  2910.             ok = ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
  2911.                                                  linked_prog);
  2912.             break;
  2913.          case GL_FRAGMENT_SHADER:
  2914.             _mesa_reference_fragprog(ctx, &prog->FragmentProgram,
  2915.                                      (struct gl_fragment_program *)linked_prog);
  2916.             ok = ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
  2917.                                                  linked_prog);
  2918.             break;
  2919.          case GL_GEOMETRY_SHADER:
  2920.             _mesa_reference_geomprog(ctx, &prog->GeometryProgram,
  2921.                                      (struct gl_geometry_program *)linked_prog);
  2922.             ok = ctx->Driver.ProgramStringNotify(ctx, GL_GEOMETRY_PROGRAM_NV,
  2923.                                                  linked_prog);
  2924.             break;
  2925.          }
  2926.          if (!ok) {
  2927.             return GL_FALSE;
  2928.          }
  2929.       }
  2930.  
  2931.       _mesa_reference_program(ctx, &linked_prog, NULL);
  2932.    }
  2933.  
  2934.    return GL_TRUE;
  2935. }
  2936.  
  2937.  
  2938. /**
  2939.  * Compile a GLSL shader.  Called via glCompileShader().
  2940.  */
  2941. void
  2942. _mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader)
  2943. {
  2944.    struct _mesa_glsl_parse_state *state =
  2945.       new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
  2946.  
  2947.    const char *source = shader->Source;
  2948.    /* Check if the user called glCompileShader without first calling
  2949.     * glShaderSource.  This should fail to compile, but not raise a GL_ERROR.
  2950.     */
  2951.    if (source == NULL) {
  2952.       shader->CompileStatus = GL_FALSE;
  2953.       return;
  2954.    }
  2955.  
  2956.    state->error = preprocess(state, &source, &state->info_log,
  2957.                              &ctx->Extensions, ctx->API);
  2958.  
  2959.    if (ctx->Shader.Flags & GLSL_DUMP) {
  2960.       printf("GLSL source for shader %d:\n", shader->Name);
  2961.       printf("%s\n", shader->Source);
  2962.    }
  2963.  
  2964.    if (!state->error) {
  2965.      _mesa_glsl_lexer_ctor(state, source);
  2966.      _mesa_glsl_parse(state);
  2967.      _mesa_glsl_lexer_dtor(state);
  2968.    }
  2969.  
  2970.    ralloc_free(shader->ir);
  2971.    shader->ir = new(shader) exec_list;
  2972.    if (!state->error && !state->translation_unit.is_empty())
  2973.       _mesa_ast_to_hir(shader->ir, state);
  2974.  
  2975.    if (!state->error && !shader->ir->is_empty()) {
  2976.       validate_ir_tree(shader->ir);
  2977.  
  2978.       /* Do some optimization at compile time to reduce shader IR size
  2979.        * and reduce later work if the same shader is linked multiple times
  2980.        */
  2981.       while (do_common_optimization(shader->ir, false, 32))
  2982.          ;
  2983.  
  2984.       validate_ir_tree(shader->ir);
  2985.    }
  2986.  
  2987.    shader->symbols = state->symbols;
  2988.  
  2989.    shader->CompileStatus = !state->error;
  2990.    shader->InfoLog = state->info_log;
  2991.    shader->Version = state->language_version;
  2992.    memcpy(shader->builtins_to_link, state->builtins_to_link,
  2993.           sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
  2994.    shader->num_builtins_to_link = state->num_builtins_to_link;
  2995.  
  2996.    if (ctx->Shader.Flags & GLSL_LOG) {
  2997.       _mesa_write_shader_to_file(shader);
  2998.    }
  2999.  
  3000.    if (ctx->Shader.Flags & GLSL_DUMP) {
  3001.       if (shader->CompileStatus) {
  3002.          printf("GLSL IR for shader %d:\n", shader->Name);
  3003.          _mesa_print_ir(shader->ir, NULL);
  3004.          printf("\n\n");
  3005.       } else {
  3006.          printf("GLSL shader %d failed to compile.\n", shader->Name);
  3007.       }
  3008.       if (shader->InfoLog && shader->InfoLog[0] != 0) {
  3009.          printf("GLSL shader %d info log:\n", shader->Name);
  3010.          printf("%s\n", shader->InfoLog);
  3011.       }
  3012.    }
  3013.  
  3014.    /* Retain any live IR, but trash the rest. */
  3015.    reparent_ir(shader->ir, shader->ir);
  3016.  
  3017.    ralloc_free(state);
  3018.  
  3019.    if (shader->CompileStatus) {
  3020.       if (!ctx->Driver.CompileShader(ctx, shader))
  3021.          shader->CompileStatus = GL_FALSE;
  3022.    }
  3023. }
  3024.  
  3025.  
  3026. /**
  3027.  * Link a GLSL shader program.  Called via glLinkProgram().
  3028.  */
  3029. void
  3030. _mesa_glsl_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
  3031. {
  3032.    unsigned int i;
  3033.  
  3034.    _mesa_clear_shader_program_data(ctx, prog);
  3035.  
  3036.    prog->LinkStatus = GL_TRUE;
  3037.  
  3038.    for (i = 0; i < prog->NumShaders; i++) {
  3039.       if (!prog->Shaders[i]->CompileStatus) {
  3040.          fail_link(prog, "linking with uncompiled shader");
  3041.          prog->LinkStatus = GL_FALSE;
  3042.       }
  3043.    }
  3044.  
  3045.    prog->Varying = _mesa_new_parameter_list();
  3046.    _mesa_reference_vertprog(ctx, &prog->VertexProgram, NULL);
  3047.    _mesa_reference_fragprog(ctx, &prog->FragmentProgram, NULL);
  3048.    _mesa_reference_geomprog(ctx, &prog->GeometryProgram, NULL);
  3049.  
  3050.    if (prog->LinkStatus) {
  3051.       link_shaders(ctx, prog);
  3052.    }
  3053.  
  3054.    if (prog->LinkStatus) {
  3055.       if (!ctx->Driver.LinkShader(ctx, prog)) {
  3056.          prog->LinkStatus = GL_FALSE;
  3057.       }
  3058.    }
  3059.  
  3060.    set_uniform_initializers(ctx, prog);
  3061.  
  3062.    if (ctx->Shader.Flags & GLSL_DUMP) {
  3063.       if (!prog->LinkStatus) {
  3064.          printf("GLSL shader program %d failed to link\n", prog->Name);
  3065.       }
  3066.  
  3067.       if (prog->InfoLog && prog->InfoLog[0] != 0) {
  3068.          printf("GLSL shader program %d info log:\n", prog->Name);
  3069.          printf("%s\n", prog->InfoLog);
  3070.       }
  3071.    }
  3072. }
  3073.  
  3074. } /* extern "C" */
  3075.