[llvm] [BOLT][RISCV] Handle cross-fragment branches in split functions (PR #223958)

via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 16 03:43:23 PDT 2026


https://github.com/Thrrreeee updated https://github.com/llvm/llvm-project/pull/223958

>From 110f9d631428b7fc3a4563c67785f350bb10bfcc Mon Sep 17 00:00:00 2001
From: shijinrui <shijinrui at bytedance.com>
Date: Wed, 16 Sep 2026 18:42:56 +0800
Subject: [PATCH] [BOLT][RISCV] Handle cross-fragment branches in split
 functions

---
 bolt/include/bolt/Core/MCPlusBuilder.h        |   6 +
 bolt/include/bolt/Passes/RISCVLongJmpPass.h   |  28 +++
 bolt/lib/Passes/CMakeLists.txt                |   1 +
 bolt/lib/Passes/RISCVLongJmpPass.cpp          | 173 ++++++++++++++++++
 bolt/lib/Rewrite/BinaryPassManager.cpp        |   4 +
 bolt/lib/Target/RISCV/RISCVMCPlusBuilder.cpp  |  11 ++
 bolt/test/RISCV/split-functions-cfi-scratch.s |  35 ++++
 bolt/test/RISCV/split-functions-long-jump.s   |  58 ++++++
 .../RISCV/split-functions-multi-fragment.s    |  51 ++++++
 bolt/test/RISCV/split-functions-no-scratch.s  |  49 +++++
 .../RISCV/split-functions-non-abi-live-out.s  |  30 +++
 bolt/test/runtime/RISCV/split-branches.s      | 128 +++++++++++++
 12 files changed, 574 insertions(+)
 create mode 100644 bolt/include/bolt/Passes/RISCVLongJmpPass.h
 create mode 100644 bolt/lib/Passes/RISCVLongJmpPass.cpp
 create mode 100644 bolt/test/RISCV/split-functions-cfi-scratch.s
 create mode 100644 bolt/test/RISCV/split-functions-long-jump.s
 create mode 100644 bolt/test/RISCV/split-functions-multi-fragment.s
 create mode 100644 bolt/test/RISCV/split-functions-no-scratch.s
 create mode 100644 bolt/test/RISCV/split-functions-non-abi-live-out.s
 create mode 100644 bolt/test/runtime/RISCV/split-branches.s

diff --git a/bolt/include/bolt/Core/MCPlusBuilder.h b/bolt/include/bolt/Core/MCPlusBuilder.h
index e55db33834ee8..95649c06f7cb9 100644
--- a/bolt/include/bolt/Core/MCPlusBuilder.h
+++ b/bolt/include/bolt/Core/MCPlusBuilder.h
@@ -1972,6 +1972,12 @@ class MCPlusBuilder {
     llvm_unreachable("not implemented");
   }
 
+  /// Create a long branch using a register proven dead at the target.
+  virtual void createLongBranch(MCInst &Inst, const MCSymbol *Target,
+                                MCPhysReg ScratchReg, MCContext *Ctx) const {
+    llvm_unreachable("not implemented");
+  }
+
   /// Creates a new call instruction in Inst and sets its operand to
   /// Target.
   virtual void createCall(MCInst &Inst, const MCSymbol *Target,
diff --git a/bolt/include/bolt/Passes/RISCVLongJmpPass.h b/bolt/include/bolt/Passes/RISCVLongJmpPass.h
new file mode 100644
index 0000000000000..14eebe4f3247f
--- /dev/null
+++ b/bolt/include/bolt/Passes/RISCVLongJmpPass.h
@@ -0,0 +1,28 @@
+//===- RISCVLongJmpPass.h --------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef BOLT_PASSES_RISCVLONGJMPPASS_H
+#define BOLT_PASSES_RISCVLONGJMPPASS_H
+
+#include "bolt/Passes/BinaryPasses.h"
+
+namespace llvm::bolt {
+
+/// Insert long jumps between function fragments using dead scratch registers.
+/// Keep fragments together when no safe scratch register is available.
+class RISCVLongJmpPass : public BinaryFunctionPass {
+public:
+  explicit RISCVLongJmpPass(const cl::opt<bool> &PrintPass)
+      : BinaryFunctionPass(PrintPass) {}
+  const char *getName() const override { return "riscv-long-jmp"; }
+  Error runOnFunctions(BinaryContext &BC) override;
+};
+
+} // namespace llvm::bolt
+
+#endif
diff --git a/bolt/lib/Passes/CMakeLists.txt b/bolt/lib/Passes/CMakeLists.txt
index 686dee6987a73..a7514d4be945a 100644
--- a/bolt/lib/Passes/CMakeLists.txt
+++ b/bolt/lib/Passes/CMakeLists.txt
@@ -33,6 +33,7 @@ add_llvm_library(LLVMBOLTPasses
   ProfileQualityStats.cpp
   RegAnalysis.cpp
   RegReAssign.cpp
+  RISCVLongJmpPass.cpp
   ReorderAlgorithm.cpp
   ReorderFunctions.cpp
   ReorderData.cpp
diff --git a/bolt/lib/Passes/RISCVLongJmpPass.cpp b/bolt/lib/Passes/RISCVLongJmpPass.cpp
new file mode 100644
index 0000000000000..26cfe06dff247
--- /dev/null
+++ b/bolt/lib/Passes/RISCVLongJmpPass.cpp
@@ -0,0 +1,173 @@
+//===- RISCVLongJmpPass.cpp -----------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the RISCVLongJmpPass class.
+//
+//===----------------------------------------------------------------------===//
+
+#include "bolt/Passes/RISCVLongJmpPass.h"
+#include "bolt/Passes/DataflowInfoManager.h"
+#include "bolt/Passes/RegAnalysis.h"
+
+using namespace llvm;
+using namespace llvm::bolt;
+
+namespace {
+
+/// Return scratch candidates among caller-saved GPRs, including argument
+/// registers, excluding special registers and registers referenced by CFI.
+BitVector getScratchRegCandidates(BinaryFunction &BF) {
+  BinaryContext &BC = BF.getBinaryContext();
+  BitVector Regs(BC.MRI->getNumRegs());
+  BC.MIB->getGPRegs(Regs, /*IncludeAlias=*/false);
+  BC.MIB->removeNonScavengeableRegs(Regs);
+  BitVector CalleeSaved(Regs.size());
+  BC.MIB->getCalleeSavedRegs(CalleeSaved);
+  Regs.reset(CalleeSaved);
+
+  // Ordinary liveness does not account for registers needed by stack unwinding.
+  // Conservatively exclude CFI references throughout the function instead of
+  // interpreting the unwind state separately at every prospective stub.
+  auto removeCFIRegs = [&](const MCCFIInstruction &CFI) {
+    switch (CFI.getOperation()) {
+    case MCCFIInstruction::OpEscape:
+      // Raw DWARF may refer to registers that this scan cannot identify.
+      return false;
+    case MCCFIInstruction::OpRegister:
+      if (auto Reg = BC.MRI->getLLVMRegNum(CFI.getRegister2(), false))
+        Regs.reset(*Reg);
+      [[fallthrough]];
+    case MCCFIInstruction::OpDefCfa:
+    case MCCFIInstruction::OpDefCfaRegister:
+    case MCCFIInstruction::OpLLVMDefAspaceCfa:
+    case MCCFIInstruction::OpOffset:
+    case MCCFIInstruction::OpRelOffset:
+    case MCCFIInstruction::OpValOffset:
+    case MCCFIInstruction::OpRestore:
+    case MCCFIInstruction::OpUndefined:
+    case MCCFIInstruction::OpSameValue:
+      if (auto Reg = BC.MRI->getLLVMRegNum(CFI.getRegister(), false))
+        Regs.reset(*Reg);
+      break;
+    default:
+      break;
+    }
+    return true;
+  };
+  for (const MCCFIInstruction &CFI : BF.cie())
+    if (!removeCFIRegs(CFI))
+      return BitVector(Regs.size());
+  for (const BinaryBasicBlock &BB : BF)
+    for (const MCInst &Inst : BB)
+      if (const MCCFIInstruction *CFI = BF.getCFIFor(Inst))
+        if (!removeCFIRegs(*CFI))
+          return BitVector(Regs.size());
+  return Regs;
+}
+
+/// Cancel splitting while preserving the current basic block layout order.
+/// This avoids introducing a long jump that clobbers a required register.
+void keepFragmentsTogether(BinaryFunction &BF) {
+  BinaryFunction::BasicBlockOrderType Order(BF.getLayout().block_begin(),
+                                            BF.getLayout().block_end());
+  for (BinaryBasicBlock *BB : Order)
+    BB->setFragmentNum(FragmentNum::main());
+  BF.getLayout().update(Order);
+  if (BF.hasEHRanges())
+    BF.setLPFragment(FragmentNum::main(), FragmentNum::main());
+  BF.fixBranches();
+}
+
+/// Insert a stub for every cross-fragment CFG edge, without estimating its
+/// final distance. Return false if splitting was cancelled for lack of scratch.
+/// Analyze all edges before mutating the CFG so fallback needs no stub
+/// rollback.
+bool relaxFunction(BinaryFunction &BF, RegAnalysis &RA) {
+  BinaryContext &BC = BF.getBinaryContext();
+  BitVector Candidates = getScratchRegCandidates(BF);
+  struct LongJumpEdge {
+    BinaryBasicBlock *Source;
+    BinaryBasicBlock *Target;
+    BinaryBasicBlock *Stub;
+  };
+  SmallVector<LongJumpEdge> Edges;
+  DenseMap<BinaryBasicBlock *, MCPhysReg> ScratchRegs;
+  {
+    DataflowInfoManager DIM(BF, &RA, nullptr);
+    LivenessAnalysis &LA = DIM.getLivenessAnalysis();
+    for (BinaryBasicBlock &BB : BF) {
+      for (BinaryBasicBlock *Target : BB.successors()) {
+        if (Target->getFragmentNum() == BB.getFragmentNum())
+          continue;
+        Edges.push_back({&BB, Target, nullptr});
+        if (ScratchRegs.contains(Target))
+          continue;
+        BitVector Dead = *LA.getStateAt(ProgramPoint::getFirstPointAt(*Target));
+        Dead.flip();
+        Dead &= Candidates;
+        // There is no ABI-reserved temporary for arbitrary intra-function
+        // branches on RISC-V. Never insert a clobber when no register is dead.
+        if (Dead.none()) {
+          BC.errs() << "BOLT-WARNING: keeping " << BF
+                    << " unsplit: no dead register for a RISC-V long jump\n";
+          DIM.invalidateLivenessAnalysis();
+          keepFragmentsTogether(BF);
+          return false;
+        }
+        ScratchRegs[Target] = Dead.find_first();
+      }
+    }
+  }
+
+  // splitEdge() assumes at most two fragments, so insert the stubs here.
+  for (LongJumpEdge &E : Edges) {
+    auto Stub = BF.createBasicBlock();
+    E.Stub = Stub.get();
+    const auto BI = E.Source->getBranchInfo(*E.Target);
+    Stub->setFragmentNum(E.Source->getFragmentNum());
+    Stub->setExecutionCount(BI.Count);
+    Stub->addSuccessor(E.Target, BI.Count, BI.MispredictedCount);
+    E.Source->replaceSuccessor(E.Target, Stub.get(), BI.Count,
+                               BI.MispredictedCount);
+    std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks;
+    NewBlocks.push_back(std::move(Stub));
+    BF.insertBasicBlocks(E.Source, std::move(NewBlocks),
+                         /*UpdateLayout=*/true, /*UpdateCFIState=*/true,
+                         /*RecomputeLandingPads=*/false);
+  }
+  BF.fixBranches();
+  for (const LongJumpEdge &E : Edges) {
+    MCInst Jump;
+    // PseudoJump expands to AUIPC scratch + JALR x0, scratch. It overwrites the
+    // chosen dead register without changing ra; JITLink may later shorten it.
+    BC.MIB->createLongBranch(Jump, E.Target->getLabel(), ScratchRegs[E.Target],
+                             BC.Ctx.get());
+    E.Stub->clear();
+    E.Stub->addInstruction(Jump);
+  }
+  return true;
+}
+
+} // namespace
+
+Error RISCVLongJmpPass::runOnFunctions(BinaryContext &BC) {
+  RegAnalysis RA(BC, nullptr, nullptr);
+  unsigned Relaxed = 0, KeptTogether = 0;
+  for (auto &[Address, BF] : BC.getBinaryFunctions()) {
+    if (!BC.shouldEmit(BF) || !BF.isSimple() || !BF.isSplit())
+      continue;
+    if (relaxFunction(BF, RA))
+      ++Relaxed;
+    else
+      ++KeptTogether;
+  }
+  BC.outs() << "BOLT-INFO: RISC-V relaxed branches in " << Relaxed
+            << " split functions; kept " << KeptTogether
+            << " functions together without a dead scratch register\n";
+  return Error::success();
+}
diff --git a/bolt/lib/Rewrite/BinaryPassManager.cpp b/bolt/lib/Rewrite/BinaryPassManager.cpp
index e61297f94ff98..10fc1ff5682e5 100644
--- a/bolt/lib/Rewrite/BinaryPassManager.cpp
+++ b/bolt/lib/Rewrite/BinaryPassManager.cpp
@@ -29,6 +29,7 @@
 #include "bolt/Passes/PointerAuthCFIAnalyzer.h"
 #include "bolt/Passes/PointerAuthCFIFixup.h"
 #include "bolt/Passes/ProfileQualityStats.h"
+#include "bolt/Passes/RISCVLongJmpPass.h"
 #include "bolt/Passes/RegReAssign.h"
 #include "bolt/Passes/ReorderData.h"
 #include "bolt/Passes/ReorderFunctions.h"
@@ -549,6 +550,9 @@ Error BinaryFunctionPassManager::runAllPasses(BinaryContext &BC) {
         std::make_unique<PointerAuthCFIFixup>(PrintPAuthCFIFixup));
   }
 
+  if (BC.isRISCV())
+    Manager.registerPass(std::make_unique<RISCVLongJmpPass>(PrintLongJmp));
+
   // This pass should always run last.*
   Manager.registerPass(std::make_unique<FinalizeFunctions>(PrintFinalized));
 
diff --git a/bolt/lib/Target/RISCV/RISCVMCPlusBuilder.cpp b/bolt/lib/Target/RISCV/RISCVMCPlusBuilder.cpp
index a9cd6d98c4a03..7a325aade3203 100644
--- a/bolt/lib/Target/RISCV/RISCVMCPlusBuilder.cpp
+++ b/bolt/lib/Target/RISCV/RISCVMCPlusBuilder.cpp
@@ -175,6 +175,7 @@ class RISCVMCPlusBuilder : public MCPlusBuilder {
     case RISCV::PseudoCALL:
     case RISCV::PseudoCALLReg:
     case RISCV::PseudoTAIL:
+    case RISCV::PseudoJump:
       return false;
     }
   }
@@ -323,6 +324,15 @@ class RISCVMCPlusBuilder : public MCPlusBuilder {
     Inst.addOperand(MCOperand::createExpr(MCSymbolRefExpr::create(TBB, *Ctx)));
   }
 
+  void createLongBranch(MCInst &Inst, const MCSymbol *Target,
+                        MCPhysReg ScratchReg, MCContext *Ctx) const override {
+    Inst = MCInstBuilder(RISCV::PseudoJump)
+               .addReg(ScratchReg)
+               .addExpr(MCSpecifierExpr::create(
+                   MCSymbolRefExpr::create(Target, *Ctx), RISCV::S_CALL_PLT,
+                   *Ctx));
+  }
+
   StringRef getTrapFillValue() const override {
     return StringRef("\0\0\0\0", 4);
   }
@@ -487,6 +497,7 @@ class RISCVMCPlusBuilder : public MCPlusBuilder {
       return true;
     case RISCV::AUIPC:
     case RISCV::JAL:
+    case RISCV::PseudoJump:
     case RISCV::C_BEQZ:
     case RISCV::C_BNEZ:
       OpNum = 1;
diff --git a/bolt/test/RISCV/split-functions-cfi-scratch.s b/bolt/test/RISCV/split-functions-cfi-scratch.s
new file mode 100644
index 0000000000000..a299265302719
--- /dev/null
+++ b/bolt/test/RISCV/split-functions-cfi-scratch.s
@@ -0,0 +1,35 @@
+## A register can be dead at the branch target but still be needed to unwind
+## from the trampoline. Keep the CFA register intact while crossing fragments.
+
+# RUN: llvm-mc -triple riscv64 -filetype=obj -o %t.o %s
+# RUN: ld.lld --emit-relocs -e _start -o %t.exe %t.o
+# RUN: llvm-bolt %t.exe -o %t.bolt --split-functions \
+# RUN:   --split-strategy=random2 --bolt-seed=1 --pad-funcs-before=_start:2097152
+# RUN: llvm-objdump -d --disassemble-symbols=_start %t.bolt | FileCheck %s
+
+# CHECK-LABEL: <_start>:
+# CHECK-NOT: auipc t0,
+# CHECK: auipc t1,
+# CHECK-NOT: auipc t0,
+
+  .text
+  .globl _start
+  .type _start, @function
+_start:
+  .cfi_startproc
+  mv t0, sp
+  .cfi_def_cfa t0, 0
+  beqz a0, .Lcold
+  .cfi_def_cfa sp, 0
+  li t0, 0
+  li t1, 0
+  ret
+.Lcold:
+  .cfi_def_cfa sp, 0
+  li t0, 0
+  li t1, 0
+  ret
+  .cfi_endproc
+  .size _start, .-_start
+
+  .reloc 0, R_RISCV_NONE
diff --git a/bolt/test/RISCV/split-functions-long-jump.s b/bolt/test/RISCV/split-functions-long-jump.s
new file mode 100644
index 0000000000000..20a9b5d9eb69a
--- /dev/null
+++ b/bolt/test/RISCV/split-functions-long-jump.s
@@ -0,0 +1,58 @@
+## Check that a branch crossing a split-function fragment is redirected through
+## a local trampoline. The trampoline uses AUIPC+JALR instead of JAL so the
+## cold fragment can be placed outside the +/-1 MiB JAL range. Force a 2 MiB
+## gap so linker relaxation cannot shorten the trampoline back into a JAL.
+## Also check that --print-longjmp dumps the RV CFG before linker relaxation.
+
+# RUN: llvm-mc -triple riscv64 -mattr=+c -filetype=obj -o %t.o %s
+# RUN: ld.lld --emit-relocs -e _start -o %t.exe %t.o
+# RUN: llvm-bolt %t.exe -o %t.bolt --split-functions \
+# RUN:   -split-strategy=random2 -bolt-seed=1 --pad-funcs-before=_start:2097152 \
+# RUN:   --print-longjmp --print-only=_start | FileCheck %s --check-prefix=PRINT
+# RUN: llvm-objdump -d --show-all-symbols %t.bolt | FileCheck %s
+# RUN: llvm-readobj --symbols %t.bolt | FileCheck --check-prefix=SYMBOLS %s
+# RUN: llvm-mc -triple riscv32 -mattr=+c -filetype=obj -o %t.32.o %s
+# RUN: ld.lld --emit-relocs -e _start -o %t.32.exe %t.32.o
+# RUN: llvm-bolt %t.32.exe -o %t.32.bolt --split-functions \
+# RUN:   -split-strategy=random2 -bolt-seed=1 --pad-funcs-before=_start:2097152 \
+# RUN:   --print-longjmp --print-only=_start | FileCheck %s --check-prefix=PRINT
+# RUN: llvm-objdump -d --show-all-symbols %t.32.bolt | FileCheck %s
+# RUN: llvm-readobj --symbols %t.32.bolt | FileCheck --check-prefix=SYMBOLS %s
+# RUN: llvm-bolt %t.exe -o %t.unsplit.bolt --split-functions=false
+# RUN: llvm-readelf -S %t.unsplit.bolt | FileCheck --check-prefix=UNSPLIT %s
+
+# UNSPLIT-NOT: .text.cold
+
+# PRINT-LABEL: Binary Function "_start" after riscv-long-jmp {
+# PRINT: jump {{.*}}, {{[a-z][a-z0-9]*}}
+
+# CHECK: Disassembly of section .text:
+# CHECK-LABEL: <_start>:
+# CHECK: auipc [[REG:[a-z0-9]+]],
+# CHECK-NEXT: {{(jalr zero,|jr)}} {{.*}}([[REG]])
+# CHECK: Disassembly of section .text.cold:
+# CHECK-LABEL: <secondary>:
+# SYMBOLS:      Name: secondary
+# SYMBOLS-NEXT: Value:
+# SYMBOLS-NEXT: Size: 0
+# SYMBOLS-NEXT: Binding: Global
+# SYMBOLS-NEXT: Type: Function
+# SYMBOLS-NEXT: Other:
+# SYMBOLS-NEXT: Section: .text.cold
+
+  .text
+  .globl _start
+  .type _start, @function
+_start:
+  beq a0, zero, .Lcold
+  .globl secondary
+  .type secondary, @function
+secondary:
+  li a0, 1
+  ret
+.Lcold:
+  li a0, 2
+  ret
+  .size _start, .-_start
+
+  .reloc 0, R_RISCV_NONE
diff --git a/bolt/test/RISCV/split-functions-multi-fragment.s b/bolt/test/RISCV/split-functions-multi-fragment.s
new file mode 100644
index 0000000000000..9f0f69c83066a
--- /dev/null
+++ b/bolt/test/RISCV/split-functions-multi-fragment.s
@@ -0,0 +1,51 @@
+## Exercise long jumps from fragments beyond the first cold fragment, and
+## two predecessors sharing the same target and scratch register. Padding every
+## fragment keeps all four trampolines outside the JAL range.
+
+# RUN: llvm-mc -triple riscv64 -filetype=obj %s -o %t.o
+# RUN: ld.lld --emit-relocs -e _start %t.o -o %t.exe
+# RUN: llvm-bolt %t.exe -o %t.bolt --split-functions --split-strategy=all \
+# RUN:   --pad-funcs-before=_start:2097152
+# RUN: llvm-objdump -d \
+# RUN:   --disassemble-symbols=_start,_start.cold.0,_start.cold.1,_start.cold.2 %t.bolt | FileCheck %s
+# RUN: llvm-mc -triple riscv32 -filetype=obj %s -o %t.32.o
+# RUN: ld.lld --emit-relocs -e _start %t.32.o -o %t.32.exe
+# RUN: llvm-bolt %t.32.exe -o %t.32.bolt --split-functions --split-strategy=all \
+# RUN:   --pad-funcs-before=_start:2097152
+# RUN: llvm-objdump -d \
+# RUN:   --disassemble-symbols=_start,_start.cold.0,_start.cold.1,_start.cold.2 %t.32.bolt | FileCheck %s
+
+# CHECK-LABEL: <_start>:
+# CHECK: auipc t0,
+# CHECK-NEXT: jr {{.*}} <_start.cold.0>
+# CHECK: auipc t0,
+# CHECK-NEXT: jr {{.*}} <_start.cold.1>
+# CHECK-LABEL: <_start.cold.0>:
+# CHECK-NEXT: addi a0, a0, 0x1
+# CHECK-NEXT: auipc t0,
+# CHECK-NEXT: jr {{.*}} <_start.cold.2>
+# CHECK-LABEL: <_start.cold.1>:
+# CHECK-NEXT: addi a0, a0, 0x2
+# CHECK-NEXT: auipc t0,
+# CHECK-NEXT: jr {{.*}} <_start.cold.2>
+# CHECK-LABEL: <_start.cold.2>:
+# CHECK-NEXT: li t0, 0x0
+# CHECK-NEXT: ret
+
+  .text
+  .globl _start
+  .type _start, @function
+_start:
+  .cfi_startproc
+  beqz a0, .Lright
+.Lleft:
+  addi a0, a0, 1
+  j .Ljoin
+.Lright:
+  addi a0, a0, 2
+.Ljoin:
+  li t0, 0
+  ret
+  .cfi_endproc
+  .size _start, .-_start
+  .reloc 0, R_RISCV_NONE
diff --git a/bolt/test/RISCV/split-functions-no-scratch.s b/bolt/test/RISCV/split-functions-no-scratch.s
new file mode 100644
index 0000000000000..b3841268a318c
--- /dev/null
+++ b/bolt/test/RISCV/split-functions-no-scratch.s
@@ -0,0 +1,49 @@
+## RISC-V has no ABI-reserved linker scratch register. If every usable GPR is
+## live across a split edge, check that BOLT keeps that function unsplit rather
+## than clobbering state in an AUIPC+JALR trampoline.
+
+# RUN: llvm-mc -triple riscv64 -filetype=obj -o %t.o %s
+# RUN: ld.lld --emit-relocs -e _start -o %t.exe %t.o
+# RUN: llvm-bolt %t.exe -o %t.bolt -split-functions \
+# RUN:   -split-strategy=random2 -bolt-seed=1 2>&1 | FileCheck %s
+# RUN: llvm-readelf -S %t.bolt | FileCheck --check-prefix=SECTIONS %s
+
+# CHECK: BOLT-WARNING: keeping _start unsplit: no dead register for a RISC-V long jump
+# SECTIONS-NOT: .text.cold
+
+  .text
+  .globl _start
+  .type _start, @function
+_start:
+  beq a0, zero, .Lcold
+  ret
+.Lcold:
+  add a0, a0, t0
+  add a0, a0, t1
+  add a0, a0, t2
+  add a0, a0, s1
+  add a0, a0, a1
+  add a0, a0, a2
+  add a0, a0, a3
+  add a0, a0, a4
+  add a0, a0, a5
+  add a0, a0, a6
+  add a0, a0, a7
+  add a0, a0, s2
+  add a0, a0, s3
+  add a0, a0, s4
+  add a0, a0, s5
+  add a0, a0, s6
+  add a0, a0, s7
+  add a0, a0, s8
+  add a0, a0, s9
+  add a0, a0, s10
+  add a0, a0, s11
+  add a0, a0, t3
+  add a0, a0, t4
+  add a0, a0, t5
+  add a0, a0, t6
+  ret
+  .size _start, .-_start
+
+  .reloc 0, R_RISCV_NONE
diff --git a/bolt/test/RISCV/split-functions-non-abi-live-out.s b/bolt/test/RISCV/split-functions-non-abi-live-out.s
new file mode 100644
index 0000000000000..7d07b9362b8a9
--- /dev/null
+++ b/bolt/test/RISCV/split-functions-non-abi-live-out.s
@@ -0,0 +1,30 @@
+## Without --assume-abi, registers that are not ABI return registers may still
+## be live at a function exit. Check that BOLT does not use such a register for
+## a cross-fragment long jump.
+
+# RUN: llvm-mc -triple riscv64 -filetype=obj -o %t.o %s
+# RUN: ld.lld --emit-relocs -e _start -o %t.exe %t.o
+# RUN: llvm-bolt %t.exe -o %t.bolt -split-functions \
+# RUN:   -split-strategy=random2 -bolt-seed=1 2>&1 | FileCheck %s
+# RUN: llvm-readelf -S %t.bolt | FileCheck --check-prefix=SECTIONS %s
+# RUN: llvm-objdump -d --section=.text %t.bolt | \
+# RUN:   FileCheck --check-prefix=DISASM %s
+
+# CHECK: BOLT-WARNING: keeping _start unsplit: no dead register for a RISC-V long jump
+# SECTIONS-NOT: .text.cold
+# DISASM-LABEL: <_start>:
+# DISASM: li t0, 0x7
+# DISASM-NOT: auipc
+
+  .text
+  .globl _start
+  .type _start, @function
+_start:
+  li t0, 7
+  beq a0, zero, .Lcold
+  ret
+.Lcold:
+  ret
+  .size _start, .-_start
+
+  .reloc 0, R_RISCV_NONE
diff --git a/bolt/test/runtime/RISCV/split-branches.s b/bolt/test/runtime/RISCV/split-branches.s
new file mode 100644
index 0000000000000..2b6979bdeca68
--- /dev/null
+++ b/bolt/test/runtime/RISCV/split-branches.s
@@ -0,0 +1,128 @@
+## Reduced from clang's hot/cold JAL overflow. Both directions must preserve
+## live t0; a function with no dead temporary must remain contiguous.
+# REQUIRES: system-linux
+# RUN: llvm-mc -triple=riscv64 -filetype=obj %s -o %t.o
+# RUN: link_fdata %s %t.o %t.fdata
+# RUN: llvm-strip --strip-unneeded %t.o
+# RUN: ld.lld --emit-relocs %t.o -o %t.exe
+# RUN: %t.exe
+# RUN: llvm-bolt %t.exe -o %t.bolt --data=%t.fdata --reorder-blocks=ext-tsp \
+# RUN:   --reorder-functions=cdsort --split-functions --split-all-cold \
+# RUN:   --pad-funcs-before=foo:2097152 | FileCheck %s
+# RUN: %t.bolt
+# RUN: llvm-objdump -d --disassemble-symbols=foo,foo.cold.0 %t.bolt | FileCheck %s --check-prefix=CODE
+# RUN: llvm-nm %t.bolt | FileCheck %s --check-prefix=SYMS
+# RUN: llvm-bolt %t.exe -o %t.all.bolt --split-functions --split-strategy=all
+# RUN: %t.all.bolt
+# RUN: llvm-bolt %t.exe -o %t.random.bolt --split-functions \
+# RUN:   --split-strategy=randomN --bolt-seed=1
+# RUN: %t.random.bolt
+# RUN: llvm-mc -triple=riscv32 -filetype=obj %s -o %t.rv32.o
+# RUN: llvm-strip --strip-unneeded %t.rv32.o
+# RUN: ld.lld --emit-relocs %t.rv32.o -o %t.rv32.exe
+# RUN: llvm-bolt %t.rv32.exe -o %t.rv32.bolt --data=%t.fdata --reorder-blocks=ext-tsp \
+# RUN:   --reorder-functions=cdsort --split-functions --split-all-cold \
+# RUN:   --pad-funcs-before=foo:2097152 | FileCheck %s
+# RUN: llvm-objdump -d --disassemble-symbols=foo,foo.cold.0 %t.rv32.bolt | FileCheck %s --check-prefix=CODE
+# RUN: llvm-mc -triple=riscv64 -mattr=+c -filetype=obj %s -o %t.c.o
+# RUN: link_fdata %s %t.c.o %t.c.fdata
+# RUN: llvm-strip --strip-unneeded %t.c.o
+# RUN: ld.lld --emit-relocs %t.c.o -o %t.c.exe
+# RUN: llvm-bolt %t.c.exe -o %t.c.bolt --data=%t.c.fdata --reorder-blocks=ext-tsp \
+# RUN:   --reorder-functions=cdsort --split-functions --split-all-cold \
+# RUN:   --pad-funcs-before=foo:2097152 | FileCheck %s
+# RUN: %t.c.bolt
+# RUN: llvm-mc -triple=riscv64 -filetype=obj --defsym ARG_SCRATCH=1 %s -o %t.arg.o
+# RUN: llvm-strip --strip-unneeded %t.arg.o
+# RUN: ld.lld --emit-relocs %t.arg.o -o %t.arg.exe
+# RUN: llvm-bolt %t.arg.exe -o %t.arg.bolt --data=%t.fdata --reorder-blocks=ext-tsp \
+# RUN:   --reorder-functions=cdsort --split-functions --split-all-cold \
+# RUN:   --pad-funcs-before=foo:2097152 | FileCheck %s
+# RUN: %t.arg.bolt
+# RUN: llvm-objdump -d --disassemble-symbols=foo,foo.cold.0 %t.arg.bolt | FileCheck %s --check-prefix=ARG
+
+# CHECK: RISC-V relaxed branches in
+# CODE: <foo>:
+# CODE: auipc t1,
+# CODE: jr
+# CODE: <foo.cold.0>:
+# CODE: auipc t1,
+# CODE: jr
+# SYMS: foo.cold.0
+# SYMS-NOT: unsplittable.cold
+# ARG: <foo>:
+# ARG: auipc a0,
+# ARG: <foo.cold.0>:
+# ARG: auipc a0,
+
+  .text
+  .globl _start
+  .type _start, at function
+_start:
+# FDATA: 0 [unknown] 0 1 _start 0 0 100
+  addi sp, sp, -16
+  li t0, 42
+  li a0, 0
+  call foo
+  bnez a0, fail
+  li a0, 1
+  call foo
+  bnez a0, fail
+  li a0, 0
+  call unsplittable
+  bnez a0, fail
+  li a0, 1
+  call unsplittable
+fail:
+  li a7, 93
+  ecall
+  .size _start, .-_start
+
+  .globl foo
+  .type foo, at function
+foo:
+  .cfi_startproc
+# FDATA: 0 [unknown] 0 1 foo 0 0 100
+branch:
+  beqz a0, cold
+# FDATA: 1 foo #branch# 1 foo #cold# 0 0
+# FDATA: 1 foo #branch# 1 foo #hot# 0 100
+hot:
+  .ifdef ARG_SCRATCH
+  li a1, 9
+  .else
+  li t1, 9
+  .endif
+  addi a0, t0, -42
+  ret
+cold:
+  .ifdef ARG_SCRATCH
+  li a1, 7
+  .else
+  li t1, 7
+  .endif
+  j hot
+  .cfi_endproc
+  .size foo, .-foo
+
+  .globl unsplittable
+  .type unsplittable, at function
+unsplittable:
+# FDATA: 0 [unknown] 0 1 unsplittable 0 0 100
+keep_branch:
+  beqz a0, keep_cold
+# FDATA: 1 unsplittable #keep_branch# 1 unsplittable #keep_cold# 0 0
+# FDATA: 1 unsplittable #keep_branch# 1 unsplittable #keep_hot# 0 100
+keep_hot:
+  .irp reg, t0, t1, t2, t3, t4, t5, t6, a0, a1, a2, a3, a4, a5, a6, a7
+  sw \reg, 0(sp)
+  .endr
+  addi a0, t0, -42
+  ret
+keep_cold:
+  .irp reg, t0, t1, t2, t3, t4, t5, t6, a0, a1, a2, a3, a4, a5, a6, a7
+  sw \reg, 0(sp)
+  .endr
+  addi a0, t0, -42
+  ret
+  .size unsplittable, .-unsplittable



More information about the llvm-commits mailing list