llvm / llvm/llvm-project

[Clang] const objects can be assumed to be immutable

Open
#160,441 1 comment 0 reactions 0 assignees View on GitHub
clang:codegen missed-optimization
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

According to both C and C++ standards, object defined with const is not allowed to be modified in any way(UB), thus can be assumed to be immutable.

However, currently clang/llvm doens't utilize it for optimization unless the initializer of the object is constant expression:
```c
// https://godbolt.org/z/6qe8vEK15
void f(const int *p);

int t1()
{
const int x = 5;
f(&x);

return x;
}

int t2(int y)
{
const int x = y;
f(&x);

return x;
}
```
For t1, clang optimizes the load away.
For t2, clang doesn't.

There are a similar GCC bug report: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80794, from which I copy the title.

#59694 may be related.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.