llvm / llvm/llvm-project

[clang] [codegen] unexpected codegen when struct is returned from a function or when struct has specific field order

Open
#162,031 0 comments 0 reactions 0 assignees View on GitHub
clang
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

clang 21.1 x86-64 -O3
https://godbolt.org/z/3WY37brEY simplified case where f1 codegen is expected to match f2. Define `FIX1` to make the codegen match, or define `FIX2`.

`FIX1` changes the struct field order so that the bool does not occur as the last field.
`FIX2` changes struct creation is returned from a function rather than constructed in the function f2.

Full code:
```cpp
void act(unsigned);

// baseline
void f1(unsigned stop)
{
auto i = 0;
do {
act(i);
++i;
} while ( i != stop );
}

struct Iter
{
#ifdef FIX1
bool done = false;
unsigned i = 0;
unsigned stop;
#else
unsigned i = 0;
unsigned stop;
bool done = false; // codegen can differ when last field
#endif

explicit constexpr Iter(unsigned stop) noexcept
: stop(stop) {}

constexpr bool more() const noexcept { return !done; }

constexpr unsigned front() const noexcept { return i; }

constexpr void popFront() noexcept
{
++i;
done = i == stop;
}
};

// codegen can differ when Iter is returned from a function
constexpr Iter mkIter(unsigned stop) noexcept
{
return Iter(stop);
}

// does not match f1
// define FIX1 to match f1
// define FIX2 to match f1
void f2(unsigned stop)
{
#ifdef FIX2
auto r = Iter(stop);
#else
auto r = mkIter(stop);
#endif
for ( ; r.more(); r.popFront() ) {
act(r.front());
}
}
```

Contributor guide

Open the contributing guide

Research direction

Reproduce the provided C++ case with clang 21.1 on x86-64 at -O3, using the Godbolt link as the starting point. Compare f1 and f2, then repeat with FIX1 and FIX2 to isolate the code-generation difference; done when the cause is identified and the relevant code-generation behavior is covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.