[llvm] [BOLT][NFC] Simplify instruction iteration. (PR #174898)

Harald van Dijk via llvm-commits llvm-commits at lists.llvm.org
Mon Jan 12 08:33:13 PST 2026


https://github.com/hvdijk updated https://github.com/llvm/llvm-project/pull/174898

>From e882d7cec806607083cdc8e6c8dc42cac54f0ce7 Mon Sep 17 00:00:00 2001
From: Harald van Dijk <hdijk at accesssoftek.com>
Date: Thu, 8 Jan 2026 02:34:54 +0000
Subject: [PATCH] [BOLT][NFC] Simplify instruction iteration.

PAuthGadgetScanner needs to be able to iterate over either a function's
CFG, or if no CFG is available, a function's pre-CFG instructions. For
that, it has a iterateOverInstrs helper function that takes a callback.
This helper function existed because although BinaryFunction has an
instrs() function, that was not able to handle CFG, it only supported
pre-CFG instructions.

This commit changes instrs() to always work by giving BinaryFunction
custom instr_iterator and instr_const_iterator classes that determine
which iteration type is needed, and removes iterateOverInstrs.
---
 bolt/include/bolt/Core/BinaryFunction.h | 178 +++++++++++++++++++++++-
 bolt/lib/Core/MCInstUtils.cpp           |  16 +--
 bolt/lib/Passes/LongJmp.cpp             |   2 +-
 bolt/lib/Passes/PAuthGadgetScanner.cpp  |  65 ++++-----
 4 files changed, 202 insertions(+), 59 deletions(-)

diff --git a/bolt/include/bolt/Core/BinaryFunction.h b/bolt/include/bolt/Core/BinaryFunction.h
index 12aef415aa050..55fc7a4ba8b69 100644
--- a/bolt/include/bolt/Core/BinaryFunction.h
+++ b/bolt/include/bolt/Core/BinaryFunction.h
@@ -64,6 +64,8 @@ class DWARFUnit;
 
 namespace bolt {
 
+class MCInstReference;
+
 using InputOffsetToAddressMapTy = std::unordered_multimap<uint64_t, uint64_t>;
 
 /// Types of macro-fusion alignment corrections.
@@ -830,6 +832,11 @@ class BinaryFunction {
   BasicBlockListType::iterator pbegin()  { return BasicBlocks.begin(); }
   BasicBlockListType::iterator pend()    { return BasicBlocks.end(); }
 
+  // Do not use BasicBlockListType::const_iterator here as it would expose
+  // BasicBlocks as non-const.
+  const BinaryBasicBlock *const *pbegin() const { return BasicBlocks.begin(); }
+  const BinaryBasicBlock *const *pend()   const { return BasicBlocks.end(); }
+
   cfi_iterator        cie_begin()       { return CIEFrameInstructions.begin(); }
   const_cfi_iterator  cie_begin() const { return CIEFrameInstructions.begin(); }
   cfi_iterator        cie_end()         { return CIEFrameInstructions.end(); }
@@ -843,14 +850,171 @@ class BinaryFunction {
     return iterator_range<const_cfi_iterator>(cie_begin(), cie_end());
   }
 
-  /// Iterate over instructions (only if CFG is unavailable or not built yet).
-  iterator_range<InstrMapType::iterator> instrs() {
-    assert(!hasCFG() && "Iterate over basic blocks instead");
-    return make_range(Instructions.begin(), Instructions.end());
+private:
+  template <typename BinaryFunction> struct instr_iterator_impl {
+    using InstrMapIterator =
+        decltype(std::declval<BinaryFunction>().Instructions.begin());
+    using BasicBlockIterator =
+        decltype(std::declval<BinaryFunction>().pbegin());
+    using BinaryBasicBlock =
+        std::remove_reference_t<decltype(**std::declval<BasicBlockIterator>())>;
+    using InstructionIterator =
+        decltype(std::declval<BinaryBasicBlock>().begin());
+    using MCInst =
+        std::remove_reference_t<decltype(*std::declval<InstructionIterator>())>;
+
+  public:
+    instr_iterator_impl() : BF{nullptr} {}
+    instr_iterator_impl(BinaryFunction &BF, InstrMapIterator I)
+        : BF{&BF}, BFI{I} {}
+    instr_iterator_impl(BinaryFunction &BF, BasicBlockIterator BB) : BF{&BF} {
+      setBB(BB);
+    }
+    instr_iterator_impl(BinaryFunction &BF, BasicBlockIterator BB,
+                        InstructionIterator I)
+        : BF{&BF}, BBI{BB, I} {}
+    instr_iterator_impl(BinaryFunction &BF, BinaryBasicBlock &BB, MCInst &I)
+        : instr_iterator_impl(BF, BF.pbegin() + BB.getIndex(),
+                              BB.begin() + (&I - &BB.front())) {}
+    instr_iterator_impl(BinaryBasicBlock &BB, MCInst &I)
+        : instr_iterator_impl(*BB.getFunction(), BB, I) {}
+
+    using value_type = std::remove_cv_t<MCInst>;
+    using pointer = MCInst *;
+    using reference = MCInst &;
+    using difference_type = std::ptrdiff_t;
+    using iterator_category = std::bidirectional_iterator_tag;
+
+    MCInst &operator*() const { return BF->hasCFG() ? *BBI.I : BFI->second; }
+
+    instr_iterator_impl &operator++() {
+      if (BF->hasCFG()) {
+        if (++BBI.I == (*BBI.BB)->end())
+          setBB(std::next(BBI.BB));
+      } else {
+        ++BFI;
+      }
+      return *this;
+    }
+
+    instr_iterator_impl operator++(int) {
+      instr_iterator_impl result = *this;
+      ++*this;
+      return result;
+    }
+
+    instr_iterator_impl &operator--() {
+      if (BF->hasCFG()) {
+        if (BBI.I == InstructionListType::iterator{} ||
+            BBI.I == (*BBI.BB)->begin()) {
+          do {
+            --BBI.BB;
+          } while ((*BBI.BB)->empty());
+          BBI.I = (*BBI.BB)->end();
+        }
+        --BBI.I;
+      } else {
+        --BFI;
+      }
+      return *this;
+    }
+
+    instr_iterator_impl operator--(int) {
+      instr_iterator result = *this;
+      --*this;
+      return result;
+    }
+
+    friend bool operator==(instr_iterator_impl a, instr_iterator_impl b) {
+      return a.BF == b.BF &&
+             (a.BF == nullptr ||
+              (a.BF->hasCFG() ? a.BBI.BB == b.BBI.BB && a.BBI.I == b.BBI.I
+                              : a.BFI == b.BFI));
+    }
+
+    friend bool operator!=(instr_iterator_impl a, instr_iterator_impl b) {
+      return !(a == b);
+    }
+
+    BinaryFunction *getFunction() const { return BF; }
+
+    BinaryBasicBlock *getBasicBlock() const {
+      return BF && BF->hasCFG() ? *BBI.BB : nullptr;
+    }
+
+    uint32_t getOffset() const {
+      assert(!BF->hasCFG());
+      return BFI->first;
+    }
+
+    operator instr_iterator_impl<const BinaryFunction>() const {
+      using T = instr_iterator_impl<const BinaryFunction>;
+      return getFunction()
+                 ? getBasicBlock() ? T(*BF, BBI.BB, BBI.I) : T(*BF, BFI)
+                 : T();
+    }
+
+    // Defined as a template function to avoid requiring MCInstReference to be
+    // complete here.
+    template <typename T = MCInstReference>
+    operator std::enable_if_t<std::is_same_v<T, MCInstReference>, T>() const {
+      return getFunction() ? getBasicBlock() ? T(**BBI.BB, *BBI.I) : T(*BF, BFI)
+                           : T();
+    }
+
+  private:
+    void setBB(BasicBlockIterator BB) {
+      for (;;) {
+        if (BB == BF->pend()) {
+          BBI = {BB, {}};
+          return;
+        }
+        if (!(*BB)->empty()) {
+          BBI = {BB, (*BB)->begin()};
+          return;
+        }
+        ++BB;
+      }
+    }
+
+    struct BasicBlockInstructionIterators {
+      BasicBlockIterator BB;
+      InstructionIterator I;
+    };
+
+    BinaryFunction *BF;
+    union {
+      InstrMapIterator BFI;
+      BasicBlockInstructionIterators BBI;
+    };
+  };
+
+public:
+  using instr_iterator = instr_iterator_impl<BinaryFunction>;
+  using instr_const_iterator = instr_iterator_impl<const BinaryFunction>;
+
+  /// Iterate over instructions.
+  iterator_range<instr_iterator> instrs() {
+    return make_range(instr_begin(), instr_end());
+  }
+  iterator_range<instr_const_iterator> instrs() const {
+    return make_range(instr_begin(), instr_end());
+  }
+  instr_iterator instr_begin() {
+    if (hasCFG())
+      return instr_iterator(*this, pbegin());
+    return instr_iterator(*this, Instructions.begin());
+  }
+  instr_iterator instr_end() {
+    if (hasCFG())
+      return instr_iterator(*this, pend());
+    return instr_iterator(*this, Instructions.end());
+  }
+  instr_const_iterator instr_begin() const {
+    return const_cast<BinaryFunction *>(this)->instr_begin();
   }
-  iterator_range<InstrMapType::const_iterator> instrs() const {
-    assert(!hasCFG() && "Iterate over basic blocks instead");
-    return make_range(Instructions.begin(), Instructions.end());
+  instr_const_iterator instr_end() const {
+    return const_cast<BinaryFunction *>(this)->instr_end();
   }
 
   /// Returns whether there are any labels at Offset.
diff --git a/bolt/lib/Core/MCInstUtils.cpp b/bolt/lib/Core/MCInstUtils.cpp
index f505bf73c64eb..8d8e47132d415 100644
--- a/bolt/lib/Core/MCInstUtils.cpp
+++ b/bolt/lib/Core/MCInstUtils.cpp
@@ -24,19 +24,9 @@ static_assert(BasicBlockStorageIsVector::value);
 
 MCInstReference MCInstReference::get(const MCInst &Inst,
                                      const BinaryFunction &BF) {
-  if (BF.hasCFG()) {
-    for (BinaryBasicBlock &BB : BF) {
-      for (MCInst &MI : BB)
-        if (&MI == &Inst)
-          return MCInstReference(BB, Inst);
-    }
-    llvm_unreachable("Inst is not contained in BF");
-  }
-
-  for (auto I = BF.instrs().begin(), E = BF.instrs().end(); I != E; ++I) {
-    if (&I->second == &Inst)
-      return MCInstReference(BF, I);
-  }
+  for (auto It = BF.instr_begin(), End = BF.instr_end(); It != End; ++It)
+    if (&*It == &Inst)
+      return MCInstReference(It);
   llvm_unreachable("Inst is not contained in BF");
 }
 
diff --git a/bolt/lib/Passes/LongJmp.cpp b/bolt/lib/Passes/LongJmp.cpp
index 9fedf919dd489..270af46f645fd 100644
--- a/bolt/lib/Passes/LongJmp.cpp
+++ b/bolt/lib/Passes/LongJmp.cpp
@@ -508,7 +508,7 @@ Error LongJmpPass::relaxStub(BinaryBasicBlock &StubBB, bool &Modified) {
     if (TargetFunction && !TargetFunction->hasCFG()) {
       if (TargetFunction->hasInstructions()) {
         auto FirstII = TargetFunction->instrs().begin();
-        MCInst FirstInst = FirstII->second;
+        MCInst FirstInst = *FirstII;
         if (BC.MIB->isCallCoveredByBTI(*StubBB.getLastNonPseudoInstr(),
                                        FirstInst))
           return;
diff --git a/bolt/lib/Passes/PAuthGadgetScanner.cpp b/bolt/lib/Passes/PAuthGadgetScanner.cpp
index 22ceeabe36c67..48f692b327481 100644
--- a/bolt/lib/Passes/PAuthGadgetScanner.cpp
+++ b/bolt/lib/Passes/PAuthGadgetScanner.cpp
@@ -123,22 +123,6 @@ static cl::opt<bool> AuthTrapsOnFailure(
   dbgs() << "\n";
 }
 
-// Iterates over BinaryFunction's instructions like a range-based for loop:
-//
-// iterateOverInstrs(BF, [&](MCInstReference Inst) {
-//   // loop body
-// });
-template <typename T> static void iterateOverInstrs(BinaryFunction &BF, T Fn) {
-  if (BF.hasCFG()) {
-    for (BinaryBasicBlock &BB : BF)
-      for (int64_t I = 0, E = BB.size(); I < E; ++I)
-        Fn(MCInstReference(BB, I));
-  } else {
-    for (auto I = BF.instrs().begin(), E = BF.instrs().end(); I != E; ++I)
-      Fn(MCInstReference(BF, I));
-  }
-}
-
 // This class represents mapping from a set of arbitrary physical registers to
 // consecutive array indexes.
 class TrackedRegisters {
@@ -390,7 +374,7 @@ class SrcSafetyAnalysis {
   /// clobbered inside this function.
   SrcState computePessimisticState(BinaryFunction &BF) {
     BitVector ClobberedRegs(NumRegs);
-    iterateOverInstrs(BF, [&](MCInstReference Inst) {
+    for (auto &Inst : BF.instrs()) {
       BC.MIB->getClobberedRegs(Inst, ClobberedRegs);
 
       // If this is a call instruction, no register is safe anymore, unless
@@ -399,7 +383,7 @@ class SrcSafetyAnalysis {
       // caller after this point anyway.
       if (BC.MIB->isCall(Inst) && !BC.MIB->isTailCall(Inst))
         ClobberedRegs.set();
-    });
+    }
 
     SrcState S = createEntryState();
     S.SafeToDerefRegs.reset(ClobberedRegs);
@@ -726,8 +710,8 @@ template <typename StateTy> class CFGUnawareAnalysis {
   unsigned StateAnnotationIndex;
 
   void cleanStateAnnotations() {
-    for (auto &I : BF.instrs())
-      BC.MIB->removeAnnotation(I.second, StateAnnotationIndex);
+    for (auto &Inst : BF.instrs())
+      BC.MIB->removeAnnotation(Inst, StateAnnotationIndex);
   }
 
 protected:
@@ -804,8 +788,9 @@ class CFGUnawareSrcSafetyAnalysis : public SrcSafetyAnalysis,
   void run() override {
     const SrcState DefaultState = computePessimisticState(BF);
     SrcState S = createEntryState();
-    for (auto &I : BF.instrs()) {
-      MCInst &Inst = I.second;
+    for (auto It = BF.instr_begin(), End = BF.instr_end(); It != End; ++It) {
+      MCInstReference Point(It);
+      MCInst &Inst = *It;
       if (BC.MIB->isCFI(Inst))
         continue;
 
@@ -813,7 +798,8 @@ class CFGUnawareSrcSafetyAnalysis : public SrcSafetyAnalysis,
       // can be jumped-to, thus conservatively resetting S. As an exception,
       // let's ignore any labels at the beginning of the function, as at least
       // one label is expected there.
-      if (BF.hasLabelAt(I.first) && &Inst != &BF.instrs().begin()->second) {
+      unsigned Offset = Point.computeAddress() - BF.getAddress();
+      if (Offset && BF.hasLabelAt(Offset)) {
         LLVM_DEBUG({
           traceInst(BC, "Due to label, resetting the state before", Inst);
         });
@@ -1297,8 +1283,7 @@ class CFGUnawareDstSafetyAnalysis : public DstSafetyAnalysis,
 
   void run() override {
     DstState S = createUnsafeState();
-    for (auto &I : llvm::reverse(BF.instrs())) {
-      MCInst &Inst = I.second;
+    for (auto &Inst : llvm::reverse(BF.instrs())) {
       if (BC.MIB->isCFI(Inst))
         continue;
 
@@ -1605,32 +1590,34 @@ void FunctionAnalysisContext::findUnsafeUses(
   // FIXME: Warn the user about imprecise analysis when the function has no CFG
   //        information at all.
 
-  iterateOverInstrs(BF, [&](MCInstReference Inst) {
+  for (auto It = BF.instr_begin(), End = BF.instr_end(); It != End; ++It) {
+    MCInstReference Point(It);
+    MCInst &Inst = *It;
     if (BC.MIB->isCFI(Inst))
-      return;
+      continue;
 
     const SrcState &S = Analysis->getStateBefore(Inst);
     if (S.empty()) {
       LLVM_DEBUG(traceInst(BC, "Instruction has no state, skipping", Inst));
       assert(UnreachableBBReported && "Should be reported at least once");
       (void)UnreachableBBReported;
-      return;
+      continue;
     }
 
-    if (auto Report = shouldReportReturnGadget(BC, Inst, S))
+    if (auto Report = shouldReportReturnGadget(BC, Point, S))
       Reports.push_back(*Report);
 
     if (PacRetGadgetsOnly)
-      return;
+      continue;
 
-    if (auto Report = shouldReportUnsafeTailCall(BC, BF, Inst, S))
+    if (auto Report = shouldReportUnsafeTailCall(BC, BF, Point, S))
       Reports.push_back(*Report);
 
-    if (auto Report = shouldReportCallGadget(BC, Inst, S))
+    if (auto Report = shouldReportCallGadget(BC, Point, S))
       Reports.push_back(*Report);
-    if (auto Report = shouldReportSigningOracle(BC, Inst, S))
+    if (auto Report = shouldReportSigningOracle(BC, Point, S))
       Reports.push_back(*Report);
-  });
+  }
 }
 
 void FunctionAnalysisContext::augmentUnsafeUseReports(
@@ -1673,15 +1660,17 @@ void FunctionAnalysisContext::findUnsafeDefs(
     BF.dump();
   });
 
-  iterateOverInstrs(BF, [&](MCInstReference Inst) {
+  for (auto It = BF.instr_begin(), End = BF.instr_end(); It != End; ++It) {
+    MCInstReference Point(It);
+    MCInst &Inst = *It;
     if (BC.MIB->isCFI(Inst))
-      return;
+      continue;
 
     const DstState &S = Analysis->getStateAfter(Inst);
 
-    if (auto Report = shouldReportAuthOracle(BC, Inst, S))
+    if (auto Report = shouldReportAuthOracle(BC, Point, S))
       Reports.push_back(*Report);
-  });
+  }
 }
 
 void FunctionAnalysisContext::augmentUnsafeDefReports(



More information about the llvm-commits mailing list