[llvm] [SPIR-V] Sort basic blocks to match the SPIR-V spec (PR #102929)

Nathan Gauër via llvm-commits llvm-commits at lists.llvm.org
Tue Aug 20 09:47:20 PDT 2024


================
@@ -150,6 +152,51 @@ static void processNewInstrs(MachineFunction &MF, SPIRVGlobalRegistry *GR,
   }
 }
 
+// Do a preorder traversal of the CFG starting from the BB |Start|.
+// point. Calls |op| on each basic block encountered during the traversal.
+void visit(MachineFunction &MF, MachineBasicBlock &Start,
+           std::function<void(MachineBasicBlock *)> op) {
+  std::stack<MachineBasicBlock *> ToVisit;
+  SmallPtrSet<MachineBasicBlock *, 8> Seen;
+
+  ToVisit.push(&Start);
+  Seen.insert(ToVisit.top());
+  while (ToVisit.size() != 0) {
+    MachineBasicBlock *MBB = ToVisit.top();
+    ToVisit.pop();
+
+    op(MBB);
+
+    for (auto Succ : MBB->successors()) {
+      if (Seen.contains(Succ))
+        continue;
+      ToVisit.push(Succ);
+      Seen.insert(Succ);
+    }
+  }
+}
+
+// Do a preorder traversal of the CFG starting from the given function's entry
+// point. Calls |op| on each basic block encountered during the traversal.
+void visit(MachineFunction &MF, std::function<void(MachineBasicBlock *)> op) {
+  visit(MF, *MF.begin(), op);
+}
+
+// Sorts basic blocks by dominance to respect the SPIR-V spec.
+void sortBlocks(MachineFunction &MF) {
+  MachineDominatorTree MDT(MF);
+
+  std::unordered_map<MachineBasicBlock *, size_t> Order;
----------------
Keenuts wrote:

Yes, that's a good idea! Updated the PR, thanks!

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


More information about the llvm-commits mailing list