Issue 233283
Summary [clang] Address of, or reference to, a global register variable gives invalid IR in C++
Labels clang
Assignees
Reporter Nemi26
    In C++, Clang accepts taking the address of a global register variable, or binding a reference to one, and emits invalid IR. In C, `&sp` is rejected with "address of register variable requested".

```c++
register unsigned long sp asm("rsp");

unsigned long *p() { return &sp; }
const unsigned long &r() { return sp; }

template <class T> unsigned long f(const T &x) { return x; }
unsigned long g() { return f(sp); }
```

With `clang++ -std=c++20 --target=x86_64-unknown-linux-gnu -S -emit-llvm`, `g` passes the register's metadata as a pointer:

```llvm
define dso_local noundef i64 @_Z1gv() {
  %1 = addrspacecast metadata !0 to ptr
  %2 = call noundef i64 @_Z1fImEmRKT_(ptr noundef nonnull align 8 dereferenceable(8) %1)
  ret i64 %2
}
```

and compiling with `-c` crashes the backend:

```
fatal error: error in backend: Cannot select: ... ch = store<(store (s0) into %ir.1)> ..., MDNode:ch<...>, FrameIndex:i64<0>, undef:i64
In function: _Z1pv
```

`std::bit_cast<long>(sp)` and `__builtin_bit_cast(long, sp)` reach the same reference binding, found while working on #231830.

Sema could reject these in C++ as it does in C, or bind a `const` reference to a temporary holding the register's value.

This report was written with the assistance of an AI tool (Claude Code, Claude Opus); I checked the reproducer.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to