<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/65090>65090</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Incorrect branch targets in RISC-V executables built with LTO
</td>
</tr>
<tr>
<th>Labels</th>
<td>
backend:RISC-V,
llvm:codegen,
LTO
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
ilovepi
</td>
</tr>
</table>
<pre>
We're seeing several cases where branch targets are invalid, for example in the middle of another instruction, when building Fuchsia's zircon kernel with `flto=full`. This only seems to occur under `-flto-full`, and both non-LTO and ThinLTO do not seem to have this issue.
Most branches appear to be correct, or at least have valid targets, but in some cases the target isn't the location of a valid instruction. This sounds like it could be related to linker relaxation, but https://discourse.llvm.org/t/riscv-status-of-lto-for-risc-v/58518 isn't clear on the current status of LTO for RISC-V, so it may be related.
I'm working on getting something smaller than our kernel image as a reproducer, but in the meantime I'm providing a snippet from a relevant case. The target for the `bne` instruction is in the middle of another instruction sequence
```
1b2ac8: 1d051363 bne a0,a6,1b2c8e <VmCowPages::AddNewPageLocked(unsigned long, vm_page*, VmCowPages::CanOverwriteContent, VmPageOrMarker*, bool, bool)+0x1ea>
...
1b2c80: 0d000593 li a1,208
1b2c84: 000ac097 auipc ra,0xac
1b2c88: 8a8080e7 jalr -1880(ra) # 25e52c <assert_fail>
fbl::Canary<1447904080u>::Assert() const:
./../../zircon/system/ulib/fbl/include/fbl/canary.h:64
1b2c8c: 030aa783 lw a5,48(s5)
1b2c90: ffea5517 auipc a0,0xffea5
```
https://fxbug.dev/129493 has additional context.
CC: @topperc @MaskRay @asb
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyMVU1v4zwO_jXKhUggy3FiH3LIpBtggM52MVvMHge0TMeayFJWktN0f_2CSppJB-_hLQpbZvjw4yFFYozm4Ig2ovoiqqcZTmnwYWOsP9PJzFrfvW_-Q0KtA0EkMu4Akc4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