llvm / llvm/llvm-project

Certain floating-point constants and flags cause nominally constant initializers to be executed at runtime

Open
#174,340 9 comments 0 reactions 0 assignees View on GitHub
clang:frontend floating-point missed-optimization
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

I have a program which needs constant static data tables to be constant-initialized so they are available for global constructors and external parsing of the binary. This turns out to break if all of the following are true:
* The initialization also involves an expression which is not constexpr
* The flag `-ftrapping-math` is passed
* A double precision float literal is assigned to a single precision float member

In this case, Clang decides to initialize the data tables with zero in the binary and fill them in at runtime, which is a problem.

I don't know if this is a bug, but it's unexpected and not something GCC does. I've prepared a godbolt example which demonstrates the problem and explains how to mitigate the problem by removing one of the above factors: https://godbolt.org/z/fs8v7h1hx . But I don't think we should have to apply any mitigation and there may be an issue in the compiler.

In the broken case, the table is zero and there's a bunch of extra code:

```
Container::data:
.zero 64
```

In the working case, the table is filled out:

```
Container::data:
.quad .str
.quad 0
.long 0x3ed70a3d
.zero 4
.zero 40
```

Contributor guide

Open the contributing guide

Research direction

Reproduce the Godbolt example with Clang and inspect the generated assembly for Container::data and its runtime initialization. Compare the broken case with variants that remove -ftrapping-math, the non-constexpr expression, or the double-to-single precision assignment. Done means the qualifying initializer is emitted as constant table data rather than zero-filled data with extra runtime code, with a regression test covering the case.

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.