[llvm] MachineBlockPlacement: Add tolerance to comparisons (PR #67197)

Rahman Lavaee via llvm-commits llvm-commits at lists.llvm.org
Thu Oct 5 18:27:12 PDT 2023


================
@@ -1750,12 +1753,33 @@ MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
     //                 +-------------------------------------+
     //                 V                                     |
     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
-    if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
+    if (BestFreq > BlockFrequency(0) &&
+        (ReverseOrder ^ (BestFreq >= CandidateFreq)))
       continue;
 
-    BestBlock = MBB;
     BestFreq = CandidateFreq;
   }
+  // Perform a 2nd pass to make the output more stable: Check for blocks with
+  // almost the same frequency as `BestFreq` and prefer the one that is already
+  // a successor to `ChainEnd` first or whichever comes first in `WorkList`.
+  MachineBasicBlock *BestBlock = nullptr;
+  for (MachineBasicBlock *MBB : WorkList) {
+    BlockChain &SuccChain = *BlockToChain[MBB];
+    if (&SuccChain == &Chain)
+      continue;
+    BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
+    if (!ReverseOrder) {
+      if (!BestFreq.almostEqual(CandidateFreq))
+        continue;
+    } else if (!CandidateFreq.almostEqual(BestFreq)) {
+      continue;
+    }
+    // Give precedence to the block already following `ChainEnd`, otherwise take
+    // the first one we encounter.
+    if (BestBlock == nullptr || ChainEnd->isLayoutSuccessor(MBB)) {
----------------
rlavaee wrote:

I was mostly considering readability. performance-wise, you can just store the layout successor (since it won't change in the loop) and compare against that.  This also allows avoiding the expensive DenseMap lookup.  Roughly: 

```
 const MachineBasicBlock * LayoutSucc =  ChainEnd->getNextBlock();
 for (MachineBasicBlock *MBB : WorkList) {
   if (BestBlock != nullptr && MBB  != LayoutSucc)
     continue;
    BlockChain &SuccChain = *BlockToChain[MBB];
    if (&SuccChain == &Chain)
      continue;
    BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
    if (!BestFreq.almostEqual(CandidateFreq))
        continue;
    BestBlock = MBB;
  }

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


More information about the llvm-commits mailing list