| Issue |
233745
|
| Summary |
[LTO][Passes] Full-LTO post-link pipeline never runs SimpleLoopUnswitch, so loops exposed by link-time inlining keep loop-invariant branches (ThinLTO is fine)
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
psiha
|
A loop whose loop-invariant branch only appears after **link-time (cross-module) inlining** is never unswitched under **full LTO**, because the full-LTO post-link pipeline (`buildLTODefaultPipeline`, `lto<O3>`) contains no `SimpleLoopUnswitch` at all. The same source gets the unswitched loop when the callee body is visible at compile time (unswitched in the O3 pre-link pipeline), and also under ThinLTO (its post-link pipeline runs `simple-loop-unswitch<nontrivial;trivial>`).
Reproduced with the official release builds of clang/lld **22.1.8** and **23.1.3** (x86-64 Linux), and on `opt` trunk via Compiler Explorer.
### Reproducer
A binary search over packed keys whose byte width is a runtime value. `KeyCmp::less` is defined either in the header (`-DIN_HEADER`) or in its own TU.
<details><summary>cmp.h</summary>
```cpp
#pragma once
#include <cstdint>
#include <cstring>
// Compares packed little-endian keys of a runtime byte width.
struct KeyCmp {
std::uint8_t bytes; // key width in bytes
std::uint8_t hiWords; // 8-byte words above the lowest one
std::uint64_t loMask; // bytes of the lowest word that belong to the key
explicit KeyCmp(std::uint8_t n) noexcept
: bytes(n), hiWords(std::uint8_t((n - 1) / 8)),
loMask(~std::uint64_t(0) >> ((8 - (n - 8 * ((n - 1) / 8))) * 8)) {}
static std::uint64_t load(const unsigned char* p, unsigned at) noexcept {
std::uint64_t v; std::memcpy(&v, p + at, 8); return v;
}
bool less(const unsigned char* l, const unsigned char* r) const noexcept
#ifdef IN_HEADER
{
for (std::uint8_t w = 1; w <= hiWords; ++w) {
unsigned at = bytes - 8 * w;
std::uint64_t a = load(l, at), b = load(r, at);
if (a != b) return a < b;
}
return (load(l, 0) & loMask) < (load(r, 0) & loMask);
}
#else
;
#endif
};
```
</details>
<details><summary>less.cpp</summary>
```cpp
#include "cmp.h"
#ifndef IN_HEADER
bool KeyCmp::less(const unsigned char* l, const unsigned char* r) const noexcept {
for (std::uint8_t w = 1; w <= hiWords; ++w) {
unsigned at = bytes - 8 * w;
std::uint64_t a = load(l, at), b = load(r, at);
if (a != b) return a < b;
}
return (load(l, 0) & loMask) < (load(r, 0) & loMask);
}
#endif
```
</details>
<details><summary>search.cpp</summary>
```cpp
#include "cmp.h"
// Binary search over `count` sorted keys of `width` bytes each.
[[gnu::noinline]] bool contains(const unsigned char* keys, std::uint32_t count,
std::uint8_t width, const unsigned char* key) noexcept {
const KeyCmp cmp(width);
std::uint32_t lo = 0, hi = count;
while (lo < hi) {
std::uint32_t mid = lo + (hi - lo) / 2;
if (cmp.less(keys + std::size_t(mid) * width, key)) lo = mid + 1;
else hi = mid;
}
return lo < count && !cmp.less(key, keys + std::size_t(lo) * width);
}
```
</details>
<details><summary>main.cpp (driver)</summary>
```cpp
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <vector>
bool contains(const unsigned char*, std::uint32_t, std::uint8_t, const unsigned char*) noexcept;
int main(int argc, char** argv) {
const std::uint8_t width = argc > 1 ? std::uint8_t(std::atoi(argv[1])) : 4;
const std::uint32_t n = argc > 2 ? std::uint32_t(std::atoi(argv[2])) : 1u << 16;
std::vector<unsigned char> keys(std::size_t(n) * width + 8);
for (std::uint32_t i = 0; i < n; ++i)
for (unsigned b = 0; b < width; ++b)
keys[std::size_t(i) * width + b] = b < 8 ? (unsigned char)((std::uint64_t(i) * 2) >> (8 * b)) : 0;
unsigned char probe[24] = {};
std::uint64_t hits = 0;
for (std::uint32_t rep = 0; rep < 200; ++rep)
for (std::uint32_t q = 0; q < n; ++q) {
std::uint64_t v = (std::uint64_t(q) * 40503u) & (2 * std::uint64_t(n) - 1);
for (unsigned b = 0; b < width; ++b) probe[b] = b < 8 ? (unsigned char)(v >> (8 * b)) : 0;
hits += contains(keys.data(), n, width, probe);
}
std::printf("%llu\n", (unsigned long long)hits);
}
```
</details>
```sh
# body in the header
clang++ -O3 -flto -DIN_HEADER -c search.cpp less.cpp main.cpp && clang++ -O3 -flto -fuse-ld=lld search.o less.o main.o -o hdr
# body in less.cpp, inlined at link time
clang++ -O3 -flto -c search.cpp less.cpp main.cpp && clang++ -O3 -flto -fuse-ld=lld search.o less.o main.o -o cpp
```
### Result (identical for 22.1.8 and 23.1.3)
Static instruction count of `contains` and dynamic instructions executed in it (`valgrind --tool=callgrind --toggle-collect='contains*' ./a.out 4`):
| build | `less` body | `contains` insns | Ir in `contains` |
|---|---|---|---|
| `-flto` | header | 119 | 3,434,085,000 |
| `-flto` | separate TU | 91 | **4,967,635,000** (+45 %) |
| `-flto=thin` | header | 118 | 3,479,960,000 |
| `-flto=thin` | separate TU | 118 | 3,479,960,000 |
| `-flto`, link with `--lto-newpm-passes=` (pipeline below) | separate TU | 114 | 3,447,192,000 |
Header body, full LTO: the one-word case (`bytes < 9`) gets its own loop, with the key's word loaded and masked once before it:
```asm
cmp $0x9,%dl
jae <multi-word loop>
mov (%rax),%rdx ; key word, hoisted
and %r9,%rdx
...
.loop:
mov %r10d,%r11d
sub %ecx,%r11d
shr $1,%r11d
lea (%r11,%rcx,1),%ebx
mov %rbx,%r14
imul %r8,%r14
mov (%rdi,%r14,1),%r14
and %r9,%r14
cmp %rdx,%r14
jae ...
add %r11d,%ecx
inc %ecx
cmp %r10d,%ecx
jb .loop
```
Body in a separate TU, full LTO (`less` is fully inlined, no call remains): the width test stays inside the loop, and the key is reloaded and re-masked every iteration:
```asm
.loop:
mov %r11d,%ebx
sub %r10d,%ebx
shr $1,%ebx
add %r10d,%ebx
mov %rbx,%r14
imul %rcx,%r14
add %rdi,%r14
cmp $0x9,%dl ; loop-invariant width test, every iteration
jb .low
... ; upper-word loop
.low:
mov (%r14),%r14
and %r9,%r14
mov (%rax),%r15 ; key reloaded
and %r9,%r15 ; and re-masked
cmp %r15,%r14
setb %bpl
test %bpl,%bpl
cmove %ebx,%r11d
lea 0x1(%rbx),%ebx
cmovne %ebx,%r10d
cmp %r11d,%r10d
jb .loop
```
The key load cannot be hoisted by LICM on its own, because it is only conditionally executed until the `bytes < 9` branch is unswitched.
### Why
```
$ opt -passes='lto<O3>' -print-pipeline-passes -disable-output x.ll | grep -o 'simple-loop-unswitch<[^>]*>' | sort -u
(nothing)
$ opt -passes='thinlto<O3>' -print-pipeline-passes -disable-output x.ll | grep -o 'simple-loop-unswitch<[^>]*>' | sort -u
simple-loop-unswitch<nontrivial;trivial>
```
Consistent with that, compiling the header variant at `-O2` (where non-trivial unswitching is off in the pre-link pipeline too) gives the same loop as the separate-TU full-LTO build (92 instructions, width test inside the loop; only register allocation differs).
Appending non-trivial unswitching to the full-LTO post-link pipeline restores the header-variant code (last table row):
```
-Xlinker --lto-newpm-passes='lto<O3>,function(loop-mssa(simple-loop-unswitch<nontrivial>),simplifycfg,instcombine,loop-mssa(licm),gvn,simplifycfg)'
```
`opt` trunk on the merged bitcode of `search.cpp` + `less.cpp`, `lto<O3>` vs. the pipeline above (13 vs. 15 blocks in `contains`; only the second has the `.us` loop): https://godbolt.org/z/rnoKaasTz
`[[gnu::always_inline]]` on `less`, `-Wl,-mllvm,-inline-threshold=1000`, `-fwhole-program-vtables` and `-Wl,--lto-O2` do not change the full-LTO result (the call is already inlined; the missing step is the unswitch after it). `-Wl,-mllvm,-enable-nontrivial-unswitch` does not help either, since the pass is not in the pipeline.
Related: #197678 adds a second module inliner plus SROA/SimplifyCFG/LICM late in the full-LTO pipeline, but no loop unswitching; LICM alone does not fix this case (tested: `lto<O3>` followed by simplifycfg, instcombine, LICM and GVN still has no unswitched loop in `contains`).
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs