LLVM API Documentation
00001 //===- BranchProbability.h - Branch Probability Wrapper ---------*- 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 // Definition of BranchProbability shared by IR and Machine Instructions. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #ifndef LLVM_SUPPORT_BRANCHPROBABILITY_H 00015 #define LLVM_SUPPORT_BRANCHPROBABILITY_H 00016 00017 #include "llvm/Support/DataTypes.h" 00018 #include <cassert> 00019 00020 namespace llvm { 00021 00022 class raw_ostream; 00023 00024 // This class represents Branch Probability as a non-negative fraction. 00025 class BranchProbability { 00026 // Numerator 00027 uint32_t N; 00028 00029 // Denominator 00030 uint32_t D; 00031 00032 public: 00033 BranchProbability(uint32_t n, uint32_t d) : N(n), D(d) { 00034 assert(d > 0 && "Denomiator cannot be 0!"); 00035 assert(n <= d && "Probability cannot be bigger than 1!"); 00036 } 00037 00038 static BranchProbability getZero() { return BranchProbability(0, 1); } 00039 static BranchProbability getOne() { return BranchProbability(1, 1); } 00040 00041 uint32_t getNumerator() const { return N; } 00042 uint32_t getDenominator() const { return D; } 00043 00044 // Return (1 - Probability). 00045 BranchProbability getCompl() const { 00046 return BranchProbability(D - N, D); 00047 } 00048 00049 raw_ostream &print(raw_ostream &OS) const; 00050 00051 void dump() const; 00052 00053 /// \brief Scale a large integer. 00054 /// 00055 /// Scales \c Num. Guarantees full precision. Returns the floor of the 00056 /// result. 00057 /// 00058 /// \return \c Num times \c this. 00059 uint64_t scale(uint64_t Num) const; 00060 00061 /// \brief Scale a large integer by the inverse. 00062 /// 00063 /// Scales \c Num by the inverse of \c this. Guarantees full precision. 00064 /// Returns the floor of the result. 00065 /// 00066 /// \return \c Num divided by \c this. 00067 uint64_t scaleByInverse(uint64_t Num) const; 00068 00069 bool operator==(BranchProbability RHS) const { 00070 return (uint64_t)N * RHS.D == (uint64_t)D * RHS.N; 00071 } 00072 bool operator!=(BranchProbability RHS) const { 00073 return !(*this == RHS); 00074 } 00075 bool operator<(BranchProbability RHS) const { 00076 return (uint64_t)N * RHS.D < (uint64_t)D * RHS.N; 00077 } 00078 bool operator>(BranchProbability RHS) const { return RHS < *this; } 00079 bool operator<=(BranchProbability RHS) const { return !(RHS < *this); } 00080 bool operator>=(BranchProbability RHS) const { return !(*this < RHS); } 00081 }; 00082 00083 inline raw_ostream &operator<<(raw_ostream &OS, const BranchProbability &Prob) { 00084 return Prob.print(OS); 00085 } 00086 00087 } 00088 00089 #endif