BlockFrequency: Use a smarter overflow check.
authorBenjamin Kramer <benny.kra@googlemail.com>
Thu, 27 Oct 2011 16:38:50 +0000 (16:38 +0000)
committerBenjamin Kramer <benny.kra@googlemail.com>
Thu, 27 Oct 2011 16:38:50 +0000 (16:38 +0000)
This trades one 64 bit div for one 64 bit mul and some arithmetic.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@143106 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Support/BlockFrequency.cpp

index a63bf83f20394344f003fcd37cca980f7e6d8ccc..84a993e3e5b6fd6a54dad76dc982b2c7ced36cf1 100644 (file)
@@ -70,8 +70,13 @@ BlockFrequency &BlockFrequency::operator*=(const BranchProbability &Prob) {
 
   assert(n <= d && "Probability must be less or equal to 1.");
 
-  // If we can overflow use 96-bit operations.
-  if (n > 0 && Frequency > UINT64_MAX / n) {
+  // Calculate Frequency * n.
+  uint64_t mulLo = (Frequency & UINT32_MAX) * n;
+  uint64_t mulHi = (Frequency >> 32) * n;
+  uint64_t mulRes = (mulHi << 32) + mulLo;
+
+  // If there was overflow use 96-bit operations.
+  if (mulHi > UINT32_MAX || mulRes < mulLo) {
     // 96-bit value represented as W[1]:W[0].
     uint64_t W[2];
 
@@ -82,8 +87,7 @@ BlockFrequency &BlockFrequency::operator*=(const BranchProbability &Prob) {
     return *this;
   }
 
-  Frequency *= n;
-  Frequency /= d;
+  Frequency = mulRes / d;
   return *this;
 }