[llvm] [SimplifyCFG][PGO] Add missing overflow check to ConstantFoldTerminator (PR #178964)

Mitchel Dickerson via llvm-commits llvm-commits at lists.llvm.org
Sat Jan 31 04:41:15 PST 2026


================
@@ -223,17 +223,21 @@ bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
         // left, unless the metadata doesn't match the switch.
         if (NCases > 1 && MD) {
           // Collect branch weights into a vector.
-          SmallVector<uint32_t, 8> Weights;
-          extractBranchWeights(MD, Weights);
+          SmallVector<uint64_t, 8> Weights;
+          extractFromBranchWeightMD64(MD, Weights);
 
           // Merge weight of this case to the default weight.
           unsigned Idx = It->getCaseIndex();
-          // TODO: Add overflow check.
+
+          // Check for and prevent uint64_t overflow by reducing branch weights.
+          if (Weights[0] > UINT64_MAX - Weights[Idx + 1])
+            fitWeights(Weights);
+
           Weights[0] += Weights[Idx + 1];
----------------
mauve-stinger wrote:

My understanding is that yes, SimplifyCFG is mostly expecting 32 bit branch weights. I try to match that expectation and pattern by using `setFittedBranchWeights` in the assignment after folding, and thought that fitting items that overflow 64 bit adds would maintain more information than saturating.

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


More information about the llvm-commits mailing list