[llvm] [CodeGen] Publish locally unprofitable outliner candidates (PR #223125)

Kyungwoo Lee via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 11 23:06:10 PDT 2026


https://github.com/kyulee-com created https://github.com/llvm/llvm-project/pull/223125

The Machine Outliner currently publishes only sequences that it outlines locally. This misses opportunities split across code-generation partitions. For example, a sequence occurring twice in each of two partitions may be unprofitable in isolation even though the merged count of four makes outlining profitable.

When enabled, remember short candidates rejected by the local profitability check and publish their surviving occurrence counts to outlined CGData. Derive eligibility from the target-provided sequence, call, and frame costs instead of assuming an instruction width or call encoding. Prune occurrences consumed by ordinary local outlining so the profile describes only the remaining opportunities.

Candidates must still be discovered as repetitions within a partition. Consequently, a 2+1 split retains the existing singleton limitation, while a 2+2 split can be combined and outlined globally. Tests also cover exact tree contents and the two- and three-instruction policy.

On a large iOS binary, this saved about 1 MB out of a 128 MB __TEXT segment.

>From c2e06b37cb791e32b00ab3fb426ed2a2567b61d2 Mon Sep 17 00:00:00 2001
From: Kyungwoo Lee <kyulee at meta.com>
Date: Fri, 11 Sep 2026 12:01:41 -0700
Subject: [PATCH] [CodeGen] Publish locally unprofitable outliner candidates

The Machine Outliner currently publishes only sequences that it outlines locally. This misses opportunities split across code-generation partitions. For example, a sequence occurring twice in each of two partitions may be unprofitable in isolation even though the merged count of four makes outlining profitable.

When enabled, remember short candidates rejected by the local profitability check and publish their surviving occurrence counts to outlined CGData. Derive eligibility from the target-provided sequence, call, and frame costs instead of assuming an instruction width or call encoding. Prune occurrences consumed by ordinary local outlining so the profile describes only the remaining opportunities.

Candidates must still be discovered as repetitions within a partition. Consequently, a 2+1 split retains the existing singleton limitation, while a 2+2 split can be combined and outlined globally. Tests also cover exact tree contents and the two- and three-instruction policy.

On a large iOS binary, this saved about 1 MB out of a 128 MB __TEXT segment.
---
 llvm/lib/CodeGen/MachineOutliner.cpp          | 174 ++++++++++++++++--
 .../cgdata-write-unprofitable-max-instrs.mir  |  46 +++++
 .../AArch64/cgdata-write-unprofitable.ll      | 109 +++++++++++
 3 files changed, 312 insertions(+), 17 deletions(-)
 create mode 100644 llvm/test/CodeGen/AArch64/cgdata-write-unprofitable-max-instrs.mir
 create mode 100644 llvm/test/CodeGen/AArch64/cgdata-write-unprofitable.ll

diff --git a/llvm/lib/CodeGen/MachineOutliner.cpp b/llvm/lib/CodeGen/MachineOutliner.cpp
index 6716dc8d14467..25bcf001a7cc7 100644
--- a/llvm/lib/CodeGen/MachineOutliner.cpp
+++ b/llvm/lib/CodeGen/MachineOutliner.cpp
@@ -79,10 +79,12 @@
 #include "llvm/InitializePasses.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/MathExtras.h"
 #include "llvm/Support/SuffixTree.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
+#include <limits>
 #include <tuple>
 #include <vector>
 
@@ -109,6 +111,13 @@ STATISTIC(StableHashAttempts,
           "Count of hashing attempts made for outlined functions");
 STATISTIC(StableHashDropped,
           "Count of unsuccessful hashing attempts for outlined functions");
+STATISTIC(UnprofitableCandidateGroupsPublished,
+          "Number of locally unprofitable candidate groups published");
+STATISTIC(UnprofitableCandidateSitesPublished,
+          "Number of locally unprofitable candidate sites published");
+STATISTIC(UnprofitableCandidateSitesPruned,
+          "Number of locally unprofitable candidate sites pruned by local "
+          "outlining");
 STATISTIC(NumRemovedLOHs, "Total number of Linker Optimization Hints removed");
 STATISTIC(NumPGOBlockedOutlined,
           "Number of times outlining was blocked by PGO");
@@ -144,6 +153,23 @@ static cl::opt<unsigned> OutlinerBenefitThreshold(
     cl::desc(
         "The minimum size in bytes before an outlining candidate is accepted"));
 
+static cl::opt<bool> PublishUnprofitableCandidates(
+    "machine-outliner-publish-unprofitable-candidates", cl::init(false),
+    cl::Hidden,
+    cl::desc("Publish locally unprofitable candidates to Machine Outliner "
+             "CGData"));
+
+static cl::opt<unsigned> UnprofitableCandidateMaxInstrs(
+    "machine-outliner-unprofitable-candidate-max-instrs", cl::init(3),
+    cl::Hidden,
+    cl::desc("Maximum instruction count for locally unprofitable candidates"));
+
+static cl::opt<unsigned> UnprofitableCandidateMaxOccurrences(
+    "machine-outliner-unprofitable-candidate-max-occurrences", cl::init(4),
+    cl::Hidden,
+    cl::desc("Maximum global occurrence count at which a locally "
+             "unprofitable candidate must become profitable"));
+
 static cl::opt<bool> OutlinerLeafDescendants(
     "outliner-leaf-descendants", cl::init(true), cl::Hidden,
     cl::desc("Consider all leaf descendants of internal nodes of the suffix "
@@ -165,6 +191,8 @@ static cl::opt<bool> AppendContentHashToOutlinedName(
 
 namespace {
 
+constexpr unsigned InvalidInstrMapping = std::numeric_limits<unsigned>::max();
+
 /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
 struct InstructionMapper {
   const MachineModuleInfo &MMI;
@@ -459,6 +487,18 @@ struct MachineOutliner : public ModulePass {
   /// outlined hash tree that has been built by the previous codegen.
   CGDataMode OutlinerMode = CGDataMode::None;
 
+  struct UnprofitableCandidateSite {
+    unsigned StartIdx;
+    unsigned EndIdx;
+  };
+
+  struct UnprofitableCandidateGroup {
+    SmallVector<stable_hash> HashSequence;
+    SmallVector<UnprofitableCandidateSite> Sites;
+  };
+
+  SmallVector<UnprofitableCandidateGroup> UnprofitableCandidates;
+
   StringRef getPassName() const override { return "Machine Outliner"; }
 
   void getAnalysisUsage(AnalysisUsage &AU) const override {
@@ -534,6 +574,16 @@ struct MachineOutliner : public ModulePass {
   /// of candidates that have identical instruction sequences to \p MF.
   void computeAndPublishHashSequence(MachineFunction &MF, unsigned CandSize);
 
+  /// Record a locally unprofitable candidate that may become profitable once
+  /// occurrence counts from multiple code-generation partitions are merged.
+  void recordUnprofitableCandidate(OutlinedFunction &OF);
+
+  /// Remove recorded sites consumed by ordinary local outlining.
+  void pruneUnprofitableCandidateSites(ArrayRef<unsigned> InstructionMapping);
+
+  /// Add surviving locally unprofitable candidate counts to LocalHashTree.
+  bool publishUnprofitableCandidates();
+
   /// Initialize the outliner mode.
   void initializeOutlinerMode(const Module &M);
 
@@ -748,6 +798,7 @@ void MachineOutliner::findCandidates(
     InstructionMapper &Mapper,
     std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
   FunctionList.clear();
+  UnprofitableCandidates.clear();
   SuffixTree ST(Mapper.UnsignedVec, OutlinerLeafDescendants);
 
   // First, find all of the repeated substrings in the tree of minimum length
@@ -845,6 +896,7 @@ void MachineOutliner::findCandidates(
 
     // Is it better to outline this candidate than not?
     if (OF.value()->getBenefit() < OutlinerBenefitThreshold) {
+      recordUnprofitableCandidate(*OF.value());
       emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq,
                                     *OF.value());
       continue;
@@ -887,6 +939,87 @@ void MachineOutliner::computeAndPublishHashSequence(MachineFunction &MF,
   }
 }
 
+void MachineOutliner::recordUnprofitableCandidate(OutlinedFunction &OF) {
+  if (!PublishUnprofitableCandidates || OutlinerMode != CGDataMode::Write ||
+      OF.getNumInstrs() > UnprofitableCandidateMaxInstrs)
+    return;
+
+  SmallVector<UnprofitableCandidateSite> Sites;
+  for (const Candidate &C : OF.Candidates) {
+    const unsigned CallOverhead = C.getCallOverhead();
+    if (OF.SequenceSize <= CallOverhead)
+      continue;
+
+    // Outlining N occurrences is profitable when
+    //
+    //   N * SequenceSize >= N * CallOverhead + SequenceSize +
+    //                       FrameOverhead + OutlinerBenefitThreshold.
+    //
+    // Derive the required count from the target's costs instead of assuming a
+    // particular instruction or call size.
+    const uint64_t SavingsPerOccurrence = OF.SequenceSize - CallOverhead;
+    const uint64_t FixedCost =
+        uint64_t(OF.SequenceSize) + OF.FrameOverhead + OutlinerBenefitThreshold;
+    const uint64_t ProfitableOccurrenceCount =
+        divideCeil(FixedCost, SavingsPerOccurrence);
+    if (ProfitableOccurrenceCount <= UnprofitableCandidateMaxOccurrences)
+      Sites.push_back({C.getStartIdx(), C.getEndIdx()});
+  }
+  if (Sites.empty())
+    return;
+
+  SmallVector<stable_hash> HashSequence;
+  for (MachineInstr &MI : OF.Candidates.front()) {
+    if (MI.isDebugInstr())
+      continue;
+    const stable_hash Hash = stableHashValue(MI);
+    if (!Hash)
+      return;
+    HashSequence.push_back(Hash);
+  }
+  if (!HashSequence.empty())
+    UnprofitableCandidates.push_back(
+        {std::move(HashSequence), std::move(Sites)});
+}
+
+void MachineOutliner::pruneUnprofitableCandidateSites(
+    ArrayRef<unsigned> InstructionMapping) {
+  if (!PublishUnprofitableCandidates)
+    return;
+
+  for (UnprofitableCandidateGroup &CandidateGroup : UnprofitableCandidates) {
+    const size_t SitesBefore = CandidateGroup.Sites.size();
+    llvm::erase_if(CandidateGroup.Sites,
+                   [&](const UnprofitableCandidateSite &CandidateSite) {
+                     return llvm::is_contained(
+                         InstructionMapping.slice(
+                             CandidateSite.StartIdx,
+                             CandidateSite.EndIdx - CandidateSite.StartIdx + 1),
+                         InvalidInstrMapping);
+                   });
+    UnprofitableCandidateSitesPruned +=
+        SitesBefore - CandidateGroup.Sites.size();
+  }
+}
+
+bool MachineOutliner::publishUnprofitableCandidates() {
+  if (!PublishUnprofitableCandidates || OutlinerMode != CGDataMode::Write)
+    return false;
+
+  bool Published = false;
+  for (const UnprofitableCandidateGroup &CandidateGroup :
+       UnprofitableCandidates) {
+    if (CandidateGroup.Sites.empty())
+      continue;
+    LocalHashTree->insert({CandidateGroup.HashSequence,
+                           static_cast<unsigned>(CandidateGroup.Sites.size())});
+    ++UnprofitableCandidateGroupsPublished;
+    UnprofitableCandidateSitesPublished += CandidateGroup.Sites.size();
+    Published = true;
+  }
+  return Published;
+}
+
 MachineFunction *MachineOutliner::createOutlinedFunction(
     Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
 
@@ -1058,9 +1191,8 @@ bool MachineOutliner::outline(
     // step, then we can't outline from it.
     erase_if(OF->Candidates, [&UnsignedVecBegin](Candidate &C) {
       return std::any_of(UnsignedVecBegin + C.getStartIdx(),
-                         UnsignedVecBegin + C.getEndIdx() + 1, [](unsigned I) {
-                           return I == static_cast<unsigned>(-1);
-                         });
+                         UnsignedVecBegin + C.getEndIdx() + 1,
+                         [](unsigned I) { return I == InvalidInstrMapping; });
     });
 
 #ifndef NDEBUG
@@ -1189,10 +1321,10 @@ bool MachineOutliner::outline(
       // Erase needs one past the end, so we need std::next there too.
       MBB.erase(std::next(StartIt), std::next(EndIt));
 
-      // Keep track of what we removed by marking them all as -1.
+      // Keep track of what we removed by invalidating their mappings.
       for (unsigned &I : make_range(UnsignedVecBegin + C.getStartIdx(),
                                     UnsignedVecBegin + C.getEndIdx() + 1))
-        I = static_cast<unsigned>(-1);
+        I = InvalidInstrMapping;
       OutlinedSomething = true;
 
       // Statistics.
@@ -1465,21 +1597,27 @@ bool MachineOutliner::runOnModule(Module &M) {
   unsigned OutlinedFunctionNum = 0;
 
   OutlineRepeatedNum = 0;
-  if (!doOutline(M, OutlinedFunctionNum))
-    return false;
-
-  for (unsigned I = 0; I < OutlinerReruns; ++I) {
-    OutlinedFunctionNum = 0;
-    OutlineRepeatedNum++;
-    if (!doOutline(M, OutlinedFunctionNum)) {
-      LLVM_DEBUG({
-        dbgs() << "Did not outline on iteration " << I + 2 << " out of "
-               << OutlinerReruns + 1 << "\n";
-      });
-      break;
+  bool OutlinedSomething = doOutline(M, OutlinedFunctionNum);
+
+  if (OutlinedSomething) {
+    for (unsigned I = 0; I < OutlinerReruns; ++I) {
+      OutlinedFunctionNum = 0;
+      OutlineRepeatedNum++;
+      if (!doOutline(M, OutlinedFunctionNum)) {
+        LLVM_DEBUG({
+          dbgs() << "Did not outline on iteration " << I + 2 << " out of "
+                 << OutlinerReruns + 1 << "\n";
+        });
+        break;
+      }
     }
   }
 
+  const bool PublishedUnprofitableCandidates = publishUnprofitableCandidates();
+
+  if (!OutlinedSomething && !PublishedUnprofitableCandidates)
+    return false;
+
   if (OutlinerMode == CGDataMode::Write)
     emitOutlinedHashTree(M);
 
@@ -1546,6 +1684,8 @@ bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
   bool OutlinedSomething =
       outline(M, FunctionList, Mapper, OutlinedFunctionNum);
 
+  pruneUnprofitableCandidateSites(Mapper.UnsignedVec);
+
   // If we outlined something, we definitely changed the MI count of the
   // module. If we've asked for size remarks, then output them.
   // FIXME: This should be in the pass manager.
diff --git a/llvm/test/CodeGen/AArch64/cgdata-write-unprofitable-max-instrs.mir b/llvm/test/CodeGen/AArch64/cgdata-write-unprofitable-max-instrs.mir
new file mode 100644
index 0000000000000..954bf6d8238c5
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/cgdata-write-unprofitable-max-instrs.mir
@@ -0,0 +1,46 @@
+# REQUIRES: asserts
+# RUN: llc -mtriple=aarch64-apple-darwin -run-pass=machine-outliner \
+# RUN:   -codegen-data-generate \
+# RUN:   -machine-outliner-publish-unprofitable-candidates -stats %s \
+# RUN:   -o /dev/null 2>&1 | FileCheck %s --check-prefix=MAX-THREE
+# RUN: llc -mtriple=aarch64-apple-darwin -run-pass=machine-outliner \
+# RUN:   -codegen-data-generate \
+# RUN:   -machine-outliner-publish-unprofitable-candidates \
+# RUN:   -machine-outliner-unprofitable-candidate-max-instrs=2 -stats %s \
+# RUN:   -o /dev/null 2>&1 | FileCheck %s --check-prefix=MAX-TWO
+
+# The repeated three-instruction sequence and one of its two-instruction
+# subsequences are locally unprofitable. Lowering the maximum length excludes
+# only the three-instruction candidate.
+#
+# MAX-THREE: 2 machine-outliner - Number of locally unprofitable candidate groups published
+# MAX-THREE: 4 machine-outliner - Number of locally unprofitable candidate sites published
+# MAX-TWO: 1 machine-outliner - Number of locally unprofitable candidate groups published
+# MAX-TWO: 2 machine-outliner - Number of locally unprofitable candidate sites published
+
+--- |
+  define void @three1() noredzone { unreachable }
+  define void @three2() noredzone { unreachable }
+...
+---
+name: three1
+tracksRegLiveness: true
+body: |
+  bb.0:
+    $w0 = ORRWri $wzr, 1
+    $w1 = ORRWri $wzr, 2
+    $w2 = ORRWri $wzr, 3
+    INLINEASM &"", sideeffect attdialect
+    RET undef $lr
+...
+---
+name: three2
+tracksRegLiveness: true
+body: |
+  bb.0:
+    $w0 = ORRWri $wzr, 1
+    $w1 = ORRWri $wzr, 2
+    $w2 = ORRWri $wzr, 3
+    INLINEASM &"", sideeffect attdialect
+    RET undef $lr
+...
diff --git a/llvm/test/CodeGen/AArch64/cgdata-write-unprofitable.ll b/llvm/test/CodeGen/AArch64/cgdata-write-unprofitable.ll
new file mode 100644
index 0000000000000..3f76ed6b7fc73
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/cgdata-write-unprofitable.ll
@@ -0,0 +1,109 @@
+; RUN: rm -rf %t && split-file %s %t
+; RUN: llc -mtriple=arm64-apple-darwin -enable-machine-outliner \
+; RUN:   -codegen-data-generate -filetype=obj %t/module-a.ll -o %t/a.base.o
+; RUN: llvm-objdump -h %t/a.base.o | \
+; RUN:   FileCheck /dev/null --implicit-check-not=__llvm_outline
+; RUN: llc -mtriple=arm64-apple-darwin -enable-machine-outliner \
+; RUN:   -codegen-data-generate \
+; RUN:   -machine-outliner-publish-unprofitable-candidates \
+; RUN:   -filetype=obj %t/module-a.ll -o %t/a.publish.o
+; RUN: llc -mtriple=arm64-apple-darwin -enable-machine-outliner \
+; RUN:   -codegen-data-generate \
+; RUN:   -machine-outliner-publish-unprofitable-candidates \
+; RUN:   -filetype=obj %t/module-b.ll -o %t/b.publish.o
+; RUN: llc -mtriple=arm64-apple-darwin -enable-machine-outliner \
+; RUN:   -codegen-data-generate \
+; RUN:   -machine-outliner-publish-unprofitable-candidates \
+; RUN:   -filetype=obj %t/module-c.ll -o %t/c.publish.o
+; RUN: llvm-objdump -h %t/a.publish.o %t/b.publish.o | \
+; RUN:   FileCheck %s --check-prefix=SECTION
+; RUN: llvm-objdump -h %t/c.publish.o | \
+; RUN:   FileCheck /dev/null --implicit-check-not=__llvm_outline
+; RUN: llvm-cgdata --merge %t/a.publish.o -o %t/count-two.cgdata
+; RUN: llvm-cgdata --convert --format text %t/count-two.cgdata -o - | \
+; RUN:   FileCheck %s --check-prefix=COUNT-TWO \
+; RUN:     --implicit-check-not='Terminals: {{[1-9]}}'
+; RUN: llvm-cgdata --merge %t/a.publish.o %t/b.publish.o \
+; RUN:   -o %t/count-four.cgdata
+; RUN: llvm-cgdata --convert --format text %t/count-four.cgdata -o - | \
+; RUN:   FileCheck %s --check-prefix=COUNT-FOUR \
+; RUN:     --implicit-check-not='Terminals: {{[1-9]}}'
+; RUN: llc -mtriple=arm64-apple-darwin -enable-machine-outliner \
+; RUN:   -codegen-data-use-path=%t/count-four.cgdata -verify-machineinstrs \
+; RUN:   -filetype=obj %t/module-a.ll -o %t/a.read-four.o
+; RUN: llc -mtriple=arm64-apple-darwin -enable-machine-outliner \
+; RUN:   -codegen-data-use-path=%t/count-four.cgdata -verify-machineinstrs \
+; RUN:   -filetype=obj %t/module-b.ll -o %t/b.read-four.o
+; RUN: llvm-nm --defined-only %t/a.read-four.o %t/b.read-four.o | \
+; RUN:   FileCheck %s --check-prefix=READ-FOUR
+; RUN: llvm-cgdata --merge %t/a.publish.o %t/c.publish.o \
+; RUN:   -o %t/count-two-plus-one.cgdata
+; RUN: llvm-cgdata --convert --format text %t/count-two-plus-one.cgdata -o - | \
+; RUN:   FileCheck %s --check-prefix=COUNT-TWO \
+; RUN:     --implicit-check-not='Terminals: {{[1-9]}}'
+; RUN: llc -mtriple=arm64-apple-darwin -enable-machine-outliner \
+; RUN:   -codegen-data-use-path=%t/count-two-plus-one.cgdata \
+; RUN:   -verify-machineinstrs -filetype=obj %t/module-a.ll \
+; RUN:   -o %t/a.read-two-plus-one.o
+; RUN: llvm-nm --defined-only %t/a.read-two-plus-one.o | \
+; RUN:   FileCheck /dev/null --implicit-check-not=OUTLINED_FUNCTION
+; RUN: llc -mtriple=arm64-apple-darwin -enable-machine-outliner \
+; RUN:   -codegen-data-generate \
+; RUN:   -machine-outliner-publish-unprofitable-candidates \
+; RUN:   -machine-outliner-unprofitable-candidate-max-instrs=1 \
+; RUN:   -filetype=obj %t/module-a.ll -o %t/a.max-one-instr.o
+; RUN: llvm-objdump -h %t/a.max-one-instr.o | \
+; RUN:   FileCheck /dev/null --implicit-check-not=__llvm_outline
+
+; Each of modules A and B has two instances of the two-instruction `mov; bl`
+; sequence. The sequence is locally unprofitable, but merging both modules'
+; profiles raises its global count to four and makes Read mode outline it.
+;
+; A single occurrence in module C is not found by the suffix tree and therefore
+; cannot be published. Merging A and C consequently retains a count of two and
+; preserves the known 2+1 limitation.
+;
+; SECTION-COUNT-2: __llvm_outline
+; COUNT-TWO: Terminals:       2
+; COUNT-FOUR: Terminals:       4
+; READ-FOUR-COUNT-2: _OUTLINED_FUNCTION_0.content.
+
+;--- module-a.ll
+target triple = "arm64-apple-darwin"
+
+declare void @g(i64)
+
+define void @a1() minsize noredzone {
+  call void @g(i64 7)
+  ret void
+}
+
+define void @a2() minsize noredzone {
+  call void @g(i64 7)
+  ret void
+}
+
+;--- module-b.ll
+target triple = "arm64-apple-darwin"
+
+declare void @g(i64)
+
+define void @b1() minsize noredzone {
+  call void @g(i64 7)
+  ret void
+}
+
+define void @b2() minsize noredzone {
+  call void @g(i64 7)
+  ret void
+}
+
+;--- module-c.ll
+target triple = "arm64-apple-darwin"
+
+declare void @g(i64)
+
+define void @c1() minsize noredzone {
+  call void @g(i64 7)
+  ret void
+}



More information about the llvm-commits mailing list