<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/55225>55225</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
UBSan check optimized away in function marked with __attribute__((const))
</td>
</tr>
<tr>
<th>Labels</th>
<td>
compiler-rt:ubsan,
llvm:optimizations
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
Teemperor
</td>
</tr>
</table>
<pre>
The following reduced example shifts by 2000 (which is clearly UB), but when this happens inside a `__attribute__((const))` function then an optimized program doesn't report this (or fail) with -fsanitize=undefined.
```c++
__attribute__((const))
int getShift() {
return 2000;
}
__attribute__((const))
int hasUB() {
return 1 << getShift();
}
int main() {
return hasUB();
}
```
Example here:
https://godbolt.org/z/dKccK99dd
Note that the `__attribute__((const))` is actually suggested by GCC here for the function containing UB.
```c++
source>: In function 'int hasUB()':
<source>:7:5: warning: function might be candidate for attribute 'const' [-Wsuggest-attribute=const]
7 | int hasUB() {
| ^~~~~
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyNVE1z2yAQ_TX4wtiDsWRbBx1iO-l0MtNLkukxg2Al0WDQAKrr_PousuOoaZNGsxJiWd5-PaicOpb3LdDaGeMO2jbUg-olKAq_xL4zQEOr6xhodaScMUYJXx9aLVuqA5UGhDdH-rAhvCB8S6s-0kMLlsYWl1vRdWAD1TZoBVRQsmSPjyJGr9EQHh8RC0U6G-IAUKABrXsro3YJA4GEpa6Leq-fMaTOu8aLPVUOgiV8FTHYzvl4codQztNaaINI9KBjS6d1EFZH3EwWu94qqLUFNSNsR9jV-btkJ5GEb5IM2v-EOdhoG2kD8S7VZzApKFmd91OMLPbeDjUji7OWrHZj15910oqQKvyOhzkliy3Km1jec5oA90Lbv_EuiCN__0B5qdcY9PrMlRY8VvqsbGPsQprxG5TGqcqZOHO-wdkzvupWytuiUGqM9M1FwHaK1FP4HGGw9ULGXhhkYuibBkJEriBfv2y3Q0RIbj_AXaiFCBFrkOj-sPkEHYLrvcTMrjEd-tW-AiEJ33QINZcKYFfGO9NCnhAOwiff6feCtNdNG2kFVAqrtBLxFPYl-eTqnPiKknwz_X7OdXoxQY6fLPLda0_ReLWlH9AoPclkGPNrshrJnyWZqHKhikUhJlFHA-XD5g6Pp2xBPo0OqTiII_obZSb8E-qHA_lxNye9N-Ub2uCuvppJt8eJMT9fhineBT9A4sYbHUIPAX_ynPN80pYLsV6ILMvUkvFsnWeslhVfswqyrMgqVU2MqMCEEqtIOEfoThvwUx_Ra1_hjYHadJvhMHhcXJ2zEymfkFbz3USXnHHOcsbnc7aas9lc5cu6qNeS5Vles5xkDPCkmVkCSbyf-HIIveqbgItGhxheF0UIurEAQ1iIL_rYOl_eA-w78M5PhjzLIcnfoKq4Xw">