LLVM API Documentation
00001 //===-------------- lib/Support/BranchProbability.cpp -----------*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements Branch Probability class. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "llvm/Support/BranchProbability.h" 00015 #include "llvm/Support/Debug.h" 00016 #include "llvm/Support/Format.h" 00017 #include "llvm/Support/raw_ostream.h" 00018 00019 using namespace llvm; 00020 00021 raw_ostream &BranchProbability::print(raw_ostream &OS) const { 00022 return OS << N << " / " << D << " = " 00023 << format("%g%%", ((double)N / D) * 100.0); 00024 } 00025 00026 void BranchProbability::dump() const { print(dbgs()) << '\n'; } 00027 00028 static uint64_t scale(uint64_t Num, uint32_t N, uint32_t D) { 00029 assert(D && "divide by 0"); 00030 00031 // Fast path for multiplying by 1.0. 00032 if (!Num || D == N) 00033 return Num; 00034 00035 // Split Num into upper and lower parts to multiply, then recombine. 00036 uint64_t ProductHigh = (Num >> 32) * N; 00037 uint64_t ProductLow = (Num & UINT32_MAX) * N; 00038 00039 // Split into 32-bit digits. 00040 uint32_t Upper32 = ProductHigh >> 32; 00041 uint32_t Lower32 = ProductLow & UINT32_MAX; 00042 uint32_t Mid32Partial = ProductHigh & UINT32_MAX; 00043 uint32_t Mid32 = Mid32Partial + (ProductLow >> 32); 00044 00045 // Carry. 00046 Upper32 += Mid32 < Mid32Partial; 00047 00048 // Check for overflow. 00049 if (Upper32 >= D) 00050 return UINT64_MAX; 00051 00052 uint64_t Rem = (uint64_t(Upper32) << 32) | Mid32; 00053 uint64_t UpperQ = Rem / D; 00054 00055 // Check for overflow. 00056 if (UpperQ > UINT32_MAX) 00057 return UINT64_MAX; 00058 00059 Rem = ((Rem % D) << 32) | Lower32; 00060 uint64_t LowerQ = Rem / D; 00061 uint64_t Q = (UpperQ << 32) + LowerQ; 00062 00063 // Check for overflow. 00064 return Q < LowerQ ? UINT64_MAX : Q; 00065 } 00066 00067 uint64_t BranchProbability::scale(uint64_t Num) const { 00068 return ::scale(Num, N, D); 00069 } 00070 00071 uint64_t BranchProbability::scaleByInverse(uint64_t Num) const { 00072 return ::scale(Num, D, N); 00073 }