[llvm] [BOLT][AArch64] Support call ICP (PR #208158)

via llvm-commits llvm-commits at lists.llvm.org
Wed Jul 8 00:24:56 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-bolt

Author: Haibo Jiang (Jianghibo)

<details>
<summary>Changes</summary>

* extends MCPlusBuilder with comparision between registers.
* updates the ICP pass to request a scavenged register for AArch64 callsites.
* wires ICP code generation on AArch64.

---

This PR contains the same content as https://github.com/llvm/llvm-project/pull/184733. An issue with GitHub itself prevented PR 184733 from being merged successfully, so a new PR was created.

---
Full diff: https://github.com/llvm/llvm-project/pull/208158.diff


7 Files Affected:

- (modified) bolt/include/bolt/Core/MCPlusBuilder.h (+11-1) 
- (modified) bolt/lib/Passes/IndirectCallPromotion.cpp (+27-6) 
- (modified) bolt/lib/Target/AArch64/AArch64MCPlusBuilder.cpp (+147) 
- (modified) bolt/lib/Target/X86/X86MCPlusBuilder.cpp (+1-1) 
- (added) bolt/test/AArch64/icp-inline.c (+39) 
- (added) bolt/test/AArch64/icp.c (+46) 
- (modified) bolt/test/AArch64/unsupported-passes.test (+2-2) 


``````````diff
diff --git a/bolt/include/bolt/Core/MCPlusBuilder.h b/bolt/include/bolt/Core/MCPlusBuilder.h
index 84b44a9ab5483..aae520d5afe54 100644
--- a/bolt/include/bolt/Core/MCPlusBuilder.h
+++ b/bolt/include/bolt/Core/MCPlusBuilder.h
@@ -2082,6 +2082,16 @@ class MCPlusBuilder {
     return {};
   }
 
+  /// Create a sequence of instructions to compare contents of a register
+  /// \p Reg1 to a register \p Reg2 and jump to \p Target if they are different.
+  virtual InstructionListType createCmpJNEWithReg(MCPhysReg Reg1,
+                                                  MCPhysReg Reg2,
+                                                  const MCSymbol *Target,
+                                                  MCContext *Ctx) const {
+    llvm_unreachable("not implemented");
+    return {};
+  }
+
   /// Find memcpy size in bytes by using preceding instructions.
   /// Returns std::nullopt if size cannot be determined (no-op for most
   /// targets).
@@ -2506,7 +2516,7 @@ class MCPlusBuilder {
   };
 
   virtual BlocksVectorTy indirectCallPromotion(
-      const MCInst &CallInst,
+      const MCInst &CallInst, MCPhysReg Reg,
       const std::vector<std::pair<MCSymbol *, uint64_t>> &Targets,
       const std::vector<std::pair<MCSymbol *, uint64_t>> &VtableSyms,
       const std::vector<MCInst *> &MethodFetchInsns,
diff --git a/bolt/lib/Passes/IndirectCallPromotion.cpp b/bolt/lib/Passes/IndirectCallPromotion.cpp
index 54fd31e37a313..39ae4cda145c4 100644
--- a/bolt/lib/Passes/IndirectCallPromotion.cpp
+++ b/bolt/lib/Passes/IndirectCallPromotion.cpp
@@ -1142,20 +1142,27 @@ Error IndirectCallPromotion::runOnFunctions(BinaryContext &BC) {
   if (opts::ICP == ICP_NONE)
     return Error::success();
 
-  if (!BC.isX86()) {
-    BC.errs() << "BOLT-ERROR: " << getName() << " is supported only on X86\n";
+  if (!BC.isX86() && !BC.isAArch64()) {
+    BC.errs() << "BOLT-ERROR: " << getName()
+              << " is supported only on X86 and AArch64\n";
     exit(1);
   }
 
   auto &BFs = BC.getBinaryFunctions();
 
   const bool OptimizeCalls = (opts::ICP == ICP_CALLS || opts::ICP == ICP_ALL);
+  if (BC.isAArch64() && opts::ICP == ICP_JUMP_TABLES) {
+    BC.errs()
+        << "BOLT-ERROR: ICP jump table promotion is disabled on AArch64\n";
+    exit(1);
+  }
+
   const bool OptimizeJumpTables =
-      (opts::ICP == ICP_JUMP_TABLES || opts::ICP == ICP_ALL);
+      (opts::ICP == ICP_JUMP_TABLES || opts::ICP == ICP_ALL) && !BC.isAArch64();
 
   std::unique_ptr<RegAnalysis> RA;
   std::unique_ptr<BinaryFunctionCallGraph> CG;
-  if (OptimizeJumpTables) {
+  if (OptimizeJumpTables || BC.isAArch64()) {
     CG.reset(new BinaryFunctionCallGraph(buildCallGraph(BC)));
     RA.reset(new RegAnalysis(BC, &BFs, &*CG));
   }
@@ -1369,14 +1376,28 @@ Error IndirectCallPromotion::runOnFunctions(BinaryContext &BC) {
           MethodInfo.second.push_back(TargetFetchInst);
         }
 
+        MCPhysReg Reg = 0;
+        if (BC.isAArch64()) {
+          Reg = Info.getLivenessAnalysis().scavengeRegAfter(&Inst);
+          LLVM_DEBUG({
+            dbgs() << "BOLT-DEBUG: ICP ";
+            if (Reg)
+              dbgs() << "found the free register " << BC.MRI->getName(Reg);
+            else
+              dbgs() << "could not find a free register";
+            dbgs() << " to save function address.\n";
+          });
+        }
+
         // Generate new promoted call code for this callsite.
         MCPlusBuilder::BlocksVectorTy ICPcode =
             (IsJumpTable && !opts::ICPJumpTablesByTarget)
                 ? BC.MIB->jumpTablePromotion(Inst, SymTargets,
                                              MethodInfo.second, BC.Ctx.get())
                 : BC.MIB->indirectCallPromotion(
-                      Inst, SymTargets, MethodInfo.first, MethodInfo.second,
-                      opts::ICPOldCodeSequence, BC.Ctx.get());
+                      Inst, Reg, SymTargets, MethodInfo.first,
+                      MethodInfo.second, opts::ICPOldCodeSequence,
+                      BC.Ctx.get());
 
         if (ICPcode.empty()) {
           if (opts::Verbosity >= 1)
diff --git a/bolt/lib/Target/AArch64/AArch64MCPlusBuilder.cpp b/bolt/lib/Target/AArch64/AArch64MCPlusBuilder.cpp
index b4a9dff9d25b2..26004c94acdd0 100644
--- a/bolt/lib/Target/AArch64/AArch64MCPlusBuilder.cpp
+++ b/bolt/lib/Target/AArch64/AArch64MCPlusBuilder.cpp
@@ -2281,6 +2281,23 @@ class AArch64MCPlusBuilder : public MCPlusBuilder {
     return Code;
   }
 
+  // This helper function creates the snippet of code that compares a register
+  // Reg1 with a register Reg2, and jumps to Target if they are not equal.
+  InstructionListType createCmpJNEWithReg(MCPhysReg Reg1, MCPhysReg Reg2,
+                                          const MCSymbol *Target,
+                                          MCContext *Ctx) const override {
+    InstructionListType Code;
+    Code.emplace_back(MCInstBuilder(AArch64::SUBSXrs)
+                          .addReg(AArch64::XZR)
+                          .addReg(Reg1)
+                          .addReg(Reg2)
+                          .addImm(0));
+    Code.emplace_back(MCInstBuilder(AArch64::Bcc)
+                          .addImm(AArch64CC::NE)
+                          .addExpr(MCSymbolRefExpr::create(Target, *Ctx)));
+    return Code;
+  }
+
   void createTailCall(MCInst &Inst, const MCSymbol *Target,
                       MCContext *Ctx) override {
     return createDirectCall(Inst, Target, Ctx, /*IsTailCall*/ true);
@@ -3329,6 +3346,136 @@ class AArch64MCPlusBuilder : public MCPlusBuilder {
     return Insts;
   }
 
+  BlocksVectorTy indirectCallPromotion(
+      const MCInst &CallInst, MCPhysReg Reg,
+      const std::vector<std::pair<MCSymbol *, uint64_t>> &Targets,
+      const std::vector<std::pair<MCSymbol *, uint64_t>> &VtableSyms,
+      const std::vector<MCInst *> &MethodFetchInsns,
+      const bool MinimizeCodeSize, MCContext *Ctx) override {
+    const bool IsTailCall = isTailCall(CallInst);
+    BlocksVectorTy Results;
+    if (getJumpTable(CallInst))
+      return Results;
+
+    if (!Reg)
+      return Results;
+
+    // Label for the current code block.
+    MCSymbol *NextTarget = nullptr;
+
+    // The join block which contains all the instructions following CallInst.
+    // MergeBlock remains null if CallInst is a tail call.
+    MCSymbol *MergeBlock = nullptr;
+
+    MCPhysReg FuncAddrReg = Reg;
+
+    const bool LoadElim = !VtableSyms.empty();
+    assert((!LoadElim || VtableSyms.size() == Targets.size()) &&
+           "There must be a vtable entry for every method "
+           "in the targets vector.");
+
+    // The compact old-style sequence used by X86 is not implemented for
+    // AArch64 regular call ICP. AArch64 currently emits the default sequence
+    // that branches or calls directly to the hot target.
+    if (MinimizeCodeSize && !LoadElim)
+      return Results;
+
+    assert(CallInst.getOperand(0).isReg() &&
+           "No register was found for indirect call.");
+    const MCPhysReg TargetReg = CallInst.getOperand(0).getReg();
+
+    const auto jumpToMergeBlock = [&](InstructionListType &NewCall) {
+      assert(MergeBlock);
+      NewCall.push_back(CallInst);
+      MCInst &Merge = NewCall.back();
+      Merge.clear();
+      createUncondBranch(Merge, MergeBlock, Ctx);
+    };
+
+    for (unsigned int i = 0; i < Targets.size(); ++i) {
+      Results.emplace_back(NextTarget, InstructionListType());
+      InstructionListType *NewCall = &Results.back().second;
+
+      // Compare current call target to a specific address.
+      assert(Targets[i].first && "All ICP targets must be to known symbols");
+      const MCSymbol *Sym = LoadElim ? VtableSyms[i].first : Targets[i].first;
+      const uint64_t Addend = LoadElim ? VtableSyms[i].second : 0;
+
+      // Materialize the promoted target address.
+      InstructionListType Adr =
+          materializeAddress(Sym, Ctx, FuncAddrReg, Addend);
+      NewCall->insert(NewCall->end(), Adr.begin(), Adr.end());
+
+      // Generate a label for the next compare block.
+      NextTarget = Ctx->createNamedTempSymbol();
+
+      // Jump to the next compare if the target address does not match.
+      InstructionListType CmpJmp =
+          createCmpJNEWithReg(TargetReg, FuncAddrReg, NextTarget, Ctx);
+      NewCall->insert(NewCall->end(), CmpJmp.begin(), CmpJmp.end());
+
+      // Call the promoted target directly.
+      Results.emplace_back(Ctx->createNamedTempSymbol(), InstructionListType());
+      NewCall = &Results.back().second;
+      NewCall->push_back(CallInst);
+      MCInst &CallOrJmp = NewCall->back();
+
+      CallOrJmp.clear();
+      CallOrJmp.setOpcode(IsTailCall ? AArch64::B : AArch64::BL);
+      CallOrJmp.addOperand(MCOperand::createExpr(getTargetExprFor(
+          CallOrJmp, MCSymbolRefExpr::create(Targets[i].first, *Ctx), *Ctx,
+          0)));
+
+      if (IsTailCall) {
+        setTailCall(CallOrJmp);
+      } else {
+        if (std::optional<uint32_t> Offset = getOffset(CallInst))
+          // Annotated as duplicated call.
+          setOffset(CallOrJmp, *Offset);
+      }
+
+      if (isInvoke(CallInst) && !isInvoke(CallOrJmp)) {
+        // Copy over any EH or GNU args size information from the original call.
+        std::optional<MCPlus::MCLandingPad> EHInfo = getEHInfo(CallInst);
+        if (EHInfo)
+          addEHInfo(CallOrJmp, *EHInfo);
+        int64_t GnuArgsSize = getGnuArgsSize(CallInst);
+        if (GnuArgsSize >= 0)
+          addGnuArgsSize(CallOrJmp, GnuArgsSize);
+      }
+
+      if (!IsTailCall) {
+        // The fallthrough block for the most common target should be the merge
+        // block.
+        if (i == 0) {
+          // Fallthrough to merge block. The CFG will be fixed in the ICP pass.
+          MergeBlock = Ctx->createNamedTempSymbol();
+        } else {
+          // Insert jump to the merge block if we are not doing a fallthrough.
+          jumpToMergeBlock(*NewCall);
+        }
+      }
+    }
+
+    // Cold call block
+    Results.emplace_back(NextTarget, InstructionListType());
+    InstructionListType &NewCall = Results.back().second;
+    for (const MCInst *Inst : MethodFetchInsns)
+      if (Inst != &CallInst)
+        NewCall.push_back(*Inst);
+    NewCall.push_back(CallInst);
+
+    // Jump to merge block from cold call block
+    if (!IsTailCall) {
+      jumpToMergeBlock(NewCall);
+
+      // Record merge block
+      Results.emplace_back(MergeBlock, InstructionListType());
+    }
+
+    return Results;
+  }
+
   void createBTI(MCInst &Inst, BTIKind BTI) const override {
     Inst.setOpcode(AArch64::HINT);
     Inst.clear();
diff --git a/bolt/lib/Target/X86/X86MCPlusBuilder.cpp b/bolt/lib/Target/X86/X86MCPlusBuilder.cpp
index 11a297f514530..9fd3cdb909ce6 100644
--- a/bolt/lib/Target/X86/X86MCPlusBuilder.cpp
+++ b/bolt/lib/Target/X86/X86MCPlusBuilder.cpp
@@ -3289,7 +3289,7 @@ class X86MCPlusBuilder : public MCPlusBuilder {
   }
 
   BlocksVectorTy indirectCallPromotion(
-      const MCInst &CallInst,
+      const MCInst &CallInst, MCPhysReg Reg,
       const std::vector<std::pair<MCSymbol *, uint64_t>> &Targets,
       const std::vector<std::pair<MCSymbol *, uint64_t>> &VtableSyms,
       const std::vector<MCInst *> &MethodFetchInsns,
diff --git a/bolt/test/AArch64/icp-inline.c b/bolt/test/AArch64/icp-inline.c
new file mode 100644
index 0000000000000..f2a4f47147eaa
--- /dev/null
+++ b/bolt/test/AArch64/icp-inline.c
@@ -0,0 +1,39 @@
+// This test verifies inlining after indirect call promotion on AArch64.
+
+// RUN: %clang %cflags -O0 %s -o %t.exe -Wl,-q
+// RUN: link_fdata %s %t.exe %t.fdata
+// RUN: llvm-bolt %t.exe --icp=calls --icp-calls-topn=1 \
+// RUN:   --inline-small-functions -o %t.null --lite=0 --assume-abi \
+// RUN:   --inline-small-functions-bytes=32 --print-inline --data %t.fdata \
+// RUN:   | FileCheck %s
+
+// CHECK:     Binary Function "indirectTailCall" after inlining
+// CHECK:     adrp [[BAR_ADDR:x[0-9]+]], bar
+// CHECK-NEXT: add [[BAR_ADDR]], [[BAR_ADDR]], :lo12:bar
+// CHECK-NEXT: cmp x{{[0-9]+}}, [[BAR_ADDR]]
+// CHECK-NEXT: b.ne
+// The multiply comes from bar's body, confirming it was inlined after ICP.
+// CHECK:     mul     w8, w8, w9
+// CHECK-NOT: b    bar
+// CHECK:     br    x{{[0-9]+}}
+// CHECK:     End of Function "indirectTailCall"
+
+__attribute__((noinline)) int foo(int X) { return X + 1; }
+__attribute__((noinline)) int bar(int X) { return X * 100 + 42; }
+
+typedef int (*Fn)(int);
+
+Fn funcs[] = {foo, bar};
+
+__attribute__((noinline)) int indirectTailCall(int Argc) {
+  Fn Func = funcs[Argc];
+  __attribute__((musttail)) return Func(0);
+}
+
+// FDATA: 1 indirectTailCall 28 1 foo 0 0 1
+// FDATA: 1 indirectTailCall 28 1 bar 0 0 2
+
+int main(int Argc, char **Argv) {
+  (void)Argv;
+  return indirectTailCall(Argc & 1);
+}
diff --git a/bolt/test/AArch64/icp.c b/bolt/test/AArch64/icp.c
new file mode 100644
index 0000000000000..bdec02e4766a4
--- /dev/null
+++ b/bolt/test/AArch64/icp.c
@@ -0,0 +1,46 @@
+// This test verifies basic indirect call promotion on AArch64.
+
+// RUN: %clang %cflags -O0 %s -o %t.exe -Wl,-q
+// RUN: link_fdata %s %t.exe %t.fdata
+// RUN: llvm-bolt %t.exe --icp=calls --icp-calls-topn=1 \
+// RUN:   -o %t.null --lite=0 --assume-abi --print-icp --data %t.fdata \
+// RUN:   | FileCheck %s
+
+// CHECK: Binary Function "execute" after indirect-call-promotion
+// CHECK: adrp [[HELLO_ADDR:x[0-9]+]], hello
+// CHECK-NEXT: add [[HELLO_ADDR]], [[HELLO_ADDR]], :lo12:hello
+// CHECK-NEXT: cmp x{{[0-9]+}}, [[HELLO_ADDR]]
+// CHECK-NEXT: b.ne
+// CHECK: bl    hello
+// CHECK: End of Function "execute"
+// CHECK: Binary Function "executeTailCall" after indirect-call-promotion
+// CHECK: adrp [[EXIT_ADDR:x[0-9]+]], exit_success
+// CHECK-NEXT: add [[EXIT_ADDR]], [[EXIT_ADDR]], :lo12:exit_success
+// CHECK-NEXT: cmp x{{[0-9]+}}, [[EXIT_ADDR]]
+// CHECK-NEXT: b.ne
+// CHECK: b    exit_success
+// CHECK: End of Function "executeTailCall"
+
+typedef int (*IntCallback)(int);
+typedef void (*VoidCallback)(void);
+
+__attribute__((noinline)) void hello(void) {}
+
+__attribute__((noinline)) void execute(VoidCallback Callback) { Callback(); }
+
+// FDATA: 1 execute 14 1 hello 0 0 1
+
+__attribute__((noinline)) int exit_success(int X) { return X; }
+
+IntCallback TailCallback = exit_success;
+
+__attribute__((noinline)) int executeTailCall(int X) {
+  __attribute__((musttail)) return TailCallback(X);
+}
+
+// FDATA: 1 executeTailCall 18 1 exit_success 0 0 1
+
+int main(void) {
+  execute(hello);
+  return executeTailCall(0);
+}
diff --git a/bolt/test/AArch64/unsupported-passes.test b/bolt/test/AArch64/unsupported-passes.test
index 5e5eac19447ae..dcf8a9ba6660d 100644
--- a/bolt/test/AArch64/unsupported-passes.test
+++ b/bolt/test/AArch64/unsupported-passes.test
@@ -6,13 +6,13 @@ RUN: %clang %cflags %p/../Inputs/hello.c -o %t -Wl,-q,-z,undefs
 RUN: not llvm-bolt %t -o %t.bolt --frame-opt=all 2>&1 | FileCheck %s --check-prefix=CHECK-FRAME-OPT
 RUN: not llvm-bolt %t -o %t.bolt --three-way-branch 2>&1 | FileCheck %s --check-prefix=CHECK-THREE-WAY
 RUN: not llvm-bolt %t -o %t.bolt --jt-footprint-reduction 2>&1 | FileCheck %s --check-prefix=CHECK-JT-FOOTPRINT-REDUCTION
-RUN: not llvm-bolt %t -o %t.bolt --indirect-call-promotion=all 2>&1 | FileCheck %s --check-prefix=CHECK-INDIRECT-CALL-PROMOTION
+RUN: not llvm-bolt %t -o %t.bolt --indirect-call-promotion=jump-tables 2>&1 | FileCheck %s --check-prefix=CHECK-INDIRECT-CALL-PROMOTION
 RUN: not llvm-bolt %t -o %t.bolt --memcpy1-spec=main 2>&1 | FileCheck %s --check-prefix=CHECK-MEMCPY1-SPEC
 
 CHECK-FRAME-OPT: BOLT-ERROR: frame-optimizer is supported only on X86
 CHECK-THREE-WAY: BOLT-ERROR: three way branch is supported only on X86
 CHECK-JT-FOOTPRINT-REDUCTION: BOLT-ERROR: jt-footprint-reduction is supported only on X86
-CHECK-INDIRECT-CALL-PROMOTION: BOLT-ERROR: indirect-call-promotion is supported only on X86
+CHECK-INDIRECT-CALL-PROMOTION: BOLT-ERROR: ICP jump table promotion is disabled on AArch64
 CHECK-MEMCPY1-SPEC: BOLT-ERROR: specialize-memcpy is currently supported only on X86
 
 // Passes specific to X86 arch

``````````

</details>


https://github.com/llvm/llvm-project/pull/208158


More information about the llvm-commits mailing list