xref: /openbmc/qemu/target/hexagon/hex_common.py (revision 0038e9a2)
1#!/usr/bin/env python3
2
3##
4##  Copyright(c) 2019-2022 Qualcomm Innovation Center, Inc. All Rights Reserved.
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 sys
21import re
22import string
23
24behdict = {}          # tag ->behavior
25semdict = {}          # tag -> semantics
26attribdict = {}       # tag -> attributes
27macros = {}           # macro -> macro information...
28attribinfo = {}       # Register information and misc
29tags = []             # list of all tags
30overrides = {}        # tags with helper overrides
31idef_parser_enabled = {} # tags enabled for idef-parser
32
33# We should do this as a hash for performance,
34# but to keep order let's keep it as a list.
35def uniquify(seq):
36    seen = set()
37    seen_add = seen.add
38    return [x for x in seq if x not in seen and not seen_add(x)]
39
40regre = re.compile(
41    r"((?<!DUP)[MNORCPQXSGVZA])([stuvwxyzdefg]+)([.]?[LlHh]?)(\d+S?)")
42immre = re.compile(r"[#]([rRsSuUm])(\d+)(?:[:](\d+))?")
43reg_or_immre = \
44    re.compile(r"(((?<!DUP)[MNRCOPQXSGVZA])([stuvwxyzdefg]+)" + \
45                "([.]?[LlHh]?)(\d+S?))|([#]([rRsSuUm])(\d+)[:]?(\d+)?)")
46relimmre = re.compile(r"[#]([rR])(\d+)(?:[:](\d+))?")
47absimmre = re.compile(r"[#]([sSuUm])(\d+)(?:[:](\d+))?")
48
49finished_macros = set()
50
51def expand_macro_attribs(macro,allmac_re):
52    if macro.key not in finished_macros:
53        # Get a list of all things that might be macros
54        l = allmac_re.findall(macro.beh)
55        for submacro in l:
56            if not submacro: continue
57            if not macros[submacro]:
58                raise Exception("Couldn't find macro: <%s>" % l)
59            macro.attribs |= expand_macro_attribs(
60                macros[submacro], allmac_re)
61            finished_macros.add(macro.key)
62    return macro.attribs
63
64# When qemu needs an attribute that isn't in the imported files,
65# we'll add it here.
66def add_qemu_macro_attrib(name, attrib):
67    macros[name].attribs.add(attrib)
68
69immextre = re.compile(r'f(MUST_)?IMMEXT[(]([UuSsRr])')
70
71def is_cond_jump(tag):
72    if tag == 'J2_rte':
73        return False
74    if ('A_HWLOOP0_END' in attribdict[tag] or
75        'A_HWLOOP1_END' in attribdict[tag]):
76        return False
77    return \
78        re.compile(r"(if.*fBRANCH)|(if.*fJUMPR)").search(semdict[tag]) != None
79
80def is_cond_call(tag):
81    return re.compile(r"(if.*fCALL)").search(semdict[tag]) != None
82
83def calculate_attribs():
84    add_qemu_macro_attrib('fREAD_PC', 'A_IMPLICIT_READS_PC')
85    add_qemu_macro_attrib('fTRAP', 'A_IMPLICIT_READS_PC')
86    add_qemu_macro_attrib('fWRITE_P0', 'A_WRITES_PRED_REG')
87    add_qemu_macro_attrib('fWRITE_P1', 'A_WRITES_PRED_REG')
88    add_qemu_macro_attrib('fWRITE_P2', 'A_WRITES_PRED_REG')
89    add_qemu_macro_attrib('fWRITE_P3', 'A_WRITES_PRED_REG')
90    add_qemu_macro_attrib('fSET_OVERFLOW', 'A_IMPLICIT_WRITES_USR')
91    add_qemu_macro_attrib('fSET_LPCFG', 'A_IMPLICIT_WRITES_USR')
92    add_qemu_macro_attrib('fSTORE', 'A_SCALAR_STORE')
93
94    # Recurse down macros, find attributes from sub-macros
95    macroValues = list(macros.values())
96    allmacros_restr = "|".join(set([ m.re.pattern for m in macroValues ]))
97    allmacros_re = re.compile(allmacros_restr)
98    for macro in macroValues:
99        expand_macro_attribs(macro,allmacros_re)
100    # Append attributes to all instructions
101    for tag in tags:
102        for macname in allmacros_re.findall(semdict[tag]):
103            if not macname: continue
104            macro = macros[macname]
105            attribdict[tag] |= set(macro.attribs)
106    # Figure out which instructions write predicate registers
107    tagregs = get_tagregs()
108    for tag in tags:
109        regs = tagregs[tag]
110        for regtype, regid, toss, numregs in regs:
111            if regtype == "P" and is_written(regid):
112                attribdict[tag].add('A_WRITES_PRED_REG')
113    # Mark conditional jumps and calls
114    #     Not all instructions are properly marked with A_CONDEXEC
115    for tag in tags:
116        if is_cond_jump(tag) or is_cond_call(tag):
117            attribdict[tag].add('A_CONDEXEC')
118
119def SEMANTICS(tag, beh, sem):
120    #print tag,beh,sem
121    behdict[tag] = beh
122    semdict[tag] = sem
123    attribdict[tag] = set()
124    tags.append(tag)        # dicts have no order, this is for order
125
126def ATTRIBUTES(tag, attribstring):
127    attribstring = \
128        attribstring.replace("ATTRIBS","").replace("(","").replace(")","")
129    if not attribstring:
130        return
131    attribs = attribstring.split(",")
132    for attrib in attribs:
133        attribdict[tag].add(attrib.strip())
134
135class Macro(object):
136    __slots__ = ['key','name', 'beh', 'attribs', 're']
137    def __init__(self, name, beh, attribs):
138        self.key = name
139        self.name = name
140        self.beh = beh
141        self.attribs = set(attribs)
142        self.re = re.compile("\\b" + name + "\\b")
143
144def MACROATTRIB(macname,beh,attribstring):
145    attribstring = attribstring.replace("(","").replace(")","")
146    if attribstring:
147        attribs = attribstring.split(",")
148    else:
149        attribs = []
150    macros[macname] = Macro(macname,beh,attribs)
151
152def compute_tag_regs(tag):
153    return uniquify(regre.findall(behdict[tag]))
154
155def compute_tag_immediates(tag):
156    return uniquify(immre.findall(behdict[tag]))
157
158##
159##  tagregs is the main data structure we'll use
160##  tagregs[tag] will contain the registers used by an instruction
161##  Within each entry, we'll use the regtype and regid fields
162##      regtype can be one of the following
163##          C                control register
164##          N                new register value
165##          P                predicate register
166##          R                GPR register
167##          M                modifier register
168##          Q                HVX predicate vector
169##          V                HVX vector register
170##          O                HVX new vector register
171##      regid can be one of the following
172##          d, e             destination register
173##          dd               destination register pair
174##          s, t, u, v, w    source register
175##          ss, tt, uu, vv   source register pair
176##          x, y             read-write register
177##          xx, yy           read-write register pair
178##
179def get_tagregs():
180    return dict(zip(tags, list(map(compute_tag_regs, tags))))
181
182def get_tagimms():
183    return dict(zip(tags, list(map(compute_tag_immediates, tags))))
184
185def is_pair(regid):
186    return len(regid) == 2
187
188def is_single(regid):
189    return len(regid) == 1
190
191def is_written(regid):
192    return regid[0] in "dexy"
193
194def is_writeonly(regid):
195    return regid[0] in "de"
196
197def is_read(regid):
198    return regid[0] in "stuvwxy"
199
200def is_readwrite(regid):
201    return regid[0] in "xy"
202
203def is_scalar_reg(regtype):
204    return regtype in "RPC"
205
206def is_hvx_reg(regtype):
207    return regtype in "VQ"
208
209def is_old_val(regtype, regid, tag):
210    return regtype+regid+'V' in semdict[tag]
211
212def is_new_val(regtype, regid, tag):
213    return regtype+regid+'N' in semdict[tag]
214
215def need_slot(tag):
216    if (('A_CONDEXEC' in attribdict[tag] and
217         'A_JUMP' not in attribdict[tag]) or
218        'A_STORE' in attribdict[tag] or
219        'A_LOAD' in attribdict[tag]):
220        return 1
221    else:
222        return 0
223
224def need_part1(tag):
225    return re.compile(r"fPART1").search(semdict[tag])
226
227def need_ea(tag):
228    return re.compile(r"\bEA\b").search(semdict[tag])
229
230def need_PC(tag):
231    return 'A_IMPLICIT_READS_PC' in attribdict[tag]
232
233def helper_needs_next_PC(tag):
234    return 'A_CALL' in attribdict[tag]
235
236def need_pkt_has_multi_cof(tag):
237    return 'A_COF' in attribdict[tag]
238
239def skip_qemu_helper(tag):
240    return tag in overrides.keys()
241
242def is_tmp_result(tag):
243    return ('A_CVI_TMP' in attribdict[tag] or
244            'A_CVI_TMP_DST' in attribdict[tag])
245
246def is_new_result(tag):
247    return ('A_CVI_NEW' in attribdict[tag])
248
249def is_idef_parser_enabled(tag):
250    return tag in idef_parser_enabled
251
252def imm_name(immlett):
253    return "%siV" % immlett
254
255def read_semantics_file(name):
256    eval_line = ""
257    for line in open(name, 'rt').readlines():
258        if not line.startswith("#"):
259            eval_line += line
260            if line.endswith("\\\n"):
261                eval_line.rstrip("\\\n")
262            else:
263                eval(eval_line.strip())
264                eval_line = ""
265
266def read_attribs_file(name):
267    attribre = re.compile(r'DEF_ATTRIB\(([A-Za-z0-9_]+), ([^,]*), ' +
268            r'"([A-Za-z0-9_\.]*)", "([A-Za-z0-9_\.]*)"\)')
269    for line in open(name, 'rt').readlines():
270        if not attribre.match(line):
271            continue
272        (attrib_base,descr,rreg,wreg) = attribre.findall(line)[0]
273        attrib_base = 'A_' + attrib_base
274        attribinfo[attrib_base] = {'rreg':rreg, 'wreg':wreg, 'descr':descr}
275
276def read_overrides_file(name):
277    overridere = re.compile("#define fGEN_TCG_([A-Za-z0-9_]+)\(.*")
278    for line in open(name, 'rt').readlines():
279        if not overridere.match(line):
280            continue
281        tag = overridere.findall(line)[0]
282        overrides[tag] = True
283
284def read_idef_parser_enabled_file(name):
285    global idef_parser_enabled
286    with open(name, "r") as idef_parser_enabled_file:
287        lines = idef_parser_enabled_file.read().strip().split("\n")
288        idef_parser_enabled = set(lines)
289