llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.58k stars 11.81k forks source link

Clang omits variable with "used" attribute #91262

Open pogo59 opened 5 months ago

pogo59 commented 5 months ago

GCC specifies the "used" attribute as:

This attribute, attached to a variable with static storage, means that the variable must be emitted even if it appears that the variable is not referenced.

Inside a constant "if" condition, clang will fail to emit a "used" variable in the not-taken branch. This differs from GCC behavior.

void foo() {
  if (sizeof(double) == sizeof(long double)) {
    __attribute__((used)) static int my_item(__LINE__);
  } else {
    __attribute__((used)) static int my_item(__LINE__);
  }
}

Clang allocates only one variable, GCC allocates both. Given it's a GCC-defined attribute, we should behave the way GCC does. This appears to be a Clang codegen bug, as -emit-llvm -disable-llvm-passes shows only one item.

(Why would I need this? It's part of the instrumentation for my Rotten Green Tests project. My static variables are actually allocated into a custom section, but that's not needed to trigger the bug.)

llvmbot commented 5 months ago

@llvm/issue-subscribers-clang-codegen

Author: Paul T Robinson (pogo59)

[GCC](https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html) specifies the "used" attribute as: > This attribute, attached to a variable with static storage, means that the variable must be emitted even if it appears that the variable is not referenced. Inside a constant "if" condition, clang will fail to emit a "used" variable in the not-taken branch. This differs from GCC behavior. ``` void foo() { if (sizeof(double) == sizeof(long double)) { __attribute__((used)) static int my_item(__LINE__); } else { __attribute__((used)) static int my_item(__LINE__); } } ``` Clang allocates only one variable, GCC allocates both. Given it's a GCC-defined attribute, we should behave the way GCC does. This appears to be a Clang codegen bug, as `-emit-llvm -disable-llvm-passes` shows only one item. (Why would I need this? It's part of the instrumentation for my Rotten Green Tests project. My static variables are actually allocated into a custom section, but that's not needed to trigger the bug.)
efriedma-quic commented 5 months ago

See also https://github.com/llvm/llvm-project/issues/82994#issuecomment-1979503984 . (Not the same issue, but it's in the same part of the implementation.)