1 //====--------------- lib/Support/BlockFrequency.cpp -----------*- C++ -*-====//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements Block Frequency class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Support/BlockFrequency.h"
14 #include "llvm/Support/BranchProbability.h"
15 #include <cassert>
16 
17 using namespace llvm;
18 
19 BlockFrequency &BlockFrequency::operator*=(BranchProbability Prob) {
20   Frequency = Prob.scale(Frequency);
21   return *this;
22 }
23 
24 BlockFrequency BlockFrequency::operator*(BranchProbability Prob) const {
25   BlockFrequency Freq(Frequency);
26   Freq *= Prob;
27   return Freq;
28 }
29 
30 BlockFrequency &BlockFrequency::operator/=(BranchProbability Prob) {
31   Frequency = Prob.scaleByInverse(Frequency);
32   return *this;
33 }
34 
35 BlockFrequency BlockFrequency::operator/(BranchProbability Prob) const {
36   BlockFrequency Freq(Frequency);
37   Freq /= Prob;
38   return Freq;
39 }
40 
41 BlockFrequency &BlockFrequency::operator+=(BlockFrequency Freq) {
42   uint64_t Before = Freq.Frequency;
43   Frequency += Freq.Frequency;
44 
45   // If overflow, set frequency to the maximum value.
46   if (Frequency < Before)
47     Frequency = UINT64_MAX;
48 
49   return *this;
50 }
51 
52 BlockFrequency BlockFrequency::operator+(BlockFrequency Freq) const {
53   BlockFrequency NewFreq(Frequency);
54   NewFreq += Freq;
55   return NewFreq;
56 }
57 
58 BlockFrequency &BlockFrequency::operator-=(BlockFrequency Freq) {
59   // If underflow, set frequency to 0.
60   if (Frequency <= Freq.Frequency)
61     Frequency = 0;
62   else
63     Frequency -= Freq.Frequency;
64   return *this;
65 }
66 
67 BlockFrequency BlockFrequency::operator-(BlockFrequency Freq) const {
68   BlockFrequency NewFreq(Frequency);
69   NewFreq -= Freq;
70   return NewFreq;
71 }
72 
73 BlockFrequency &BlockFrequency::operator>>=(const unsigned count) {
74   // Frequency can never be 0 by design.
75   assert(Frequency != 0);
76 
77   // Shift right by count.
78   Frequency >>= count;
79 
80   // Saturate to 1 if we are 0.
81   Frequency |= Frequency == 0;
82   return *this;
83 }
84