[llvm] [profcheck][coro] Adding Branch weights PGO in Coroutines Passes (PR #184466)

Jin Huang via llvm-commits llvm-commits at lists.llvm.org
Sun Mar 8 17:50:11 PDT 2026


================
@@ -1594,6 +1604,23 @@ struct SwitchCoroutineSplitter {
       ++SuspendIndex;
     }
 
+    // Add the branch weights to the switch instruction.
+    if (!ProfcheckDisableMetadataFixes) {
+      if (!Shape.CoroSuspends.empty()) {
+        SmallVector<uint32_t> Weights;
+        // Add the Unlikly weight for the default case.
+        Weights.push_back(llvm::MDBuilder::kUnlikelyBranchWeight);
+        // The first case (IndexVal == 0) represents the coroutine initialization, 
+        // which is expected to be the most common case, so we give it the highest weight. 
+        Weights.push_back(llvm::MDBuilder::kLikelyBranchWeight);
+        // Remaning cases are unlikely to be hit, so we give them the unlikely weight.
----------------
jinhuang1102 wrote:

You are right.

```
entry.resume:
  ...
  switch i2 %index, label %unreachable [
    i2 0, label %CoroSave1
    i2 1, label %AfterCoroSuspend3
    i2 -2, label %AfterCoroSuspend7
    i2 -1, label %cleanup
  ]
```
Among these four cases, 
- `i2 0` represents the initial creation and first resume of the coroutine, occurring once.  
- The cases `i2 1` and `i2 -2` represent the steady-state resume cycles and can occur multiple times. Therefore, we assign `kLikelyBranchWeight` to reflect their higher execution frequency.
- The cleanup case `i2 -1` is a terminal state that only executes once.


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


More information about the llvm-commits mailing list