# Copyright (C) 2020 Collabora, Ltd.
# SPDX-License-Identifier: MIT

TEMPLATE = """#include "bi_opcodes.h"
<%
def hasmod(mods, name):
        return 1 if name in mods else 0
%>
struct bi_op_props bi_opcode_props[BI_NUM_OPCODES] = {
% for opcode in sorted(mnemonics):
    <%
        add = instructions["+" + opcode][0][1] if "+" + opcode in instructions else None
        size = typesize(opcode)
        message = add["message"].upper() if add else "NONE"
        sr_count = add["staging_count"].upper() if add else "0"
        sr_read = int(add["staging"] in ["r", "rw"] if add else False)
        sr_write = int(add["staging"] in ["w", "rw"] if add else False)
        last = int(bool(add["last"]) if add else False)
        table = int(bool(add["table"]) if add else False)
        branch = int(opcode.startswith('BRANCH'))
        has_fma = int("*" + opcode in instructions)
        has_add = int("+" + opcode in instructions)
        is_float = int(opcode.endswith("f32") or opcode.endswith("f16"))
        mods = ops[opcode]['modifiers']
        clamp = hasmod(mods, 'clamp')
        not_result = hasmod(mods, 'not_result')
        abs = hasmod(mods, 'abs0') | (hasmod(mods, 'abs1') << 1) | (hasmod(mods, 'abs2') << 2)
        neg = hasmod(mods, 'neg0') | (hasmod(mods, 'neg1') << 1) | (hasmod(mods, 'neg2') << 2)
        m_not = hasmod(mods, 'not1')
    %>
    [BI_OPCODE_${opcode.replace('.', '_').upper()}] = {
        "${opcode}", BIFROST_MESSAGE_${message}, BI_SIZE_${size},
        BI_SR_COUNT_${sr_count}, ${sr_read}, ${sr_write}, ${last}, ${branch},
        ${table}, ${has_fma}, ${has_add}, ${is_float}, ${clamp}, ${not_result},
        ${abs}, ${neg}, ${m_not},
    },
% endfor
};"""

import sys
from bifrost_isa import *
from mako.template import Template

instructions = {}
for arg in sys.argv[1:]:
    new_instructions = parse_instructions(arg, include_pseudo = True)
    instructions.update(new_instructions)

ir_instructions = partition_mnemonics(instructions)
mnemonics = set(x[1:] for x in instructions.keys())

print(Template(COPYRIGHT + TEMPLATE).render(ops = ir_instructions, mnemonics = mnemonics, instructions = instructions, typesize = typesize))
