Skip to content

[AMDGPU] Add islands to StructurizeCFG - #201675

Open
ro-i wants to merge 17 commits into
mainfrom
users/ro-i/structurize-islands
Open

ro-i wants to merge 17 commits into
mainfrom
users/ro-i/structurize-islands

Conversation

@ro-i

@ro-i ro-i commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Handle an "island", i.e. a block whose terminator is not rewritable (e.g., a callbr) in this context and considered immutable from this pass's perspective.

The island is left untouched; its edges are split into forwarders that converge at a new Flow block (ExitFlow). The callbr's runtime target choice is recovered as a per-target i1 "sel" phi and re-dispatched by a structured ladder of 2-way branches:

                 callbr
               /   |   \
           fwd_0 fwd_1 fwd_2      forwarders (intermediate target blocks)
               \   |   /
            ExitFlow (Flow_0) -- sel_0? --> real_0
                  |  else
                Flow_1 --------- sel_1? --> real_1
                  |  else
             real_2
           or Flow_2 (if real_1 == real_2) ------> real_2   (shared last target)

Not sure if already 100% perfect. But should be not bad and I'd like to see what people think about the approach.

Note that I'll let this circle through internal testing between PR approval and PR merge.

Fixes crash in #170830.

Claude assisted with this patch.

@llvmorg-github-actions

llvmorg-github-actions Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

@llvm/pr-subscribers-backend-amdgpu

@llvm/pr-subscribers-llvm-transforms

Author: Robert Imschweiler (ro-i)

Changes

Handle an "island", i.e. a block whose terminator is not rewritable (e.g., a callbr) in this context and considered immutable from this pass's perspective.

The island is left untouched; its edges are split into forwarders that converge at a new Flow block (ExitFlow). The callbr's runtime target choice is recovered as a per-target i1 "sel" phi and re-dispatched by a structured ladder of 2-way branches:

                 callbr
               /   |   \
           fwd_0 fwd_1 fwd_2      forwarders (intermediate target blocks)
               \   |   /
            ExitFlow (Flow_0) -- sel_0? --> real_0
                  |  else
                Flow_1 --------- sel_1? --> real_1
                  |  else
             real_2
           or Flow_2 (if real_1 == real_2) ------> real_2   (shared last target)

Not sure if already 100% perfect. But should be not bad and I'd like to see what people think about the approach.

Note that I'll let this circle through internal testing between PR approval and PR merge.

Fixes crash in #170830.


Patch is 102.56 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/201675.diff

7 Files Affected:

  • (modified) llvm/lib/Transforms/Scalar/StructurizeCFG.cpp (+356-36)
  • (modified) llvm/test/CodeGen/AMDGPU/callbr-intrinsics.ll (+2-2)
  • (modified) llvm/test/CodeGen/AMDGPU/callbr.ll (+29-11)
  • (modified) llvm/test/CodeGen/AMDGPU/infinite-loop.ll (+117-43)
  • (modified) llvm/test/CodeGen/AMDGPU/si-annotate-nested-control-flows.ll (+60-29)
  • (modified) llvm/test/CodeGen/AMDGPU/si-unify-exit-multiple-unreachables.ll (+95-34)
  • (modified) llvm/test/Transforms/StructurizeCFG/callbr.ll (+1284-112)
diff --git a/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp b/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp
index 04ece92b74375..d1ada89d9d246 100644
--- a/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp
+++ b/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp
@@ -14,6 +14,7 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Analysis/DomTreeUpdater.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/RegionInfo.h"
 #include "llvm/Analysis/RegionIterator.h"
@@ -28,6 +29,8 @@
 #include "llvm/IR/InstrTypes.h"
 #include "llvm/IR/Instruction.h"
 #include "llvm/IR/Instructions.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/IntrinsicsAMDGPU.h"
 #include "llvm/IR/Metadata.h"
 #include "llvm/IR/PassManager.h"
 #include "llvm/IR/PatternMatch.h"
@@ -59,6 +62,32 @@ using namespace llvm::PatternMatch;
 // The name for newly created blocks.
 const char FlowBlockName[] = "Flow";
 
+// True if BB contains nothing but an unconditional branch and has only one
+// predecessor.
+static bool isIntermediateTarget(const BasicBlock &BB) {
+  return BB.size() == 1 && isa<UncondBrInst>(BB.getTerminator()) &&
+         BB.hasNPredecessors(1);
+}
+
+/// True if BB's terminator must be preserved verbatim and therefore cannot
+/// serve as a rewritable flow tail (it can be neither killed nor have its
+/// successors rewritten). Currently only callbr.
+static bool isIsland(const BasicBlock &BB) {
+  return isa<CallBrInst>(BB.getTerminator());
+}
+
+/// True if BB is an unreachable target block: it is terminated by
+/// `unreachable`, or (after exit unification) it is marked by an
+/// @llvm.amdgcn.unreachable call.
+static bool isUnreachableTarget(const BasicBlock &BB) {
+  if (isa<UnreachableInst>(BB.getTerminator()))
+    return true;
+  return any_of(BB, [](const Instruction &I) {
+    const auto *CB = dyn_cast<CallBase>(&I);
+    return CB && CB->getIntrinsicID() == Intrinsic::amdgcn_unreachable;
+  });
+}
+
 namespace {
 
 static cl::opt<bool> ForceSkipUniformRegions(
@@ -227,6 +256,52 @@ class NearestCommonDominator {
   bool resultIsRememberedBlock() { return ResultIsRemembered; }
 };
 
+class StructurizeCFG; // forward declaration
+
+/// The state of the current flow tail, i.e. the node that is the current tail
+/// of our structurization chain:
+/// - None:        region entry, no pending tail yet
+/// - Rewritable:  node with a rewritable terminator
+/// - Closed:      node with a non-rewritable terminator that cannot be used for
+///                flow stitching
+class FlowTail {
+  enum class TailState { None, Rewritable, Closed };
+
+  RegionNode *Node;
+  TailState State;
+
+public:
+  FlowTail() : Node(nullptr), State(TailState::None) {}
+  FlowTail(RegionNode *Node)
+      : Node(Node), State(Node ? TailState::Rewritable : TailState::None) {}
+
+  RegionNode &operator*() {
+    assert(isRewritable() && "FlowTail is not rewritable");
+    return *Node;
+  }
+
+  RegionNode *operator->() {
+    assert(isRewritable() && "FlowTail is not rewritable");
+    return Node;
+  }
+
+  /// Close the flow tail, marking the end of an island.
+  void close(RegionNode *Boundary) {
+    assert(Boundary && "closing requires a boundary node");
+    Node = Boundary;
+    State = TailState::Closed;
+  }
+
+  RegionNode *getClosedEntry() const {
+    assert(isClosed() && "FlowTail is not closed");
+    return Node;
+  }
+
+  bool isClosed() const { return State == TailState::Closed; }
+  bool isNone() const { return State == TailState::None; }
+  bool isRewritable() const { return State == TailState::Rewritable; }
+};
+
 /// Transforms the control flow graph on one single entry/exit region
 /// at a time.
 ///
@@ -302,7 +377,11 @@ class StructurizeCFG {
 
   Val2BBMap HoistedValues;
 
-  RegionNode *PrevNode;
+  FlowTail Tail;
+
+  // True if the region exit domination info needs to be fixed after the
+  // transform due to specific island requirements, see handleIsland.
+  bool NeedFixRegionExitDom = false;
 
   void hoistZeroCostElseBlockPhiValues(BasicBlock *ElseBB, BasicBlock *ThenBB);
 
@@ -342,8 +421,9 @@ class StructurizeCFG {
 
   DebugLoc killTerminator(BasicBlock *BB);
 
-  void changeExit(RegionNode *Node, BasicBlock *NewExit,
-                  bool IncludeDominator);
+  void changeExit(FlowTail &Tail, BasicBlock *NewExit, bool IncludeDominator);
+
+  void checkClosedFlow();
 
   BasicBlock *getNextFlow(BasicBlock *Dominator);
 
@@ -359,6 +439,8 @@ class StructurizeCFG {
 
   void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
 
+  void handleIsland(BasicBlock *CallBrBlock);
+
   void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
 
   void createFlow();
@@ -561,9 +643,8 @@ void StructurizeCFG::analyzeLoops(RegionNode *N) {
 
   } else {
     // Test for successors as back edge
-    // TODO: support other terminators other than branches.
     BasicBlock *BB = N->getNodeAs<BasicBlock>();
-    if (isa<UncondBrInst, CondBrInst>(BB->getTerminator()))
+    if (isa<UncondBrInst, CondBrInst, CallBrInst>(BB->getTerminator()))
       for (BasicBlock *Succ : successors(BB))
         if (Visited.count(Succ))
           Loops[Succ] = BB;
@@ -620,6 +701,14 @@ void StructurizeCFG::gatherPredicates(RegionNode *N) {
           LPred[P] = buildCondition(CondBr, Idx, true);
         }
       }
+      // } else if (isIsland(*P)) {
+      //   // Island edges have no SSA condition, so we treat them as an
+      //   // unconditional branch.
+      //   if (Visited.count(P))
+      //     Pred[P] = {BoolTrue, std::nullopt};
+      //   else
+      //     LPred[P] = {BoolFalse, std::nullopt};
+      // }
     } else {
       // It's an exit from a sub region
       while (R->getParent() != ParentRegion)
@@ -1037,10 +1126,10 @@ DebugLoc StructurizeCFG::killTerminator(BasicBlock *BB) {
 }
 
 /// Let node exit(s) point to NewExit
-void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
+void StructurizeCFG::changeExit(FlowTail &Tail, BasicBlock *NewExit,
                                 bool IncludeDominator) {
-  if (Node->isSubRegion()) {
-    Region *SubRegion = Node->getNodeAs<Region>();
+  if (Tail->isSubRegion()) {
+    Region *SubRegion = Tail->getNodeAs<Region>();
     BasicBlock *OldExit = SubRegion->getExit();
     BasicBlock *Dominator = nullptr;
 
@@ -1071,7 +1160,7 @@ void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
     // Update the region info
     SubRegion->replaceExit(NewExit);
   } else {
-    BasicBlock *BB = Node->getNodeAs<BasicBlock>();
+    BasicBlock *BB = Tail->getNodeAs<BasicBlock>();
     DebugLoc DL = killTerminator(BB);
     UncondBrInst *Br = UncondBrInst::Create(NewExit, BB);
     Br->setDebugLoc(DL);
@@ -1081,6 +1170,18 @@ void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
   }
 }
 
+/// A closed flow tail marks an island boundary that handleIsland already wired
+/// (the callbr itself, whose terminator is immutable, or one of its forwarders,
+/// already converged into the dispatch ladder; see wireFlow). Such a node must
+/// not be rewritten or extended, so before more flow is stitched onto the tail
+/// (needPrefix) swap in a fresh, rewritable Flow node to continue from.
+void StructurizeCFG::checkClosedFlow() {
+  if (!Tail.isClosed())
+    return;
+  BasicBlock *Flow = getNextFlow(ParentRegion->getEntry());
+  Tail = ParentRegion->getBBNode(Flow);
+}
+
 /// Create a new flow node and update dominator tree and region info
 BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
   LLVMContext &Context = Func->getContext();
@@ -1097,9 +1198,10 @@ BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
 /// Create a new or reuse the previous node as flow node. Returns a block and a
 /// debug location to be used for new instructions in that block.
 std::pair<BasicBlock *, DebugLoc> StructurizeCFG::needPrefix(bool NeedEmpty) {
-  BasicBlock *Entry = PrevNode->getEntry();
+  checkClosedFlow();
+  BasicBlock *Entry = Tail->getEntry();
 
-  if (!PrevNode->isSubRegion()) {
+  if (!Tail->isSubRegion()) {
     DebugLoc DL = killTerminator(Entry);
     if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
       return {Entry, DL};
@@ -1109,8 +1211,8 @@ std::pair<BasicBlock *, DebugLoc> StructurizeCFG::needPrefix(bool NeedEmpty) {
   BasicBlock *Flow = getNextFlow(Entry);
 
   // and wire it up
-  changeExit(PrevNode, Flow, true);
-  PrevNode = ParentRegion->getBBNode(Flow);
+  changeExit(Tail, Flow, true);
+  Tail = ParentRegion->getBBNode(Flow);
   return {Flow, DebugLoc()};
 }
 
@@ -1128,8 +1230,7 @@ BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
 
 /// Set the previous node
 void StructurizeCFG::setPrevNode(BasicBlock *BB) {
-  PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
-                                        : nullptr;
+  Tail = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB) : nullptr;
 }
 
 /// Does BB dominate all the predicates of Node?
@@ -1146,14 +1247,15 @@ bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
   bool Dominated = false;
 
   // Regionentry is always true
-  if (!PrevNode)
+  // If we're in a closed flow, we assume that anything might be called.
+  if (Tail.isNone() || Tail.isClosed())
     return true;
 
   for (auto [BB, PI] : Preds) {
     if (PI.Pred != BoolTrue)
       return false;
 
-    if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
+    if (!Dominated && DT->dominates(BB, Tail->getEntry()))
       Dominated = true;
   }
 
@@ -1165,20 +1267,41 @@ bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
 void StructurizeCFG::wireFlow(bool ExitUseAllowed,
                               BasicBlock *LoopEnd) {
   RegionNode *Node = Order.pop_back_val();
-  Visited.insert(Node->getEntry());
+  BasicBlock *Entry = Node->getEntry();
+  Visited.insert(Entry);
+
+  // There is nothing to do for island blocks because they are handled by
+  // handleIsland and we think of their terminators as immutable here.
+  // A subregion whose entry happens to be an island must be wired normally, or
+  // everything inside it past the entry would be dropped.
+  if (!Node->isSubRegion() && isIsland(*Entry)) {
+    Tail.close(Node);
+    return;
+  }
+
+  // A callbr forwarder, a simple single-branch block reached straight from the
+  // callbr (created by handleIsland's edge split, or a reused trivial target),
+  // has already been converged into the dispatch ladder. Close the tail and
+  // leave it, so the normal machinery does not redirect it out of the ladder.
+  bool HasIslandPred = llvm::any_of(
+      predecessors(Entry), [](BasicBlock *Pred) { return isIsland(*Pred); });
+  if (HasIslandPred && isIntermediateTarget(*Entry)) {
+    Tail.close(Node);
+    return;
+  }
 
   if (isPredictableTrue(Node)) {
-    // Just a linear flow
-    if (PrevNode) {
-      changeExit(PrevNode, Node->getEntry(), true);
-    }
-    PrevNode = Node;
+    // Just a linear flow. Only a rewritable tail is redirected to flow into
+    // this node; a closed tail is an island boundary handleIsland already
+    // wired, so it is left as-is.
+    if (Tail.isRewritable())
+      changeExit(Tail, Entry, true);
+    Tail = Node;
   } else {
     // Insert extra prefix node (or reuse last one)
     auto [Flow, DL] = needPrefix(false);
 
     // Insert extra postfix node (or use exit instead)
-    BasicBlock *Entry = Node->getEntry();
     BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
 
     // let it point to entry and next block
@@ -1188,17 +1311,200 @@ void StructurizeCFG::wireFlow(bool ExitUseAllowed,
     addPhiValues(Flow, Entry);
     DT->changeImmediateDominator(Entry, Flow);
 
-    PrevNode = Node;
+    Tail = Node;
     while (!Order.empty() && !Visited.count(LoopEnd) &&
            dominatesPredicates(Entry, Order.back())) {
       handleLoops(false, LoopEnd);
     }
 
-    changeExit(PrevNode, Next, false);
+    if (Tail.isRewritable())
+      changeExit(Tail, Next, false);
     setPrevNode(Next);
   }
 }
 
+/// Handle an "island", i.e. a block whose terminator is not rewritable (e.g., a
+/// callbr) in this context and considered immutable from this pass's
+/// perspective.
+///
+/// The island is left untouched; its edges are split into forwarders that
+/// converge at a new Flow block (ExitFlow). The callbr's runtime target choice
+/// is recovered as a per-target i1 "sel" phi and re-dispatched by a structured
+/// ladder of 2-way branches:
+///
+///                  callbr
+///                /   |   \
+///            fwd_0 fwd_1 fwd_2      forwarders (intermediate target blocks)
+///                \   |   /
+///             ExitFlow (Flow_0) -- sel_0? --> real_0
+///                   |  else
+///                 Flow_1 --------- sel_1? --> real_1
+///                   |  else
+///              real_2
+///            or Flow_2 (if real_1 == real_2) ------> real_2   (shared last
+///            target)
+///
+void StructurizeCFG::handleIsland(BasicBlock *IslandBB) {
+  DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
+
+  // 1. Split the island's edges into forwarders, so the island's targets are no
+  // longer direct successors of the (immutable) callbr terminator. This also
+  // turns a self-loop back-edge into a *mutable* forwarder, so later steps
+  // never rewrite the island edge itself.
+  //
+  // Reuse a target as-is only if it is already a trivial forwarder *inside this
+  // region*. A trivial target that is the region's exit block is still split:
+  // the ladder consumes its forwarders, and consuming the exit block would move
+  // the region's SESE boundary, which the precomputed RegionInfo cannot
+  // represent.
+  SmallVector<BasicBlock *, 4> Targets;
+  if (CallBrInst *CallBr = dyn_cast<CallBrInst>(IslandBB->getTerminator())) {
+    for (unsigned I = 0; I < CallBr->getNumSuccessors(); ++I) {
+      BasicBlock *Target = CallBr->getSuccessor(I);
+      // Leave an unreachable target's callbr edge direct and keep the dead lane
+      // out of the dispatch sel phi, which SILowerI1Copies cannot lower. It
+      // stays a direct predecessor of its successor and is not part of the
+      // ladder.
+      // However, that gives the region exit a predecessor createFlow's
+      // single-pred exit wiring does not account for. Flag that the exit's
+      // immediate dominator needs to be fixed.
+      if (isUnreachableTarget(*Target)) {
+        NeedFixRegionExitDom = true;
+        continue;
+      }
+      if (isIntermediateTarget(*Target) && ParentRegion->contains(Target)) {
+        Targets.push_back(Target);
+        continue;
+      }
+      BasicBlock *NewBB = SplitCallBrEdge(IslandBB, Target, I, &DTU);
+      ParentRegion->getRegionInfo()->setRegionFor(NewBB, ParentRegion);
+      Targets.push_back(NewBB);
+    }
+  } else {
+    llvm_unreachable("not a supported island type");
+  }
+
+  // 2. Create EntryFlow in front of the island for its in-region, non-forwarder
+  // predecessors (e.g. a loop back-edge from a separate latch), giving a
+  // rewritable header anchor. Forwarders route through the ladder instead.
+  // Out-of-region predecessors (only the region entry has any, by SESE) stay
+  // direct, keeping the region boundary intact. Skipped when empty to avoid an
+  // orphan Flow.
+  SmallVector<BasicBlock *, 4> Preds;
+  for (BasicBlock *Pred : predecessors(IslandBB))
+    if (ParentRegion->contains(Pred) && !llvm::is_contained(Targets, Pred))
+      Preds.push_back(Pred);
+  if (!Preds.empty()) {
+    BasicBlock *EntryFlow = SplitBlockPredecessors(IslandBB, Preds, "", &DTU);
+    EntryFlow->setName(FlowBlockName);
+    FlowSet.insert(EntryFlow);
+    ParentRegion->getRegionInfo()->setRegionFor(EntryFlow, ParentRegion);
+  }
+
+  // 3. Build the dispatch ladder shown in the diagram above. sel_k is the i1
+  // phi in ExitFlow that is true only on the edge from forwarder k; ExitFlow
+  // dominates the whole ladder, so the sel phis are usable at every level. If
+  // the island has a self-loop, it is dispatched by the ladder as well.
+  //
+  // Edge edits are recorded in DTUpdates and applied via the same
+  // DomTreeUpdater, keeping the DominatorTree incrementally correct. The island
+  // Flow blocks are created without DT->addNewBlock and get their idoms from
+  // the inserted edges, so we must not mix in a direct getNextFlow here.
+  unsigned N = Targets.size();
+  SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
+  auto MakeFlow = [&]() {
+    BasicBlock *Flow = BasicBlock::Create(Func->getContext(), FlowBlockName,
+                                          Func, ParentRegion->getExit());
+    FlowSet.insert(Flow);
+    ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
+    return Flow;
+  };
+  BasicBlock *ExitFlow = MakeFlow();
+
+  // Converge every forwarder into ExitFlow and remember the real target each
+  // one guards (its single successor). Real's phi incomings from the forwarder
+  // are re-bound onto the ladder edge in the dispatch loop below: we maintain
+  // SSA directly because handleIsland runs before createFlow, which clears the
+  // deferred delPhiValues/addPhiValues bookkeeping.
+  SmallVector<BasicBlock *, 4> RealTargets;
+  RealTargets.reserve(N);
+  for (BasicBlock *Fwd : Targets) {
+    BasicBlock *Real = Fwd->getSingleSuccessor();
+    assert(Real && "forwarder must have a single successor");
+    RealTargets.push_back(Real);
+
+    DebugLoc DL = Fwd->getTerminator()->getDebugLoc();
+    Fwd->getTerminator()->eraseFromParent();
+    UncondBrInst::Create(ExitFlow, Fwd)->setDebugLoc(DL);
+    DTUpdates.push_back({DominatorTree::Delete, Fwd, Real});
+    DTUpdates.push_back({DominatorTree::Insert, Fwd, ExitFlow});
+  }
+
+  // Materialize the per-target selection booleans in ExitFlow: sel_k is true
+  // exactly on the edge coming from Targets[k]. The last target needs no
+  // sel: it is the unconditional "else" of the ladder.
+  SmallVector<PHINode *, 4> Sel;
+  Sel.reserve(N ? N - 1 : 0);
+  for (unsigned I = 0; I + 1 < N; ++I) {
+    PHINode *P = PHINode::Create(Boolean, N, "island.sel");
+    P->insertInto(ExitFlow, ExitFlow->end());
+    for (unsigned J = 0; J < N; ++J)
+      P->addIncoming(J == I ? BoolTrue : BoolFalse, Targets[J]);
+    Sel.push_back(P);
+  }
+
+  // Wire each ladder level's 2-way branch to its real target.
+  BasicBlock *CurFlow = ExitFlow;
+  auto RebindRealPhis = [](BasicBlock *Real, BasicBlock *Fwd,
+                           BasicBlock *NewPred) {
+    for (PHINode &Phi : Real->phis()) {
+      int Idx = Phi.getBasicBlockIndex(Fwd);
+      if (Idx != -1)
+        Phi.setIncomingBlock(Idx, NewPred);
+    }
+  };
+  for (unsigned I = 0; I < N; ++I) {
+    BasicBlock *Fwd = Targets[I];
+    BasicBlock *Real = RealTargets[I];
+
+    // Real is now entered from CurFlow instead of from its forwarder. Re-bind
+    // Real's phi incomings from Fwd onto the new CurFlow edge, keeping the
+    // original value. This preserves phis that distinguish island targets (e.g.
+    // a join phi selecting the callbr's =r output on the fallthrough vs another
+    // value on an indirect target). The value was defined before the callbr (or
+    // is the callbr's own output), so it dominates CurFlow.
+    RebindRealPhis(Real, Fwd, CurFlow);
+
+    if (I + 1 < N) {
+      BasicBlock *NextReal = RealTargets[I + 1];
+      if (I + 2 == N && Real != NextReal) {
+        // Optimization for last target: branch directly to the final real
+        // target when that keeps the two island lanes as distinct CFG edges.
+        // Shared targets need the final Flow block so PHIs can retain per-lane
+        // values.
+        RebindRealPhis(NextReal, Targets[I + 1], CurFlow);
+        CondBrInst::Create(Sel[I], Real, NextReal, CurFlow);
+        DTUpdates.push_back({DominatorTree::Insert, CurFlow, Real});
+        DTUpdates.push_back({DominatorTree::Insert, CurFlow, NextReal});
+        break;
+      }
+
+      BasicBlock *NextFlow = MakeFlow();
+      CondBrInst::Create(Sel[I], Real, NextFlow, CurFlow);
+      DTUpdates.push_back({DominatorTree::Insert, CurFlow, Real});
+      DTUpdates.push_back({DominatorTree::Insert, CurFlow, NextFlow});
+      CurFlow = NextFlow;
+    } else {
+      // Last target: unconditional else of the ladder.
+      UncondBrInst::Create(Real, CurFlow);
+      DTUpdates.push_back({DominatorTree::Insert, CurFlow, R...
[truncated]

@jayfoad
jayfoad requested a review from ruiling June 8, 2026 13:31
@ro-i

ro-i commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

(the test failure is the current Windows CI issue sccache: error: Timed out waiting for server startup. Maybe the remote service is unreachable?, unrelated to this PR)

@ro-i

ro-i commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

(history of this PR: #152161)

@ro-i

ro-i commented Jun 22, 2026

Copy link
Copy Markdown
Contributor Author

ping (since this is probably for everyone a bit of a side project, it's ~2week ping :) )

@ro-i
ro-i force-pushed the users/ro-i/structurize-islands branch from d8f9b04 to b4503ac Compare July 8, 2026 15:50
/// serve as a rewritable flow tail (it can be neither killed nor have its
/// successors rewritten). Currently only callbr.
static bool isIsland(const BasicBlock *BB) {
return isa<CallBrInst>(BB->getTerminator());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we handle invoke next, or does that already work?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this PR builds the base for all "multi-branch" constructs, it should not be that hard to make work, ig. But I feel like this is out-of-scope for this PR at the moment

Comment thread llvm/test/CodeGen/AMDGPU/callbr.ll Resolved
@ro-i
ro-i force-pushed the users/ro-i/structurize-islands branch from b4503ac to 34e7907 Compare August 27, 2026 07:15
@ro-i

ro-i commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

note to potential reviewers: pls put this again in your review queue, I first need to fix/investigate something I just noticed :)

@ro-i
ro-i force-pushed the users/ro-i/structurize-islands branch from 34e7907 to 00f03e7 Compare October 13, 2026 08:44
@ro-i

ro-i commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

the top 5 commits are new. Mostly test updates after rebases. This branch had been waiting on #206739 and #228744.
Also a fix for the hasOnlyUniformBranches.

PR should now be in a good shape to enter CQE. This might take an undefined amount of time

@ro-i

ro-i commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

(test failure unrelated)

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

🪟 Windows x64 Test Results

  • 147251 tests passed
  • 2297 tests skipped

✅ The build succeeded and all tests passed.

@jayfoad

jayfoad commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

With this test case, opt -passes=structurizecfg hits the assertion "cannot get terminator of non-well-formed block"

term.red.txt

@jayfoad

jayfoad commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

With these test cases, verify<domtree> will complain that the domtree has not been updated properly:

dt.amdgpu.txt
dt.red.txt

@ro-i

ro-i commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@jayfoad

jayfoad commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

I have not had a chance to dive deep into this PR yet.

I would like to see a better description. What terminators are currently unsupported by StructurizeCFG and how does it fail? What support is add by this PR? Does it now fully support callbr? switch?

Handle an "island", i.e. a block whose terminator is not rewritable (e.g., a callbr) in this context and considered immutable from this pass's perspective.

In what sense is callbr less rewritable than a normal conditional branch?

@ro-i

ro-i commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

In what sense is callbr less rewritable than a normal conditional branch?

A conditional branch can be inspected and targets can be exchanged. For example a br i1 %c, label %then, label %else can be rewritten to br i1 %c, label %then, label %Flow to generate the flow structure that this pass should ensure. Flow will have two incoming blocks: the block of the branch and %then. It can use %c to determine where the control flow came from. But you cannot rewrite the target branches of a callbr because then you cannot reconstruct in the Flow block structure from where the control flow came. Because from the POV of the structurizer, the callbr's callee is a black box. Aka, you need these intermediate target blocks that are shown in the ASCII art. Then, you can use them to determine in the Flow block (chain) from where the control flow came.

What terminators are currently unsupported by StructurizeCFG and how does it fail?

Only (conditional) br was supported and callbr "partially" in the sense that we let it through if we thought that it's not going to cause issues (like for the llvm.amdgcn.kill() usage). See, e.g. #152161 (comment) for more history. If these conditions are not met, it fails like #170830 shows.

What support is add by this PR? Does it now fully support callbr? switch?

This PR now actually supports structurizing the callbr's children (see the examples in the many tests I added). It does so by adding an infrastructure that can be used for any kind of multi-branch terminator*. Thus, the support for switch is prepared, but I did not implement it in the same go. And I probably won't add support for switch for now, because it's not going to help any use case - the AMDGPU backend doesn't support switches anyway at the moment (that's why the lowerswitches pass exists afaik).
*I called them islands because they are supposed to be left alone. Only their intermediate target blocks that I talked about are supposed to be touched by the structurizer.

@ro-i

ro-i commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

But you cannot rewrite the target branches of a callbr ...

... in the sense that you directly let them go into the flow block like callbr ... to label %a [label %Flow, label %Flow, label %Flow]
You can rewrite them to redirect them through the intermediate targets, but that's not what I'm referring to when I speak of "rewriting" in the context of this pass.
Just to further clarify 😅

@ro-i

ro-i commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

added test suggested by @mgcarrasco 's tool in ROCm/fuzz-fill#182 (comment). PR has now verified coverage (see the report in ROCm/fuzz-fill#182)

ro-i added 16 commits November 5, 2026 10:47
Handle an "island", i.e. a block whose terminator is not rewritable
(e.g., a callbr) in this context and considered immutable from this
pass's perspective.

The island is left untouched; its edges are split into forwarders that
converge at a new Flow block (ExitFlow). The callbr's runtime target
choice is recovered as a per-target i1 "sel" phi and re-dispatched by a
structured ladder of 2-way branches:

                 callbr
               /   |   \
           fwd_0 fwd_1 fwd_2      forwarders (intermediate target blocks)
               \   |   /
            ExitFlow (Flow_0) -- sel_0? --> real_0
                  |  else
                Flow_1 --------- sel_1? --> real_1
                  |  else
             real_2
           or Flow_2 (if real_1 == real_2) ------> real_2   (shared last target)
@jayfoad

jayfoad commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

And I probably won't add support for switch for now, because it's not going to help any use case - the AMDGPU backend doesn't support switches anyway at the moment (that's why the lowerswitches pass exists afaik).

It's kind of the other way round: the backend doesn't support switch because the structurizer doesn't support switch. Adding backend support for uniform switch implemented with a jump table would be a nice improvement.

@ro-i

ro-i commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

that is most probably true, but not in scope for this PR :) Regarding this PR, I think it does not conflict with such future scenario

@ro-i
ro-i force-pushed the users/ro-i/structurize-islands branch from 0562159 to e23aefa Compare November 5, 2026 17:07
@ro-i

ro-i commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

rebased to verify CI results with current llvm/main + added CHECK lines for the new test (forgot that 5mins ago when I added it 🙃 )

@jayfoad

jayfoad commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Next question, is this intended to handle callbr asm or callbr to an intrinsic (or both)? In either case, is the branch condition (i.e. the choice of which successor it branches to) expected to be uniform or divergent? If it's uniform then why do we need to structurize it? If it's divergent then how do we codegen it -- it seems like that could only work for certain known intrinsics, and not for arbitrary asm?

@ro-i

ro-i commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Next question, is this intended to handle callbr asm or callbr to an intrinsic (or both)?

Both, but callbr with intrinsics is only supported for selected intrinsics, not arbitrary ones. The only one currently supported is llvm.amdgcn.kill().

In either case, is the branch condition (i.e. the choice of which successor it branches to) expected to be uniform or divergent?

no expectation

If it's uniform then why do we need to structurize it?

We need to let the target blocks participate in the structurization.

If it's divergent then how do we codegen it -- it seems like that could only work for certain known intrinsics, and not for arbitrary asm?

Yes, if the asm is clashing with what our backend expects, it happens what happens for any unsupported inline asm blob. And for the intrinsic case: we're only supporting selected intrinsics for callbr (that's not even decided by the structurizer, that's already checked by the verifier)

@github-actions
github-actions Bot deleted the users/ro-i/structurize-islands branch November 12, 2026 08:11

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[AMDGPU] LLVM ERROR: failed to annotate CFG

3 participants