• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2012 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 
24 /** @file elk_fs_copy_propagation.cpp
25  *
26  * Support for global copy propagation in two passes: A local pass that does
27  * intra-block copy (and constant) propagation, and a global pass that uses
28  * dataflow analysis on the copies available at the end of each block to re-do
29  * local copy propagation with more copies available.
30  *
31  * See Muchnick's Advanced Compiler Design and Implementation, section
32  * 12.5 (p356).
33  */
34 
35 #include "util/bitset.h"
36 #include "util/u_math.h"
37 #include "util/rb_tree.h"
38 #include "elk_fs.h"
39 #include "elk_fs_live_variables.h"
40 #include "elk_cfg.h"
41 #include "elk_eu.h"
42 
43 using namespace elk;
44 
45 namespace { /* avoid conflict with opt_copy_propagation_elements */
46 struct acp_entry {
47    struct rb_node by_dst;
48    struct rb_node by_src;
49    elk_fs_reg dst;
50    elk_fs_reg src;
51    unsigned global_idx;
52    unsigned size_written;
53    unsigned size_read;
54    enum elk_opcode opcode;
55    bool is_partial_write;
56    bool force_writemask_all;
57 };
58 
59 /**
60  * Compare two acp_entry::src.nr
61  *
62  * This is intended to be used as the comparison function for rb_tree.
63  */
64 static int
cmp_entry_dst_entry_dst(const struct rb_node * a_node,const struct rb_node * b_node)65 cmp_entry_dst_entry_dst(const struct rb_node *a_node, const struct rb_node *b_node)
66 {
67    const struct acp_entry *a_entry =
68       rb_node_data(struct acp_entry, a_node, by_dst);
69 
70    const struct acp_entry *b_entry =
71       rb_node_data(struct acp_entry, b_node, by_dst);
72 
73    return a_entry->dst.nr - b_entry->dst.nr;
74 }
75 
76 static int
cmp_entry_dst_nr(const struct rb_node * a_node,const void * b_key)77 cmp_entry_dst_nr(const struct rb_node *a_node, const void *b_key)
78 {
79    const struct acp_entry *a_entry =
80       rb_node_data(struct acp_entry, a_node, by_dst);
81 
82    return a_entry->dst.nr - (uintptr_t) b_key;
83 }
84 
85 static int
cmp_entry_src_entry_src(const struct rb_node * a_node,const struct rb_node * b_node)86 cmp_entry_src_entry_src(const struct rb_node *a_node, const struct rb_node *b_node)
87 {
88    const struct acp_entry *a_entry =
89       rb_node_data(struct acp_entry, a_node, by_src);
90 
91    const struct acp_entry *b_entry =
92       rb_node_data(struct acp_entry, b_node, by_src);
93 
94    return a_entry->src.nr - b_entry->src.nr;
95 }
96 
97 /**
98  * Compare an acp_entry::src.nr with a raw nr.
99  *
100  * This is intended to be used as the comparison function for rb_tree.
101  */
102 static int
cmp_entry_src_nr(const struct rb_node * a_node,const void * b_key)103 cmp_entry_src_nr(const struct rb_node *a_node, const void *b_key)
104 {
105    const struct acp_entry *a_entry =
106       rb_node_data(struct acp_entry, a_node, by_src);
107 
108    return a_entry->src.nr - (uintptr_t) b_key;
109 }
110 
111 class acp_forward_iterator {
112 public:
acp_forward_iterator(struct rb_node * n,unsigned offset)113    acp_forward_iterator(struct rb_node *n, unsigned offset)
114       : curr(n), next(nullptr), offset(offset)
115    {
116       next = rb_node_next_or_null(curr);
117    }
118 
operator ++()119    acp_forward_iterator &operator++()
120    {
121       curr = next;
122       next = rb_node_next_or_null(curr);
123 
124       return *this;
125    }
126 
operator !=(const acp_forward_iterator & other) const127    bool operator!=(const acp_forward_iterator &other) const
128    {
129       return curr != other.curr;
130    }
131 
operator *() const132    struct acp_entry *operator*() const
133    {
134       /* This open-codes part of rb_node_data. */
135       return curr != NULL ? (struct acp_entry *)(((char *)curr) - offset)
136                           : NULL;
137    }
138 
139 private:
140    struct rb_node *curr;
141    struct rb_node *next;
142    unsigned offset;
143 };
144 
145 struct acp {
146    DECLARE_LINEAR_ALLOC_CXX_OPERATORS(acp);
147 
148    struct rb_tree by_dst;
149    struct rb_tree by_src;
150 
acp__anon4a7ce22c0111::acp151    acp()
152    {
153       rb_tree_init(&by_dst);
154       rb_tree_init(&by_src);
155    }
156 
begin__anon4a7ce22c0111::acp157    acp_forward_iterator begin()
158    {
159       return acp_forward_iterator(rb_tree_first(&by_src),
160                                   rb_tree_offsetof(struct acp_entry, by_src, 0));
161    }
162 
end__anon4a7ce22c0111::acp163    const acp_forward_iterator end() const
164    {
165       return acp_forward_iterator(nullptr, 0);
166    }
167 
length__anon4a7ce22c0111::acp168    unsigned length()
169    {
170       unsigned l = 0;
171 
172       for (rb_node *iter = rb_tree_first(&by_src);
173            iter != NULL; iter = rb_node_next(iter))
174          l++;
175 
176       return l;
177    }
178 
add__anon4a7ce22c0111::acp179    void add(acp_entry *entry)
180    {
181       rb_tree_insert(&by_dst, &entry->by_dst, cmp_entry_dst_entry_dst);
182       rb_tree_insert(&by_src, &entry->by_src, cmp_entry_src_entry_src);
183    }
184 
remove__anon4a7ce22c0111::acp185    void remove(acp_entry *entry)
186    {
187       rb_tree_remove(&by_dst, &entry->by_dst);
188       rb_tree_remove(&by_src, &entry->by_src);
189    }
190 
find_by_src__anon4a7ce22c0111::acp191    acp_forward_iterator find_by_src(unsigned nr)
192    {
193       struct rb_node *rbn = rb_tree_search(&by_src,
194                                            (void *)(uintptr_t) nr,
195                                            cmp_entry_src_nr);
196 
197       return acp_forward_iterator(rbn, rb_tree_offsetof(struct acp_entry,
198                                                         by_src, rbn));
199    }
200 
find_by_dst__anon4a7ce22c0111::acp201    acp_forward_iterator find_by_dst(unsigned nr)
202    {
203       struct rb_node *rbn = rb_tree_search(&by_dst,
204                                            (void *)(uintptr_t) nr,
205                                            cmp_entry_dst_nr);
206 
207       return acp_forward_iterator(rbn, rb_tree_offsetof(struct acp_entry,
208                                                         by_dst, rbn));
209    }
210 };
211 
212 struct block_data {
213    /**
214     * Which entries in the fs_copy_prop_dataflow acp table are live at the
215     * start of this block.  This is the useful output of the analysis, since
216     * it lets us plug those into the local copy propagation on the second
217     * pass.
218     */
219    BITSET_WORD *livein;
220 
221    /**
222     * Which entries in the fs_copy_prop_dataflow acp table are live at the end
223     * of this block.  This is done in initial setup from the per-block acps
224     * returned by the first local copy prop pass.
225     */
226    BITSET_WORD *liveout;
227 
228    /**
229     * Which entries in the fs_copy_prop_dataflow acp table are generated by
230     * instructions in this block which reach the end of the block without
231     * being killed.
232     */
233    BITSET_WORD *copy;
234 
235    /**
236     * Which entries in the fs_copy_prop_dataflow acp table are killed over the
237     * course of this block.
238     */
239    BITSET_WORD *kill;
240 
241    /**
242     * Which entries in the fs_copy_prop_dataflow acp table are guaranteed to
243     * have a fully uninitialized destination at the end of this block.
244     */
245    BITSET_WORD *undef;
246 
247    /**
248     * Which entries in the fs_copy_prop_dataflow acp table can the
249     * start of this block be reached from.  Note that this is a weaker
250     * condition than livein.
251     */
252    BITSET_WORD *reachin;
253 
254    /**
255     * Which entries in the fs_copy_prop_dataflow acp table are
256     * overwritten by an instruction with channel masks inconsistent
257     * with the copy instruction (e.g. due to force_writemask_all).
258     * Such an overwrite can cause the copy entry to become invalid
259     * even if the copy instruction is subsequently re-executed for any
260     * given channel i, since the execution of the overwrite for
261     * channel i may corrupt other channels j!=i inactive for the
262     * subsequent copy.
263     */
264    BITSET_WORD *exec_mismatch;
265 };
266 
267 class fs_copy_prop_dataflow
268 {
269 public:
270    fs_copy_prop_dataflow(linear_ctx *lin_ctx, elk_cfg_t *cfg,
271                          const fs_live_variables &live,
272                          struct acp *out_acp);
273 
274    void setup_initial_values();
275    void run();
276 
277    void dump_block_data() const UNUSED;
278 
279    elk_cfg_t *cfg;
280    const fs_live_variables &live;
281 
282    acp_entry **acp;
283    int num_acp;
284    int bitset_words;
285 
286   struct block_data *bd;
287 };
288 } /* anonymous namespace */
289 
fs_copy_prop_dataflow(linear_ctx * lin_ctx,elk_cfg_t * cfg,const fs_live_variables & live,struct acp * out_acp)290 fs_copy_prop_dataflow::fs_copy_prop_dataflow(linear_ctx *lin_ctx, elk_cfg_t *cfg,
291                                              const fs_live_variables &live,
292                                              struct acp *out_acp)
293    : cfg(cfg), live(live)
294 {
295    bd = linear_zalloc_array(lin_ctx, struct block_data, cfg->num_blocks);
296 
297    num_acp = 0;
298    foreach_block (block, cfg)
299       num_acp += out_acp[block->num].length();
300 
301    bitset_words = BITSET_WORDS(num_acp);
302 
303    foreach_block (block, cfg) {
304       bd[block->num].livein = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
305       bd[block->num].liveout = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
306       bd[block->num].copy = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
307       bd[block->num].kill = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
308       bd[block->num].undef = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
309       bd[block->num].reachin = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
310       bd[block->num].exec_mismatch = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
311    }
312 
313    acp = linear_zalloc_array(lin_ctx, struct acp_entry *, num_acp);
314 
315    int next_acp = 0;
316    foreach_block (block, cfg) {
317       for (auto iter = out_acp[block->num].begin();
318            iter != out_acp[block->num].end(); ++iter) {
319          acp[next_acp] = *iter;
320 
321          (*iter)->global_idx = next_acp;
322 
323          /* opt_copy_propagation_local populates out_acp with copies created
324           * in a block which are still live at the end of the block.  This
325           * is exactly what we want in the COPY set.
326           */
327          BITSET_SET(bd[block->num].copy, next_acp);
328 
329          next_acp++;
330       }
331    }
332 
333    assert(next_acp == num_acp);
334 
335    setup_initial_values();
336    run();
337 }
338 
339 /**
340  * Like reg_offset, but register must be VGRF or FIXED_GRF.
341  */
342 static inline unsigned
grf_reg_offset(const elk_fs_reg & r)343 grf_reg_offset(const elk_fs_reg &r)
344 {
345    return (r.file == VGRF ? 0 : r.nr) * REG_SIZE +
346           r.offset +
347           (r.file == FIXED_GRF ? r.subnr : 0);
348 }
349 
350 /**
351  * Like regions_overlap, but register must be VGRF or FIXED_GRF.
352  */
353 static inline bool
grf_regions_overlap(const elk_fs_reg & r,unsigned dr,const elk_fs_reg & s,unsigned ds)354 grf_regions_overlap(const elk_fs_reg &r, unsigned dr, const elk_fs_reg &s, unsigned ds)
355 {
356    return reg_space(r) == reg_space(s) &&
357           !(grf_reg_offset(r) + dr <= grf_reg_offset(s) ||
358             grf_reg_offset(s) + ds <= grf_reg_offset(r));
359 }
360 
361 /**
362  * Set up initial values for each of the data flow sets, prior to running
363  * the fixed-point algorithm.
364  */
365 void
setup_initial_values()366 fs_copy_prop_dataflow::setup_initial_values()
367 {
368    /* Initialize the COPY and KILL sets. */
369    {
370       struct acp acp_table;
371 
372       /* First, get all the KILLs for instructions which overwrite ACP
373        * destinations.
374        */
375       for (int i = 0; i < num_acp; i++)
376          acp_table.add(acp[i]);
377 
378       foreach_block (block, cfg) {
379          foreach_inst_in_block(elk_fs_inst, inst, block) {
380             if (inst->dst.file != VGRF &&
381                 inst->dst.file != FIXED_GRF)
382                continue;
383 
384             for (auto iter = acp_table.find_by_src(inst->dst.nr);
385               iter != acp_table.end() && (*iter)->src.nr == inst->dst.nr;
386               ++iter) {
387                if (grf_regions_overlap(inst->dst, inst->size_written,
388                                        (*iter)->src, (*iter)->size_read)) {
389                   BITSET_SET(bd[block->num].kill, (*iter)->global_idx);
390                   if (inst->force_writemask_all && !(*iter)->force_writemask_all)
391                      BITSET_SET(bd[block->num].exec_mismatch, (*iter)->global_idx);
392                }
393             }
394 
395             if (inst->dst.file != VGRF)
396                continue;
397 
398             for (auto iter = acp_table.find_by_dst(inst->dst.nr);
399               iter != acp_table.end() && (*iter)->dst.nr == inst->dst.nr;
400               ++iter) {
401                if (grf_regions_overlap(inst->dst, inst->size_written,
402                                        (*iter)->dst, (*iter)->size_written)) {
403                   BITSET_SET(bd[block->num].kill, (*iter)->global_idx);
404                   if (inst->force_writemask_all && !(*iter)->force_writemask_all)
405                      BITSET_SET(bd[block->num].exec_mismatch, (*iter)->global_idx);
406                }
407             }
408          }
409       }
410    }
411 
412    /* Populate the initial values for the livein and liveout sets.  For the
413     * block at the start of the program, livein = 0 and liveout = copy.
414     * For the others, set liveout and livein to ~0 (the universal set).
415     */
416    foreach_block (block, cfg) {
417       if (block->parents.is_empty()) {
418          for (int i = 0; i < bitset_words; i++) {
419             bd[block->num].livein[i] = 0u;
420             bd[block->num].liveout[i] = bd[block->num].copy[i];
421          }
422       } else {
423          for (int i = 0; i < bitset_words; i++) {
424             bd[block->num].liveout[i] = ~0u;
425             bd[block->num].livein[i] = ~0u;
426          }
427       }
428    }
429 
430    /* Initialize the undef set. */
431    foreach_block (block, cfg) {
432       for (int i = 0; i < num_acp; i++) {
433          BITSET_SET(bd[block->num].undef, i);
434          for (unsigned off = 0; off < acp[i]->size_written; off += REG_SIZE) {
435             if (BITSET_TEST(live.block_data[block->num].defout,
436                             live.var_from_reg(byte_offset(acp[i]->dst, off))))
437                BITSET_CLEAR(bd[block->num].undef, i);
438          }
439       }
440    }
441 }
442 
443 /**
444  * Walk the set of instructions in the block, marking which entries in the acp
445  * are killed by the block.
446  */
447 void
run()448 fs_copy_prop_dataflow::run()
449 {
450    bool progress;
451 
452    do {
453       progress = false;
454 
455       foreach_block (block, cfg) {
456          if (block->parents.is_empty())
457             continue;
458 
459          for (int i = 0; i < bitset_words; i++) {
460             const BITSET_WORD old_liveout = bd[block->num].liveout[i];
461             const BITSET_WORD old_reachin = bd[block->num].reachin[i];
462             BITSET_WORD livein_from_any_block = 0;
463 
464             /* Update livein for this block.  If a copy is live out of all
465              * parent blocks, it's live coming in to this block.
466              */
467             bd[block->num].livein[i] = ~0u;
468             foreach_list_typed(elk_bblock_link, parent_link, link, &block->parents) {
469                elk_bblock_t *parent = parent_link->block;
470                /* Consider ACP entries with a known-undefined destination to
471                 * be available from the parent.  This is valid because we're
472                 * free to set the undefined variable equal to the source of
473                 * the ACP entry without breaking the application's
474                 * expectations, since the variable is undefined.
475                 */
476                bd[block->num].livein[i] &= (bd[parent->num].liveout[i] |
477                                             bd[parent->num].undef[i]);
478                livein_from_any_block |= bd[parent->num].liveout[i];
479 
480                /* Update reachin for this block.  If the end of any
481                 * parent block is reachable from the copy, the start
482                 * of this block is reachable from it as well.
483                 */
484                bd[block->num].reachin[i] |= (bd[parent->num].reachin[i] |
485                                              bd[parent->num].copy[i]);
486             }
487 
488             /* Limit to the set of ACP entries that can possibly be available
489              * at the start of the block, since propagating from a variable
490              * which is guaranteed to be undefined (rather than potentially
491              * undefined for some dynamic control-flow paths) doesn't seem
492              * particularly useful.
493              */
494             bd[block->num].livein[i] &= livein_from_any_block;
495 
496             /* Update liveout for this block. */
497             bd[block->num].liveout[i] =
498                bd[block->num].copy[i] | (bd[block->num].livein[i] &
499                                          ~bd[block->num].kill[i]);
500 
501             if (old_liveout != bd[block->num].liveout[i] ||
502                 old_reachin != bd[block->num].reachin[i])
503                progress = true;
504          }
505       }
506    } while (progress);
507 
508    /* Perform a second fixed-point pass in order to propagate the
509     * exec_mismatch bitsets.  Note that this requires an accurate
510     * value of the reachin bitsets as input, which isn't available
511     * until the end of the first propagation pass, so this loop cannot
512     * be folded into the previous one.
513     */
514    do {
515       progress = false;
516 
517       foreach_block (block, cfg) {
518          for (int i = 0; i < bitset_words; i++) {
519             const BITSET_WORD old_exec_mismatch = bd[block->num].exec_mismatch[i];
520 
521             /* Update exec_mismatch for this block.  If the end of a
522              * parent block is reachable by an overwrite with
523              * inconsistent execution masking, the start of this block
524              * is reachable by such an overwrite as well.
525              */
526             foreach_list_typed(elk_bblock_link, parent_link, link, &block->parents) {
527                elk_bblock_t *parent = parent_link->block;
528                bd[block->num].exec_mismatch[i] |= (bd[parent->num].exec_mismatch[i] &
529                                                    bd[parent->num].reachin[i]);
530             }
531 
532             /* Only consider overwrites with inconsistent execution
533              * masking if they are reachable from the copy, since
534              * overwrites unreachable from a copy are harmless to that
535              * copy.
536              */
537             bd[block->num].exec_mismatch[i] &= bd[block->num].reachin[i];
538             if (old_exec_mismatch != bd[block->num].exec_mismatch[i])
539                progress = true;
540          }
541       }
542    } while (progress);
543 }
544 
545 void
dump_block_data() const546 fs_copy_prop_dataflow::dump_block_data() const
547 {
548    foreach_block (block, cfg) {
549       fprintf(stderr, "Block %d [%d, %d] (parents ", block->num,
550              block->start_ip, block->end_ip);
551       foreach_list_typed(elk_bblock_link, link, link, &block->parents) {
552          elk_bblock_t *parent = link->block;
553          fprintf(stderr, "%d ", parent->num);
554       }
555       fprintf(stderr, "):\n");
556       fprintf(stderr, "       livein = 0x");
557       for (int i = 0; i < bitset_words; i++)
558          fprintf(stderr, "%08x", bd[block->num].livein[i]);
559       fprintf(stderr, ", liveout = 0x");
560       for (int i = 0; i < bitset_words; i++)
561          fprintf(stderr, "%08x", bd[block->num].liveout[i]);
562       fprintf(stderr, ",\n       copy   = 0x");
563       for (int i = 0; i < bitset_words; i++)
564          fprintf(stderr, "%08x", bd[block->num].copy[i]);
565       fprintf(stderr, ", kill    = 0x");
566       for (int i = 0; i < bitset_words; i++)
567          fprintf(stderr, "%08x", bd[block->num].kill[i]);
568       fprintf(stderr, "\n");
569    }
570 }
571 
572 static bool
is_logic_op(enum elk_opcode opcode)573 is_logic_op(enum elk_opcode opcode)
574 {
575    return (opcode == ELK_OPCODE_AND ||
576            opcode == ELK_OPCODE_OR  ||
577            opcode == ELK_OPCODE_XOR ||
578            opcode == ELK_OPCODE_NOT);
579 }
580 
581 static bool
can_take_stride(elk_fs_inst * inst,elk_reg_type dst_type,unsigned arg,unsigned stride,const struct elk_compiler * compiler)582 can_take_stride(elk_fs_inst *inst, elk_reg_type dst_type,
583                 unsigned arg, unsigned stride,
584                 const struct elk_compiler *compiler)
585 {
586    const struct intel_device_info *devinfo = compiler->devinfo;
587 
588    if (stride > 4)
589       return false;
590 
591    /* Bail if the channels of the source need to be aligned to the byte offset
592     * of the corresponding channel of the destination, and the provided stride
593     * would break this restriction.
594     */
595    if (has_dst_aligned_region_restriction(devinfo, inst, dst_type) &&
596        !(type_sz(inst->src[arg].type) * stride ==
597            type_sz(dst_type) * inst->dst.stride ||
598          stride == 0))
599       return false;
600 
601    /* 3-source instructions can only be Align16, which restricts what strides
602     * they can take. They can only take a stride of 1 (the usual case), or 0
603     * with a special "repctrl" bit. But the repctrl bit doesn't work for
604     * 64-bit datatypes, so if the source type is 64-bit then only a stride of
605     * 1 is allowed. From the Broadwell PRM, Volume 7 "3D Media GPGPU", page
606     * 944:
607     *
608     *    This is applicable to 32b datatypes and 16b datatype. 64b datatypes
609     *    cannot use the replicate control.
610     */
611    if (inst->elk_is_3src(compiler)) {
612       if (type_sz(inst->src[arg].type) > 4)
613          return stride == 1;
614       else
615          return stride == 1 || stride == 0;
616    }
617 
618    /* From the Broadwell PRM, Volume 2a "Command Reference - Instructions",
619     * page 391 ("Extended Math Function"):
620     *
621     *     The following restrictions apply for align1 mode: Scalar source is
622     *     supported. Source and destination horizontal stride must be the
623     *     same.
624     *
625     * From the Haswell PRM Volume 2b "Command Reference - Instructions", page
626     * 134 ("Extended Math Function"):
627     *
628     *    Scalar source is supported. Source and destination horizontal stride
629     *    must be 1.
630     *
631     * and similar language exists for IVB and SNB. Pre-SNB, math instructions
632     * are sends, so the sources are moved to MRF's and there are no
633     * restrictions.
634     */
635    if (inst->is_math()) {
636       if (devinfo->ver == 6 || devinfo->ver == 7) {
637          assert(inst->dst.stride == 1);
638          return stride == 1 || stride == 0;
639       } else if (devinfo->ver >= 8) {
640          return stride == inst->dst.stride || stride == 0;
641       }
642    }
643 
644    return true;
645 }
646 
647 static bool
instruction_requires_packed_data(elk_fs_inst * inst)648 instruction_requires_packed_data(elk_fs_inst *inst)
649 {
650    switch (inst->opcode) {
651    case ELK_FS_OPCODE_DDX_FINE:
652    case ELK_FS_OPCODE_DDX_COARSE:
653    case ELK_FS_OPCODE_DDY_FINE:
654    case ELK_FS_OPCODE_DDY_COARSE:
655    case ELK_SHADER_OPCODE_QUAD_SWIZZLE:
656       return true;
657    default:
658       return false;
659    }
660 }
661 
662 static bool
try_copy_propagate(const elk_compiler * compiler,elk_fs_inst * inst,acp_entry * entry,int arg,const elk::simple_allocator & alloc)663 try_copy_propagate(const elk_compiler *compiler, elk_fs_inst *inst,
664                    acp_entry *entry, int arg,
665                    const elk::simple_allocator &alloc)
666 {
667    if (inst->src[arg].file != VGRF)
668       return false;
669 
670    const struct intel_device_info *devinfo = compiler->devinfo;
671 
672    assert(entry->src.file == VGRF || entry->src.file == UNIFORM ||
673           entry->src.file == ATTR || entry->src.file == FIXED_GRF);
674 
675    /* Avoid propagating a LOAD_PAYLOAD instruction into another if there is a
676     * good chance that we'll be able to eliminate the latter through register
677     * coalescing.  If only part of the sources of the second LOAD_PAYLOAD can
678     * be simplified through copy propagation we would be making register
679     * coalescing impossible, ending up with unnecessary copies in the program.
680     * This is also the case for is_multi_copy_payload() copies that can only
681     * be coalesced when the instruction is lowered into a sequence of MOVs.
682     *
683     * Worse -- In cases where the ACP entry was the result of CSE combining
684     * multiple LOAD_PAYLOAD subexpressions, propagating the first LOAD_PAYLOAD
685     * into the second would undo the work of CSE, leading to an infinite
686     * optimization loop.  Avoid this by detecting LOAD_PAYLOAD copies from CSE
687     * temporaries which should match is_coalescing_payload().
688     */
689    if (entry->opcode == ELK_SHADER_OPCODE_LOAD_PAYLOAD &&
690        (is_coalescing_payload(alloc, inst) || is_multi_copy_payload(inst)))
691       return false;
692 
693    assert(entry->dst.file == VGRF);
694    if (inst->src[arg].nr != entry->dst.nr)
695       return false;
696 
697    /* Bail if inst is reading a range that isn't contained in the range
698     * that entry is writing.
699     */
700    if (!region_contained_in(inst->src[arg], inst->size_read(arg),
701                             entry->dst, entry->size_written))
702       return false;
703 
704    /* Send messages with EOT set are restricted to use g112-g127 (and we
705     * sometimes need g127 for other purposes), so avoid copy propagating
706     * anything that would make it impossible to satisfy that restriction.
707     */
708    if (inst->eot) {
709       /* Avoid propagating a FIXED_GRF register, as that's already pinned. */
710       if (entry->src.file == FIXED_GRF)
711          return false;
712 
713       /* We might be propagating from a large register, while the SEND only
714        * is reading a portion of it (say the .A channel in an RGBA value).
715        * We need to pin both split SEND sources in g112-g126/127, so only
716        * allow this if the registers aren't too large.
717        */
718       if (inst->opcode == ELK_SHADER_OPCODE_SEND && entry->src.file == VGRF) {
719          unsigned prop_src_size = alloc.sizes[entry->src.nr];
720          if (prop_src_size > 15)
721             return false;
722       }
723    }
724 
725    /* Avoid propagating odd-numbered FIXED_GRF registers into the first source
726     * of a LINTERP instruction on platforms where the PLN instruction has
727     * register alignment restrictions.
728     */
729    if (devinfo->has_pln && devinfo->ver <= 6 &&
730        entry->src.file == FIXED_GRF && (entry->src.nr & 1) &&
731        inst->opcode == ELK_FS_OPCODE_LINTERP && arg == 0)
732       return false;
733 
734    /* we can't generally copy-propagate UD negations because we
735     * can end up accessing the resulting values as signed integers
736     * instead. See also resolve_ud_negate() and comment in
737     * elk_fs_generator::generate_code.
738     */
739    if (entry->src.type == ELK_REGISTER_TYPE_UD &&
740        entry->src.negate)
741       return false;
742 
743    bool has_source_modifiers = entry->src.abs || entry->src.negate;
744 
745    if (has_source_modifiers && !inst->can_do_source_mods(devinfo))
746       return false;
747 
748    /* Reject cases that would violate register regioning restrictions. */
749    if ((entry->src.file == UNIFORM || !entry->src.is_contiguous()) &&
750        ((devinfo->ver == 6 && inst->is_math()) ||
751         inst->is_send_from_grf() ||
752         inst->uses_indirect_addressing())) {
753       return false;
754    }
755 
756    if (has_source_modifiers &&
757        inst->opcode == ELK_SHADER_OPCODE_GFX4_SCRATCH_WRITE)
758       return false;
759 
760    /* Some instructions implemented in the generator backend, such as
761     * derivatives, assume that their operands are packed so we can't
762     * generally propagate strided regions to them.
763     */
764    const unsigned entry_stride = (entry->src.file == FIXED_GRF ? 1 :
765                                   entry->src.stride);
766    if (instruction_requires_packed_data(inst) && entry_stride != 1)
767       return false;
768 
769    const elk_reg_type dst_type = (has_source_modifiers &&
770                                   entry->dst.type != inst->src[arg].type) ?
771       entry->dst.type : inst->dst.type;
772 
773    /* Bail if the result of composing both strides would exceed the
774     * hardware limit.
775     */
776    if (!can_take_stride(inst, dst_type, arg,
777                         entry_stride * inst->src[arg].stride,
778                         compiler))
779       return false;
780 
781    /* From the Cherry Trail/Braswell PRMs, Volume 7: 3D Media GPGPU:
782     *    EU Overview
783     *       Register Region Restrictions
784     *          Special Requirements for Handling Double Precision Data Types :
785     *
786     *   "When source or destination datatype is 64b or operation is integer
787     *    DWord multiply, regioning in Align1 must follow these rules:
788     *
789     *      1. Source and Destination horizontal stride must be aligned to the
790     *         same qword.
791     *      2. Regioning must ensure Src.Vstride = Src.Width * Src.Hstride.
792     *      3. Source and Destination offset must be the same, except the case
793     *         of scalar source."
794     *
795     * Most of this is already checked in can_take_stride(), we're only left
796     * with checking 3.
797     */
798    if (has_dst_aligned_region_restriction(devinfo, inst, dst_type) &&
799        entry_stride != 0 &&
800        (reg_offset(inst->dst) % REG_SIZE) != (reg_offset(entry->src) % REG_SIZE))
801       return false;
802 
803    /* Bail if the source FIXED_GRF region of the copy cannot be trivially
804     * composed with the source region of the instruction -- E.g. because the
805     * copy uses some extended stride greater than 4 not supported natively by
806     * the hardware as a horizontal stride, or because instruction compression
807     * could require us to use a vertical stride shorter than a GRF.
808     */
809    if (entry->src.file == FIXED_GRF &&
810        (inst->src[arg].stride > 4 ||
811         inst->dst.component_size(inst->exec_size) >
812         inst->src[arg].component_size(inst->exec_size)))
813       return false;
814 
815    /* Bail if the instruction type is larger than the execution type of the
816     * copy, what implies that each channel is reading multiple channels of the
817     * destination of the copy, and simply replacing the sources would give a
818     * program with different semantics.
819     */
820    if ((type_sz(entry->dst.type) < type_sz(inst->src[arg].type) ||
821         entry->is_partial_write) &&
822        inst->opcode != ELK_OPCODE_MOV) {
823       return false;
824    }
825 
826    /* Bail if the result of composing both strides cannot be expressed
827     * as another stride. This avoids, for example, trying to transform
828     * this:
829     *
830     *     MOV (8) rX<1>UD rY<0;1,0>UD
831     *     FOO (8) ...     rX<8;8,1>UW
832     *
833     * into this:
834     *
835     *     FOO (8) ...     rY<0;1,0>UW
836     *
837     * Which would have different semantics.
838     */
839    if (entry_stride != 1 &&
840        (inst->src[arg].stride *
841         type_sz(inst->src[arg].type)) % type_sz(entry->src.type) != 0)
842       return false;
843 
844    /* Since semantics of source modifiers are type-dependent we need to
845     * ensure that the meaning of the instruction remains the same if we
846     * change the type. If the sizes of the types are different the new
847     * instruction will read a different amount of data than the original
848     * and the semantics will always be different.
849     */
850    if (has_source_modifiers &&
851        entry->dst.type != inst->src[arg].type &&
852        (!inst->can_change_types() ||
853         type_sz(entry->dst.type) != type_sz(inst->src[arg].type)))
854       return false;
855 
856    if (devinfo->ver >= 8 && (entry->src.negate || entry->src.abs) &&
857        is_logic_op(inst->opcode)) {
858       return false;
859    }
860 
861    /* Save the offset of inst->src[arg] relative to entry->dst for it to be
862     * applied later.
863     */
864    const unsigned rel_offset = inst->src[arg].offset - entry->dst.offset;
865 
866    /* Fold the copy into the instruction consuming it. */
867    inst->src[arg].file = entry->src.file;
868    inst->src[arg].nr = entry->src.nr;
869    inst->src[arg].subnr = entry->src.subnr;
870    inst->src[arg].offset = entry->src.offset;
871 
872    /* Compose the strides of both regions. */
873    if (entry->src.file == FIXED_GRF) {
874       if (inst->src[arg].stride) {
875          const unsigned orig_width = 1 << entry->src.width;
876          const unsigned reg_width = REG_SIZE / (type_sz(inst->src[arg].type) *
877                                                 inst->src[arg].stride);
878          inst->src[arg].width = cvt(MIN2(orig_width, reg_width)) - 1;
879          inst->src[arg].hstride = cvt(inst->src[arg].stride);
880          inst->src[arg].vstride = inst->src[arg].hstride + inst->src[arg].width;
881       } else {
882          inst->src[arg].vstride = inst->src[arg].hstride =
883             inst->src[arg].width = 0;
884       }
885 
886       inst->src[arg].stride = 1;
887 
888       /* Hopefully no Align16 around here... */
889       assert(entry->src.swizzle == ELK_SWIZZLE_XYZW);
890       inst->src[arg].swizzle = entry->src.swizzle;
891    } else {
892       inst->src[arg].stride *= entry->src.stride;
893    }
894 
895    /* Compute the first component of the copy that the instruction is
896     * reading, and the base byte offset within that component.
897     */
898    assert((entry->dst.offset % REG_SIZE == 0 || inst->opcode == ELK_OPCODE_MOV) &&
899            entry->dst.stride == 1);
900    const unsigned component = rel_offset / type_sz(entry->dst.type);
901    const unsigned suboffset = rel_offset % type_sz(entry->dst.type);
902 
903    /* Calculate the byte offset at the origin of the copy of the given
904     * component and suboffset.
905     */
906    inst->src[arg] = byte_offset(inst->src[arg],
907       component * entry_stride * type_sz(entry->src.type) + suboffset);
908 
909    if (has_source_modifiers) {
910       if (entry->dst.type != inst->src[arg].type) {
911          /* We are propagating source modifiers from a MOV with a different
912           * type.  If we got here, then we can just change the source and
913           * destination types of the instruction and keep going.
914           */
915          for (int i = 0; i < inst->sources; i++) {
916             inst->src[i].type = entry->dst.type;
917          }
918          inst->dst.type = entry->dst.type;
919       }
920 
921       if (!inst->src[arg].abs) {
922          inst->src[arg].abs = entry->src.abs;
923          inst->src[arg].negate ^= entry->src.negate;
924       }
925    }
926 
927    return true;
928 }
929 
930 
931 static bool
try_constant_propagate(const elk_compiler * compiler,elk_fs_inst * inst,acp_entry * entry,int arg)932 try_constant_propagate(const elk_compiler *compiler, elk_fs_inst *inst,
933                        acp_entry *entry, int arg)
934 {
935    const struct intel_device_info *devinfo = compiler->devinfo;
936    bool progress = false;
937 
938    if (type_sz(entry->src.type) > 4)
939       return false;
940 
941    if (inst->src[arg].file != VGRF)
942       return false;
943 
944    assert(entry->dst.file == VGRF);
945    if (inst->src[arg].nr != entry->dst.nr)
946       return false;
947 
948    /* Bail if inst is reading a range that isn't contained in the range
949     * that entry is writing.
950     */
951    if (!region_contained_in(inst->src[arg], inst->size_read(arg),
952                             entry->dst, entry->size_written))
953       return false;
954 
955    /* If the size of the use type is larger than the size of the entry
956     * type, the entry doesn't contain all of the data that the user is
957     * trying to use.
958     */
959    if (type_sz(inst->src[arg].type) > type_sz(entry->dst.type))
960       return false;
961 
962    elk_fs_reg val = entry->src;
963 
964    /* If the size of the use type is smaller than the size of the entry,
965     * clamp the value to the range of the use type.  This enables constant
966     * copy propagation in cases like
967     *
968     *
969     *    mov(8)          g12<1>UD        0x0000000cUD
970     *    ...
971     *    mul(8)          g47<1>D         g86<8,8,1>D     g12<16,8,2>W
972     */
973    if (type_sz(inst->src[arg].type) < type_sz(entry->dst.type)) {
974       if (type_sz(inst->src[arg].type) != 2 || type_sz(entry->dst.type) != 4)
975          return false;
976 
977       assert(inst->src[arg].subnr == 0 || inst->src[arg].subnr == 2);
978 
979       /* When subnr is 0, we want the lower 16-bits, and when it's 2, we
980        * want the upper 16-bits. No other values of subnr are valid for a
981        * UD source.
982        */
983       const uint16_t v = inst->src[arg].subnr == 2 ? val.ud >> 16 : val.ud;
984 
985       val.ud = v | (uint32_t(v) << 16);
986    }
987 
988    val.type = inst->src[arg].type;
989 
990    if (inst->src[arg].abs) {
991       if ((devinfo->ver >= 8 && is_logic_op(inst->opcode)) ||
992           !elk_abs_immediate(val.type, &val.as_elk_reg())) {
993          return false;
994       }
995    }
996 
997    if (inst->src[arg].negate) {
998       if ((devinfo->ver >= 8 && is_logic_op(inst->opcode)) ||
999           !elk_negate_immediate(val.type, &val.as_elk_reg())) {
1000          return false;
1001       }
1002    }
1003 
1004    switch (inst->opcode) {
1005    case ELK_OPCODE_MOV:
1006    case ELK_SHADER_OPCODE_LOAD_PAYLOAD:
1007    case ELK_FS_OPCODE_PACK:
1008       inst->src[arg] = val;
1009       progress = true;
1010       break;
1011 
1012    case ELK_SHADER_OPCODE_POW:
1013       /* Allow constant propagation into src1 (except on Gen 6 which
1014        * doesn't support scalar source math), and let constant combining
1015        * promote the constant on Gen < 8.
1016        */
1017       if (devinfo->ver == 6)
1018          break;
1019 
1020       if (arg == 1) {
1021          inst->src[arg] = val;
1022          progress = true;
1023       }
1024       break;
1025 
1026    case ELK_OPCODE_SUBB:
1027       if (arg == 1) {
1028          inst->src[arg] = val;
1029          progress = true;
1030       }
1031       break;
1032 
1033    case ELK_OPCODE_MACH:
1034    case ELK_OPCODE_MUL:
1035    case ELK_SHADER_OPCODE_MULH:
1036    case ELK_OPCODE_ADD:
1037    case ELK_OPCODE_XOR:
1038    case ELK_OPCODE_ADDC:
1039       if (arg == 1) {
1040          inst->src[arg] = val;
1041          progress = true;
1042       } else if (arg == 0 && inst->src[1].file != IMM) {
1043          /* Don't copy propagate the constant in situations like
1044           *
1045           *    mov(8)          g8<1>D          0x7fffffffD
1046           *    mul(8)          g16<1>D         g8<8,8,1>D      g15<16,8,2>W
1047           *
1048           * On platforms that only have a 32x16 multiplier, this will
1049           * result in lowering the multiply to
1050           *
1051           *    mul(8)          g15<1>D         g14<8,8,1>D     0xffffUW
1052           *    mul(8)          g16<1>D         g14<8,8,1>D     0x7fffUW
1053           *    add(8)          g15.1<2>UW      g15.1<16,8,2>UW g16<16,8,2>UW
1054           *
1055           * On Gfx8 and Gfx9, which have the full 32x32 multiplier, it
1056           * results in
1057           *
1058           *    mul(8)          g16<1>D         g15<16,8,2>W    0x7fffffffD
1059           *
1060           * Volume 2a of the Skylake PRM says:
1061           *
1062           *    When multiplying a DW and any lower precision integer, the
1063           *    DW operand must on src0.
1064           */
1065          if (inst->opcode == ELK_OPCODE_MUL &&
1066              type_sz(inst->src[1].type) < 4 &&
1067              type_sz(val.type) == 4)
1068             break;
1069 
1070          /* Fit this constant in by commuting the operands.
1071           * Exception: we can't do this for 32-bit integer MUL/MACH
1072           * because it's asymmetric.
1073           *
1074           * The BSpec says for Broadwell that
1075           *
1076           *    "When multiplying DW x DW, the dst cannot be accumulator."
1077           *
1078           * Integer MUL with a non-accumulator destination will be lowered
1079           * by lower_integer_multiplication(), so don't restrict it.
1080           */
1081          if (((inst->opcode == ELK_OPCODE_MUL &&
1082                inst->dst.is_accumulator()) ||
1083               inst->opcode == ELK_OPCODE_MACH) &&
1084              (inst->src[1].type == ELK_REGISTER_TYPE_D ||
1085               inst->src[1].type == ELK_REGISTER_TYPE_UD))
1086             break;
1087          inst->src[0] = inst->src[1];
1088          inst->src[1] = val;
1089          progress = true;
1090       }
1091       break;
1092 
1093    case ELK_OPCODE_CMP:
1094    case ELK_OPCODE_IF:
1095       if (arg == 1) {
1096          inst->src[arg] = val;
1097          progress = true;
1098       } else if (arg == 0 && inst->src[1].file != IMM) {
1099          enum elk_conditional_mod new_cmod;
1100 
1101          new_cmod = elk_swap_cmod(inst->conditional_mod);
1102          if (new_cmod != ELK_CONDITIONAL_NONE) {
1103             /* Fit this constant in by swapping the operands and
1104              * flipping the test
1105              */
1106             inst->src[0] = inst->src[1];
1107             inst->src[1] = val;
1108             inst->conditional_mod = new_cmod;
1109             progress = true;
1110          }
1111       }
1112       break;
1113 
1114    case ELK_OPCODE_SEL:
1115       if (arg == 1) {
1116          inst->src[arg] = val;
1117          progress = true;
1118       } else if (arg == 0) {
1119          if (inst->src[1].file != IMM &&
1120              (inst->conditional_mod == ELK_CONDITIONAL_NONE ||
1121               /* Only GE and L are commutative. */
1122               inst->conditional_mod == ELK_CONDITIONAL_GE ||
1123               inst->conditional_mod == ELK_CONDITIONAL_L)) {
1124             inst->src[0] = inst->src[1];
1125             inst->src[1] = val;
1126 
1127             /* If this was predicated, flipping operands means
1128              * we also need to flip the predicate.
1129              */
1130             if (inst->conditional_mod == ELK_CONDITIONAL_NONE) {
1131                inst->predicate_inverse =
1132                   !inst->predicate_inverse;
1133             }
1134          } else {
1135             inst->src[0] = val;
1136          }
1137 
1138          progress = true;
1139       }
1140       break;
1141 
1142    case ELK_FS_OPCODE_FB_WRITE_LOGICAL:
1143       /* The omask source of ELK_FS_OPCODE_FB_WRITE_LOGICAL is
1144        * bit-cast using a strided region so they cannot be immediates.
1145        */
1146       if (arg != FB_WRITE_LOGICAL_SRC_OMASK) {
1147          inst->src[arg] = val;
1148          progress = true;
1149       }
1150       break;
1151 
1152    case ELK_SHADER_OPCODE_INT_QUOTIENT:
1153    case ELK_SHADER_OPCODE_INT_REMAINDER:
1154       /* Allow constant propagation into either source (except on Gen 6
1155        * which doesn't support scalar source math). Constant combining
1156        * promote the src1 constant on Gen < 8, and it will promote the src0
1157        * constant on all platforms.
1158        */
1159       if (devinfo->ver == 6)
1160          break;
1161 
1162       FALLTHROUGH;
1163    case ELK_OPCODE_AND:
1164    case ELK_OPCODE_ASR:
1165    case ELK_OPCODE_BFE:
1166    case ELK_OPCODE_BFI1:
1167    case ELK_OPCODE_BFI2:
1168    case ELK_OPCODE_SHL:
1169    case ELK_OPCODE_SHR:
1170    case ELK_OPCODE_OR:
1171    case ELK_SHADER_OPCODE_TEX_LOGICAL:
1172    case ELK_SHADER_OPCODE_TXD_LOGICAL:
1173    case ELK_SHADER_OPCODE_TXF_LOGICAL:
1174    case ELK_SHADER_OPCODE_TXL_LOGICAL:
1175    case ELK_SHADER_OPCODE_TXS_LOGICAL:
1176    case ELK_FS_OPCODE_TXB_LOGICAL:
1177    case ELK_SHADER_OPCODE_TXF_CMS_LOGICAL:
1178    case ELK_SHADER_OPCODE_TXF_CMS_W_LOGICAL:
1179    case ELK_SHADER_OPCODE_TXF_CMS_W_GFX12_LOGICAL:
1180    case ELK_SHADER_OPCODE_TXF_UMS_LOGICAL:
1181    case ELK_SHADER_OPCODE_TXF_MCS_LOGICAL:
1182    case ELK_SHADER_OPCODE_LOD_LOGICAL:
1183    case ELK_SHADER_OPCODE_TG4_LOGICAL:
1184    case ELK_SHADER_OPCODE_TG4_OFFSET_LOGICAL:
1185    case ELK_SHADER_OPCODE_SAMPLEINFO_LOGICAL:
1186    case ELK_SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
1187    case ELK_SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
1188    case ELK_SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
1189    case ELK_SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
1190    case ELK_SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
1191    case ELK_SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
1192    case ELK_SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
1193    case ELK_SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
1194    case ELK_SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
1195    case ELK_FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
1196    case ELK_SHADER_OPCODE_BROADCAST:
1197    case ELK_OPCODE_MAD:
1198    case ELK_OPCODE_LRP:
1199    case ELK_FS_OPCODE_PACK_HALF_2x16_SPLIT:
1200    case ELK_SHADER_OPCODE_SHUFFLE:
1201       inst->src[arg] = val;
1202       progress = true;
1203       break;
1204 
1205    default:
1206       break;
1207    }
1208 
1209    return progress;
1210 }
1211 
1212 static bool
can_propagate_from(elk_fs_inst * inst)1213 can_propagate_from(elk_fs_inst *inst)
1214 {
1215    return (inst->opcode == ELK_OPCODE_MOV &&
1216            inst->dst.file == VGRF &&
1217            ((inst->src[0].file == VGRF &&
1218              !grf_regions_overlap(inst->dst, inst->size_written,
1219                                   inst->src[0], inst->size_read(0))) ||
1220             inst->src[0].file == ATTR ||
1221             inst->src[0].file == UNIFORM ||
1222             inst->src[0].file == IMM ||
1223             (inst->src[0].file == FIXED_GRF &&
1224              inst->src[0].is_contiguous())) &&
1225            inst->src[0].type == inst->dst.type &&
1226            !inst->saturate &&
1227            /* Subset of !is_partial_write() conditions. */
1228            !inst->predicate && inst->dst.is_contiguous()) ||
1229           is_identity_payload(FIXED_GRF, inst);
1230 }
1231 
1232 /* Walks a basic block and does copy propagation on it using the acp
1233  * list.
1234  */
1235 static bool
opt_copy_propagation_local(const elk_compiler * compiler,linear_ctx * lin_ctx,elk_bblock_t * block,struct acp & acp,const elk::simple_allocator & alloc)1236 opt_copy_propagation_local(const elk_compiler *compiler, linear_ctx *lin_ctx,
1237                            elk_bblock_t *block, struct acp &acp,
1238                            const elk::simple_allocator &alloc)
1239 {
1240    bool progress = false;
1241 
1242    foreach_inst_in_block(elk_fs_inst, inst, block) {
1243       /* Try propagating into this instruction. */
1244       bool instruction_progress = false;
1245       for (int i = inst->sources - 1; i >= 0; i--) {
1246          if (inst->src[i].file != VGRF)
1247             continue;
1248 
1249          for (auto iter = acp.find_by_dst(inst->src[i].nr);
1250               iter != acp.end() && (*iter)->dst.nr == inst->src[i].nr;
1251               ++iter) {
1252             if ((*iter)->src.file == IMM) {
1253                if (try_constant_propagate(compiler, inst, *iter, i)) {
1254                   instruction_progress = true;
1255                   break;
1256                }
1257             } else {
1258                if (try_copy_propagate(compiler, inst, *iter, i, alloc)) {
1259                   instruction_progress = true;
1260                   break;
1261                }
1262             }
1263          }
1264       }
1265 
1266       if (instruction_progress) {
1267          progress = true;
1268 
1269          /* If only one of the sources of a 2-source, commutative instruction (e.g.,
1270           * AND) is immediate, it must be src1. If both are immediate, opt_algebraic
1271           * should fold it away.
1272           */
1273          if (inst->sources == 2 && inst->is_commutative() &&
1274              inst->src[0].file == IMM && inst->src[1].file != IMM) {
1275             const auto src1 = inst->src[1];
1276             inst->src[1] = inst->src[0];
1277             inst->src[0] = src1;
1278          }
1279       }
1280 
1281       /* kill the destination from the ACP */
1282       if (inst->dst.file == VGRF || inst->dst.file == FIXED_GRF) {
1283          for (auto iter = acp.find_by_dst(inst->dst.nr);
1284               iter != acp.end() && (*iter)->dst.nr == inst->dst.nr;
1285               ++iter) {
1286             if (grf_regions_overlap((*iter)->dst, (*iter)->size_written,
1287                                     inst->dst, inst->size_written))
1288                acp.remove(*iter);
1289          }
1290 
1291          for (auto iter = acp.find_by_src(inst->dst.nr);
1292               iter != acp.end() && (*iter)->src.nr == inst->dst.nr;
1293               ++iter) {
1294             /* Make sure we kill the entry if this instruction overwrites
1295              * _any_ of the registers that it reads
1296              */
1297             if (grf_regions_overlap((*iter)->src, (*iter)->size_read,
1298                                     inst->dst, inst->size_written))
1299                acp.remove(*iter);
1300          }
1301       }
1302 
1303       /* If this instruction's source could potentially be folded into the
1304        * operand of another instruction, add it to the ACP.
1305        */
1306       if (can_propagate_from(inst)) {
1307          acp_entry *entry = linear_zalloc(lin_ctx, acp_entry);
1308          entry->dst = inst->dst;
1309          entry->src = inst->src[0];
1310          entry->size_written = inst->size_written;
1311          for (unsigned i = 0; i < inst->sources; i++)
1312             entry->size_read += inst->size_read(i);
1313          entry->opcode = inst->opcode;
1314          entry->is_partial_write = inst->is_partial_write();
1315          entry->force_writemask_all = inst->force_writemask_all;
1316          acp.add(entry);
1317       } else if (inst->opcode == ELK_SHADER_OPCODE_LOAD_PAYLOAD &&
1318                  inst->dst.file == VGRF) {
1319          int offset = 0;
1320          for (int i = 0; i < inst->sources; i++) {
1321             int effective_width = i < inst->header_size ? 8 : inst->exec_size;
1322             const unsigned size_written = effective_width *
1323                                           type_sz(inst->src[i].type);
1324             if (inst->src[i].file == VGRF ||
1325                 (inst->src[i].file == FIXED_GRF &&
1326                  inst->src[i].is_contiguous())) {
1327                const elk_reg_type t = i < inst->header_size ?
1328                   ELK_REGISTER_TYPE_UD : inst->src[i].type;
1329                elk_fs_reg dst = byte_offset(retype(inst->dst, t), offset);
1330                if (!dst.equals(inst->src[i])) {
1331                   acp_entry *entry = linear_zalloc(lin_ctx, acp_entry);
1332                   entry->dst = dst;
1333                   entry->src = retype(inst->src[i], t);
1334                   entry->size_written = size_written;
1335                   entry->size_read = inst->size_read(i);
1336                   entry->opcode = inst->opcode;
1337                   entry->force_writemask_all = inst->force_writemask_all;
1338                   acp.add(entry);
1339                }
1340             }
1341             offset += size_written;
1342          }
1343       }
1344    }
1345 
1346    return progress;
1347 }
1348 
1349 bool
opt_copy_propagation()1350 elk_fs_visitor::opt_copy_propagation()
1351 {
1352    bool progress = false;
1353    void *copy_prop_ctx = ralloc_context(NULL);
1354    linear_ctx *lin_ctx = linear_context(copy_prop_ctx);
1355    struct acp *out_acp = new (lin_ctx) acp[cfg->num_blocks];
1356 
1357    const fs_live_variables &live = live_analysis.require();
1358 
1359    /* First, walk through each block doing local copy propagation and getting
1360     * the set of copies available at the end of the block.
1361     */
1362    foreach_block (block, cfg) {
1363       progress = opt_copy_propagation_local(compiler, lin_ctx, block,
1364                                             out_acp[block->num], alloc) || progress;
1365 
1366       /* If the destination of an ACP entry exists only within this block,
1367        * then there's no need to keep it for dataflow analysis.  We can delete
1368        * it from the out_acp table and avoid growing the bitsets any bigger
1369        * than we absolutely have to.
1370        *
1371        * Because nothing in opt_copy_propagation_local touches the block
1372        * start/end IPs and opt_copy_propagation_local is incapable of
1373        * extending the live range of an ACP destination beyond the block,
1374        * it's safe to use the liveness information in this way.
1375        */
1376       for (auto iter = out_acp[block->num].begin();
1377            iter != out_acp[block->num].end(); ++iter) {
1378          assert((*iter)->dst.file == VGRF);
1379          if (block->start_ip <= live.vgrf_start[(*iter)->dst.nr] &&
1380              live.vgrf_end[(*iter)->dst.nr] <= block->end_ip) {
1381             out_acp[block->num].remove(*iter);
1382          }
1383       }
1384    }
1385 
1386    /* Do dataflow analysis for those available copies. */
1387    fs_copy_prop_dataflow dataflow(lin_ctx, cfg, live, out_acp);
1388 
1389    /* Next, re-run local copy propagation, this time with the set of copies
1390     * provided by the dataflow analysis available at the start of a block.
1391     */
1392    foreach_block (block, cfg) {
1393       struct acp in_acp;
1394 
1395       for (int i = 0; i < dataflow.num_acp; i++) {
1396          if (BITSET_TEST(dataflow.bd[block->num].livein, i) &&
1397              !BITSET_TEST(dataflow.bd[block->num].exec_mismatch, i)) {
1398             struct acp_entry *entry = dataflow.acp[i];
1399             in_acp.add(entry);
1400          }
1401       }
1402 
1403       progress = opt_copy_propagation_local(compiler, lin_ctx, block,
1404                                             in_acp, alloc) ||
1405                  progress;
1406    }
1407 
1408    ralloc_free(copy_prop_ctx);
1409 
1410    if (progress)
1411       invalidate_analysis(DEPENDENCY_INSTRUCTION_DATA_FLOW |
1412                           DEPENDENCY_INSTRUCTION_DETAIL);
1413 
1414    return progress;
1415 }
1416