mesa/st/glsl_to_tgsi: move evaluation of read mask up in the call hierarchy
[mesa.git] / src / mesa / state_tracker / st_glsl_to_tgsi_temprename.cpp
1 /*
2 * Copyright © 2017 Gert Wollny
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 #include "st_glsl_to_tgsi_temprename.h"
25 #include "tgsi/tgsi_info.h"
26 #include "tgsi/tgsi_strings.h"
27 #include "program/prog_instruction.h"
28 #include "util/bitscan.h"
29 #include <limits>
30 #include <cstdlib>
31
32 /* std::sort is significantly faster than qsort */
33 #define USE_STL_SORT
34 #ifdef USE_STL_SORT
35 #include <algorithm>
36 #endif
37
38 #ifndef NDEBUG
39 #include <iostream>
40 #include <iomanip>
41 #include "program/prog_print.h"
42 #include "util/debug.h"
43 using std::cerr;
44 using std::setw;
45 using std::ostream;
46 #endif
47
48 /* If <windows.h> is included this is defined and clashes with
49 * std::numeric_limits<>::max()
50 */
51 #ifdef max
52 #undef max
53 #endif
54
55 using std::numeric_limits;
56
57 /* Without c++11 define the nullptr for forward-compatibility
58 * and better readibility */
59 #if __cplusplus < 201103L
60 #define nullptr 0
61 #endif
62
63 #ifndef NDEBUG
64 /* Prepare to make it possible to specify log file */
65 static std::ostream& debug_log = cerr;
66
67 /* Helper function to check whether we want to seen debugging output */
68 static inline bool is_debug_enabled ()
69 {
70 static int debug_enabled = -1;
71 if (debug_enabled < 0)
72 debug_enabled = env_var_as_boolean("GLSL_TO_TGSI_RENAME_DEBUG", false);
73 return debug_enabled > 0;
74 }
75 #define RENAME_DEBUG(X) if (is_debug_enabled()) do { X; } while (false);
76 #else
77 #define RENAME_DEBUG(X)
78 #endif
79
80 namespace {
81
82 enum prog_scope_type {
83 outer_scope, /* Outer program scope */
84 loop_body, /* Inside a loop */
85 if_branch, /* Inside if branch */
86 else_branch, /* Inside else branch */
87 switch_body, /* Inside switch statmenet */
88 switch_case_branch, /* Inside switch case statmenet */
89 switch_default_branch, /* Inside switch default statmenet */
90 undefined_scope
91 };
92
93 class prog_scope {
94 public:
95 prog_scope(prog_scope *parent, prog_scope_type type, int id,
96 int depth, int begin);
97
98 prog_scope_type type() const;
99 prog_scope *parent() const;
100 int nesting_depth() const;
101 int id() const;
102 int end() const;
103 int begin() const;
104 int loop_break_line() const;
105
106 const prog_scope *in_else_scope() const;
107 const prog_scope *in_ifelse_scope() const;
108 const prog_scope *in_parent_ifelse_scope() const;
109 const prog_scope *innermost_loop() const;
110 const prog_scope *outermost_loop() const;
111 const prog_scope *enclosing_conditional() const;
112
113 bool is_loop() const;
114 bool is_in_loop() const;
115 bool is_switchcase_scope_in_loop() const;
116 bool is_conditional() const;
117 bool is_child_of(const prog_scope *scope) const;
118 bool is_child_of_ifelse_id_sibling(const prog_scope *scope) const;
119
120 bool break_is_for_switchcase() const;
121 bool contains_range_of(const prog_scope& other) const;
122
123 void set_end(int end);
124 void set_loop_break_line(int line);
125
126 private:
127 prog_scope_type scope_type;
128 int scope_id;
129 int scope_nesting_depth;
130 int scope_begin;
131 int scope_end;
132 int break_loop_line;
133 prog_scope *parent_scope;
134 };
135
136 /* Some storage class to encapsulate the prog_scope (de-)allocations */
137 class prog_scope_storage {
138 public:
139 prog_scope_storage(void *mem_ctx, int n);
140 ~prog_scope_storage();
141 prog_scope * create(prog_scope *p, prog_scope_type type, int id,
142 int lvl, int s_begin);
143 private:
144 void *mem_ctx;
145 int current_slot;
146 prog_scope *storage;
147 };
148
149 /* Class to track the access to a component of a temporary register. */
150
151 class temp_comp_access {
152 public:
153 temp_comp_access();
154
155 void record_read(int line, prog_scope *scope);
156 void record_write(int line, prog_scope *scope);
157 register_live_range get_required_live_range();
158 private:
159 void propagate_live_range_to_dominant_write_scope();
160 bool conditional_ifelse_write_in_loop() const;
161
162 void record_ifelse_write(const prog_scope& scope);
163 void record_if_write(const prog_scope& scope);
164 void record_else_write(const prog_scope& scope);
165
166 prog_scope *last_read_scope;
167 prog_scope *first_read_scope;
168 prog_scope *first_write_scope;
169
170 int first_write;
171 int last_read;
172 int last_write;
173 int first_read;
174
175 /* This member variable tracks the current resolution of conditional writing
176 * to this temporary in IF/ELSE clauses.
177 *
178 * The initial value "conditionality_untouched" indicates that this
179 * temporary has not yet been written to within an if clause.
180 *
181 * A positive (other than "conditionality_untouched") number refers to the
182 * last loop id for which the write was resolved as unconditional. With each
183 * new loop this value will be overwitten by "conditionality_unresolved"
184 * on entering the first IF clause writing this temporary.
185 *
186 * The value "conditionality_unresolved" indicates that no resolution has
187 * been achieved so far. If the variable is set to this value at the end of
188 * the processing of the whole shader it also indicates a conditional write.
189 *
190 * The value "write_is_conditional" marks that the variable is written
191 * conditionally (i.e. not in all relevant IF/ELSE code path pairs) in at
192 * least one loop.
193 */
194 int conditionality_in_loop_id;
195
196 /* Helper constants to make the tracking code more readable. */
197 static const int write_is_conditional = -1;
198 static const int conditionality_unresolved = 0;
199 static const int conditionality_untouched;
200 static const int write_is_unconditional;
201
202 /* A bit field tracking the nexting levels of if-else clauses where the
203 * temporary has (so far) been written to in the if branch, but not in the
204 * else branch.
205 */
206 unsigned int if_scope_write_flags;
207
208 int next_ifelse_nesting_depth;
209 static const int supported_ifelse_nesting_depth = 32;
210
211 /* Tracks the last if scope in which the temporary was written to
212 * without a write in the correspondig else branch. Is also used
213 * to track read-before-write in the according scope.
214 */
215 const prog_scope *current_unpaired_if_write_scope;
216
217 /* Flag to resolve read-before-write in the else scope. */
218 bool was_written_in_current_else_scope;
219 };
220
221 const int
222 temp_comp_access::conditionality_untouched = numeric_limits<int>::max();
223
224 const int
225 temp_comp_access::write_is_unconditional = numeric_limits<int>::max() - 1;
226
227 /* Class to track the access to all components of a temporary register. */
228 class temp_access {
229 public:
230 temp_access();
231 void record_read(int line, prog_scope *scope, int swizzle);
232 void record_write(int line, prog_scope *scope, int writemask);
233 register_live_range get_required_live_range();
234 private:
235 void update_access_mask(int mask);
236
237 temp_comp_access comp[4];
238 int access_mask;
239 bool needs_component_tracking;
240 };
241
242 prog_scope_storage::prog_scope_storage(void *mc, int n):
243 mem_ctx(mc),
244 current_slot(0)
245 {
246 storage = ralloc_array(mem_ctx, prog_scope, n);
247 }
248
249 prog_scope_storage::~prog_scope_storage()
250 {
251 ralloc_free(storage);
252 }
253
254 prog_scope*
255 prog_scope_storage::create(prog_scope *p, prog_scope_type type, int id,
256 int lvl, int s_begin)
257 {
258 storage[current_slot] = prog_scope(p, type, id, lvl, s_begin);
259 return &storage[current_slot++];
260 }
261
262 prog_scope::prog_scope(prog_scope *parent, prog_scope_type type, int id,
263 int depth, int scope_begin):
264 scope_type(type),
265 scope_id(id),
266 scope_nesting_depth(depth),
267 scope_begin(scope_begin),
268 scope_end(-1),
269 break_loop_line(numeric_limits<int>::max()),
270 parent_scope(parent)
271 {
272 }
273
274 prog_scope_type prog_scope::type() const
275 {
276 return scope_type;
277 }
278
279 prog_scope *prog_scope::parent() const
280 {
281 return parent_scope;
282 }
283
284 int prog_scope::nesting_depth() const
285 {
286 return scope_nesting_depth;
287 }
288
289 bool prog_scope::is_loop() const
290 {
291 return (scope_type == loop_body);
292 }
293
294 bool prog_scope::is_in_loop() const
295 {
296 if (scope_type == loop_body)
297 return true;
298
299 if (parent_scope)
300 return parent_scope->is_in_loop();
301
302 return false;
303 }
304
305 const prog_scope *prog_scope::innermost_loop() const
306 {
307 if (scope_type == loop_body)
308 return this;
309
310 if (parent_scope)
311 return parent_scope->innermost_loop();
312
313 return nullptr;
314 }
315
316 const prog_scope *prog_scope::outermost_loop() const
317 {
318 const prog_scope *loop = nullptr;
319 const prog_scope *p = this;
320
321 do {
322 if (p->type() == loop_body)
323 loop = p;
324 p = p->parent();
325 } while (p);
326
327 return loop;
328 }
329
330 bool prog_scope::is_child_of_ifelse_id_sibling(const prog_scope *scope) const
331 {
332 const prog_scope *my_parent = in_parent_ifelse_scope();
333 while (my_parent) {
334 /* is a direct child? */
335 if (my_parent == scope)
336 return false;
337 /* is a child of the conditions sibling? */
338 if (my_parent->id() == scope->id())
339 return true;
340 my_parent = my_parent->in_parent_ifelse_scope();
341 }
342 return false;
343 }
344
345 bool prog_scope::is_child_of(const prog_scope *scope) const
346 {
347 const prog_scope *my_parent = parent();
348 while (my_parent) {
349 if (my_parent == scope)
350 return true;
351 my_parent = my_parent->parent();
352 }
353 return false;
354 }
355
356 const prog_scope *prog_scope::enclosing_conditional() const
357 {
358 if (is_conditional())
359 return this;
360
361 if (parent_scope)
362 return parent_scope->enclosing_conditional();
363
364 return nullptr;
365 }
366
367 bool prog_scope::contains_range_of(const prog_scope& other) const
368 {
369 return (begin() <= other.begin()) && (end() >= other.end());
370 }
371
372 bool prog_scope::is_conditional() const
373 {
374 return scope_type == if_branch ||
375 scope_type == else_branch ||
376 scope_type == switch_case_branch ||
377 scope_type == switch_default_branch;
378 }
379
380 const prog_scope *prog_scope::in_else_scope() const
381 {
382 if (scope_type == else_branch)
383 return this;
384
385 if (parent_scope)
386 return parent_scope->in_else_scope();
387
388 return nullptr;
389 }
390
391 const prog_scope *prog_scope::in_parent_ifelse_scope() const
392 {
393 if (parent_scope)
394 return parent_scope->in_ifelse_scope();
395 else
396 return nullptr;
397 }
398
399 const prog_scope *prog_scope::in_ifelse_scope() const
400 {
401 if (scope_type == if_branch ||
402 scope_type == else_branch)
403 return this;
404
405 if (parent_scope)
406 return parent_scope->in_ifelse_scope();
407
408 return nullptr;
409 }
410
411 bool prog_scope::is_switchcase_scope_in_loop() const
412 {
413 return (scope_type == switch_case_branch ||
414 scope_type == switch_default_branch) &&
415 is_in_loop();
416 }
417
418 bool prog_scope::break_is_for_switchcase() const
419 {
420 if (scope_type == loop_body)
421 return false;
422
423 if (scope_type == switch_case_branch ||
424 scope_type == switch_default_branch ||
425 scope_type == switch_body)
426 return true;
427
428 if (parent_scope)
429 return parent_scope->break_is_for_switchcase();
430
431 return false;
432 }
433
434 int prog_scope::id() const
435 {
436 return scope_id;
437 }
438
439 int prog_scope::begin() const
440 {
441 return scope_begin;
442 }
443
444 int prog_scope::end() const
445 {
446 return scope_end;
447 }
448
449 void prog_scope::set_end(int end)
450 {
451 if (scope_end == -1)
452 scope_end = end;
453 }
454
455 void prog_scope::set_loop_break_line(int line)
456 {
457 if (scope_type == loop_body) {
458 break_loop_line = MIN2(break_loop_line, line);
459 } else {
460 if (parent_scope)
461 parent()->set_loop_break_line(line);
462 }
463 }
464
465 int prog_scope::loop_break_line() const
466 {
467 return break_loop_line;
468 }
469
470 temp_access::temp_access():
471 access_mask(0),
472 needs_component_tracking(false)
473 {
474 }
475
476 void temp_access::update_access_mask(int mask)
477 {
478 if (access_mask && access_mask != mask)
479 needs_component_tracking = true;
480 access_mask |= mask;
481 }
482
483 void temp_access::record_write(int line, prog_scope *scope, int writemask)
484 {
485 update_access_mask(writemask);
486
487 if (writemask & WRITEMASK_X)
488 comp[0].record_write(line, scope);
489 if (writemask & WRITEMASK_Y)
490 comp[1].record_write(line, scope);
491 if (writemask & WRITEMASK_Z)
492 comp[2].record_write(line, scope);
493 if (writemask & WRITEMASK_W)
494 comp[3].record_write(line, scope);
495 }
496
497 void temp_access::record_read(int line, prog_scope *scope, int readmask)
498 {
499 update_access_mask(readmask);
500
501 if (readmask & WRITEMASK_X)
502 comp[0].record_read(line, scope);
503 if (readmask & WRITEMASK_Y)
504 comp[1].record_read(line, scope);
505 if (readmask & WRITEMASK_Z)
506 comp[2].record_read(line, scope);
507 if (readmask & WRITEMASK_W)
508 comp[3].record_read(line, scope);
509 }
510
511 inline static register_live_range make_live_range(int b, int e)
512 {
513 register_live_range lt;
514 lt.begin = b;
515 lt.end = e;
516 return lt;
517 }
518
519 register_live_range temp_access::get_required_live_range()
520 {
521 register_live_range result = make_live_range(-1, -1);
522
523 unsigned mask = access_mask;
524 while (mask) {
525 unsigned chan = u_bit_scan(&mask);
526 register_live_range lt = comp[chan].get_required_live_range();
527
528 if (lt.begin >= 0) {
529 if ((result.begin < 0) || (result.begin > lt.begin))
530 result.begin = lt.begin;
531 }
532
533 if (lt.end > result.end)
534 result.end = lt.end;
535
536 if (!needs_component_tracking)
537 break;
538 }
539 return result;
540 }
541
542 temp_comp_access::temp_comp_access():
543 last_read_scope(nullptr),
544 first_read_scope(nullptr),
545 first_write_scope(nullptr),
546 first_write(-1),
547 last_read(-1),
548 last_write(-1),
549 first_read(numeric_limits<int>::max()),
550 conditionality_in_loop_id(conditionality_untouched),
551 if_scope_write_flags(0),
552 next_ifelse_nesting_depth(0),
553 current_unpaired_if_write_scope(nullptr),
554 was_written_in_current_else_scope(false)
555 {
556 }
557
558 void temp_comp_access::record_read(int line, prog_scope *scope)
559 {
560 last_read_scope = scope;
561 last_read = line;
562
563 if (first_read > line) {
564 first_read = line;
565 first_read_scope = scope;
566 }
567
568 /* If the conditionality of the first write is already resolved then
569 * no further checks are required.
570 */
571 if (conditionality_in_loop_id == write_is_unconditional ||
572 conditionality_in_loop_id == write_is_conditional)
573 return;
574
575 /* Check whether we are in a condition within a loop */
576 const prog_scope *ifelse_scope = scope->in_ifelse_scope();
577 const prog_scope *enclosing_loop;
578 if (ifelse_scope && (enclosing_loop = ifelse_scope->innermost_loop())) {
579
580 /* If we have either not yet written to this register nor writes are
581 * resolved as unconditional in the enclosing loop then check whether
582 * we read before write in an IF/ELSE branch.
583 */
584 if ((conditionality_in_loop_id != write_is_conditional) &&
585 (conditionality_in_loop_id != enclosing_loop->id())) {
586
587 if (current_unpaired_if_write_scope) {
588
589 /* Has been written in this or a parent scope? - this makes the temporary
590 * unconditionally set at this point.
591 */
592 if (scope->is_child_of(current_unpaired_if_write_scope))
593 return;
594
595 /* Has been written in the same scope before it was read? */
596 if (ifelse_scope->type() == if_branch) {
597 if (current_unpaired_if_write_scope->id() == scope->id())
598 return;
599 } else {
600 if (was_written_in_current_else_scope)
601 return;
602 }
603 }
604
605 /* The temporary was read (conditionally) before it is written, hence
606 * it should survive a loop. This can be signaled like if it were
607 * conditionally written.
608 */
609 conditionality_in_loop_id = write_is_conditional;
610 }
611 }
612 }
613
614 void temp_comp_access::record_write(int line, prog_scope *scope)
615 {
616 last_write = line;
617
618 if (first_write < 0) {
619 first_write = line;
620 first_write_scope = scope;
621
622 /* If the first write we encounter is not in a conditional branch, or
623 * the conditional write is not within a loop, then this is to be
624 * considered an unconditional dominant write.
625 */
626 const prog_scope *conditional = scope->enclosing_conditional();
627 if (!conditional || !conditional->innermost_loop()) {
628 conditionality_in_loop_id = write_is_unconditional;
629 }
630 }
631
632 /* The conditionality of the first write is already resolved. */
633 if (conditionality_in_loop_id == write_is_unconditional ||
634 conditionality_in_loop_id == write_is_conditional)
635 return;
636
637 /* If the nesting depth is larger than the supported level,
638 * then we assume conditional writes.
639 */
640 if (next_ifelse_nesting_depth >= supported_ifelse_nesting_depth) {
641 conditionality_in_loop_id = write_is_conditional;
642 return;
643 }
644
645 /* If we are in an IF/ELSE scope within a loop and the loop has not
646 * been resolved already, then record this write.
647 */
648 const prog_scope *ifelse_scope = scope->in_ifelse_scope();
649 if (ifelse_scope && ifelse_scope->innermost_loop() &&
650 ifelse_scope->innermost_loop()->id() != conditionality_in_loop_id)
651 record_ifelse_write(*ifelse_scope);
652 }
653
654 void temp_comp_access::record_ifelse_write(const prog_scope& scope)
655 {
656 if (scope.type() == if_branch) {
657 /* The first write in an IF branch within a loop implies unresolved
658 * conditionality (if it was untouched or unconditional before).
659 */
660 conditionality_in_loop_id = conditionality_unresolved;
661 was_written_in_current_else_scope = false;
662 record_if_write(scope);
663 } else {
664 was_written_in_current_else_scope = true;
665 record_else_write(scope);
666 }
667 }
668
669 void temp_comp_access::record_if_write(const prog_scope& scope)
670 {
671 /* Don't record write if this IF scope if it ...
672 * - is not the first write in this IF scope,
673 * - has already been written in a parent IF scope.
674 * In both cases this write is a secondary write that doesn't contribute
675 * to resolve conditionality.
676 *
677 * Record the write if it
678 * - is the first one (obviously),
679 * - happens in an IF branch that is a child of the ELSE branch of the
680 * last active IF/ELSE pair. In this case recording this write is used to
681 * established whether the write is (un-)conditional in the scope enclosing
682 * this outer IF/ELSE pair.
683 */
684 if (!current_unpaired_if_write_scope ||
685 (current_unpaired_if_write_scope->id() != scope.id() &&
686 scope.is_child_of_ifelse_id_sibling(current_unpaired_if_write_scope))) {
687 if_scope_write_flags |= 1 << next_ifelse_nesting_depth;
688 current_unpaired_if_write_scope = &scope;
689 next_ifelse_nesting_depth++;
690 }
691 }
692
693 void temp_comp_access::record_else_write(const prog_scope& scope)
694 {
695 int mask = 1 << (next_ifelse_nesting_depth - 1);
696
697 /* If the temporary was written in an IF branch on the same scope level
698 * and this branch is the sibling of this ELSE branch, then we have a
699 * pair of writes that makes write access to this temporary unconditional
700 * in the enclosing scope.
701 */
702
703 if ((if_scope_write_flags & mask) &&
704 (scope.id() == current_unpaired_if_write_scope->id())) {
705 --next_ifelse_nesting_depth;
706 if_scope_write_flags &= ~mask;
707
708 /* The following code deals with propagating unconditionality from
709 * inner levels of nested IF/ELSE to the outer levels like in
710 *
711 * 1: var t;
712 * 2: if (a) { <- start scope A
713 * 3: if (b)
714 * 4: t = ...
715 * 5: else
716 * 6: t = ...
717 * 7: } else { <- start scope B
718 * 8: if (c)
719 * 9: t = ...
720 * A: else <- start scope C
721 * B: t = ...
722 * C: }
723 *
724 */
725
726 const prog_scope *parent_ifelse = scope.parent()->in_ifelse_scope();
727
728 if (1 << (next_ifelse_nesting_depth - 1) & if_scope_write_flags) {
729 /* We are at the end of scope C and already recorded a write
730 * within an IF scope (A), the sibling of the parent ELSE scope B,
731 * and it is not yet resolved. Mark that as the last relevant
732 * IF scope. Below the write will be resolved for the A/B
733 * scope pair.
734 */
735 current_unpaired_if_write_scope = parent_ifelse;
736 } else {
737 current_unpaired_if_write_scope = nullptr;
738 }
739 /* Promote the first write scope to the enclosing scope because
740 * the current IF/ELSE pair is now irrelevant for the analysis.
741 * This is also required to evaluate the minimum life time for t in
742 * {
743 * var t;
744 * if (a)
745 * t = ...
746 * else
747 * t = ...
748 * x = t;
749 * ...
750 * }
751 */
752 first_write_scope = scope.parent();
753
754 /* If some parent is IF/ELSE and in a loop then propagate the
755 * write to that scope. Otherwise the write is unconditional
756 * because it happens in both corresponding IF/ELSE branches
757 * in this loop, and hence, record the loop id to signal the
758 * resolution.
759 */
760 if (parent_ifelse && parent_ifelse->is_in_loop()) {
761 record_ifelse_write(*parent_ifelse);
762 } else {
763 conditionality_in_loop_id = scope.innermost_loop()->id();
764 }
765 } else {
766 /* The temporary was not written in the IF branch corresponding
767 * to this ELSE branch, hence the write is conditional.
768 */
769 conditionality_in_loop_id = write_is_conditional;
770 }
771 }
772
773 bool temp_comp_access::conditional_ifelse_write_in_loop() const
774 {
775 return conditionality_in_loop_id <= conditionality_unresolved;
776 }
777
778 void temp_comp_access::propagate_live_range_to_dominant_write_scope()
779 {
780 first_write = first_write_scope->begin();
781 int lr = first_write_scope->end();
782
783 if (last_read < lr)
784 last_read = lr;
785 }
786
787 register_live_range temp_comp_access::get_required_live_range()
788 {
789 bool keep_for_full_loop = false;
790
791 /* This register component is not used at all, or only read,
792 * mark it as unused and ignore it when renaming.
793 * glsl_to_tgsi_visitor::renumber_registers will take care of
794 * eliminating registers that are not written to.
795 */
796 if (last_write < 0)
797 return make_live_range(-1, -1);
798
799 assert(first_write_scope);
800
801 /* Only written to, just make sure the register component is not
802 * reused in the range it is used to write to
803 */
804 if (!last_read_scope)
805 return make_live_range(first_write, last_write + 1);
806
807 const prog_scope *enclosing_scope_first_read = first_read_scope;
808 const prog_scope *enclosing_scope_first_write = first_write_scope;
809
810 /* We read before writing in a loop
811 * hence the value must survive the loops
812 */
813 if ((first_read <= first_write) &&
814 first_read_scope->is_in_loop()) {
815 keep_for_full_loop = true;
816 enclosing_scope_first_read = first_read_scope->outermost_loop();
817 }
818
819 /* A conditional write within a (nested) loop must survive the outermost
820 * loop if the last read was not within the same scope.
821 */
822 const prog_scope *conditional = enclosing_scope_first_write->enclosing_conditional();
823 if (conditional && !conditional->contains_range_of(*last_read_scope) &&
824 (conditional->is_switchcase_scope_in_loop() ||
825 conditional_ifelse_write_in_loop())) {
826 keep_for_full_loop = true;
827 enclosing_scope_first_write = conditional->outermost_loop();
828 }
829
830 /* Evaluate the scope that is shared by all: required first write scope,
831 * required first read before write scope, and last read scope.
832 */
833 const prog_scope *enclosing_scope = enclosing_scope_first_read;
834 if (enclosing_scope_first_write->contains_range_of(*enclosing_scope))
835 enclosing_scope = enclosing_scope_first_write;
836
837 if (last_read_scope->contains_range_of(*enclosing_scope))
838 enclosing_scope = last_read_scope;
839
840 while (!enclosing_scope->contains_range_of(*enclosing_scope_first_write) ||
841 !enclosing_scope->contains_range_of(*last_read_scope)) {
842 enclosing_scope = enclosing_scope->parent();
843 assert(enclosing_scope);
844 }
845
846 /* Propagate the last read scope to the target scope */
847 while (enclosing_scope->nesting_depth() < last_read_scope->nesting_depth()) {
848 /* If the read is in a loop and we have to move up the scope we need to
849 * extend the live range to the end of this current loop because at this
850 * point we don't know whether the component was written before
851 * un-conditionally in the same loop.
852 */
853 if (last_read_scope->is_loop())
854 last_read = last_read_scope->end();
855
856 last_read_scope = last_read_scope->parent();
857 }
858
859 /* If the variable has to be kept for the whole loop, and we
860 * are currently in a loop, then propagate the live range.
861 */
862 if (keep_for_full_loop && first_write_scope->is_loop())
863 propagate_live_range_to_dominant_write_scope();
864
865 /* Propagate the first_dominant_write scope to the target scope */
866 while (enclosing_scope->nesting_depth() < first_write_scope->nesting_depth()) {
867 /* Propagate live_range if there was a break in a loop and the write was
868 * after the break inside that loop. Note, that this is only needed if
869 * we move up in the scopes.
870 */
871 if (first_write_scope->loop_break_line() < first_write) {
872 keep_for_full_loop = true;
873 propagate_live_range_to_dominant_write_scope();
874 }
875
876 first_write_scope = first_write_scope->parent();
877
878 /* Propagte live_range if we are now in a loop */
879 if (keep_for_full_loop && first_write_scope->is_loop())
880 propagate_live_range_to_dominant_write_scope();
881 }
882
883 /* The last write past the last read is dead code, but we have to
884 * ensure that the component is not reused too early, hence extend the
885 * live_range past the last write.
886 */
887 if (last_write >= last_read)
888 last_read = last_write + 1;
889
890 /* Here we are at the same scope, all is resolved */
891 return make_live_range(first_write, last_read);
892 }
893
894 /* Helper class for sorting and searching the registers based
895 * on live ranges. */
896 class register_merge_record {
897 public:
898 int begin;
899 int end;
900 int reg;
901 bool erase;
902
903 bool operator < (const register_merge_record& rhs) const {
904 return begin < rhs.begin;
905 }
906 };
907
908 class access_recorder {
909 public:
910 access_recorder(int _ntemps);
911 ~access_recorder();
912
913 void record_read(const st_src_reg& src, int line, prog_scope *scope);
914 void record_write(const st_dst_reg& src, int line, prog_scope *scope);
915
916 void get_required_live_ranges(register_live_range *register_live_ranges);
917 private:
918
919 int ntemps;
920 temp_access *temp_acc;
921
922 };
923
924 access_recorder::access_recorder(int _ntemps):
925 ntemps(_ntemps)
926 {
927 temp_acc = new temp_access[ntemps];
928 }
929
930 access_recorder::~access_recorder()
931 {
932 delete[] temp_acc;
933 }
934
935 void access_recorder::record_read(const st_src_reg& src, int line,
936 prog_scope *scope)
937 {
938 int readmask = 0;
939 for (int idx = 0; idx < 4; ++idx) {
940 int swz = GET_SWZ(src.swizzle, idx);
941 readmask |= (1 << swz) & 0xF;
942 }
943
944 if (src.file == PROGRAM_TEMPORARY)
945 temp_acc[src.index].record_read(line, scope, readmask);
946
947 if (src.reladdr)
948 record_read(*src.reladdr, line, scope);
949 if (src.reladdr2)
950 record_read(*src.reladdr2, line, scope);
951 }
952
953 void access_recorder::record_write(const st_dst_reg& dst, int line,
954 prog_scope *scope)
955 {
956 if (dst.file == PROGRAM_TEMPORARY)
957 temp_acc[dst.index].record_write(line, scope, dst.writemask);
958
959 if (dst.reladdr)
960 record_read(*dst.reladdr, line, scope);
961 if (dst.reladdr2)
962 record_read(*dst.reladdr2, line, scope);
963 }
964
965 void access_recorder::get_required_live_ranges(struct register_live_range *register_live_ranges)
966 {
967 RENAME_DEBUG(debug_log << "== register live ranges ==========\n");
968 for(int i = 0; i < ntemps; ++i) {
969 RENAME_DEBUG(debug_log << setw(4) << i);
970 register_live_ranges[i] = temp_acc[i].get_required_live_range();
971 RENAME_DEBUG(debug_log << ": [" << register_live_ranges[i].begin << ", "
972 << register_live_ranges[i].end << "]\n");
973 }
974 RENAME_DEBUG(debug_log << "==================================\n\n");
975 }
976
977 }
978
979 #ifndef NDEBUG
980 /* Function used for debugging. */
981 static void dump_instruction(ostream& os, int line, prog_scope *scope,
982 const glsl_to_tgsi_instruction& inst);
983 #endif
984
985 /* Scan the program and estimate the required register live ranges.
986 * The arraylive_ranges must be pre-allocated
987 */
988 bool
989 get_temp_registers_required_live_ranges(void *mem_ctx, exec_list *instructions,
990 int ntemps, struct register_live_range *register_live_ranges)
991 {
992 int line = 0;
993 int loop_id = 1;
994 int if_id = 1;
995 int switch_id = 0;
996 bool is_at_end = false;
997 int n_scopes = 1;
998
999 /* Count scopes to allocate the needed space without the need for
1000 * re-allocation
1001 */
1002 foreach_in_list(glsl_to_tgsi_instruction, inst, instructions) {
1003 if (inst->op == TGSI_OPCODE_BGNLOOP ||
1004 inst->op == TGSI_OPCODE_SWITCH ||
1005 inst->op == TGSI_OPCODE_CASE ||
1006 inst->op == TGSI_OPCODE_IF ||
1007 inst->op == TGSI_OPCODE_UIF ||
1008 inst->op == TGSI_OPCODE_ELSE ||
1009 inst->op == TGSI_OPCODE_DEFAULT)
1010 ++n_scopes;
1011 }
1012
1013 prog_scope_storage scopes(mem_ctx, n_scopes);
1014
1015 access_recorder access(ntemps);
1016
1017 prog_scope *cur_scope = scopes.create(nullptr, outer_scope, 0, 0, line);
1018
1019 RENAME_DEBUG(debug_log << "========= Begin shader ============\n");
1020
1021 foreach_in_list(glsl_to_tgsi_instruction, inst, instructions) {
1022 if (is_at_end) {
1023 assert(!"GLSL_TO_TGSI: shader has instructions past end marker");
1024 break;
1025 }
1026
1027 RENAME_DEBUG(dump_instruction(debug_log, line, cur_scope, *inst));
1028
1029 switch (inst->op) {
1030 case TGSI_OPCODE_BGNLOOP: {
1031 cur_scope = scopes.create(cur_scope, loop_body, loop_id++,
1032 cur_scope->nesting_depth() + 1, line);
1033 break;
1034 }
1035 case TGSI_OPCODE_ENDLOOP: {
1036 cur_scope->set_end(line);
1037 cur_scope = cur_scope->parent();
1038 assert(cur_scope);
1039 break;
1040 }
1041 case TGSI_OPCODE_IF:
1042 case TGSI_OPCODE_UIF: {
1043 assert(num_inst_src_regs(inst) == 1);
1044 access.record_read(inst->src[0], line, cur_scope);
1045 cur_scope = scopes.create(cur_scope, if_branch, if_id++,
1046 cur_scope->nesting_depth() + 1, line + 1);
1047 break;
1048 }
1049 case TGSI_OPCODE_ELSE: {
1050 assert(cur_scope->type() == if_branch);
1051 cur_scope->set_end(line - 1);
1052 cur_scope = scopes.create(cur_scope->parent(), else_branch,
1053 cur_scope->id(), cur_scope->nesting_depth(),
1054 line + 1);
1055 break;
1056 }
1057 case TGSI_OPCODE_END: {
1058 cur_scope->set_end(line);
1059 is_at_end = true;
1060 break;
1061 }
1062 case TGSI_OPCODE_ENDIF: {
1063 cur_scope->set_end(line - 1);
1064 cur_scope = cur_scope->parent();
1065 assert(cur_scope);
1066 break;
1067 }
1068 case TGSI_OPCODE_SWITCH: {
1069 assert(num_inst_src_regs(inst) == 1);
1070 prog_scope *scope = scopes.create(cur_scope, switch_body, switch_id++,
1071 cur_scope->nesting_depth() + 1, line);
1072 /* We record the read only for the SWITCH statement itself, like it
1073 * is used by the only consumer of TGSI_OPCODE_SWITCH in tgsi_exec.c.
1074 */
1075 access.record_read(inst->src[0], line, cur_scope);
1076 cur_scope = scope;
1077 break;
1078 }
1079 case TGSI_OPCODE_ENDSWITCH: {
1080 cur_scope->set_end(line - 1);
1081 /* Remove the case level, it might not have been
1082 * closed with a break.
1083 */
1084 if (cur_scope->type() != switch_body)
1085 cur_scope = cur_scope->parent();
1086
1087 cur_scope = cur_scope->parent();
1088 assert(cur_scope);
1089 break;
1090 }
1091 case TGSI_OPCODE_CASE: {
1092 /* Take care of tracking the registers. */
1093 prog_scope *switch_scope = cur_scope->type() == switch_body ?
1094 cur_scope : cur_scope->parent();
1095
1096 assert(num_inst_src_regs(inst) == 1);
1097 access.record_read(inst->src[0], line, switch_scope);
1098
1099 /* Fall through to allocate the scope. */
1100 }
1101 case TGSI_OPCODE_DEFAULT: {
1102 prog_scope_type t = inst->op == TGSI_OPCODE_CASE ? switch_case_branch
1103 : switch_default_branch;
1104 prog_scope *switch_scope = (cur_scope->type() == switch_body) ?
1105 cur_scope : cur_scope->parent();
1106 assert(switch_scope->type() == switch_body);
1107 prog_scope *scope = scopes.create(switch_scope, t,
1108 switch_scope->id(),
1109 switch_scope->nesting_depth() + 1,
1110 line);
1111 /* Previous case falls through, so scope was not yet closed. */
1112 if ((cur_scope != switch_scope) && (cur_scope->end() == -1))
1113 cur_scope->set_end(line - 1);
1114 cur_scope = scope;
1115 break;
1116 }
1117 case TGSI_OPCODE_BRK: {
1118 if (cur_scope->break_is_for_switchcase()) {
1119 cur_scope->set_end(line - 1);
1120 } else {
1121 cur_scope->set_loop_break_line(line);
1122 }
1123 break;
1124 }
1125 case TGSI_OPCODE_CAL:
1126 case TGSI_OPCODE_RET:
1127 /* These opcodes are not supported and if a subroutine would
1128 * be called in a shader, then the live_range tracking would have
1129 * to follow that call to see which registers are used there.
1130 * Since this is not done, we have to bail out here and signal
1131 * that no register merge will take place.
1132 */
1133 return false;
1134 default: {
1135 for (unsigned j = 0; j < num_inst_src_regs(inst); j++) {
1136 access.record_read(inst->src[j], line, cur_scope);
1137 }
1138 for (unsigned j = 0; j < inst->tex_offset_num_offset; j++) {
1139 access.record_read(inst->tex_offsets[j], line, cur_scope);
1140 }
1141 for (unsigned j = 0; j < num_inst_dst_regs(inst); j++) {
1142 access.record_write(inst->dst[j], line, cur_scope);
1143 }
1144 }
1145 }
1146 ++line;
1147 }
1148
1149 RENAME_DEBUG(debug_log << "==================================\n\n");
1150
1151 /* Make sure last scope is closed, even though no
1152 * TGSI_OPCODE_END was given.
1153 */
1154 if (cur_scope->end() < 0)
1155 cur_scope->set_end(line - 1);
1156
1157 access.get_required_live_ranges(register_live_ranges);
1158 return true;
1159 }
1160
1161 /* Find the next register between [start, end) that has a live range starting
1162 * at or after bound by using a binary search.
1163 * start points at the beginning of the search range,
1164 * end points at the element past the end of the search range, and
1165 * the array comprising [start, end) must be sorted in ascending order.
1166 */
1167 static register_merge_record*
1168 find_next_rename(register_merge_record* start, register_merge_record* end, int bound)
1169 {
1170 int delta = (end - start);
1171
1172 while (delta > 0) {
1173 int half = delta >> 1;
1174 register_merge_record* middle = start + half;
1175
1176 if (bound <= middle->begin) {
1177 delta = half;
1178 } else {
1179 start = middle;
1180 ++start;
1181 delta -= half + 1;
1182 }
1183 }
1184
1185 return start;
1186 }
1187
1188 #ifndef USE_STL_SORT
1189 static int register_merge_record_compare (const void *a, const void *b) {
1190 const register_merge_record *aa = static_cast<const register_merge_record*>(a);
1191 const register_merge_record *bb = static_cast<const register_merge_record*>(b);
1192 return aa->begin < bb->begin ? -1 : (aa->begin > bb->begin ? 1 : 0);
1193 }
1194 #endif
1195
1196 /* This functions evaluates the register merges by using a binary
1197 * search to find suitable merge candidates. */
1198 void get_temp_registers_remapping(void *mem_ctx, int ntemps,
1199 const struct register_live_range *live_ranges,
1200 struct rename_reg_pair *result)
1201 {
1202 register_merge_record *reg_access = ralloc_array(mem_ctx, register_merge_record, ntemps);
1203
1204 int used_temps = 0;
1205 for (int i = 0; i < ntemps; ++i) {
1206 if (live_ranges[i].begin >= 0) {
1207 reg_access[used_temps].begin =live_ranges[i].begin;
1208 reg_access[used_temps].end =live_ranges[i].end;
1209 reg_access[used_temps].reg = i;
1210 reg_access[used_temps].erase = false;
1211 ++used_temps;
1212 }
1213 }
1214
1215 #ifdef USE_STL_SORT
1216 std::sort(reg_access, reg_access + used_temps);
1217 #else
1218 std::qsort(reg_access, used_temps, sizeof(register_merge_record),
1219 register_merge_record_compare);
1220 #endif
1221
1222 register_merge_record *trgt = reg_access;
1223 register_merge_record *reg_access_end = reg_access + used_temps;
1224 register_merge_record *first_erase = reg_access_end;
1225 register_merge_record *search_start = trgt + 1;
1226
1227 while (trgt != reg_access_end) {
1228 register_merge_record *src = find_next_rename(search_start, reg_access_end,
1229 trgt->end);
1230 if (src != reg_access_end) {
1231 result[src->reg].new_reg = trgt->reg;
1232 result[src->reg].valid = true;
1233 trgt->end = src->end;
1234
1235 /* Since we only search forward, don't remove the renamed
1236 * register just now, only mark it. */
1237 src->erase = true;
1238
1239 if (first_erase == reg_access_end)
1240 first_erase = src;
1241
1242 search_start = src + 1;
1243 } else {
1244 /* Moving to the next target register it is time to remove
1245 * the already merged registers from the search range */
1246 if (first_erase != reg_access_end) {
1247 register_merge_record *outp = first_erase;
1248 register_merge_record *inp = first_erase + 1;
1249
1250 while (inp != reg_access_end) {
1251 if (!inp->erase)
1252 *outp++ = *inp;
1253 ++inp;
1254 }
1255
1256 reg_access_end = outp;
1257 first_erase = reg_access_end;
1258 }
1259 ++trgt;
1260 search_start = trgt + 1;
1261 }
1262 }
1263 ralloc_free(reg_access);
1264 }
1265
1266 /* Code below used for debugging */
1267 #ifndef NDEBUG
1268 static
1269 void dump_instruction(ostream& os, int line, prog_scope *scope,
1270 const glsl_to_tgsi_instruction& inst)
1271 {
1272 const struct tgsi_opcode_info *info = inst.info;
1273 int indent = scope->nesting_depth();
1274 if ((scope->type() == switch_case_branch ||
1275 scope->type() == switch_default_branch) &&
1276 (info->opcode == TGSI_OPCODE_CASE ||
1277 info->opcode == TGSI_OPCODE_DEFAULT))
1278 --indent;
1279
1280 if (info->opcode == TGSI_OPCODE_ENDIF ||
1281 info->opcode == TGSI_OPCODE_ELSE ||
1282 info->opcode == TGSI_OPCODE_ENDLOOP ||
1283 info->opcode == TGSI_OPCODE_ENDSWITCH)
1284 --indent;
1285
1286 os << setw(4) << line << ": ";
1287 os << setw(indent * 4) << " ";
1288 os << inst << "\n";
1289 }
1290 #endif