square:
push rax
test esi, esi
je .LBB0_3
imul edi, esi
mov eax, esi
not eax
lea ecx, [rdi - 2147483648]
or ecx, eax
je .LBB0_2
mov eax, edi
cdq
idiv esi
pop rcx
ret
Is there a way to ask rustc to ignore overflow and div by 0 because we now we will never have it or we don't care in our program? like a game.
Besides using unchecked operations, you could try making the denominator a NonZeroI32. The standard library knows that dividing by one of those does not have to handle division by zero.
I'm pretty sure num.unchecked_mul(fac).checked_div(fac).unwrap_unchecked() compiles down to a single mov like C++. But you really need extra care that it is never invalid.
I think the proper solution for the division in Rust would be to use NonZero and in release mode overflow checks are disabled by default (wrapping arithmetic is used). I'm on my phone, so I'm not going to write it out.
There isn't, and more generally there will never be a flag to rustc that adds UB to safe code (the way -ffast-math makes otherwise-safe things UB in C).
You always have to change the code if you want to introduce UB.
Well, this compiles to just a mov, for example:
use std::num::NonZero;
#[unsafe(no_mangle)]
pub fn square(num: i32, fac: NonZero<i32>) -> i64 {
(num as i64 * fac.get() as i64)/(fac.get() as i64)
}
Or in other words, UB enables additional optimizations compared to the fixed "panic in debug, overflow in release" logic that Rust has by default. At the same time, UB is much too strong because it can propagate beyond the function boundary (which OP may not realize).
It would be sufficient if the compiler could choose the result of overflow and division by zero arbitrarily in each case. But how many real-world optimizations would that enable?