local.py 1.8 KB
Newer Older
Alan Marchiori's avatar
Alan Marchiori committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
import math
class saturating_counter(): 
    pred = ['N', 'N', 'T', 'T']   
    def __init__(self):
        self.value = 3
    def increment(self):        
        if self.value  < 3:
            self.value += 1 
    def decrement(self):
        if self.value > 0:
            self.value -= 1
    def predict(self):
        return saturating_counter.pred[self.value]
    def __str__(self):
        return "{:02b} ({})".format(self.value, saturating_counter.pred[self.value])
    
class local_bht:
    def __init__(self, num_index_bits = 3):
        self.num_index = 2**num_index_bits        
        self.counters = [saturating_counter() for i in range(self.num_index)]
        
        # compute the correct number of significant digits
        self.bin_fmt ="{{:{}d}}".format(math.ceil(math.log10(self.num_index))) 
        
    def predict(self, pc, target, outcome, verbose):        
        i = (pc//4) % self.num_index
        result = self.counters[i].predict()

        if verbose:
            print ("predict PC = {:x}, index = {:d}, outcome = {}".format(pc, i, outcome))
            tag = {True: '<===',
                   False: ''}
            msg = {False: {True: "", False: ""},
                   True: {True: " (correct)",
                          False: " (MISSPREDICT)"}}
            
            for x in range (self.num_index):                                
                print ("BHT[" + self.bin_fmt.format(x) + "] = {} {}{}".format(self.counters[x],
                                                                            tag[i == x],
                                                                            msg[i == x][result == outcome]))

        if outcome == 'T':
            self.counters[i].increment()
        else:
            self.counters[i].decrement()
                     
        return result