[BPF] Fix a bug in peephole optimization
authorYonghong Song <yhs@fb.com>
Wed, 20 Nov 2019 17:52:29 +0000 (09:52 -0800)
committerYonghong Song <yhs@fb.com>
Wed, 20 Nov 2019 23:19:59 +0000 (15:19 -0800)
commita0841dfe8594f189d79f3612fec019eda4824474
tree005678a38852d201ac221fa7b25e49b3b5169ca1
parentcd8748a15f2d18861b3548eb26ed2b52e5ee50b4
[BPF] Fix a bug in peephole optimization

One of current peephole optimiations is to remove SLL/SRL if
the sub register has been zero extended. This phase has two bugs
and one limitations.

First, for the physical subregister used in pseudo insn COPY
like below, it permits incorrect optimization.
    %0:gpr32 = COPY $w0
    ...
    %4:gpr = MOV_32_64 %0:gpr32
    %5:gpr = SLL_ri %4:gpr(tied-def 0), 32
    %6:gpr = SRA_ri %5:gpr(tied-def 0), 32
The $w0 could be from the return value of a previous function call
and its upper 32-bit value might contain some non-zero values.
The same applies to function arguments.

Second, the current code may permits removing SLL/SRA like below:
    %0:gpr32 = COPY $w0
    %1:gpr32 = COPY %0:gpr32
    ...
    %4:gpr = MOV_32_64 %1:gpr32
    %5:gpr = SLL_ri %4:gpr(tied-def 0), 32
    %6:gpr = SRA_ri %5:gpr(tied-def 0), 32
The reason is that it did not follow def-use chain to skip all
intermediate 32bit-to-32bit COPY instructions.

The current implementation is also very conservative for PHI
instructions. If any PHI insn component is another PHI or COPY insn,
it will just permit SLL/SRA.

This patch fixed the issue as follows:
 - During def/use chain traversal, if any physical register is read,
   SLL/SRA will be preserved as these physical registers are mostly
   from function return values or current function arguments.
 - Recursively visit all COPY and PHI instructions.
llvm/lib/Target/BPF/BPFMIPeephole.cpp
llvm/test/CodeGen/BPF/32-bit-subreg-cond-select.ll
llvm/test/CodeGen/BPF/32-bit-subreg-peephole-phi-1.ll [new file with mode: 0644]
llvm/test/CodeGen/BPF/32-bit-subreg-peephole-phi-2.ll [new file with mode: 0644]
llvm/test/CodeGen/BPF/32-bit-subreg-peephole.ll