llvm / llvm-project

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

[clang-tidy] Check request: detect incorrect usage of `std::bit_cast` #106987

Open carlosgalvezp opened 2 weeks ago

carlosgalvezp commented 2 weeks ago

std::bit_cast is often presented as the correct alternative to type punning in C++. However, we see people use it as a drop-in replacement to reinterpret_cast , which only obfuscates the code and still has UB:

float x{};
-int* y = reinterpret_cast<int*>(&x);
+int* y = std::bit_cast<int*>(&x);

This usage is incorrect. Instead, the code should do:

int y = std::bit_cast<int>(x);

Most likely all usages of std::bit_cast<PointerType> are incorrect.

llvmbot commented 2 weeks ago

@llvm/issue-subscribers-clang-tidy

Author: Carlos Galvez (carlosgalvezp)

`std::bit_cast` is often presented as the correct alternative to type punning in C++. However, we see people use it as a drop-in replacement to `reinterpret_cast` , which only obfuscates the code and still has UB: ```cpp float x{}; -int* y = reinterpret_cast<int*>(&x); +int* y = std::bit_cast<int*>(&x); ``` This usage is incorrect. Instead, the code should do: ```cpp int y = std::bit_cast<int>(x); ``` Most likely all usages of `std::bit_cast<PointerType>` are incorrect.