一句话:首个大规模实证研究表明,在 C/C++ 中利用未定义行为进行优化带来的端到端性能提升甚微。
C/C++ 将大量情形定义为未定义行为(UB),编译器社区长期认为利用 UB 可实现关键优化,但此前缺乏严格的大规模实证;与此同时,为提升安全性,消除 UB 的呼声渐高。本文首次系统研究利用 UB 优化对 C/C++ 应用性能的影响。作者基于广泛使用 UB 进行优化的 LLVM,在多个 CPU 架构上针对一组基准和 UB 类别进行评测,比较利用与不利用相关 UB 假设时的端到端性能。结果发现,在所评估范围内性能收益很小;少数性能回退情形通常可通过改进优化算法或启用链接时优化恢复。
The C and C++ languages define hundreds of cases as having undefined behavior (UB). These include, for example, corner cases where different CPU architectures disagree on the semantics of an instruction and the language does not want to force a specific implementation (e.g., shift by a value larger than the bitwidth). Another class of UB involves errors that the language chooses not to detect because it would be too expensive or impractical, such as dereferencing out-of-bounds pointers. Although there is a common belief within the compiler community that UB enables certain optimizations that would not be possible otherwise, no rigorous large-scale studies have been conducted on this subject. At the same time, there is growing interest in eliminating UB from programming languages to improve security. In this paper, we present the first comprehensive study that examines the performance impact of exploiting UB in C and C++ applications across multiple CPU architectures. Using LLVM, a compiler known for its extensive use of UB for optimizations, we demonstrate that, for the benchmarks and UB categories that we evaluated, the end-to-end performance gains are minimal. Moreover, when performance regresses, it can often be recovered through small improvements to optimization algorithms or by using link-time optimizations.
@article{paperbot3140,
title = {Exploiting Undefined Behavior in C/C++ Programs for Optimization: A Study on the Performance Impact},
author = {Lucian Popescu and Nuno P. Lopes},
journal = {Proceedings of the ACM on Programming Languages},
volume = {9},
number = {PLDI},
year = {2025},
doi = {10.1145/3729260}
}