llvm-project
90f0ac9d - [BPF] Lower sdiv/smod to libcalls with --bpf-allows-libcalls (#245580)

Commit
3 days ago
[BPF] Lower sdiv/smod to libcalls with --bpf-allows-libcalls (#245580) ### Summary The BPF backend rejects signed division and remainder on targets without native `sdiv/smod` instructions so any code using these operations fails to compile. This restriction exists because the kernel rarely has a use case for signed division/remainder. However, we're using BPF to implement userspace VMs and could perform software expansion of `sdiv/smod` when the corresponding native opcodes are not available. **Rust code snippet** ``` #[unsafe(no_mangle)] pub fn entrypoint(input: *mut u8) -> u64 { unsafe { let a = core::ptr::read_unaligned(input as *const i64); let b = core::ptr::read_unaligned(input.add(8) as *const i64); a.checked_div(b).unwrap_or(0) as u64 } } ``` **C code snippet** ``` #include <stdint.h> uint64_t entrypoint(uint8_t *input) { int64_t a, b; __builtin_memcpy(&a, input, sizeof(a)); __builtin_memcpy(&b, input + 8, sizeof(b)); return (uint64_t)(a / b); } ``` **Error** ``` error: <unknown>:0:0: in function entrypoint i64 (ptr): unsupported signed division, please convert to unsigned div/mod. ``` **Fix** Register `ISD::SDIV`/`ISD::SREM` as `Expand` instead of `Custom` on targets without native `sdiv/smod` when `--bpf-allows-libcalls` is set. LLVM then falls back to the generic legalization path and emits `__divdi3`/`__divsi3` for `sdiv` and `__moddi3`/`__modsi3` for `smod` instead of erroring out. This applies to targets without native signed division/remainder: v1/v2/v3, or v4/v5 with `--disable-sdiv-smod`. v4/v5 without the `--disable-sdiv-smod` flag keep emitting the native instructions, and without `--bpf-allows-libcalls` the error is unchanged. --- *Alternative considered:* `ISD::SDIV/ISD::SREM` could always be expanded to libcalls without checking `BPFAllowsLibcalls`. This would also allow us to remove the `LowerSDIVSREM` function. ``` if (!STI.hasSdivSmod()) { setOperationAction(ISD::SDIV, VT, Expand); setOperationAction(ISD::SREM, VT, Expand); } ``` However, without the `--bpf-allows-libcalls` flag, the error would come from the whitelist check in `LowerCall`: "A call to built-in function '__divdi3' is not supported." instead of the existing "unsupported signed division" error. The current fix preserves the existing error message.
Author
Parents
Loading