1/*
2 * Copyright © 2010 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy 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, copy, 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 copyright 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 COPYRIGHT 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_dead_code_local.cpp
26 *
27 * Eliminates local dead assignments from the code.
28 *
29 * This operates on basic blocks, tracking assignments and finding if
30 * they're used before the variable is completely reassigned.
31 *
32 * Compare this to ir_dead_code.cpp, which operates globally looking
33 * for assignments to variables that are never read.
34 */
35
36#include "ir.h"
37#include "ir_basic_block.h"
38#include "ir_optimization.h"
39#include "compiler/glsl_types.h"
40
41static bool debug = false;
42
43namespace {
44
45class assignment_entry : public exec_node
46{
47public:
48   /* override operator new from exec_node */
49   DECLARE_LINEAR_ZALLOC_CXX_OPERATORS(assignment_entry)
50
51   assignment_entry(ir_variable *lhs, ir_assignment *ir)
52   {
53      assert(lhs);
54      assert(ir);
55      this->lhs = lhs;
56      this->ir = ir;
57      this->unused = ir->write_mask;
58   }
59
60   ir_variable *lhs;
61   ir_assignment *ir;
62
63   /* bitmask of xyzw channels written that haven't been used so far. */
64   int unused;
65};
66
67class kill_for_derefs_visitor : public ir_hierarchical_visitor {
68public:
69   using ir_hierarchical_visitor::visit;
70
71   kill_for_derefs_visitor(exec_list *assignments)
72   {
73      this->assignments = assignments;
74   }
75
76   void use_channels(ir_variable *const var, int used)
77   {
78      foreach_in_list_safe(assignment_entry, entry, this->assignments) {
79	 if (entry->lhs == var) {
80	    if (var->type->is_scalar() || var->type->is_vector()) {
81	       if (debug)
82		  printf("used %s (0x%01x - 0x%01x)\n", entry->lhs->name,
83			 entry->unused, used & 0xf);
84	       entry->unused &= ~used;
85	       if (!entry->unused)
86		  entry->remove();
87	    } else {
88	       if (debug)
89		  printf("used %s\n", entry->lhs->name);
90	       entry->remove();
91	    }
92	 }
93      }
94   }
95
96   virtual ir_visitor_status visit(ir_dereference_variable *ir)
97   {
98      use_channels(ir->var, ~0);
99
100      return visit_continue;
101   }
102
103   virtual ir_visitor_status visit(ir_swizzle *ir)
104   {
105      ir_dereference_variable *deref = ir->val->as_dereference_variable();
106      if (!deref)
107	 return visit_continue;
108
109      int used = 0;
110      used |= 1 << ir->mask.x;
111      if (ir->mask.num_components > 1)
112         used |= 1 << ir->mask.y;
113      if (ir->mask.num_components > 2)
114         used |= 1 << ir->mask.z;
115      if (ir->mask.num_components > 3)
116         used |= 1 << ir->mask.w;
117
118      use_channels(deref->var, used);
119
120      return visit_continue_with_parent;
121   }
122
123   virtual ir_visitor_status visit_leave(ir_emit_vertex *)
124   {
125      /* For the purpose of dead code elimination, emitting a vertex counts as
126       * "reading" all of the currently assigned output variables.
127       */
128      foreach_in_list_safe(assignment_entry, entry, this->assignments) {
129         if (entry->lhs->data.mode == ir_var_shader_out) {
130            if (debug)
131               printf("kill %s\n", entry->lhs->name);
132            entry->remove();
133         }
134      }
135
136      return visit_continue;
137   }
138
139private:
140   exec_list *assignments;
141};
142
143class array_index_visit : public ir_hierarchical_visitor {
144public:
145   array_index_visit(ir_hierarchical_visitor *v)
146   {
147      this->visitor = v;
148   }
149
150   virtual ir_visitor_status visit_enter(class ir_dereference_array *ir)
151   {
152      ir->array_index->accept(visitor);
153      return visit_continue;
154   }
155
156   static void run(ir_instruction *ir, ir_hierarchical_visitor *v)
157   {
158      array_index_visit top_visit(v);
159      ir->accept(& top_visit);
160   }
161
162   ir_hierarchical_visitor *visitor;
163};
164
165} /* unnamed namespace */
166
167/**
168 * Adds an entry to the available copy list if it's a plain assignment
169 * of a variable to a variable.
170 */
171static bool
172process_assignment(void *lin_ctx, ir_assignment *ir, exec_list *assignments)
173{
174   ir_variable *var = NULL;
175   bool progress = false;
176   kill_for_derefs_visitor v(assignments);
177
178   if (ir->condition == NULL) {
179      /* If this is an assignment of the form "foo = foo;", remove the whole
180       * instruction and be done with it.
181       */
182      const ir_variable *const lhs_var = ir->whole_variable_written();
183      if (lhs_var != NULL && lhs_var == ir->rhs->whole_variable_referenced()) {
184         ir->remove();
185         return true;
186      }
187   }
188
189   /* Kill assignment entries for things used to produce this assignment. */
190   ir->rhs->accept(&v);
191   if (ir->condition) {
192      ir->condition->accept(&v);
193   }
194
195   /* Kill assignment enties used as array indices.
196    */
197   array_index_visit::run(ir->lhs, &v);
198   var = ir->lhs->variable_referenced();
199   assert(var);
200
201   /* Now, check if we did a whole-variable assignment. */
202   if (!ir->condition) {
203      ir_dereference_variable *deref_var = ir->lhs->as_dereference_variable();
204
205      /* If it's a vector type, we can do per-channel elimination of
206       * use of the RHS.
207       */
208      if (deref_var && (deref_var->var->type->is_scalar() ||
209			deref_var->var->type->is_vector())) {
210
211	 if (debug)
212	    printf("looking for %s.0x%01x to remove\n", var->name,
213		   ir->write_mask);
214
215	 foreach_in_list_safe(assignment_entry, entry, assignments) {
216	    if (entry->lhs != var)
217	       continue;
218
219            /* Skip if the assignment we're trying to eliminate isn't a plain
220             * variable deref. */
221            if (entry->ir->lhs->ir_type != ir_type_dereference_variable)
222               continue;
223
224	    int remove = entry->unused & ir->write_mask;
225	    if (debug) {
226	       printf("%s 0x%01x - 0x%01x = 0x%01x\n",
227		      var->name,
228		      entry->ir->write_mask,
229		      remove, entry->ir->write_mask & ~remove);
230	    }
231	    if (remove) {
232	       progress = true;
233
234	       if (debug) {
235		  printf("rewriting:\n  ");
236		  entry->ir->print();
237		  printf("\n");
238	       }
239
240	       entry->ir->write_mask &= ~remove;
241	       entry->unused &= ~remove;
242	       if (entry->ir->write_mask == 0) {
243		  /* Delete the dead assignment. */
244		  entry->ir->remove();
245		  entry->remove();
246	       } else {
247		  void *mem_ctx = ralloc_parent(entry->ir);
248		  /* Reswizzle the RHS arguments according to the new
249		   * write_mask.
250		   */
251		  unsigned components[4];
252		  unsigned channels = 0;
253		  unsigned next = 0;
254
255		  for (int i = 0; i < 4; i++) {
256		     if ((entry->ir->write_mask | remove) & (1 << i)) {
257			if (!(remove & (1 << i)))
258			   components[channels++] = next;
259			next++;
260		     }
261		  }
262
263		  entry->ir->rhs = new(mem_ctx) ir_swizzle(entry->ir->rhs,
264							   components,
265							   channels);
266		  if (debug) {
267		     printf("to:\n  ");
268		     entry->ir->print();
269		     printf("\n");
270		  }
271	       }
272	    }
273	 }
274      } else if (ir->whole_variable_written() != NULL) {
275	 /* We did a whole-variable assignment.  So, any instruction in
276	  * the assignment list with the same LHS is dead.
277	  */
278	 if (debug)
279	    printf("looking for %s to remove\n", var->name);
280	 foreach_in_list_safe(assignment_entry, entry, assignments) {
281	    if (entry->lhs == var) {
282	       if (debug)
283		  printf("removing %s\n", var->name);
284	       entry->ir->remove();
285	       entry->remove();
286	       progress = true;
287	    }
288	 }
289      }
290   }
291
292   /* Add this instruction to the assignment list available to be removed. */
293   assignment_entry *entry = new(lin_ctx) assignment_entry(var, ir);
294   assignments->push_tail(entry);
295
296   if (debug) {
297      printf("add %s\n", var->name);
298
299      printf("current entries\n");
300      foreach_in_list(assignment_entry, entry, assignments) {
301	 printf("    %s (0x%01x)\n", entry->lhs->name, entry->unused);
302      }
303   }
304
305   return progress;
306}
307
308static void
309dead_code_local_basic_block(ir_instruction *first,
310			     ir_instruction *last,
311			     void *data)
312{
313   ir_instruction *ir, *ir_next;
314   /* List of avaialble_copy */
315   exec_list assignments;
316   bool *out_progress = (bool *)data;
317   bool progress = false;
318
319   void *ctx = ralloc_context(NULL);
320   void *lin_ctx = linear_alloc_parent(ctx, 0);
321
322   /* Safe looping, since process_assignment */
323   for (ir = first, ir_next = (ir_instruction *)first->next;;
324	ir = ir_next, ir_next = (ir_instruction *)ir->next) {
325      ir_assignment *ir_assign = ir->as_assignment();
326
327      if (debug) {
328	 ir->print();
329	 printf("\n");
330      }
331
332      if (ir_assign) {
333	 progress = process_assignment(lin_ctx, ir_assign, &assignments) ||
334                    progress;
335      } else {
336	 kill_for_derefs_visitor kill(&assignments);
337	 ir->accept(&kill);
338      }
339
340      if (ir == last)
341	 break;
342   }
343   *out_progress = progress;
344   ralloc_free(ctx);
345}
346
347/**
348 * Does a copy propagation pass on the code present in the instruction stream.
349 */
350bool
351do_dead_code_local(exec_list *instructions)
352{
353   bool progress = false;
354
355   call_for_basic_blocks(instructions, dead_code_local_basic_block, &progress);
356
357   return progress;
358}
359