<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/135711>135711</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [BOLT][RISC-V] Segmentation Fault in Rewritten RISC-V Executable Due to Incorrect Symbol Relocation in llvm-bolt
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            BOLT
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          Caroline-zou
      </td>
    </tr>
</table>

<pre>
    llvm-project version: 20.0.0

The issue occurs when attempting to use `llvm-bolt` on the RISC-V architecture to rewrite the SPEC2006INT benchmark. Taking the `400.perlbench` testcase as an example, I compiled the testcase using `clang` with the flags `-march=rv64gcv -fuse-ld=lld -O2 -mabi=lp64d -mrvv-vector-bits=scalable -static -Wl,-q ` . After compilation, I used `llvm-bolt` to rewrite the generated executable. However, a segmentation fault occurred when executing the rewritten binary using `qemu-riscv64`.

Upon debugging, I found that the segmentation fault was caused by a symbol that was not correctly loaded at the faulting address(Let's call it `symbol_a`). Analyzing the debug information produced during `llvm-bolt`'s rewriting process revealed that `symbol_a` was loaded 44 times, but in 6 instances, its address was incorrectly loaded. Since `symbol_a` resides in the `.got` section, its address should be consistent across all references in the code. This inconsistency likely led to the segmentation fault.

Digging deeper, I suspect that a redundant relocation entry might be the root cause of the incorrect address resolution. More specifically, when handling *relocations in bolt/lib/Rewrite/RewriteInstance.cpp*,  the offset at which the segmentation fault was caused has 2 different relocation information, thus will load `handleRelocation` twice. The relocation type for the first time is `R_RISCV_NONE` and the second time is `R_RISCV_GOT_HI20`. The second relocation type is correct.

```
void RewriteInstance::readRelocations(const SectionRef &Section) {
        for (const RelocationRef &Rel : Section.relocations())
        handleRelocation(RelocatedSection, Rel);
}
```

However, I'm unsure at which stage during `llvm-bolt`'s rewriting process this relocation entry is introduced. Understanding this could be key to resolving the issue.
</pre>
<img width="1" height="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