Skip to content

Commit f3d8dcb

Browse files
committed
[SimplifyCFG] Fix weight calculation for simplifySwitchOfPowersOfTwo
1 parent 045f3ce commit f3d8dcb

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

llvm/lib/Transforms/Utils/SimplifyCFG.cpp

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7648,13 +7648,18 @@ static bool simplifySwitchOfPowersOfTwo(SwitchInst *SI, IRBuilder<> &Builder,
76487648
NewWeights[1] = Weights[0] / 2;
76497649
NewWeights[0] = OrigDenominator - NewWeights[1];
76507650
setFittedBranchWeights(*BI, NewWeights, /*IsExpected=*/false);
7651-
7652-
// For the original switch, we reduce the weight of the default by the
7653-
// amount by which the previous branch contributes to getting to default,
7654-
// and then make sure the remaining weights have the same relative ratio
7655-
// wrt eachother.
7651+
// The probability of executing the default block stays constant. It was
7652+
// p_d = Weights[0] / OrigDenominator
7653+
// we rewrite as W/D
7654+
// We want to find the probability of the default branch of the switch
7655+
// statement. Let's call it X. We have W/D = W/2D + X * (1-W/2D)
7656+
// i.e. the original probability is the probability we go to the default
7657+
// branch from the BI branch, or we take the default branch on the SI.
7658+
// Meaning X = W / (2D - W), or (W/2) / (D - W/2)
7659+
// This matches using W/2 for the default branch probability numerator and
7660+
// D-W/2 as the denominator.
7661+
Weights[0] = NewWeights[1];
76567662
uint64_t CasesDenominator = OrigDenominator - Weights[0];
7657-
Weights[0] /= 2;
76587663
for (auto &W : drop_begin(Weights))
76597664
W = NewWeights[0] * static_cast<double>(W) / CasesDenominator;
76607665

llvm/test/Transforms/SimplifyCFG/X86/switch-of-powers-of-two.ll

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,5 +141,5 @@ return:
141141
;.
142142
; CHECK: [[PROF0]] = !{!"function_entry_count", i32 10}
143143
; CHECK: [[PROF1]] = !{!"branch_weights", i32 58, i32 5}
144-
; CHECK: [[PROF2]] = !{!"branch_weights", i32 56, i32 5}
144+
; CHECK: [[PROF2]] = !{!"branch_weights", i32 53, i32 5}
145145
;.

0 commit comments

Comments
 (0)