nir: support lowering clipdist to arrays
[mesa.git] / src / compiler / nir / nir_opt_gcm.c
1 /*
2 * Copyright © 2014 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 DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Jason Ekstrand (jason@jlekstrand.net)
25 *
26 */
27
28 #include "nir.h"
29 #include "nir_instr_set.h"
30
31 /*
32 * Implements Global Code Motion. A description of GCM can be found in
33 * "Global Code Motion; Global Value Numbering" by Cliff Click.
34 * Unfortunately, the algorithm presented in the paper is broken in a
35 * number of ways. The algorithm used here differs substantially from the
36 * one in the paper but it is, in my opinion, much easier to read and
37 * verify correcness.
38 */
39
40 struct gcm_block_info {
41 /* Number of loops this block is inside */
42 unsigned loop_depth;
43
44 /* The last instruction inserted into this block. This is used as we
45 * traverse the instructions and insert them back into the program to
46 * put them in the right order.
47 */
48 nir_instr *last_instr;
49 };
50
51 /* Flags used in the instr->pass_flags field for various instruction states */
52 enum {
53 GCM_INSTR_PINNED = (1 << 0),
54 GCM_INSTR_SCHEDULED_EARLY = (1 << 1),
55 GCM_INSTR_SCHEDULED_LATE = (1 << 2),
56 GCM_INSTR_PLACED = (1 << 3),
57 };
58
59 struct gcm_state {
60 nir_function_impl *impl;
61 nir_instr *instr;
62
63 /* The list of non-pinned instructions. As we do the late scheduling,
64 * we pull non-pinned instructions out of their blocks and place them in
65 * this list. This saves us from having linked-list problems when we go
66 * to put instructions back in their blocks.
67 */
68 struct exec_list instrs;
69
70 struct gcm_block_info *blocks;
71 };
72
73 /* Recursively walks the CFG and builds the block_info structure */
74 static void
75 gcm_build_block_info(struct exec_list *cf_list, struct gcm_state *state,
76 unsigned loop_depth)
77 {
78 foreach_list_typed(nir_cf_node, node, node, cf_list) {
79 switch (node->type) {
80 case nir_cf_node_block: {
81 nir_block *block = nir_cf_node_as_block(node);
82 state->blocks[block->index].loop_depth = loop_depth;
83 break;
84 }
85 case nir_cf_node_if: {
86 nir_if *if_stmt = nir_cf_node_as_if(node);
87 gcm_build_block_info(&if_stmt->then_list, state, loop_depth);
88 gcm_build_block_info(&if_stmt->else_list, state, loop_depth);
89 break;
90 }
91 case nir_cf_node_loop: {
92 nir_loop *loop = nir_cf_node_as_loop(node);
93 gcm_build_block_info(&loop->body, state, loop_depth + 1);
94 break;
95 }
96 default:
97 unreachable("Invalid CF node type");
98 }
99 }
100 }
101
102 /* Walks the instruction list and marks immovable instructions as pinned
103 *
104 * This function also serves to initialize the instr->pass_flags field.
105 * After this is completed, all instructions' pass_flags fields will be set
106 * to either GCM_INSTR_PINNED or 0.
107 */
108 static bool
109 gcm_pin_instructions_block(nir_block *block, struct gcm_state *state)
110 {
111 nir_foreach_instr_safe(instr, block) {
112 switch (instr->type) {
113 case nir_instr_type_alu:
114 switch (nir_instr_as_alu(instr)->op) {
115 case nir_op_fddx:
116 case nir_op_fddy:
117 case nir_op_fddx_fine:
118 case nir_op_fddy_fine:
119 case nir_op_fddx_coarse:
120 case nir_op_fddy_coarse:
121 /* These can only go in uniform control flow; pin them for now */
122 instr->pass_flags = GCM_INSTR_PINNED;
123 break;
124
125 default:
126 instr->pass_flags = 0;
127 break;
128 }
129 break;
130
131 case nir_instr_type_deref:
132 instr->pass_flags = 0;
133 break;
134
135 case nir_instr_type_tex:
136 if (nir_tex_instr_has_implicit_derivative(nir_instr_as_tex(instr)))
137 instr->pass_flags = GCM_INSTR_PINNED;
138 break;
139
140 case nir_instr_type_load_const:
141 instr->pass_flags = 0;
142 break;
143
144 case nir_instr_type_intrinsic: {
145 if (nir_intrinsic_can_reorder(nir_instr_as_intrinsic(instr))) {
146 instr->pass_flags = 0;
147 } else {
148 instr->pass_flags = GCM_INSTR_PINNED;
149 }
150 break;
151 }
152
153 case nir_instr_type_jump:
154 case nir_instr_type_ssa_undef:
155 case nir_instr_type_phi:
156 instr->pass_flags = GCM_INSTR_PINNED;
157 break;
158
159 default:
160 unreachable("Invalid instruction type in GCM");
161 }
162
163 if (!(instr->pass_flags & GCM_INSTR_PINNED)) {
164 /* If this is an unpinned instruction, go ahead and pull it out of
165 * the program and put it on the instrs list. This has a couple
166 * of benifits. First, it makes the scheduling algorithm more
167 * efficient because we can avoid walking over basic blocks and
168 * pinned instructions. Second, it keeps us from causing linked
169 * list confusion when we're trying to put everything in its
170 * proper place at the end of the pass.
171 *
172 * Note that we don't use nir_instr_remove here because that also
173 * cleans up uses and defs and we want to keep that information.
174 */
175 exec_node_remove(&instr->node);
176 exec_list_push_tail(&state->instrs, &instr->node);
177 }
178 }
179
180 return true;
181 }
182
183 static void
184 gcm_schedule_early_instr(nir_instr *instr, struct gcm_state *state);
185
186 /** Update an instructions schedule for the given source
187 *
188 * This function is called iteratively as we walk the sources of an
189 * instruction. It ensures that the given source instruction has been
190 * scheduled and then update this instruction's block if the source
191 * instruction is lower down the tree.
192 */
193 static bool
194 gcm_schedule_early_src(nir_src *src, void *void_state)
195 {
196 struct gcm_state *state = void_state;
197 nir_instr *instr = state->instr;
198
199 assert(src->is_ssa);
200
201 gcm_schedule_early_instr(src->ssa->parent_instr, void_state);
202
203 /* While the index isn't a proper dominance depth, it does have the
204 * property that if A dominates B then A->index <= B->index. Since we
205 * know that this instruction must have been dominated by all of its
206 * sources at some point (even if it's gone through value-numbering),
207 * all of the sources must lie on the same branch of the dominance tree.
208 * Therefore, we can just go ahead and just compare indices.
209 */
210 if (instr->block->index < src->ssa->parent_instr->block->index)
211 instr->block = src->ssa->parent_instr->block;
212
213 /* We need to restore the state instruction because it may have been
214 * changed through the gcm_schedule_early_instr call above. Since we
215 * may still be iterating through sources and future calls to
216 * gcm_schedule_early_src for the same instruction will still need it.
217 */
218 state->instr = instr;
219
220 return true;
221 }
222
223 /** Schedules an instruction early
224 *
225 * This function performs a recursive depth-first search starting at the
226 * given instruction and proceeding through the sources to schedule
227 * instructions as early as they can possibly go in the dominance tree.
228 * The instructions are "scheduled" by updating their instr->block field.
229 */
230 static void
231 gcm_schedule_early_instr(nir_instr *instr, struct gcm_state *state)
232 {
233 if (instr->pass_flags & GCM_INSTR_SCHEDULED_EARLY)
234 return;
235
236 instr->pass_flags |= GCM_INSTR_SCHEDULED_EARLY;
237
238 /* Pinned instructions are already scheduled so we don't need to do
239 * anything. Also, bailing here keeps us from ever following the
240 * sources of phi nodes which can be back-edges.
241 */
242 if (instr->pass_flags & GCM_INSTR_PINNED)
243 return;
244
245 /* Start with the instruction at the top. As we iterate over the
246 * sources, it will get moved down as needed.
247 */
248 instr->block = nir_start_block(state->impl);
249 state->instr = instr;
250
251 nir_foreach_src(instr, gcm_schedule_early_src, state);
252 }
253
254 static void
255 gcm_schedule_late_instr(nir_instr *instr, struct gcm_state *state);
256
257 /** Schedules the instruction associated with the given SSA def late
258 *
259 * This function works by first walking all of the uses of the given SSA
260 * definition, ensuring that they are scheduled, and then computing the LCA
261 * (least common ancestor) of its uses. It then schedules this instruction
262 * as close to the LCA as possible while trying to stay out of loops.
263 */
264 static bool
265 gcm_schedule_late_def(nir_ssa_def *def, void *void_state)
266 {
267 struct gcm_state *state = void_state;
268
269 nir_block *lca = NULL;
270
271 nir_foreach_use(use_src, def) {
272 nir_instr *use_instr = use_src->parent_instr;
273
274 gcm_schedule_late_instr(use_instr, state);
275
276 /* Phi instructions are a bit special. SSA definitions don't have to
277 * dominate the sources of the phi nodes that use them; instead, they
278 * have to dominate the predecessor block corresponding to the phi
279 * source. We handle this by looking through the sources, finding
280 * any that are usingg this SSA def, and using those blocks instead
281 * of the one the phi lives in.
282 */
283 if (use_instr->type == nir_instr_type_phi) {
284 nir_phi_instr *phi = nir_instr_as_phi(use_instr);
285
286 nir_foreach_phi_src(phi_src, phi) {
287 if (phi_src->src.ssa == def)
288 lca = nir_dominance_lca(lca, phi_src->pred);
289 }
290 } else {
291 lca = nir_dominance_lca(lca, use_instr->block);
292 }
293 }
294
295 nir_foreach_if_use(use_src, def) {
296 nir_if *if_stmt = use_src->parent_if;
297
298 /* For if statements, we consider the block to be the one immediately
299 * preceding the if CF node.
300 */
301 nir_block *pred_block =
302 nir_cf_node_as_block(nir_cf_node_prev(&if_stmt->cf_node));
303
304 lca = nir_dominance_lca(lca, pred_block);
305 }
306
307 /* Some instructions may never be used. We'll just leave them scheduled
308 * early and let dead code clean them up.
309 */
310 if (lca == NULL)
311 return true;
312
313 /* We now have the LCA of all of the uses. If our invariants hold,
314 * this is dominated by the block that we chose when scheduling early.
315 * We now walk up the dominance tree and pick the lowest block that is
316 * as far outside loops as we can get.
317 */
318 nir_block *best = lca;
319 for (nir_block *block = lca; block != NULL; block = block->imm_dom) {
320 if (state->blocks[block->index].loop_depth <
321 state->blocks[best->index].loop_depth)
322 best = block;
323
324 if (block == def->parent_instr->block)
325 break;
326 }
327 def->parent_instr->block = best;
328
329 return true;
330 }
331
332 /** Schedules an instruction late
333 *
334 * This function performs a depth-first search starting at the given
335 * instruction and proceeding through its uses to schedule instructions as
336 * late as they can reasonably go in the dominance tree. The instructions
337 * are "scheduled" by updating their instr->block field.
338 *
339 * The name of this function is actually a bit of a misnomer as it doesn't
340 * schedule them "as late as possible" as the paper implies. Instead, it
341 * first finds the lates possible place it can schedule the instruction and
342 * then possibly schedules it earlier than that. The actual location is as
343 * far down the tree as we can go while trying to stay out of loops.
344 */
345 static void
346 gcm_schedule_late_instr(nir_instr *instr, struct gcm_state *state)
347 {
348 if (instr->pass_flags & GCM_INSTR_SCHEDULED_LATE)
349 return;
350
351 instr->pass_flags |= GCM_INSTR_SCHEDULED_LATE;
352
353 /* Pinned instructions are already scheduled so we don't need to do
354 * anything. Also, bailing here keeps us from ever following phi nodes
355 * which can be back-edges.
356 */
357 if (instr->pass_flags & GCM_INSTR_PINNED)
358 return;
359
360 nir_foreach_ssa_def(instr, gcm_schedule_late_def, state);
361 }
362
363 static void
364 gcm_place_instr(nir_instr *instr, struct gcm_state *state);
365
366 static bool
367 gcm_place_instr_def(nir_ssa_def *def, void *state)
368 {
369 nir_foreach_use(use_src, def)
370 gcm_place_instr(use_src->parent_instr, state);
371
372 return false;
373 }
374
375 /** Places an instrution back into the program
376 *
377 * The earlier passes of GCM simply choose blocks for each instruction and
378 * otherwise leave them alone. This pass actually places the instructions
379 * into their chosen blocks.
380 *
381 * To do so, we use a standard post-order depth-first search linearization
382 * algorithm. We walk over the uses of the given instruction and ensure
383 * that they are placed and then place this instruction. Because we are
384 * working on multiple blocks at a time, we keep track of the last inserted
385 * instruction per-block in the state structure's block_info array. When
386 * we insert an instruction in a block we insert it before the last
387 * instruction inserted in that block rather than the last instruction
388 * inserted globally.
389 */
390 static void
391 gcm_place_instr(nir_instr *instr, struct gcm_state *state)
392 {
393 if (instr->pass_flags & GCM_INSTR_PLACED)
394 return;
395
396 instr->pass_flags |= GCM_INSTR_PLACED;
397
398 /* Phi nodes are our once source of back-edges. Since right now we are
399 * only doing scheduling within blocks, we don't need to worry about
400 * them since they are always at the top. Just skip them completely.
401 */
402 if (instr->type == nir_instr_type_phi) {
403 assert(instr->pass_flags & GCM_INSTR_PINNED);
404 return;
405 }
406
407 nir_foreach_ssa_def(instr, gcm_place_instr_def, state);
408
409 if (instr->pass_flags & GCM_INSTR_PINNED) {
410 /* Pinned instructions have an implicit dependence on the pinned
411 * instructions that come after them in the block. Since the pinned
412 * instructions will naturally "chain" together, we only need to
413 * explicitly visit one of them.
414 */
415 for (nir_instr *after = nir_instr_next(instr);
416 after;
417 after = nir_instr_next(after)) {
418 if (after->pass_flags & GCM_INSTR_PINNED) {
419 gcm_place_instr(after, state);
420 break;
421 }
422 }
423 }
424
425 struct gcm_block_info *block_info = &state->blocks[instr->block->index];
426 if (!(instr->pass_flags & GCM_INSTR_PINNED)) {
427 exec_node_remove(&instr->node);
428
429 if (block_info->last_instr) {
430 exec_node_insert_node_before(&block_info->last_instr->node,
431 &instr->node);
432 } else {
433 /* Schedule it at the end of the block */
434 nir_instr *jump_instr = nir_block_last_instr(instr->block);
435 if (jump_instr && jump_instr->type == nir_instr_type_jump) {
436 exec_node_insert_node_before(&jump_instr->node, &instr->node);
437 } else {
438 exec_list_push_tail(&instr->block->instr_list, &instr->node);
439 }
440 }
441 }
442
443 block_info->last_instr = instr;
444 }
445
446 static bool
447 opt_gcm_impl(nir_function_impl *impl, bool value_number)
448 {
449 nir_metadata_require(impl, nir_metadata_block_index |
450 nir_metadata_dominance);
451
452 struct gcm_state state;
453
454 state.impl = impl;
455 state.instr = NULL;
456 exec_list_make_empty(&state.instrs);
457 state.blocks = rzalloc_array(NULL, struct gcm_block_info, impl->num_blocks);
458
459 gcm_build_block_info(&impl->body, &state, 0);
460
461 nir_foreach_block(block, impl) {
462 gcm_pin_instructions_block(block, &state);
463 }
464
465 bool progress = false;
466 if (value_number) {
467 struct set *gvn_set = nir_instr_set_create(NULL);
468 foreach_list_typed_safe(nir_instr, instr, node, &state.instrs) {
469 if (nir_instr_set_add_or_rewrite(gvn_set, instr)) {
470 nir_instr_remove(instr);
471 progress = true;
472 }
473 }
474 nir_instr_set_destroy(gvn_set);
475 }
476
477 foreach_list_typed(nir_instr, instr, node, &state.instrs)
478 gcm_schedule_early_instr(instr, &state);
479
480 foreach_list_typed(nir_instr, instr, node, &state.instrs)
481 gcm_schedule_late_instr(instr, &state);
482
483 while (!exec_list_is_empty(&state.instrs)) {
484 nir_instr *instr = exec_node_data(nir_instr,
485 state.instrs.tail_sentinel.prev, node);
486 gcm_place_instr(instr, &state);
487 }
488
489 ralloc_free(state.blocks);
490
491 nir_metadata_preserve(impl, nir_metadata_block_index |
492 nir_metadata_dominance);
493
494 return progress;
495 }
496
497 bool
498 nir_opt_gcm(nir_shader *shader, bool value_number)
499 {
500 bool progress = false;
501
502 nir_foreach_function(function, shader) {
503 if (function->impl)
504 progress |= opt_gcm_impl(function->impl, value_number);
505 }
506
507 return progress;
508 }