#!/usr/bin/env python3
#
# Copyright 2011-2015 Jeff Bush
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""Create Verilog ROM with floating point estimates for 1/x.

The input and output will be a normalized significand with an implicit leading
one.
"""

import math
import sys

def main():
    if len(sys.argv) != 2:
        print('enter number of entries')
        sys.exit(1)

    num_entries = int(sys.argv[1])
    if (num_entries & (num_entries - 1)) != 0:
        # Must be power of two
        print('number of entries must be power of two')
        sys.exit(1)

    width = int(math.log(num_entries, 2))

    print('''
    //
    // This file is autogenerated by tools/misc/make_reciprocal_rom.py
    //

    module reciprocal_rom(
        input [''' + str(width - 1) + ''':0] significand,
        output logic['''  + str(width - 1) + ''':0] reciprocal_estimate);

        always_comb
        begin
            case (significand)''')

    for x in range(0, num_entries):
        significand = num_entries | x
        reciprocal = int((num_entries * num_entries * 2) / significand)
        print('                {}\'h{:x}: reciprocal_estimate = {}\'h{:x};'.format(
            width, x, width, reciprocal & (num_entries - 1)))

    print('''            default: reciprocal_estimate = 6'h0;
            endcase
        end
    endmodule
    ''')

if __name__ == '__main__':
    main()
