1#!/usr/bin/env python3
2
3##
4##  Copyright (c) 2024 Taylor Simpson <ltaylorsimpson@gmail.com>
5##
6##  This program is free software; you can redistribute it and/or modify
7##  it under the terms of the GNU General Public License as published by
8##  the Free Software Foundation; either version 2 of the License, or
9##  (at your option) any later version.
10##
11##  This program is distributed in the hope that it will be useful,
12##  but WITHOUT ANY WARRANTY; without even the implied warranty of
13##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14##  GNU General Public License for more details.
15##
16##  You should have received a copy of the GNU General Public License
17##  along with this program; if not, see <http://www.gnu.org/licenses/>.
18##
19
20import io
21import re
22
23import sys
24import textwrap
25import iset
26import hex_common
27
28encs = {
29    tag: "".join(reversed(iset.iset[tag]["enc"].replace(" ", "")))
30    for tag in iset.tags
31    if iset.iset[tag]["enc"] != "MISSING ENCODING"
32}
33
34
35regre = re.compile(r"((?<!DUP)[MNORCPQXSGVZA])([stuvwxyzdefg]+)([.]?[LlHh]?)(\d+S?)")
36immre = re.compile(r"[#]([rRsSuUm])(\d+)(?:[:](\d+))?")
37
38
39def ordered_unique(l):
40    return sorted(set(l), key=l.index)
41
42num_registers = {"R": 32, "V": 32}
43
44operand_letters = {
45    "P",
46    "i",
47    "I",
48    "r",
49    "s",
50    "t",
51    "u",
52    "v",
53    "w",
54    "x",
55    "y",
56    "z",
57    "d",
58    "e",
59    "f",
60    "g",
61}
62
63#
64# These instructions have unused operand letters in their encoding
65# They don't correspond to actual operands in the instruction semantics
66# We will mark them as ignored in QEMU decodetree
67#
68tags_with_unused_d_encoding = {
69    "R6_release_at_vi",
70    "R6_release_st_vi",
71    "S4_stored_rl_at_vi",
72    "S4_stored_rl_st_vi",
73    "S2_storew_rl_at_vi",
74    "S2_stored_rl_at_vi",
75    "S2_storew_rl_st_vi",
76}
77
78tags_with_unused_t_encoding = {
79    "R6_release_at_vi",
80    "R6_release_st_vi",
81}
82
83def skip_tag(tag, class_to_decode):
84    enc_class = iset.iset[tag]["enc_class"]
85    return enc_class != class_to_decode
86
87
88##
89## Generate the QEMU decodetree file for each instruction in class_to_decode
90##     For A2_add: Rd32=add(Rs32,Rt32)
91##     We produce:
92##     %A2_add_Rd   0:5
93##     %A2_add_Rs   16:5
94##     %A2_add_Rt   8:5
95##     @A2_add  11110011000.......-.....---..... Rd=%A2_add_Rd Rs=%A2_add_Rs Rt=%A2_add_Rt %PP
96##     A2_add   ..................-.....---..... @A2_add
97##
98def gen_decodetree_file(f, class_to_decode):
99    f.write(f"## DO NOT MODIFY - This file is generated by {sys.argv[0]}\n\n")
100    f.write("%PP\t14:2\n\n")
101    for tag in sorted(encs.keys(), key=iset.tags.index):
102        if skip_tag(tag, class_to_decode):
103            continue
104
105        enc = encs[tag]
106        enc_str = "".join(reversed(encs[tag]))
107        f.write(("#" * 80) + "\n"
108                f"## {tag}:\t{enc_str}\n"
109                "##\n")
110
111
112        regs = ordered_unique(regre.findall(iset.iset[tag]["syntax"]))
113        imms = ordered_unique(immre.findall(iset.iset[tag]["syntax"]))
114
115        # Write the field definitions for the registers
116        for regno, reg in enumerate(regs):
117            reg_type, reg_id, _, reg_enc_size = reg
118            reg_letter = reg_id[0]
119            reg_num_choices = int(reg_enc_size.rstrip("S"))
120            reg_mapping = reg_type + "".join("_" for letter in reg_id) + \
121                          reg_enc_size
122            reg_enc_fields = re.findall(reg_letter + "+", enc)
123
124            # Check for some errors
125            if len(reg_enc_fields) == 0:
126                raise Exception(f"{tag} missing register field!")
127            if len(reg_enc_fields) > 1:
128                raise Exception(f"{tag} has split register field!")
129            reg_enc_field = reg_enc_fields[0]
130            if 2 ** len(reg_enc_field) != reg_num_choices:
131                raise Exception(f"{tag} has incorrect register field width!")
132
133            f.write(f"%{tag}_{reg_type}{reg_id}\t"
134                    f"{enc.index(reg_enc_field)}:{len(reg_enc_field)}")
135
136            if (reg_type in num_registers and
137                reg_num_choices != num_registers[reg_type]):
138                f.write(f"\t!function=decode_mapped_reg_{reg_mapping}")
139            f.write("\n")
140
141        # Write the field definitions for the immediates
142        for imm in imms:
143            immno = 1 if imm[0].isupper() else 0
144            imm_type = imm[0]
145            imm_width = int(imm[1])
146            imm_letter = "i" if imm_type.islower() else "I"
147            fields = []
148            sign_mark = "s" if imm_type.lower() in "sr" else ""
149            for m in reversed(list(re.finditer(imm_letter + "+", enc))):
150                fields.append(f"{m.start()}:{sign_mark}{m.end() - m.start()}")
151                sign_mark = ""
152            field_str = " ".join(fields)
153            f.write(f"%{tag}_{imm_type}{imm_letter}\t{field_str}\n")
154
155        ## Handle instructions with unused encoding letters
156        ## Change the unused letters to ignored
157        if tag in tags_with_unused_d_encoding:
158            enc_str = enc_str.replace("d", "-")
159        if tag in tags_with_unused_t_encoding:
160            enc_str = enc_str.replace("t", "-")
161
162        # Replace the operand letters with .
163        for x in operand_letters:
164            enc_str = enc_str.replace(x, ".")
165
166        # Write the instruction format
167        f.write(f"@{tag}\t{enc_str}")
168        for reg in regs:
169            reg_type = reg[0]
170            reg_id = reg[1]
171            f.write(f" {reg_type}{reg_id}=%{tag}_{reg_type}{reg_id}")
172        for imm in imms:
173            imm_type = imm[0]
174            imm_letter = "i" if imm_type.islower() else "I"
175            f.write(f" {imm_type}{imm_letter}=%{tag}_{imm_type}{imm_letter}")
176
177        f.write(" %PP\n")
178
179         # Replace the 0s and 1s with .
180        enc_str = enc_str.replace("0", ".").replace("1", ".")
181
182        # Write the instruction pattern
183        f.write(f"{tag}\t{enc_str} @{tag}\n")
184
185
186if __name__ == "__main__":
187    hex_common.read_semantics_file(sys.argv[1])
188    class_to_decode = sys.argv[2]
189    with open(sys.argv[3], "w") as f:
190        gen_decodetree_file(f, class_to_decode)
191