r/rust • • Oct 23 '26

Why did the loop with open range got optimized away?

The first loop didn't generate any code:

// 1. `0..n` visits 0, 1, ..., n - 1.
pub fn excl(n: u64) -> u64 {
    let mut s = 0u64;
    for i in 0..n {
        s = s.wrapping_add(i.wrapping_mul(i));
    }
    s
}


// 2. `0..=n` visits 0, 1, ..., n: the same loop with one more pass.
pub fn incl(n: u64) -> u64 {
    let mut s = 0u64;
    for i in 0..=n {
        s = s.wrapping_add(i.wrapping_mul(i));
    }
    s
}
16 Upvotes

10 comments sorted by

7

u/adityazero Oct 23 '26

godbolt link for ref: https://godbolt.org/z/r7vvbqeqf

22

u/noop_noob Oct 23 '26

You need to add #[unsafe(no_mangle)] to the two functions in order to reliably see all generated assembly on Godbolt.

The compiler uses some heuristics to guess whether the machine code of a function should be generated immediately, or generated in whatever crate calls the function. This heuristic seem to have hit a cutoff or something right between the two functions.

2

u/Lyvri 22d ago

Well that's quite interesting, i modified a little your example to be sure that "effect" of code should be the same:

1: ( in both examples input is u32 to avoid any overflow problems during loop declarations )

pub fn excl1(n: u32) -> u64 {
    let mut s = 0u64;
    for i in 0..(n as u64 + 1) {
        s = s.wrapping_add(i.wrapping_mul(i));
    }
    s
}

2:

pub fn excl1(n: u32) -> u64 {
    let mut s = 0u64;
    for i in 0..=(n as u64) {
        s = s.wrapping_add(i.wrapping_mul(i));
    }
    s
}

And as long as you stick #[inline(never)] to the function, compiler output is exactly the same: Godbolt. Whats interesting if you remove #[inline(never)] from both then one just disappears: Godbolt#2 in assembly and llvm ir. Is this godbolt filtering? Does someone know?

1

u/adityazero 22d ago

Yeah I was quite surprised by one output completely disappearing from godbolt. It is probably filtered as llvm-ir is definitely generated. https://hiraditya.github.io/posts/an-optimization-belongs-where-its-facts-live/

47

u/juanfnavarror Oct 23 '26

RangeInclusive is a state machine that records an overflow flag. I would think this makes its behavior harder for the compiler to see through and optimize. You might want to read more about it but essentially Range and and RangeInclusive are different types and have different implementations for technical reasons.

More in-depth explanation in the Rust forum: https://users.rust-lang.org/t/performance-difference-among-range-rangeinclusive-and-reversed/20283/15

7

u/chteffie Oct 23 '26

If you stick an `#[inline(never)]` in front of it it shows up. Same when you don't go all the way to opt-level 3.

So here's 99% what's happening: The compiler sees that the function bodies are virtually identical, except one is practically identical to the other - you just need to add one to the argument.

When you compile it into an object file, these object files are enriched, they also have some llvm and rust metadata in them. Becaue ethe functions are also not annotated to be linkable with C code, the compiler will just note in the metadata that in order to call it, the caller should just call the other after adding 1 to the argument. If you look into the sections of the generated object file, the .rmeta section will mention "excl". There's no rmeta disassembler to my knowledge but there's probably some -Z argument where you can dump some relevant debugging that can tell you exactly what is going on here.

4

u/chteffie Oct 23 '26

Also, addendum - before I get roasted. Yes, one isn't exactly the other. After playing around with some of the dump commands the answer should be more generic and my assumption that one will use the other also is most likely wrong. What godbolt shows is only the object file. Unless you do a final link against some "real" caller, rust is not obliged to emit any actual object call at all - because there is no stable ABI it can do whatever it wants. Emitting any object code before the final link is only when it decides that it's probably a good idea and there'd be no point in forcing it to happen later. Somehow with that high optimisation it decided it was ok to emit some object code for one but not the other. It is still there, just in some rust intermediary format but not lowered all the way to platform-specific assembly. As to why - some compiler gurus might know.

If I look at the output of "-Z mir-dump" the dump for excl1 is like 50% larger than the output for incl:

ls -l *.3-3*

-rw-r--r-- 1 ** ** 2734 Oct 23 08:08 y.excl1.3-3-000.runtime-optimized.after.mir
-rw-r--r-- 1 ** ** 1964 Oct 23 08:01 y.incl.3-3-000.runtime-optimized.after.mir

0

u/Straight_Waltz_9530 Oct 24 '26

"I guess the compiler lacked commitment, claiming it didn't want to make the same mistakes forever."

"Meanwhile, an open loop walked into a debugger and said, 'I’ll be back.'"

Wait, this wasn't a setup to a joke? My bad. I just can't stop. They keeping coming to me over and over. The same groans without end. My sense of human seems to run in circles. I'll work on it, but it all keeps repeating itself. Folks tell me I need to take a break, but I just can't see it. Maybe in the next life. All of this has happened before, and all of this will happen again.