diff lib/Support/BranchProbability.cpp @ 77:54457678186b

LLVM 3.6
author Kaito Tokumori <e105711@ie.u-ryukyu.ac.jp>
date Mon, 08 Sep 2014 22:06:00 +0900
parents 95c75e76d11b
children afa8332a0e37
line wrap: on
line diff
--- a/lib/Support/BranchProbability.cpp	Thu Dec 12 15:22:36 2013 +0900
+++ b/lib/Support/BranchProbability.cpp	Mon Sep 08 22:06:00 2014 +0900
@@ -18,19 +18,56 @@
 
 using namespace llvm;
 
-void BranchProbability::print(raw_ostream &OS) const {
-  OS << N << " / " << D << " = " << format("%g%%", ((double)N / D) * 100.0);
-}
-
-void BranchProbability::dump() const {
-  dbgs() << *this << '\n';
+raw_ostream &BranchProbability::print(raw_ostream &OS) const {
+  return OS << N << " / " << D << " = "
+            << format("%g%%", ((double)N / D) * 100.0);
 }
 
-namespace llvm {
+void BranchProbability::dump() const { print(dbgs()) << '\n'; }
+
+static uint64_t scale(uint64_t Num, uint32_t N, uint32_t D) {
+  assert(D && "divide by 0");
+
+  // Fast path for multiplying by 1.0.
+  if (!Num || D == N)
+    return Num;
+
+  // Split Num into upper and lower parts to multiply, then recombine.
+  uint64_t ProductHigh = (Num >> 32) * N;
+  uint64_t ProductLow = (Num & UINT32_MAX) * N;
+
+  // Split into 32-bit digits.
+  uint32_t Upper32 = ProductHigh >> 32;
+  uint32_t Lower32 = ProductLow & UINT32_MAX;
+  uint32_t Mid32Partial = ProductHigh & UINT32_MAX;
+  uint32_t Mid32 = Mid32Partial + (ProductLow >> 32);
 
-raw_ostream &operator<<(raw_ostream &OS, const BranchProbability &Prob) {
-  Prob.print(OS);
-  return OS;
+  // Carry.
+  Upper32 += Mid32 < Mid32Partial;
+
+  // Check for overflow.
+  if (Upper32 >= D)
+    return UINT64_MAX;
+
+  uint64_t Rem = (uint64_t(Upper32) << 32) | Mid32;
+  uint64_t UpperQ = Rem / D;
+
+  // Check for overflow.
+  if (UpperQ > UINT32_MAX)
+    return UINT64_MAX;
+
+  Rem = ((Rem % D) << 32) | Lower32;
+  uint64_t LowerQ = Rem / D;
+  uint64_t Q = (UpperQ << 32) + LowerQ;
+
+  // Check for overflow.
+  return Q < LowerQ ? UINT64_MAX : Q;
 }
 
+uint64_t BranchProbability::scale(uint64_t Num) const {
+  return ::scale(Num, N, D);
 }
+
+uint64_t BranchProbability::scaleByInverse(uint64_t Num) const {
+  return ::scale(Num, D, N);
+}