scons: Fix scons build.
[profile/ivi/mesa.git] / src / glsl / opt_constant_propagation.cpp
1 /*
2  * Copyright © 2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * constant of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, constant, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above constantright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR CONSTANTRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23
24 /**
25  * \file opt_constant_propagation.cpp
26  *
27  * Tracks assignments of constants to channels of variables, and
28  * usage of those constant channels with direct usage of the constants.
29  *
30  * This can lead to constant folding and algebraic optimizations in
31  * those later expressions, while causing no increase in instruction
32  * count (due to constants being generally free to load from a
33  * constant push buffer or as instruction immediate values) and
34  * possibly reducing register pressure.
35  */
36
37 #include "ir.h"
38 #include "ir_visitor.h"
39 #include "ir_rvalue_visitor.h"
40 #include "ir_basic_block.h"
41 #include "ir_optimization.h"
42 #include "glsl_types.h"
43
44 namespace {
45
46 class acp_entry : public exec_node
47 {
48 public:
49    acp_entry(ir_variable *var, unsigned write_mask, ir_constant *constant)
50    {
51       assert(var);
52       assert(constant);
53       this->var = var;
54       this->write_mask = write_mask;
55       this->constant = constant;
56       this->initial_values = write_mask;
57    }
58
59    acp_entry(const acp_entry *src)
60    {
61       this->var = src->var;
62       this->write_mask = src->write_mask;
63       this->constant = src->constant;
64       this->initial_values = src->initial_values;
65    }
66
67    ir_variable *var;
68    ir_constant *constant;
69    unsigned write_mask;
70
71    /** Mask of values initially available in the constant. */
72    unsigned initial_values;
73 };
74
75
76 class kill_entry : public exec_node
77 {
78 public:
79    kill_entry(ir_variable *var, unsigned write_mask)
80    {
81       assert(var);
82       this->var = var;
83       this->write_mask = write_mask;
84    }
85
86    ir_variable *var;
87    unsigned write_mask;
88 };
89
90 class ir_constant_propagation_visitor : public ir_rvalue_visitor {
91 public:
92    ir_constant_propagation_visitor()
93    {
94       progress = false;
95       mem_ctx = ralloc_context(0);
96       this->acp = new(mem_ctx) exec_list;
97       this->kills = new(mem_ctx) exec_list;
98    }
99    ~ir_constant_propagation_visitor()
100    {
101       ralloc_free(mem_ctx);
102    }
103
104    virtual ir_visitor_status visit_enter(class ir_loop *);
105    virtual ir_visitor_status visit_enter(class ir_function_signature *);
106    virtual ir_visitor_status visit_enter(class ir_function *);
107    virtual ir_visitor_status visit_leave(class ir_assignment *);
108    virtual ir_visitor_status visit_enter(class ir_call *);
109    virtual ir_visitor_status visit_enter(class ir_if *);
110
111    void add_constant(ir_assignment *ir);
112    void kill(ir_variable *ir, unsigned write_mask);
113    void handle_if_block(exec_list *instructions);
114    void handle_rvalue(ir_rvalue **rvalue);
115
116    /** List of acp_entry: The available constants to propagate */
117    exec_list *acp;
118
119    /**
120     * List of kill_entry: The masks of variables whose values were
121     * killed in this block.
122     */
123    exec_list *kills;
124
125    bool progress;
126
127    bool killed_all;
128
129    void *mem_ctx;
130 };
131
132
133 void
134 ir_constant_propagation_visitor::handle_rvalue(ir_rvalue **rvalue)
135 {
136    if (this->in_assignee || !*rvalue)
137       return;
138
139    const glsl_type *type = (*rvalue)->type;
140    if (!type->is_scalar() && !type->is_vector())
141       return;
142
143    ir_swizzle *swiz = NULL;
144    ir_dereference_variable *deref = (*rvalue)->as_dereference_variable();
145    if (!deref) {
146       swiz = (*rvalue)->as_swizzle();
147       if (!swiz)
148          return;
149
150       deref = swiz->val->as_dereference_variable();
151       if (!deref)
152          return;
153    }
154
155    ir_constant_data data;
156    memset(&data, 0, sizeof(data));
157
158    for (unsigned int i = 0; i < type->components(); i++) {
159       int channel;
160       acp_entry *found = NULL;
161
162       if (swiz) {
163          switch (i) {
164          case 0: channel = swiz->mask.x; break;
165          case 1: channel = swiz->mask.y; break;
166          case 2: channel = swiz->mask.z; break;
167          case 3: channel = swiz->mask.w; break;
168          default: assert(!"shouldn't be reached"); channel = 0; break;
169          }
170       } else {
171          channel = i;
172       }
173
174       foreach_iter(exec_list_iterator, iter, *this->acp) {
175          acp_entry *entry = (acp_entry *)iter.get();
176          if (entry->var == deref->var && entry->write_mask & (1 << channel)) {
177             found = entry;
178             break;
179          }
180       }
181
182       if (!found)
183          return;
184
185       int rhs_channel = 0;
186       for (int j = 0; j < 4; j++) {
187          if (j == channel)
188             break;
189          if (found->initial_values & (1 << j))
190             rhs_channel++;
191       }
192
193       switch (type->base_type) {
194       case GLSL_TYPE_FLOAT:
195          data.f[i] = found->constant->value.f[rhs_channel];
196          break;
197       case GLSL_TYPE_INT:
198          data.i[i] = found->constant->value.i[rhs_channel];
199          break;
200       case GLSL_TYPE_UINT:
201          data.u[i] = found->constant->value.u[rhs_channel];
202          break;
203       case GLSL_TYPE_BOOL:
204          data.b[i] = found->constant->value.b[rhs_channel];
205          break;
206       default:
207          assert(!"not reached");
208          break;
209       }
210    }
211
212    *rvalue = new(ralloc_parent(deref)) ir_constant(type, &data);
213    this->progress = true;
214 }
215
216 ir_visitor_status
217 ir_constant_propagation_visitor::visit_enter(ir_function_signature *ir)
218 {
219    /* Treat entry into a function signature as a completely separate
220     * block.  Any instructions at global scope will be shuffled into
221     * main() at link time, so they're irrelevant to us.
222     */
223    exec_list *orig_acp = this->acp;
224    exec_list *orig_kills = this->kills;
225    bool orig_killed_all = this->killed_all;
226
227    this->acp = new(mem_ctx) exec_list;
228    this->kills = new(mem_ctx) exec_list;
229    this->killed_all = false;
230
231    visit_list_elements(this, &ir->body);
232
233    this->kills = orig_kills;
234    this->acp = orig_acp;
235    this->killed_all = orig_killed_all;
236
237    return visit_continue_with_parent;
238 }
239
240 ir_visitor_status
241 ir_constant_propagation_visitor::visit_leave(ir_assignment *ir)
242 {
243    if (this->in_assignee)
244       return visit_continue;
245
246    unsigned kill_mask = ir->write_mask;
247    if (ir->lhs->as_dereference_array()) {
248       /* The LHS of the assignment uses an array indexing operator (e.g. v[i]
249        * = ...;).  Since we only try to constant propagate vectors and
250        * scalars, this means that either (a) array indexing is being used to
251        * select a vector component, or (b) the variable in question is neither
252        * a scalar or a vector, so we don't care about it.  In the former case,
253        * we want to kill the whole vector, since in general we can't predict
254        * which vector component will be selected by array indexing.  In the
255        * latter case, it doesn't matter what we do, so go ahead and kill the
256        * whole variable anyway.
257        *
258        * Note that if the array index is constant (e.g. v[2] = ...;), we could
259        * in principle be smarter, but we don't need to, because a future
260        * optimization pass will convert it to a simple assignment with the
261        * correct mask.
262        */
263       kill_mask = ~0;
264    }
265    kill(ir->lhs->variable_referenced(), kill_mask);
266
267    add_constant(ir);
268
269    return visit_continue;
270 }
271
272 ir_visitor_status
273 ir_constant_propagation_visitor::visit_enter(ir_function *ir)
274 {
275    (void) ir;
276    return visit_continue;
277 }
278
279 ir_visitor_status
280 ir_constant_propagation_visitor::visit_enter(ir_call *ir)
281 {
282    /* Do constant propagation on call parameters, but skip any out params */
283    exec_list_iterator sig_param_iter = ir->callee->parameters.iterator();
284    foreach_iter(exec_list_iterator, iter, ir->actual_parameters) {
285       ir_variable *sig_param = (ir_variable *)sig_param_iter.get();
286       ir_rvalue *param = (ir_rvalue *)iter.get();
287       if (sig_param->mode != ir_var_out && sig_param->mode != ir_var_inout) {
288          ir_rvalue *new_param = param;
289          handle_rvalue(&new_param);
290          if (new_param != param)
291             param->replace_with(new_param);
292          else
293             param->accept(this);
294       }
295       sig_param_iter.next();
296    }
297
298    /* Since we're unlinked, we don't (necssarily) know the side effects of
299     * this call.  So kill all copies.
300     */
301    acp->make_empty();
302    this->killed_all = true;
303
304    return visit_continue_with_parent;
305 }
306
307 void
308 ir_constant_propagation_visitor::handle_if_block(exec_list *instructions)
309 {
310    exec_list *orig_acp = this->acp;
311    exec_list *orig_kills = this->kills;
312    bool orig_killed_all = this->killed_all;
313
314    this->acp = new(mem_ctx) exec_list;
315    this->kills = new(mem_ctx) exec_list;
316    this->killed_all = false;
317
318    /* Populate the initial acp with a constant of the original */
319    foreach_iter(exec_list_iterator, iter, *orig_acp) {
320       acp_entry *a = (acp_entry *)iter.get();
321       this->acp->push_tail(new(this->mem_ctx) acp_entry(a));
322    }
323
324    visit_list_elements(this, instructions);
325
326    if (this->killed_all) {
327       orig_acp->make_empty();
328    }
329
330    exec_list *new_kills = this->kills;
331    this->kills = orig_kills;
332    this->acp = orig_acp;
333    this->killed_all = this->killed_all || orig_killed_all;
334
335    foreach_iter(exec_list_iterator, iter, *new_kills) {
336       kill_entry *k = (kill_entry *)iter.get();
337       kill(k->var, k->write_mask);
338    }
339 }
340
341 ir_visitor_status
342 ir_constant_propagation_visitor::visit_enter(ir_if *ir)
343 {
344    ir->condition->accept(this);
345    handle_rvalue(&ir->condition);
346
347    handle_if_block(&ir->then_instructions);
348    handle_if_block(&ir->else_instructions);
349
350    /* handle_if_block() already descended into the children. */
351    return visit_continue_with_parent;
352 }
353
354 ir_visitor_status
355 ir_constant_propagation_visitor::visit_enter(ir_loop *ir)
356 {
357    exec_list *orig_acp = this->acp;
358    exec_list *orig_kills = this->kills;
359    bool orig_killed_all = this->killed_all;
360
361    /* FINISHME: For now, the initial acp for loops is totally empty.
362     * We could go through once, then go through again with the acp
363     * cloned minus the killed entries after the first run through.
364     */
365    this->acp = new(mem_ctx) exec_list;
366    this->kills = new(mem_ctx) exec_list;
367    this->killed_all = false;
368
369    visit_list_elements(this, &ir->body_instructions);
370
371    if (this->killed_all) {
372       orig_acp->make_empty();
373    }
374
375    exec_list *new_kills = this->kills;
376    this->kills = orig_kills;
377    this->acp = orig_acp;
378    this->killed_all = this->killed_all || orig_killed_all;
379
380    foreach_iter(exec_list_iterator, iter, *new_kills) {
381       kill_entry *k = (kill_entry *)iter.get();
382       kill(k->var, k->write_mask);
383    }
384
385    /* already descended into the children. */
386    return visit_continue_with_parent;
387 }
388
389 void
390 ir_constant_propagation_visitor::kill(ir_variable *var, unsigned write_mask)
391 {
392    assert(var != NULL);
393
394    /* We don't track non-vectors. */
395    if (!var->type->is_vector() && !var->type->is_scalar())
396       return;
397
398    /* Remove any entries currently in the ACP for this kill. */
399    foreach_iter(exec_list_iterator, iter, *this->acp) {
400       acp_entry *entry = (acp_entry *)iter.get();
401
402       if (entry->var == var) {
403          entry->write_mask &= ~write_mask;
404          if (entry->write_mask == 0)
405             entry->remove();
406       }
407    }
408
409    /* Add this writemask of the variable to the list of killed
410     * variables in this block.
411     */
412    foreach_iter(exec_list_iterator, iter, *this->kills) {
413       kill_entry *entry = (kill_entry *)iter.get();
414
415       if (entry->var == var) {
416          entry->write_mask |= write_mask;
417          return;
418       }
419    }
420    /* Not already in the list.  Make new entry. */
421    this->kills->push_tail(new(this->mem_ctx) kill_entry(var, write_mask));
422 }
423
424 /**
425  * Adds an entry to the available constant list if it's a plain assignment
426  * of a variable to a variable.
427  */
428 void
429 ir_constant_propagation_visitor::add_constant(ir_assignment *ir)
430 {
431    acp_entry *entry;
432
433    if (ir->condition)
434       return;
435
436    if (!ir->write_mask)
437       return;
438
439    ir_dereference_variable *deref = ir->lhs->as_dereference_variable();
440    ir_constant *constant = ir->rhs->as_constant();
441
442    if (!deref || !constant)
443       return;
444
445    /* Only do constant propagation on vectors.  Constant matrices,
446     * arrays, or structures would require more work elsewhere.
447     */
448    if (!deref->var->type->is_vector() && !deref->var->type->is_scalar())
449       return;
450
451    entry = new(this->mem_ctx) acp_entry(deref->var, ir->write_mask, constant);
452    this->acp->push_tail(entry);
453 }
454
455 } /* unnamed namespace */
456
457 /**
458  * Does a constant propagation pass on the code present in the instruction stream.
459  */
460 bool
461 do_constant_propagation(exec_list *instructions)
462 {
463    ir_constant_propagation_visitor v;
464
465    visit_list_elements(&v, instructions);
466
467    return v.progress;
468 }