BPF: avoid NE/EQ loop exit condition
authorYonghong Song <yhs@fb.com>
Sat, 31 Jul 2021 20:29:00 +0000 (13:29 -0700)
committerYonghong Song <yhs@fb.com>
Wed, 4 Aug 2021 23:54:16 +0000 (16:54 -0700)
commite52946b9ababcbf8e6f40b1b15900ae2e795a1c6
treee4d1dd8fd648c0872789b737ef4294adee597e2e
parent50264ff88ab1ed40119f13d482b0cc8326c1e95d
BPF: avoid NE/EQ loop exit condition

Kuniyuki Iwashima reported in [1] that llvm compiler may
convert a loop exit condition with "i < bound" to "i != bound", where
"i" is the loop index variable and "bound" is the upper bound.
In case that "bound" is not a constant, verifier will always have "i != bound"
true, which will cause verifier failure since to verifier this is
an infinite loop.

The fix is to avoid transforming "i < bound" to "i != bound".
In llvm, the transformation is done by IndVarSimplify pass.
The compiler checks loop condition cost (i = i + 1) and if the
cost is lower, it may transform "i < bound" to "i != bound".
This patch implemented getArithmeticInstrCost() in BPF TargetTransformInfo
class to return a higher cost for such an operation, which
will prevent the transformation for the test case
added in this patch.

 [1] https://lore.kernel.org/netdev/1994df05-8f01-371f-3c3b-d33d7836878c@fb.com/

Differential Revision: https://reviews.llvm.org/D107483
llvm/lib/Target/BPF/BPFTargetTransformInfo.h
llvm/test/CodeGen/BPF/loop-exit-cond.ll [new file with mode: 0644]