OpenCores
URL https://opencores.org/ocsvn/s80186/s80186/trunk

Subversion Repositories s80186

[/] [s80186/] [trunk/] [scripts/] [microassembler/] [uasm] - Blame information for rev 2

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 jamieiles
#!/usr/bin/env python3
2
 
3
# Copyright Jamie Iles, 2017
4
#
5
# This file is part of s80x86.
6
#
7
# s80x86 is free software: you can redistribute it and/or modify
8
# it under the terms of the GNU General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# s80x86 is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
# GNU General Public License for more details.
16
#
17
# You should have received a copy of the GNU General Public License
18
# along with s80x86.  If not, see .
19
 
20
import argparse
21
import math
22
import os
23
import subprocess
24
import pystache
25
 
26
from functools import partial, lru_cache
27
from textx.metamodel import metamodel_from_file
28
 
29
from microasm.types import (
30
    GPR,
31
    SR,
32
    ADriver,
33
    BDriver,
34
    ALUOp,
35
    RDSelSource,
36
    RegWrSource,
37
    UpdateFlags,
38
    JumpType,
39
    MARWrSel,
40
    TEMPWrSel,
41
    PrefixType,
42
    WidthType
43
)
44
 
45
HERE = os.path.dirname(__file__)
46
GRAMMAR = os.path.join(HERE, 'microcode_grammar.g')
47
TEMPLATE = os.path.join(HERE, '..', '..', 'rtl', 'microcode', 'Microcode.sv.templ')
48
MIF_TEMPLATE = os.path.join(HERE, '..', '..', 'rtl', 'microcode', 'microcode.mif.templ')
49
VERILOG_ENUM_TEMPLATE = os.path.join(HERE, '..', '..', 'rtl', 'microcode', 'MicrocodeTypes.sv.templ')
50
CPP_ENUM_TEMPLATE = os.path.join(HERE, '..', '..', 'rtl', 'microcode', 'MicrocodeTypes.h.templ')
51
mm = metamodel_from_file(GRAMMAR, skipws='\s\t\n\\', debug=False)
52
 
53
pystache.defaults.DELIMITERS = (u'<%', u'%>')
54
 
55
def num_bits(max_val):
56
    if max_val == 0:
57
        return 1
58
    return int(math.ceil(math.log(max_val, 2)))
59
 
60
def token_type(t):
61
    return t.__class__.__name__
62
 
63
def field_type(size):
64
    if size == 1:
65
        return ''
66
    return '[{0}:0] '.format(size - 1)
67
 
68
class MicroAssembler(object):
69
    def __init__(self, infiles, bin_output, mif_output, verilog_output,
70
                 verilog_types_output, cpp_types_output, include):
71
        self._infiles = infiles
72
        self._bin_output = bin_output
73
        self._mif_output = mif_output
74
        self._verilog_output = verilog_output
75
        self._verilog_types_output = verilog_types_output
76
        self._cpp_types_output = cpp_types_output
77
        self._immediate_pool = []
78
        self._update_flags_pool = []
79
        self._include = include
80
 
81
    def _build_microcode(self, files):
82
        label_map = {}
83
        instructions = []
84
 
85
        def assign_addresses():
86
            assigned_addresses = {}
87
            last_addr = max([i.address if i.address else 0 for i in instructions])
88
            for instr in instructions:
89
                if instr.address is None:
90
                    instr.address = last_addr + 1
91
                    last_addr += 1
92
                if instr.address in assigned_addresses:
93
                    raise ValueError('Duplicate instruction at address {0:x}'.format(instr.address))
94
                assigned_addresses[instr.address] = instr
95
 
96
        def resolve_labels():
97
            for instr in instructions:
98
                if instr.next_label:
99
                    instr.next = label_map[instr.next_label].address
100
                else:
101
                    instr.next = instr.address + 1
102
 
103
        def preprocess(filename):
104
            includes = []
105
            for i in self._include:
106
                includes.append('-I')
107
                includes.append(i)
108
            return subprocess.check_output(['cpp', '-nostdinc', filename, '-o', '-'] + includes).decode('utf-8')
109
 
110
        for f in files:
111
            model = mm.model_from_str(preprocess(f))
112
            current_label = None
113
            current_address = None
114
 
115
            line_offset = 0
116
            for d in model.lines:
117
                line, _ = mm.parser.pos_to_linecol(d._tx_position)
118
                line -= line_offset + 1
119
                if token_type(d) == 'LabelAnchor':
120
                    current_label = d.label
121
                    if current_label in label_map:
122
                        raise KeyError('Duplicate label "{0}"'.format(current_label))
123
                elif token_type(d) == 'Directive':
124
                    if d.directive == 'at':
125
                        current_address = int(d.arguments[0].value, 0)
126
                    elif d.directive == 'auto_address':
127
                        current_address = None
128
                    else:
129
                        raise ValueError('Invalid directive "{0}"'.format(d.directive))
130
                elif token_type(d) == 'MicroInstruction':
131
                    instr = MicroInstruction(f, line, current_address)
132
                    instructions.append(instr)
133
                    self._current_instr = instr
134
 
135
                    self._parse(d.fields)
136
 
137
                    if current_label:
138
                        label_map[current_label] = instr
139
                    current_address = None
140
                    current_label = None
141
                elif token_type(d) == 'PreprocessorDirective':
142
                    if d.Filename == f:
143
                        line, _ = mm.parser.pos_to_linecol(d._tx_position)
144
                        line_offset = line - d.LineNumber
145
                else:
146
                    raise ValueError('Unexpected token type {0}'.format(token_type(d)))
147
 
148
        assign_addresses()
149
        resolve_labels()
150
        self.finalize_immediates()
151
        self.finalize_flags()
152
 
153
        return sorted(instructions, key=lambda i: i.address)
154
 
155
    def _write_bin(self, filename, instructions):
156
        last_addr = 0
157
        with open(filename, 'w') as f:
158
            f.write(self.field_comment())
159
            for instr in instructions:
160
                if instr.address != last_addr + 1:
161
                    f.write('@ {0:x}\n'.format(instr.address))
162
                f.write('%s // %x %s %s\n' % (instr.encode(num_bits(instructions[-1].address + 1)),
163
                                              instr.address, instr.origin,
164
                                              ' '.join(instr.present_fields.keys())))
165
                last_addr = instr.address
166
 
167
    def _write_mif(self, filename, instructions):
168
        address_bits = num_bits(instructions[-1].address + 1)
169
        instr_list = [{'address': '%x' % (i.address,),
170
                       'value': i.encode(num_bits(instructions[-1].address + 1))}
171
                      for i in instructions]
172
        data = {
173
            'num_instructions': instructions[-1].address + 1,
174
            'width': self.width(address_bits),
175
            'instructions': instr_list,
176
        }
177
        with open(MIF_TEMPLATE) as f:
178
            template = f.read()
179
        with open(filename, 'w') as outfile:
180
            outfile.write(pystache.render(template, data))
181
 
182
    def _write_microcode_verilog(self, filename, instructions):
183
        address_bits = num_bits(instructions[-1].address + 1)
184
        data = {
185
            'fields': MicroAssembler.bitfields(address_bits),
186
            'exported_fields': MicroAssembler.exported_fields(),
187
            'num_instructions': instructions[-1].address + 1,
188
            'addr_bits': num_bits(instructions[-1].address + 1),
189
            'immediates': MicroAssembler.get_immediate_dict(),
190
            'flags': MicroAssembler.get_flags_dict(),
191
        }
192
        with open(TEMPLATE) as f:
193
            template = f.read()
194
        with open(filename, 'w') as outfile:
195
            outfile.write(pystache.render(template, data))
196
 
197
    def _write_types(self, verilog_filename, cpp_filename):
198
        enums = self._gather_enums()
199
 
200
        with open(VERILOG_ENUM_TEMPLATE) as f:
201
            template = f.read()
202
        with open(verilog_filename, 'w') as f:
203
            f.write(pystache.render(template, {'enums': enums}))
204
 
205
        with open(CPP_ENUM_TEMPLATE) as f:
206
            template = f.read()
207
        with open(cpp_filename, 'w') as f:
208
            f.write(pystache.render(template, {'enums': enums}))
209
 
210
    @staticmethod
211
    def _gather_enums():
212
        enums = []
213
        for cls in [ADriver, BDriver, ALUOp, JumpType, RDSelSource,
214
                    MARWrSel, TEMPWrSel, UpdateFlags, PrefixType,
215
                    RegWrSource, WidthType]:
216
            items = []
217
            for idx, e in enumerate(cls.__members__):
218
                name = '%s_%s' % (cls.__name__, e)
219
                value = '%d%s' % (cls[e].value, ',' if idx != len(cls.__members__) - 1 else '')
220
                items.append({'name': name, 'value': value})
221
 
222
            type_data = {
223
                'high_bit': num_bits(len(cls)) - 1,
224
                'name': 'MC_%s_t' % (cls.__name__,),
225
                'items': items,
226
                'num_bits': num_bits(len(cls)),
227
            }
228
            enums.append(type_data)
229
        return enums
230
 
231
    def _enumerated_field(self, field, enum_class=None):
232
        val = enum_class[field.arguments[0]].value
233
        self._current_instr.present_fields[field.name] = val
234
 
235
    def _boolean(self, field):
236
        self._current_instr.present_fields[field.name] = 1
237
 
238
    def _update_flags(self, field):
239
        flags = 0
240
        for arg in field.arguments:
241
            flags |= (1 << UpdateFlags[arg].value)
242
 
243
        if flags not in self._update_flags_pool:
244
            self._update_flags_pool.append(flags)
245
        self._current_instr.present_fields['update_flags'] = flags
246
 
247
    def _jump(self, field, jump_type=None):
248
        if jump_type != JumpType.OPCODE:
249
            self._current_instr.next_label = field.arguments[0]
250
        self._current_instr._has_jump = True
251
        self._current_instr.present_fields['jump_type'] = jump_type.value
252
 
253
    def _reserved(self, field):
254
        raise ValueError('Reserved keyword {0}'.format(field.name))
255
 
256
    def _parse(self, fields):
257
        for field in fields:
258
            handler = self.microcode_fields[field.name][1]
259
            handler(self, field)
260
 
261
    def _immediate(self, field):
262
        if len(field.arguments) != 1:
263
            raise ValueError('Only one immediate value supported')
264
        if int(field.arguments[0].value, 16) not in self._immediate_pool:
265
            self._immediate_pool.append(int(field.arguments[0].value, 16))
266
        self._current_instr.present_fields['immediate'] = int(field.arguments[0].value, 16)
267
 
268
    def finalize_immediates(self):
269
        MicroAssembler.immediate_dict = {0: 0}
270
        for idx, val in enumerate(self._immediate_pool):
271
            MicroAssembler.immediate_dict[val] = idx + 1
272
        self.microcode_fields['immediate'] = (num_bits(len(MicroAssembler.immediate_dict.keys()) + 1),
273
                                              self._immediate, False)
274
 
275
    def finalize_flags(self):
276
        MicroAssembler.update_flags_dict = {0: 0}
277
        for idx, val in enumerate(self._update_flags_pool):
278
            MicroAssembler.update_flags_dict[val] = idx + 1
279
        self.microcode_fields['update_flags'] = (num_bits(len(MicroAssembler.update_flags_dict.keys()) + 1),
280
                                                 self._update_flags, False)
281
 
282
    """List of microcode fields:
283
      (number of bits, handler, exported to pipeline boolean.
284
    """
285
    microcode_fields = {
286
        'ra_sel': (num_bits(len(GPR)), partial(_enumerated_field, enum_class=GPR), True),
287
        'rb_cl': (1, _boolean, True),
288
        'rd_sel': (num_bits(len(GPR)), partial(_enumerated_field, enum_class=GPR), True),
289
        'next_instruction': (1, _boolean, True),
290
        'mar_wr_sel': (num_bits(len(MARWrSel)), partial(_enumerated_field, enum_class=MARWrSel), True),
291
        'mar_write': (1, _boolean, True),
292
        'mdr_write': (1, _boolean, True),
293
        'mem_read': (1, _boolean, True),
294
        'mem_write': (1, _boolean, True),
295
        'segment': (num_bits(len(SR)), partial(_enumerated_field, enum_class=SR), True),
296
        'prefix_type': (num_bits(len(PrefixType)), partial(_enumerated_field, enum_class=PrefixType), False),
297
        'segment_wr_en': (1, _boolean, True),
298
        'segment_force': (1, _boolean, True),
299
        'a_sel': (num_bits(len(ADriver)), partial(_enumerated_field, enum_class=ADriver), True),
300
        'b_sel': (num_bits(len(BDriver)), partial(_enumerated_field, enum_class=BDriver), True),
301
        'alu_op': (num_bits(len(ALUOp)), partial(_enumerated_field, enum_class=ALUOp), True),
302
        'update_flags': (len(UpdateFlags), _update_flags, False),
303
        'modrm_start': (1, _boolean, True),
304
        'ra_modrm_rm_reg': (1, _boolean, True),
305
        'rd_sel_source': (num_bits(len(RDSelSource)), partial(_enumerated_field, enum_class=RDSelSource), True),
306
        'reg_wr_source': (num_bits(len(RegWrSource)), partial(_enumerated_field, enum_class=RegWrSource), True),
307
        'tmp_wr_en': (1, _boolean, True),
308
        'tmp_wr_sel': (num_bits(len(TEMPWrSel)), partial(_enumerated_field, enum_class=TEMPWrSel), True),
309
        'width': (num_bits(len(WidthType)), partial(_enumerated_field, enum_class=WidthType), False),
310
        'load_ip': (1, _boolean, True),
311
        'read_immed': (1, _boolean, True),
312
        'io': (1, _boolean, True),
313
        'ext_int_yield': (1, _boolean, True),
314
        'ext_int_inhibit': (1, _boolean, False),
315
        'immediate': (0, _immediate, False),
316
        # Internal keywords, generated from others
317
        'jump_type': (num_bits(len(JumpType)), _reserved, False),
318
        # Populated once we know how many address bits required
319
        'jump_target': (0, _reserved, False),
320
        # Keywords only, internally mapped to other microcode fields
321
        'jmp_opcode': (0, partial(_jump, jump_type=JumpType.OPCODE), False),
322
        'jmp_rm_reg_mem': (0, partial(_jump, jump_type=JumpType.RM_REG_MEM), False),
323
        'jmp_dispatch_reg': (0, partial(_jump, jump_type=JumpType.DISPATCH_REG), False),
324
        'jmp_if_not_rep': (0, partial(_jump, jump_type=JumpType.HAS_NO_REP_PREFIX), False),
325
        'jmp_if_zero': (0, partial(_jump, jump_type=JumpType.ZERO), False),
326
        'jmp_if_rep_not_complete': (0, partial(_jump, jump_type=JumpType.REP_NOT_COMPLETE), False),
327
        'jmp_if_taken': (0, partial(_jump, jump_type=JumpType.JUMP_TAKEN), False),
328
        'jmp_rb_zero': (0, partial(_jump, jump_type=JumpType.RB_ZERO), False),
329
        'jmp_loop_done': (0, partial(_jump, jump_type=JumpType.LOOP_DONE), False),
330
        'jmp': (0, partial(_jump, jump_type=JumpType.UNCONDITIONAL), False),
331
    }
332
 
333
    @staticmethod
334
    def sorted_field_keys():
335
        return sorted(MicroAssembler.microcode_fields.keys())
336
 
337
    @staticmethod
338
    def exported_field_keys():
339
        return sorted(filter(lambda f: MicroAssembler.microcode_fields[f][2],
340
                             MicroAssembler.microcode_fields.keys()))
341
 
342
    @staticmethod
343
    def field_comment():
344
        fields = list(filter(lambda f: MicroAssembler.microcode_fields[f][0] > 0,
345
                             MicroAssembler.sorted_field_keys()))
346
        return '//' + ' '.join(['next'] + fields) + '\n'
347
 
348
    @staticmethod
349
    def width(address_bits):
350
        w = address_bits
351
        for name in MicroAssembler.sorted_field_keys():
352
            w += MicroAssembler.microcode_fields[name][0]
353
        return w
354
 
355
    @staticmethod
356
    def bitfields(address_bits):
357
        fields = []
358
        fields.append({
359
            'type': lambda: field_type(address_bits),
360
            'name': 'next'
361
        })
362
        for name in MicroAssembler.sorted_field_keys():
363
            size = MicroAssembler.microcode_fields[name][0]
364
            if size != 0:
365
                fields.append({
366
                    'type': partial(field_type, size),
367
                    'name': name
368
                })
369
        return fields
370
 
371
    @staticmethod
372
    def get_immediate_dict():
373
        d = []
374
        for k, v in MicroAssembler.immediate_dict.items():
375
            d.append({'idx': v, 'val': '{0:x}'.format(k)})
376
        return d
377
 
378
    @staticmethod
379
    def get_flags_dict():
380
        d = []
381
        for k, v in MicroAssembler.update_flags_dict.items():
382
            d.append({'idx': v, 'val': '{0:x}'.format(k)})
383
        return d
384
 
385
    @staticmethod
386
    def exported_fields():
387
        fields = []
388
        for name in MicroAssembler.exported_field_keys():
389
            size = MicroAssembler.microcode_fields[name][0]
390
            if size != 0:
391
                fields.append({
392
                    'type': partial(field_type, size),
393
                    'name': name
394
                })
395
        return fields
396
 
397
    def assemble(self):
398
        instructions = self._build_microcode(self._infiles)
399
        self._write_bin(self._bin_output, instructions)
400
        self._write_mif(self._mif_output, instructions)
401
        self._write_microcode_verilog(self._verilog_output, instructions)
402
        self._write_types(self._verilog_types_output, self._cpp_types_output)
403
 
404
class MicroInstruction(object):
405
    def __init__(self, filename, line, address=None):
406
        self.next = None
407
        self.next_label = None
408
        self.address = address
409
        self._has_jump = False
410
        self.present_fields = {}
411
        self.origin = '%s:%d' % (filename, line)
412
 
413
    @lru_cache(maxsize=None)
414
    def encode(self, address_bits):
415
        if 'immediate' in self.present_fields:
416
            self.present_fields['immediate'] = MicroAssembler.immediate_dict[self.present_fields['immediate']]
417
        if 'update_flags' in self.present_fields:
418
            self.present_fields['update_flags'] = MicroAssembler.update_flags_dict[self.present_fields['update_flags']]
419
        for name, value in self.present_fields.items():
420
            assert num_bits(value) <= MicroAssembler.microcode_fields[name][0]
421
 
422
        if self._has_jump:
423
            self.present_fields['jump_target'] = self.next
424
 
425
        field_values = []
426
        field_values.append('{0:0{width}b}'.format(self.next, width=address_bits))
427
 
428
        for name in MicroAssembler.sorted_field_keys():
429
            width, _, _ = MicroAssembler.microcode_fields[name]
430
            if width == 0:
431
                continue
432
 
433
            value = self.present_fields.get(name, 0)
434
            field_values.append('{0:0{width}b}'.format(value, width=width))
435
        return ''.join(field_values)
436
 
437
parser = argparse.ArgumentParser()
438
parser.add_argument('--include', '-I', action='append', default=[])
439
parser.add_argument('bin_output')
440
parser.add_argument('mif_output')
441
parser.add_argument('verilog_output')
442
parser.add_argument('verilog_types_output')
443
parser.add_argument('cpp_types_output')
444
parser.add_argument('input', nargs='+')
445
args = parser.parse_args()
446
 
447
assembler = MicroAssembler(args.input, args.bin_output, args.mif_output,
448
                           args.verilog_output, args.verilog_types_output,
449
                           args.cpp_types_output, args.include)
450
assembler.assemble()

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.