Explicitly handle rounding on FP-to-integer conversions.
[gem5.git] / arch / isa_parser.py
1 #! /usr/bin/env python
2
3 # Copyright (c) 2003-2005 The Regents of The University of Michigan
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are
8 # met: redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer;
10 # redistributions in binary form must reproduce the above copyright
11 # notice, this list of conditions and the following disclaimer in the
12 # documentation and/or other materials provided with the distribution;
13 # neither the name of the copyright holders nor the names of its
14 # contributors may be used to endorse or promote products derived from
15 # this software without specific prior written permission.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 import os
30 import sys
31 import re
32 import string
33 import traceback
34 # get type names
35 from types import *
36
37 # Prepend the directory where the PLY lex & yacc modules are found
38 # to the search path. Assumes we're compiling in a subdirectory
39 # of 'build' in the current tree.
40 sys.path[0:0] = [os.environ['M5_EXT'] + '/ply']
41
42 import lex
43 import yacc
44
45 #####################################################################
46 #
47 # Lexer
48 #
49 # The PLY lexer module takes two things as input:
50 # - A list of token names (the string list 'tokens')
51 # - A regular expression describing a match for each token. The
52 # regexp for token FOO can be provided in two ways:
53 # - as a string variable named t_FOO
54 # - as the doc string for a function named t_FOO. In this case,
55 # the function is also executed, allowing an action to be
56 # associated with each token match.
57 #
58 #####################################################################
59
60 # Reserved words. These are listed separately as they are matched
61 # using the same regexp as generic IDs, but distinguished in the
62 # t_ID() function. The PLY documentation suggests this approach.
63 reserved = (
64 'BITFIELD', 'DECODE', 'DECODER', 'DEFAULT', 'DEF', 'EXEC', 'FORMAT',
65 'HEADER', 'LET', 'NAMESPACE', 'OPERAND_TYPES', 'OPERANDS',
66 'OUTPUT', 'SIGNED', 'TEMPLATE'
67 )
68
69 # List of tokens. The lex module requires this.
70 tokens = reserved + (
71 # identifier
72 'ID',
73
74 # integer literal
75 'INTLIT',
76
77 # string literal
78 'STRLIT',
79
80 # code literal
81 'CODELIT',
82
83 # ( ) [ ] { } < > , ; : :: *
84 'LPAREN', 'RPAREN',
85 # not used any more... commented out to suppress PLY warning
86 # 'LBRACKET', 'RBRACKET',
87 'LBRACE', 'RBRACE',
88 'LESS', 'GREATER',
89 'COMMA', 'SEMI', 'COLON', 'DBLCOLON',
90 'ASTERISK',
91
92 # C preprocessor directives
93 'CPPDIRECTIVE'
94 )
95
96 # Regular expressions for token matching
97 t_LPAREN = r'\('
98 t_RPAREN = r'\)'
99 # not used any more... commented out to suppress PLY warning
100 # t_LBRACKET = r'\['
101 # t_RBRACKET = r'\]'
102 t_LBRACE = r'\{'
103 t_RBRACE = r'\}'
104 t_LESS = r'\<'
105 t_GREATER = r'\>'
106 t_COMMA = r','
107 t_SEMI = r';'
108 t_COLON = r':'
109 t_DBLCOLON = r'::'
110 t_ASTERISK = r'\*'
111
112 # Identifiers and reserved words
113 reserved_map = { }
114 for r in reserved:
115 reserved_map[r.lower()] = r
116
117 def t_ID(t):
118 r'[A-Za-z_]\w*'
119 t.type = reserved_map.get(t.value,'ID')
120 return t
121
122 # Integer literal
123 def t_INTLIT(t):
124 r'(0x[\da-fA-F]+)|\d+'
125 try:
126 t.value = int(t.value,0)
127 except ValueError:
128 error(t.lineno, 'Integer value "%s" too large' % t.value)
129 t.value = 0
130 return t
131
132 # String literal. Note that these use only single quotes, and
133 # can span multiple lines.
134 def t_STRLIT(t):
135 r"(?m)'([^'])+'"
136 # strip off quotes
137 t.value = t.value[1:-1]
138 t.lineno += t.value.count('\n')
139 return t
140
141
142 # "Code literal"... like a string literal, but delimiters are
143 # '{{' and '}}' so they get formatted nicely under emacs c-mode
144 def t_CODELIT(t):
145 r"(?m)\{\{([^\}]|}(?!\}))+\}\}"
146 # strip off {{ & }}
147 t.value = t.value[2:-2]
148 t.lineno += t.value.count('\n')
149 return t
150
151 def t_CPPDIRECTIVE(t):
152 r'^\#.*\n'
153 t.lineno += t.value.count('\n')
154 return t
155
156 #
157 # The functions t_NEWLINE, t_ignore, and t_error are
158 # special for the lex module.
159 #
160
161 # Newlines
162 def t_NEWLINE(t):
163 r'\n+'
164 t.lineno += t.value.count('\n')
165
166 # Comments
167 def t_comment(t):
168 r'//.*'
169
170 # Completely ignored characters
171 t_ignore = ' \t\x0c'
172
173 # Error handler
174 def t_error(t):
175 error(t.lineno, "illegal character '%s'" % t.value[0])
176 t.skip(1)
177
178 # Build the lexer
179 lex.lex()
180
181 #####################################################################
182 #
183 # Parser
184 #
185 # Every function whose name starts with 'p_' defines a grammar rule.
186 # The rule is encoded in the function's doc string, while the
187 # function body provides the action taken when the rule is matched.
188 # The argument to each function is a list of the values of the
189 # rule's symbols: t[0] for the LHS, and t[1..n] for the symbols
190 # on the RHS. For tokens, the value is copied from the t.value
191 # attribute provided by the lexer. For non-terminals, the value
192 # is assigned by the producing rule; i.e., the job of the grammar
193 # rule function is to set the value for the non-terminal on the LHS
194 # (by assigning to t[0]).
195 #####################################################################
196
197 # The LHS of the first grammar rule is used as the start symbol
198 # (in this case, 'specification'). Note that this rule enforces
199 # that there will be exactly one namespace declaration, with 0 or more
200 # global defs/decls before and after it. The defs & decls before
201 # the namespace decl will be outside the namespace; those after
202 # will be inside. The decoder function is always inside the namespace.
203 def p_specification(t):
204 'specification : opt_defs_and_outputs name_decl opt_defs_and_outputs decode_block'
205 global_code = t[1]
206 isa_name = t[2]
207 namespace = isa_name + "Inst"
208 # wrap the decode block as a function definition
209 t[4].wrap_decode_block('''
210 StaticInstPtr<%(isa_name)s>
211 %(isa_name)s::decodeInst(%(isa_name)s::MachInst machInst)
212 {
213 using namespace %(namespace)s;
214 ''' % vars(), '}')
215 # both the latter output blocks and the decode block are in the namespace
216 namespace_code = t[3] + t[4]
217 # pass it all back to the caller of yacc.parse()
218 t[0] = (isa_name, namespace, global_code, namespace_code)
219
220 # ISA name declaration looks like "namespace <foo>;"
221 def p_name_decl(t):
222 'name_decl : NAMESPACE ID SEMI'
223 t[0] = t[2]
224
225 # 'opt_defs_and_outputs' is a possibly empty sequence of
226 # def and/or output statements.
227 def p_opt_defs_and_outputs_0(t):
228 'opt_defs_and_outputs : empty'
229 t[0] = GenCode()
230
231 def p_opt_defs_and_outputs_1(t):
232 'opt_defs_and_outputs : defs_and_outputs'
233 t[0] = t[1]
234
235 def p_defs_and_outputs_0(t):
236 'defs_and_outputs : def_or_output'
237 t[0] = t[1]
238
239 def p_defs_and_outputs_1(t):
240 'defs_and_outputs : defs_and_outputs def_or_output'
241 t[0] = t[1] + t[2]
242
243 # The list of possible definition/output statements.
244 def p_def_or_output(t):
245 '''def_or_output : def_format
246 | def_bitfield
247 | def_template
248 | def_operand_types
249 | def_operands
250 | output_header
251 | output_decoder
252 | output_exec
253 | global_let'''
254 t[0] = t[1]
255
256 # Output blocks 'output <foo> {{...}}' (C++ code blocks) are copied
257 # directly to the appropriate output section.
258
259
260 # Protect any non-dict-substitution '%'s in a format string
261 # (i.e. those not followed by '(')
262 def protect_non_subst_percents(s):
263 return re.sub(r'%(?!\()', '%%', s)
264
265 # Massage output block by substituting in template definitions and bit
266 # operators. We handle '%'s embedded in the string that don't
267 # indicate template substitutions (or CPU-specific symbols, which get
268 # handled in GenCode) by doubling them first so that the format
269 # operation will reduce them back to single '%'s.
270 def process_output(s):
271 s = protect_non_subst_percents(s)
272 # protects cpu-specific symbols too
273 s = protect_cpu_symbols(s)
274 return substBitOps(s % templateMap)
275
276 def p_output_header(t):
277 'output_header : OUTPUT HEADER CODELIT SEMI'
278 t[0] = GenCode(header_output = process_output(t[3]))
279
280 def p_output_decoder(t):
281 'output_decoder : OUTPUT DECODER CODELIT SEMI'
282 t[0] = GenCode(decoder_output = process_output(t[3]))
283
284 def p_output_exec(t):
285 'output_exec : OUTPUT EXEC CODELIT SEMI'
286 t[0] = GenCode(exec_output = process_output(t[3]))
287
288 # global let blocks 'let {{...}}' (Python code blocks) are executed
289 # directly when seen. Note that these execute in a special variable
290 # context 'exportContext' to prevent the code from polluting this
291 # script's namespace.
292 def p_global_let(t):
293 'global_let : LET CODELIT SEMI'
294 updateExportContext()
295 try:
296 exec fixPythonIndentation(t[2]) in exportContext
297 except Exception, exc:
298 error(t.lineno(1),
299 'error: %s in global let block "%s".' % (exc, t[2]))
300 t[0] = GenCode() # contributes nothing to the output C++ file
301
302 # Define the mapping from operand type extensions to C++ types and bit
303 # widths (stored in operandTypeMap).
304 def p_def_operand_types(t):
305 'def_operand_types : DEF OPERAND_TYPES CODELIT SEMI'
306 s = 'global operandTypeMap; operandTypeMap = {' + t[3] + '}'
307 try:
308 exec s
309 except Exception, exc:
310 error(t.lineno(1),
311 'error: %s in def operand_types block "%s".' % (exc, t[3]))
312 t[0] = GenCode() # contributes nothing to the output C++ file
313
314 # Define the mapping from operand names to operand classes and other
315 # traits. Stored in operandTraitsMap.
316 def p_def_operands(t):
317 'def_operands : DEF OPERANDS CODELIT SEMI'
318 s = 'global operandTraitsMap; operandTraitsMap = {' + t[3] + '}'
319 try:
320 exec s
321 except Exception, exc:
322 error(t.lineno(1),
323 'error: %s in def operands block "%s".' % (exc, t[3]))
324 defineDerivedOperandVars()
325 t[0] = GenCode() # contributes nothing to the output C++ file
326
327 # A bitfield definition looks like:
328 # 'def [signed] bitfield <ID> [<first>:<last>]'
329 # This generates a preprocessor macro in the output file.
330 def p_def_bitfield_0(t):
331 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT COLON INTLIT GREATER SEMI'
332 expr = 'bits(machInst, %2d, %2d)' % (t[6], t[8])
333 if (t[2] == 'signed'):
334 expr = 'sext<%d>(%s)' % (t[6] - t[8] + 1, expr)
335 hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr)
336 t[0] = GenCode(header_output = hash_define)
337
338 # alternate form for single bit: 'def [signed] bitfield <ID> [<bit>]'
339 def p_def_bitfield_1(t):
340 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT GREATER SEMI'
341 expr = 'bits(machInst, %2d, %2d)' % (t[6], t[6])
342 if (t[2] == 'signed'):
343 expr = 'sext<%d>(%s)' % (1, expr)
344 hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr)
345 t[0] = GenCode(header_output = hash_define)
346
347 def p_opt_signed_0(t):
348 'opt_signed : SIGNED'
349 t[0] = t[1]
350
351 def p_opt_signed_1(t):
352 'opt_signed : empty'
353 t[0] = ''
354
355 # Global map variable to hold templates
356 templateMap = {}
357
358 def p_def_template(t):
359 'def_template : DEF TEMPLATE ID CODELIT SEMI'
360 templateMap[t[3]] = Template(t[4])
361 t[0] = GenCode()
362
363 # An instruction format definition looks like
364 # "def format <fmt>(<params>) {{...}};"
365 def p_def_format(t):
366 'def_format : DEF FORMAT ID LPAREN param_list RPAREN CODELIT SEMI'
367 (id, params, code) = (t[3], t[5], t[7])
368 defFormat(id, params, code, t.lineno(1))
369 t[0] = GenCode()
370
371 # The formal parameter list for an instruction format is a possibly
372 # empty list of comma-separated parameters.
373 def p_param_list_0(t):
374 'param_list : empty'
375 t[0] = [ ]
376
377 def p_param_list_1(t):
378 'param_list : param'
379 t[0] = [t[1]]
380
381 def p_param_list_2(t):
382 'param_list : param_list COMMA param'
383 t[0] = t[1]
384 t[0].append(t[3])
385
386 # Each formal parameter is either an identifier or an identifier
387 # preceded by an asterisk. As in Python, the latter (if present) gets
388 # a tuple containing all the excess positional arguments, allowing
389 # varargs functions.
390 def p_param_0(t):
391 'param : ID'
392 t[0] = t[1]
393
394 def p_param_1(t):
395 'param : ASTERISK ID'
396 # just concatenate them: '*ID'
397 t[0] = t[1] + t[2]
398
399 # End of format definition-related rules.
400 ##############
401
402 #
403 # A decode block looks like:
404 # decode <field1> [, <field2>]* [default <inst>] { ... }
405 #
406 def p_decode_block(t):
407 'decode_block : DECODE ID opt_default LBRACE decode_stmt_list RBRACE'
408 default_defaults = defaultStack.pop()
409 codeObj = t[5]
410 # use the "default defaults" only if there was no explicit
411 # default statement in decode_stmt_list
412 if not codeObj.has_decode_default:
413 codeObj += default_defaults
414 codeObj.wrap_decode_block('switch (%s) {\n' % t[2], '}\n')
415 t[0] = codeObj
416
417 # The opt_default statement serves only to push the "default defaults"
418 # onto defaultStack. This value will be used by nested decode blocks,
419 # and used and popped off when the current decode_block is processed
420 # (in p_decode_block() above).
421 def p_opt_default_0(t):
422 'opt_default : empty'
423 # no default specified: reuse the one currently at the top of the stack
424 defaultStack.push(defaultStack.top())
425 # no meaningful value returned
426 t[0] = None
427
428 def p_opt_default_1(t):
429 'opt_default : DEFAULT inst'
430 # push the new default
431 codeObj = t[2]
432 codeObj.wrap_decode_block('\ndefault:\n', 'break;\n')
433 defaultStack.push(codeObj)
434 # no meaningful value returned
435 t[0] = None
436
437 def p_decode_stmt_list_0(t):
438 'decode_stmt_list : decode_stmt'
439 t[0] = t[1]
440
441 def p_decode_stmt_list_1(t):
442 'decode_stmt_list : decode_stmt decode_stmt_list'
443 if (t[1].has_decode_default and t[2].has_decode_default):
444 error(t.lineno(1), 'Two default cases in decode block')
445 t[0] = t[1] + t[2]
446
447 #
448 # Decode statement rules
449 #
450 # There are four types of statements allowed in a decode block:
451 # 1. Format blocks 'format <foo> { ... }'
452 # 2. Nested decode blocks
453 # 3. Instruction definitions.
454 # 4. C preprocessor directives.
455
456
457 # Preprocessor directives found in a decode statement list are passed
458 # through to the output, replicated to all of the output code
459 # streams. This works well for ifdefs, so we can ifdef out both the
460 # declarations and the decode cases generated by an instruction
461 # definition. Handling them as part of the grammar makes it easy to
462 # keep them in the right place with respect to the code generated by
463 # the other statements.
464 def p_decode_stmt_cpp(t):
465 'decode_stmt : CPPDIRECTIVE'
466 t[0] = GenCode(t[1], t[1], t[1], t[1])
467
468 # A format block 'format <foo> { ... }' sets the default instruction
469 # format used to handle instruction definitions inside the block.
470 # This format can be overridden by using an explicit format on the
471 # instruction definition or with a nested format block.
472 def p_decode_stmt_format(t):
473 'decode_stmt : FORMAT push_format_id LBRACE decode_stmt_list RBRACE'
474 # The format will be pushed on the stack when 'push_format_id' is
475 # processed (see below). Once the parser has recognized the full
476 # production (though the right brace), we're done with the format,
477 # so now we can pop it.
478 formatStack.pop()
479 t[0] = t[4]
480
481 # This rule exists so we can set the current format (& push the stack)
482 # when we recognize the format name part of the format block.
483 def p_push_format_id(t):
484 'push_format_id : ID'
485 try:
486 formatStack.push(formatMap[t[1]])
487 t[0] = ('', '// format %s' % t[1])
488 except KeyError:
489 error(t.lineno(1), 'instruction format "%s" not defined.' % t[1])
490
491 # Nested decode block: if the value of the current field matches the
492 # specified constant, do a nested decode on some other field.
493 def p_decode_stmt_decode(t):
494 'decode_stmt : case_label COLON decode_block'
495 label = t[1]
496 codeObj = t[3]
497 # just wrap the decoding code from the block as a case in the
498 # outer switch statement.
499 codeObj.wrap_decode_block('\n%s:\n' % label)
500 codeObj.has_decode_default = (label == 'default')
501 t[0] = codeObj
502
503 # Instruction definition (finally!).
504 def p_decode_stmt_inst(t):
505 'decode_stmt : case_label COLON inst SEMI'
506 label = t[1]
507 codeObj = t[3]
508 codeObj.wrap_decode_block('\n%s:' % label, 'break;\n')
509 codeObj.has_decode_default = (label == 'default')
510 t[0] = codeObj
511
512 # The case label is either a list of one or more constants or 'default'
513 def p_case_label_0(t):
514 'case_label : intlit_list'
515 t[0] = ': '.join(map(lambda a: 'case %#x' % a, t[1]))
516
517 def p_case_label_1(t):
518 'case_label : DEFAULT'
519 t[0] = 'default'
520
521 #
522 # The constant list for a decode case label must be non-empty, but may have
523 # one or more comma-separated integer literals in it.
524 #
525 def p_intlit_list_0(t):
526 'intlit_list : INTLIT'
527 t[0] = [t[1]]
528
529 def p_intlit_list_1(t):
530 'intlit_list : intlit_list COMMA INTLIT'
531 t[0] = t[1]
532 t[0].append(t[3])
533
534 # Define an instruction using the current instruction format (specified
535 # by an enclosing format block).
536 # "<mnemonic>(<args>)"
537 def p_inst_0(t):
538 'inst : ID LPAREN arg_list RPAREN'
539 # Pass the ID and arg list to the current format class to deal with.
540 currentFormat = formatStack.top()
541 codeObj = currentFormat.defineInst(t[1], t[3], t.lineno(1))
542 args = ','.join(map(str, t[3]))
543 args = re.sub('(?m)^', '//', args)
544 args = re.sub('^//', '', args)
545 comment = '\n// %s::%s(%s)\n' % (currentFormat.id, t[1], args)
546 codeObj.prepend_all(comment)
547 t[0] = codeObj
548
549 # Define an instruction using an explicitly specified format:
550 # "<fmt>::<mnemonic>(<args>)"
551 def p_inst_1(t):
552 'inst : ID DBLCOLON ID LPAREN arg_list RPAREN'
553 try:
554 format = formatMap[t[1]]
555 except KeyError:
556 error(t.lineno(1), 'instruction format "%s" not defined.' % t[1])
557 codeObj = format.defineInst(t[3], t[5], t.lineno(1))
558 comment = '\n// %s::%s(%s)\n' % (t[1], t[3], t[5])
559 codeObj.prepend_all(comment)
560 t[0] = codeObj
561
562 def p_arg_list_0(t):
563 'arg_list : empty'
564 t[0] = [ ]
565
566 def p_arg_list_1(t):
567 'arg_list : arg'
568 t[0] = [t[1]]
569
570 def p_arg_list_2(t):
571 'arg_list : arg_list COMMA arg'
572 t[0] = t[1]
573 t[0].append(t[3])
574
575 def p_arg(t):
576 '''arg : ID
577 | INTLIT
578 | STRLIT
579 | CODELIT'''
580 t[0] = t[1]
581
582 #
583 # Empty production... use in other rules for readability.
584 #
585 def p_empty(t):
586 'empty :'
587 pass
588
589 # Parse error handler. Note that the argument here is the offending
590 # *token*, not a grammar symbol (hence the need to use t.value)
591 def p_error(t):
592 if t:
593 error(t.lineno, "syntax error at '%s'" % t.value)
594 else:
595 error_bt(0, "unknown syntax error")
596
597 # END OF GRAMMAR RULES
598 #
599 # Now build the parser.
600 yacc.yacc()
601
602
603 #####################################################################
604 #
605 # Support Classes
606 #
607 #####################################################################
608
609 ################
610 # CpuModel class
611 #
612 # The CpuModel class encapsulates everything we need to know about a
613 # particular CPU model.
614
615 class CpuModel:
616 # List of all CPU models. Accessible as CpuModel.list.
617 list = []
618
619 # Constructor. Automatically adds models to CpuModel.list.
620 def __init__(self, name, filename, includes, strings):
621 self.name = name
622 self.filename = filename # filename for output exec code
623 self.includes = includes # include files needed in exec file
624 # The 'strings' dict holds all the per-CPU symbols we can
625 # substitute into templates etc.
626 self.strings = strings
627 # Add self to list.
628 CpuModel.list.append(self)
629
630 # Define CPU models. The following lines should contain the only
631 # CPU-model-specific information in this file. Note that the ISA
632 # description itself should have *no* CPU-model-specific content.
633 CpuModel('SimpleCPU', 'simple_cpu_exec.cc',
634 '#include "cpu/simple/cpu.hh"',
635 { 'CPU_exec_context': 'SimpleCPU' })
636 CpuModel('FastCPU', 'fast_cpu_exec.cc',
637 '#include "cpu/fast/cpu.hh"',
638 { 'CPU_exec_context': 'FastCPU' })
639 CpuModel('FullCPU', 'full_cpu_exec.cc',
640 '#include "encumbered/cpu/full/dyn_inst.hh"',
641 { 'CPU_exec_context': 'DynInst' })
642 CpuModel('AlphaFullCPU', 'alpha_o3_exec.cc',
643 '#include "cpu/o3/alpha_dyn_inst.hh"',
644 { 'CPU_exec_context': 'AlphaDynInst<AlphaSimpleImpl>' })
645
646 # Expand template with CPU-specific references into a dictionary with
647 # an entry for each CPU model name. The entry key is the model name
648 # and the corresponding value is the template with the CPU-specific
649 # refs substituted for that model.
650 def expand_cpu_symbols_to_dict(template):
651 # Protect '%'s that don't go with CPU-specific terms
652 t = re.sub(r'%(?!\(CPU_)', '%%', template)
653 result = {}
654 for cpu in CpuModel.list:
655 result[cpu.name] = t % cpu.strings
656 return result
657
658 # *If* the template has CPU-specific references, return a single
659 # string containing a copy of the template for each CPU model with the
660 # corresponding values substituted in. If the template has no
661 # CPU-specific references, it is returned unmodified.
662 def expand_cpu_symbols_to_string(template):
663 if template.find('%(CPU_') != -1:
664 return reduce(lambda x,y: x+y,
665 expand_cpu_symbols_to_dict(template).values())
666 else:
667 return template
668
669 # Protect CPU-specific references by doubling the corresponding '%'s
670 # (in preparation for substituting a different set of references into
671 # the template).
672 def protect_cpu_symbols(template):
673 return re.sub(r'%(?=\(CPU_)', '%%', template)
674
675 ###############
676 # GenCode class
677 #
678 # The GenCode class encapsulates generated code destined for various
679 # output files. The header_output and decoder_output attributes are
680 # strings containing code destined for decoder.hh and decoder.cc
681 # respectively. The decode_block attribute contains code to be
682 # incorporated in the decode function itself (that will also end up in
683 # decoder.cc). The exec_output attribute is a dictionary with a key
684 # for each CPU model name; the value associated with a particular key
685 # is the string of code for that CPU model's exec.cc file. The
686 # has_decode_default attribute is used in the decode block to allow
687 # explicit default clauses to override default default clauses.
688
689 class GenCode:
690 # Constructor. At this point we substitute out all CPU-specific
691 # symbols. For the exec output, these go into the per-model
692 # dictionary. For all other output types they get collapsed into
693 # a single string.
694 def __init__(self,
695 header_output = '', decoder_output = '', exec_output = '',
696 decode_block = '', has_decode_default = False):
697 self.header_output = expand_cpu_symbols_to_string(header_output)
698 self.decoder_output = expand_cpu_symbols_to_string(decoder_output)
699 if isinstance(exec_output, dict):
700 self.exec_output = exec_output
701 elif isinstance(exec_output, str):
702 # If the exec_output arg is a single string, we replicate
703 # it for each of the CPU models, substituting and
704 # %(CPU_foo)s params appropriately.
705 self.exec_output = expand_cpu_symbols_to_dict(exec_output)
706 self.decode_block = expand_cpu_symbols_to_string(decode_block)
707 self.has_decode_default = has_decode_default
708
709 # Override '+' operator: generate a new GenCode object that
710 # concatenates all the individual strings in the operands.
711 def __add__(self, other):
712 exec_output = {}
713 for cpu in CpuModel.list:
714 n = cpu.name
715 exec_output[n] = self.exec_output[n] + other.exec_output[n]
716 return GenCode(self.header_output + other.header_output,
717 self.decoder_output + other.decoder_output,
718 exec_output,
719 self.decode_block + other.decode_block,
720 self.has_decode_default or other.has_decode_default)
721
722 # Prepend a string (typically a comment) to all the strings.
723 def prepend_all(self, pre):
724 self.header_output = pre + self.header_output
725 self.decoder_output = pre + self.decoder_output
726 self.decode_block = pre + self.decode_block
727 for cpu in CpuModel.list:
728 self.exec_output[cpu.name] = pre + self.exec_output[cpu.name]
729
730 # Wrap the decode block in a pair of strings (e.g., 'case foo:'
731 # and 'break;'). Used to build the big nested switch statement.
732 def wrap_decode_block(self, pre, post = ''):
733 self.decode_block = pre + indent(self.decode_block) + post
734
735 ################
736 # Format object.
737 #
738 # A format object encapsulates an instruction format. It must provide
739 # a defineInst() method that generates the code for an instruction
740 # definition.
741
742 class Format:
743 def __init__(self, id, params, code):
744 # constructor: just save away arguments
745 self.id = id
746 self.params = params
747 label = 'def format ' + id
748 self.user_code = compile(fixPythonIndentation(code), label, 'exec')
749 param_list = string.join(params, ", ")
750 f = '''def defInst(_code, _context, %s):
751 my_locals = vars().copy()
752 exec _code in _context, my_locals
753 return my_locals\n''' % param_list
754 c = compile(f, label + ' wrapper', 'exec')
755 exec c
756 self.func = defInst
757
758 def defineInst(self, name, args, lineno):
759 context = {}
760 updateExportContext()
761 context.update(exportContext)
762 context.update({ 'name': name, 'Name': string.capitalize(name) })
763 try:
764 vars = self.func(self.user_code, context, *args)
765 except Exception, exc:
766 error(lineno, 'error defining "%s": %s.' % (name, exc))
767 for k in vars.keys():
768 if k not in ('header_output', 'decoder_output',
769 'exec_output', 'decode_block'):
770 del vars[k]
771 return GenCode(**vars)
772
773 # Special null format to catch an implicit-format instruction
774 # definition outside of any format block.
775 class NoFormat:
776 def __init__(self):
777 self.defaultInst = ''
778
779 def defineInst(self, name, args, lineno):
780 error(lineno,
781 'instruction definition "%s" with no active format!' % name)
782
783 # This dictionary maps format name strings to Format objects.
784 formatMap = {}
785
786 # Define a new format
787 def defFormat(id, params, code, lineno):
788 # make sure we haven't already defined this one
789 if formatMap.get(id, None) != None:
790 error(lineno, 'format %s redefined.' % id)
791 # create new object and store in global map
792 formatMap[id] = Format(id, params, code)
793
794
795 ##############
796 # Stack: a simple stack object. Used for both formats (formatStack)
797 # and default cases (defaultStack).
798
799 class Stack:
800 def __init__(self, initItem):
801 self.stack = [ initItem ]
802
803 def push(self, item):
804 self.stack.append(item);
805
806 def pop(self):
807 return self.stack.pop()
808
809 def top(self):
810 return self.stack[-1]
811
812 # The global format stack.
813 formatStack = Stack(NoFormat())
814
815 # The global default case stack.
816 defaultStack = Stack( None )
817
818 ###################
819 # Utility functions
820
821 #
822 # Indent every line in string 's' by two spaces
823 # (except preprocessor directives).
824 # Used to make nested code blocks look pretty.
825 #
826 def indent(s):
827 return re.sub(r'(?m)^(?!\#)', ' ', s)
828
829 #
830 # Munge a somewhat arbitrarily formatted piece of Python code
831 # (e.g. from a format 'let' block) into something whose indentation
832 # will get by the Python parser.
833 #
834 # The two keys here are that Python will give a syntax error if
835 # there's any whitespace at the beginning of the first line, and that
836 # all lines at the same lexical nesting level must have identical
837 # indentation. Unfortunately the way code literals work, an entire
838 # let block tends to have some initial indentation. Rather than
839 # trying to figure out what that is and strip it off, we prepend 'if
840 # 1:' to make the let code the nested block inside the if (and have
841 # the parser automatically deal with the indentation for us).
842 #
843 # We don't want to do this if (1) the code block is empty or (2) the
844 # first line of the block doesn't have any whitespace at the front.
845
846 def fixPythonIndentation(s):
847 # get rid of blank lines first
848 s = re.sub(r'(?m)^\s*\n', '', s);
849 if (s != '' and re.match(r'[ \t]', s[0])):
850 s = 'if 1:\n' + s
851 return s
852
853 # Error handler. Just call exit. Output formatted to work under
854 # Emacs compile-mode.
855 def error(lineno, string):
856 sys.exit("%s:%d: %s" % (input_filename, lineno, string))
857
858 # Like error(), but include a Python stack backtrace (for processing
859 # Python exceptions).
860 def error_bt(lineno, string):
861 traceback.print_exc()
862 print >> sys.stderr, "%s:%d: %s" % (input_filename, lineno, string)
863 sys.exit(1)
864
865
866 #####################################################################
867 #
868 # Bitfield Operator Support
869 #
870 #####################################################################
871
872 bitOp1ArgRE = re.compile(r'<\s*(\w+)\s*:\s*>')
873
874 bitOpWordRE = re.compile(r'(?<![\w\.])([\w\.]+)<\s*(\w+)\s*:\s*(\w+)\s*>')
875 bitOpExprRE = re.compile(r'\)<\s*(\w+)\s*:\s*(\w+)\s*>')
876
877 def substBitOps(code):
878 # first convert single-bit selectors to two-index form
879 # i.e., <n> --> <n:n>
880 code = bitOp1ArgRE.sub(r'<\1:\1>', code)
881 # simple case: selector applied to ID (name)
882 # i.e., foo<a:b> --> bits(foo, a, b)
883 code = bitOpWordRE.sub(r'bits(\1, \2, \3)', code)
884 # if selector is applied to expression (ending in ')'),
885 # we need to search backward for matching '('
886 match = bitOpExprRE.search(code)
887 while match:
888 exprEnd = match.start()
889 here = exprEnd - 1
890 nestLevel = 1
891 while nestLevel > 0:
892 if code[here] == '(':
893 nestLevel -= 1
894 elif code[here] == ')':
895 nestLevel += 1
896 here -= 1
897 if here < 0:
898 sys.exit("Didn't find '('!")
899 exprStart = here+1
900 newExpr = r'bits(%s, %s, %s)' % (code[exprStart:exprEnd+1],
901 match.group(1), match.group(2))
902 code = code[:exprStart] + newExpr + code[match.end():]
903 match = bitOpExprRE.search(code)
904 return code
905
906
907 ####################
908 # Template objects.
909 #
910 # Template objects are format strings that allow substitution from
911 # the attribute spaces of other objects (e.g. InstObjParams instances).
912
913 class Template:
914 def __init__(self, t):
915 self.template = t
916
917 def subst(self, d):
918 # Start with the template namespace. Make a copy since we're
919 # going to modify it.
920 myDict = templateMap.copy()
921 # if the argument is a dictionary, we just use it.
922 if isinstance(d, dict):
923 myDict.update(d)
924 # if the argument is an object, we use its attribute map.
925 elif hasattr(d, '__dict__'):
926 myDict.update(d.__dict__)
927 else:
928 raise TypeError, "Template.subst() arg must be or have dictionary"
929 # Protect non-Python-dict substitutions (e.g. if there's a printf
930 # in the templated C++ code)
931 template = protect_non_subst_percents(self.template)
932 # CPU-model-specific substitutions are handled later (in GenCode).
933 template = protect_cpu_symbols(template)
934 return template % myDict
935
936 # Convert to string. This handles the case when a template with a
937 # CPU-specific term gets interpolated into another template or into
938 # an output block.
939 def __str__(self):
940 return expand_cpu_symbols_to_string(self.template)
941
942 #####################################################################
943 #
944 # Code Parser
945 #
946 # The remaining code is the support for automatically extracting
947 # instruction characteristics from pseudocode.
948 #
949 #####################################################################
950
951 # Force the argument to be a list
952 def makeList(list_or_item):
953 if not list_or_item:
954 return []
955 elif type(list_or_item) == ListType:
956 return list_or_item
957 else:
958 return [ list_or_item ]
959
960 # generate operandSizeMap based on provided operandTypeMap:
961 # basically generate equiv. C++ type and make is_signed flag
962 def buildOperandSizeMap():
963 global operandSizeMap
964 operandSizeMap = {}
965 for ext in operandTypeMap.keys():
966 (desc, size) = operandTypeMap[ext]
967 if desc == 'signed int':
968 type = 'int%d_t' % size
969 is_signed = 1
970 elif desc == 'unsigned int':
971 type = 'uint%d_t' % size
972 is_signed = 0
973 elif desc == 'float':
974 is_signed = 1 # shouldn't really matter
975 if size == 32:
976 type = 'float'
977 elif size == 64:
978 type = 'double'
979 if type == '':
980 error(0, 'Unrecognized type description "%s" in operandTypeMap')
981 operandSizeMap[ext] = (size, type, is_signed)
982
983 #
984 # Base class for operand traits. An instance of this class (or actually
985 # a class derived from this one) encapsulates the traits of a particular
986 # operand type (e.g., "32-bit integer register").
987 #
988 class OperandTraits:
989 def __init__(self, dflt_ext, reg_spec, flags, sort_pri):
990 # Force construction of operandSizeMap from operandTypeMap
991 # if it hasn't happened yet
992 if not globals().has_key('operandSizeMap'):
993 buildOperandSizeMap()
994 self.dflt_ext = dflt_ext
995 (self.dflt_size, self.dflt_type, self.dflt_is_signed) = \
996 operandSizeMap[dflt_ext]
997 self.reg_spec = reg_spec
998 # Canonical flag structure is a triple of lists, where each list
999 # indicates the set of flags implied by this operand always, when
1000 # used as a source, and when used as a dest, respectively.
1001 # For simplicity this can be initialized using a variety of fairly
1002 # obvious shortcuts; we convert these to canonical form here.
1003 if not flags:
1004 # no flags specified (e.g., 'None')
1005 self.flags = ( [], [], [] )
1006 elif type(flags) == StringType:
1007 # a single flag: assumed to be unconditional
1008 self.flags = ( [ flags ], [], [] )
1009 elif type(flags) == ListType:
1010 # a list of flags: also assumed to be unconditional
1011 self.flags = ( flags, [], [] )
1012 elif type(flags) == TupleType:
1013 # it's a tuple: it should be a triple,
1014 # but each item could be a single string or a list
1015 (uncond_flags, src_flags, dest_flags) = flags
1016 self.flags = (makeList(uncond_flags),
1017 makeList(src_flags), makeList(dest_flags))
1018 self.sort_pri = sort_pri
1019
1020 def isMem(self):
1021 return 0
1022
1023 def isReg(self):
1024 return 0
1025
1026 def isFloatReg(self):
1027 return 0
1028
1029 def isIntReg(self):
1030 return 0
1031
1032 def isControlReg(self):
1033 return 0
1034
1035 def getFlags(self, op_desc):
1036 # note the empty slice '[:]' gives us a copy of self.flags[0]
1037 # instead of a reference to it
1038 my_flags = self.flags[0][:]
1039 if op_desc.is_src:
1040 my_flags += self.flags[1]
1041 if op_desc.is_dest:
1042 my_flags += self.flags[2]
1043 return my_flags
1044
1045 def makeDecl(self, op_desc):
1046 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1047 # Note that initializations in the declarations are solely
1048 # to avoid 'uninitialized variable' errors from the compiler.
1049 return type + ' ' + op_desc.munged_name + ' = 0;\n';
1050
1051 class IntRegOperandTraits(OperandTraits):
1052 def isReg(self):
1053 return 1
1054
1055 def isIntReg(self):
1056 return 1
1057
1058 def makeConstructor(self, op_desc):
1059 c = ''
1060 if op_desc.is_src:
1061 c += '\n\t_srcRegIdx[%d] = %s;' % \
1062 (op_desc.src_reg_idx, self.reg_spec)
1063 if op_desc.is_dest:
1064 c += '\n\t_destRegIdx[%d] = %s;' % \
1065 (op_desc.dest_reg_idx, self.reg_spec)
1066 return c
1067
1068 def makeRead(self, op_desc):
1069 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1070 if (type == 'float' or type == 'double'):
1071 error(0, 'Attempt to read integer register as FP')
1072 if (size == self.dflt_size):
1073 return '%s = xc->readIntReg(this, %d);\n' % \
1074 (op_desc.munged_name, op_desc.src_reg_idx)
1075 else:
1076 return '%s = bits(xc->readIntReg(this, %d), %d, 0);\n' % \
1077 (op_desc.munged_name, op_desc.src_reg_idx, size-1)
1078
1079 def makeWrite(self, op_desc):
1080 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1081 if (type == 'float' or type == 'double'):
1082 error(0, 'Attempt to write integer register as FP')
1083 if (size != self.dflt_size and is_signed):
1084 final_val = 'sext<%d>(%s)' % (size, op_desc.munged_name)
1085 else:
1086 final_val = op_desc.munged_name
1087 wb = '''
1088 {
1089 %s final_val = %s;
1090 xc->setIntReg(this, %d, final_val);\n
1091 if (traceData) { traceData->setData(final_val); }
1092 }''' % (self.dflt_type, final_val, op_desc.dest_reg_idx)
1093 return wb
1094
1095 class FloatRegOperandTraits(OperandTraits):
1096 def isReg(self):
1097 return 1
1098
1099 def isFloatReg(self):
1100 return 1
1101
1102 def makeConstructor(self, op_desc):
1103 c = ''
1104 if op_desc.is_src:
1105 c += '\n\t_srcRegIdx[%d] = %s + FP_Base_DepTag;' % \
1106 (op_desc.src_reg_idx, self.reg_spec)
1107 if op_desc.is_dest:
1108 c += '\n\t_destRegIdx[%d] = %s + FP_Base_DepTag;' % \
1109 (op_desc.dest_reg_idx, self.reg_spec)
1110 return c
1111
1112 def makeRead(self, op_desc):
1113 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1114 bit_select = 0
1115 if (type == 'float'):
1116 func = 'readFloatRegSingle'
1117 elif (type == 'double'):
1118 func = 'readFloatRegDouble'
1119 else:
1120 func = 'readFloatRegInt'
1121 if (size != self.dflt_size):
1122 bit_select = 1
1123 base = 'xc->%s(this, %d)' % \
1124 (func, op_desc.src_reg_idx)
1125 if bit_select:
1126 return '%s = bits(%s, %d, 0);\n' % \
1127 (op_desc.munged_name, base, size-1)
1128 else:
1129 return '%s = %s;\n' % (op_desc.munged_name, base)
1130
1131 def makeWrite(self, op_desc):
1132 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1133 final_val = op_desc.munged_name
1134 if (type == 'float'):
1135 func = 'setFloatRegSingle'
1136 elif (type == 'double'):
1137 func = 'setFloatRegDouble'
1138 else:
1139 func = 'setFloatRegInt'
1140 type = 'uint%d_t' % self.dflt_size
1141 if (size != self.dflt_size and is_signed):
1142 final_val = 'sext<%d>(%s)' % (size, op_desc.munged_name)
1143 wb = '''
1144 {
1145 %s final_val = %s;
1146 xc->%s(this, %d, final_val);\n
1147 if (traceData) { traceData->setData(final_val); }
1148 }''' % (type, final_val, func, op_desc.dest_reg_idx)
1149 return wb
1150
1151 class ControlRegOperandTraits(OperandTraits):
1152 def isReg(self):
1153 return 1
1154
1155 def isControlReg(self):
1156 return 1
1157
1158 def makeConstructor(self, op_desc):
1159 c = ''
1160 if op_desc.is_src:
1161 c += '\n\t_srcRegIdx[%d] = %s_DepTag;' % \
1162 (op_desc.src_reg_idx, self.reg_spec)
1163 if op_desc.is_dest:
1164 c += '\n\t_destRegIdx[%d] = %s_DepTag;' % \
1165 (op_desc.dest_reg_idx, self.reg_spec)
1166 return c
1167
1168 def makeRead(self, op_desc):
1169 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1170 bit_select = 0
1171 if (type == 'float' or type == 'double'):
1172 error(0, 'Attempt to read control register as FP')
1173 base = 'xc->read%s()' % self.reg_spec
1174 if size == self.dflt_size:
1175 return '%s = %s;\n' % (op_desc.munged_name, base)
1176 else:
1177 return '%s = bits(%s, %d, 0);\n' % \
1178 (op_desc.munged_name, base, size-1)
1179
1180 def makeWrite(self, op_desc):
1181 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1182 if (type == 'float' or type == 'double'):
1183 error(0, 'Attempt to write control register as FP')
1184 wb = 'xc->set%s(%s);\n' % (self.reg_spec, op_desc.munged_name)
1185 wb += 'if (traceData) { traceData->setData(%s); }' % \
1186 op_desc.munged_name
1187 return wb
1188
1189 class MemOperandTraits(OperandTraits):
1190 def isMem(self):
1191 return 1
1192
1193 def makeConstructor(self, op_desc):
1194 return ''
1195
1196 def makeDecl(self, op_desc):
1197 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1198 # Note that initializations in the declarations are solely
1199 # to avoid 'uninitialized variable' errors from the compiler.
1200 # Declare memory data variable.
1201 c = '%s %s = 0;\n' % (type, op_desc.munged_name)
1202 # Declare var to hold memory access flags.
1203 c += 'unsigned %s_flags = memAccessFlags;\n' % op_desc.base_name
1204 # If this operand is a dest (i.e., it's a store operation),
1205 # then we need to declare a variable for the write result code
1206 # as well.
1207 if op_desc.is_dest:
1208 c += 'uint64_t %s_write_result = 0;\n' % op_desc.base_name
1209 return c
1210
1211 def makeRead(self, op_desc):
1212 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1213 eff_type = 'uint%d_t' % size
1214 return 'fault = xc->read(EA, (%s&)%s, %s_flags);\n' \
1215 % (eff_type, op_desc.munged_name, op_desc.base_name)
1216
1217 def makeWrite(self, op_desc):
1218 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1219 eff_type = 'uint%d_t' % size
1220 wb = 'fault = xc->write((%s&)%s, EA, %s_flags, &%s_write_result);\n' \
1221 % (eff_type, op_desc.munged_name, op_desc.base_name,
1222 op_desc.base_name)
1223 wb += 'if (traceData) { traceData->setData(%s); }' % \
1224 op_desc.munged_name
1225 return wb
1226
1227 class NPCOperandTraits(OperandTraits):
1228 def makeConstructor(self, op_desc):
1229 return ''
1230
1231 def makeRead(self, op_desc):
1232 return '%s = xc->readPC() + 4;\n' % op_desc.munged_name
1233
1234 def makeWrite(self, op_desc):
1235 return 'xc->setNextPC(%s);\n' % op_desc.munged_name
1236
1237
1238 exportContextSymbols = ('IntRegOperandTraits', 'FloatRegOperandTraits',
1239 'ControlRegOperandTraits', 'MemOperandTraits',
1240 'NPCOperandTraits', 'InstObjParams', 'CodeBlock',
1241 're', 'string')
1242
1243 exportContext = {}
1244
1245 def updateExportContext():
1246 exportContext.update(exportDict(*exportContextSymbols))
1247 exportContext.update(templateMap)
1248
1249
1250 def exportDict(*symNames):
1251 return dict([(s, eval(s)) for s in symNames])
1252
1253
1254 #
1255 # Define operand variables that get derived from the basic declaration
1256 # of ISA-specific operands in operandTraitsMap. This function must be
1257 # called by the ISA description file explicitly after defining
1258 # operandTraitsMap (in a 'let' block).
1259 #
1260 def defineDerivedOperandVars():
1261 global operands
1262 operands = operandTraitsMap.keys()
1263
1264 operandsREString = (r'''
1265 (?<![\w\.]) # neg. lookbehind assertion: prevent partial matches
1266 ((%s)(?:\.(\w+))?) # match: operand with optional '.' then suffix
1267 (?![\w\.]) # neg. lookahead assertion: prevent partial matches
1268 '''
1269 % string.join(operands, '|'))
1270
1271 global operandsRE
1272 operandsRE = re.compile(operandsREString, re.MULTILINE|re.VERBOSE)
1273
1274 # Same as operandsREString, but extension is mandatory, and only two
1275 # groups are returned (base and ext, not full name as above).
1276 # Used for subtituting '_' for '.' to make C++ identifiers.
1277 operandsWithExtREString = (r'(?<![\w\.])(%s)\.(\w+)(?![\w\.])'
1278 % string.join(operands, '|'))
1279
1280 global operandsWithExtRE
1281 operandsWithExtRE = re.compile(operandsWithExtREString, re.MULTILINE)
1282
1283
1284 #
1285 # Operand descriptor class. An instance of this class represents
1286 # a specific operand for a code block.
1287 #
1288 class OperandDescriptor:
1289 def __init__(self, full_name, base_name, ext, is_src, is_dest):
1290 self.full_name = full_name
1291 self.base_name = base_name
1292 self.ext = ext
1293 self.is_src = is_src
1294 self.is_dest = is_dest
1295 self.traits = operandTraitsMap[base_name]
1296 # The 'effective extension' (eff_ext) is either the actual
1297 # extension, if one was explicitly provided, or the default.
1298 # The 'munged name' replaces the '.' between the base and
1299 # extension (if any) with a '_' to make a legal C++ variable name.
1300 if ext:
1301 self.eff_ext = ext
1302 self.munged_name = base_name + '_' + ext
1303 else:
1304 self.eff_ext = self.traits.dflt_ext
1305 self.munged_name = base_name
1306
1307 # Finalize additional fields (primarily code fields). This step
1308 # is done separately since some of these fields may depend on the
1309 # register index enumeration that hasn't been performed yet at the
1310 # time of __init__().
1311 def finalize(self):
1312 self.flags = self.traits.getFlags(self)
1313 self.constructor = self.traits.makeConstructor(self)
1314 self.op_decl = self.traits.makeDecl(self)
1315
1316 if self.is_src:
1317 self.op_rd = self.traits.makeRead(self)
1318 else:
1319 self.op_rd = ''
1320
1321 if self.is_dest:
1322 self.op_wb = self.traits.makeWrite(self)
1323 else:
1324 self.op_wb = ''
1325
1326 class OperandDescriptorList:
1327 def __init__(self):
1328 self.items = []
1329 self.bases = {}
1330
1331 def __len__(self):
1332 return len(self.items)
1333
1334 def __getitem__(self, index):
1335 return self.items[index]
1336
1337 def append(self, op_desc):
1338 self.items.append(op_desc)
1339 self.bases[op_desc.base_name] = op_desc
1340
1341 def find_base(self, base_name):
1342 # like self.bases[base_name], but returns None if not found
1343 # (rather than raising exception)
1344 return self.bases.get(base_name)
1345
1346 # internal helper function for concat[Some]Attr{Strings|Lists}
1347 def __internalConcatAttrs(self, attr_name, filter, result):
1348 for op_desc in self.items:
1349 if filter(op_desc):
1350 result += getattr(op_desc, attr_name)
1351 return result
1352
1353 # return a single string that is the concatenation of the (string)
1354 # values of the specified attribute for all operands
1355 def concatAttrStrings(self, attr_name):
1356 return self.__internalConcatAttrs(attr_name, lambda x: 1, '')
1357
1358 # like concatAttrStrings, but only include the values for the operands
1359 # for which the provided filter function returns true
1360 def concatSomeAttrStrings(self, filter, attr_name):
1361 return self.__internalConcatAttrs(attr_name, filter, '')
1362
1363 # return a single list that is the concatenation of the (list)
1364 # values of the specified attribute for all operands
1365 def concatAttrLists(self, attr_name):
1366 return self.__internalConcatAttrs(attr_name, lambda x: 1, [])
1367
1368 # like concatAttrLists, but only include the values for the operands
1369 # for which the provided filter function returns true
1370 def concatSomeAttrLists(self, filter, attr_name):
1371 return self.__internalConcatAttrs(attr_name, filter, [])
1372
1373 def sort(self):
1374 self.items.sort(lambda a, b: a.traits.sort_pri - b.traits.sort_pri)
1375
1376 # Regular expression object to match C++ comments
1377 # (used in findOperands())
1378 commentRE = re.compile(r'//.*\n')
1379
1380 # Regular expression object to match assignment statements
1381 # (used in findOperands())
1382 assignRE = re.compile(r'\s*=(?!=)', re.MULTILINE)
1383
1384 #
1385 # Find all the operands in the given code block. Returns an operand
1386 # descriptor list (instance of class OperandDescriptorList).
1387 #
1388 def findOperands(code):
1389 operands = OperandDescriptorList()
1390 # delete comments so we don't accidentally match on reg specifiers inside
1391 code = commentRE.sub('', code)
1392 # search for operands
1393 next_pos = 0
1394 while 1:
1395 match = operandsRE.search(code, next_pos)
1396 if not match:
1397 # no more matches: we're done
1398 break
1399 op = match.groups()
1400 # regexp groups are operand full name, base, and extension
1401 (op_full, op_base, op_ext) = op
1402 # if the token following the operand is an assignment, this is
1403 # a destination (LHS), else it's a source (RHS)
1404 is_dest = (assignRE.match(code, match.end()) != None)
1405 is_src = not is_dest
1406 # see if we've already seen this one
1407 op_desc = operands.find_base(op_base)
1408 if op_desc:
1409 if op_desc.ext != op_ext:
1410 error(0, 'Inconsistent extensions for operand %s' % op_base)
1411 op_desc.is_src = op_desc.is_src or is_src
1412 op_desc.is_dest = op_desc.is_dest or is_dest
1413 else:
1414 # new operand: create new descriptor
1415 op_desc = OperandDescriptor(op_full, op_base, op_ext,
1416 is_src, is_dest)
1417 operands.append(op_desc)
1418 # start next search after end of current match
1419 next_pos = match.end()
1420 operands.sort()
1421 # enumerate source & dest register operands... used in building
1422 # constructor later
1423 srcRegs = 0
1424 destRegs = 0
1425 operands.numFPDestRegs = 0
1426 operands.numIntDestRegs = 0
1427 for op_desc in operands:
1428 if op_desc.traits.isReg():
1429 if op_desc.is_src:
1430 op_desc.src_reg_idx = srcRegs
1431 srcRegs += 1
1432 if op_desc.is_dest:
1433 op_desc.dest_reg_idx = destRegs
1434 destRegs += 1
1435 if op_desc.traits.isFloatReg():
1436 operands.numFPDestRegs += 1
1437 elif op_desc.traits.isIntReg():
1438 operands.numIntDestRegs += 1
1439 operands.numSrcRegs = srcRegs
1440 operands.numDestRegs = destRegs
1441 # now make a final pass to finalize op_desc fields that may depend
1442 # on the register enumeration
1443 for op_desc in operands:
1444 op_desc.finalize()
1445 return operands
1446
1447 # Munge operand names in code string to make legal C++ variable names.
1448 # (Will match munged_name attribute of OperandDescriptor object.)
1449 def substMungedOpNames(code):
1450 return operandsWithExtRE.sub(r'\1_\2', code)
1451
1452 def joinLists(t):
1453 return map(string.join, t)
1454
1455 def makeFlagConstructor(flag_list):
1456 if len(flag_list) == 0:
1457 return ''
1458 # filter out repeated flags
1459 flag_list.sort()
1460 i = 1
1461 while i < len(flag_list):
1462 if flag_list[i] == flag_list[i-1]:
1463 del flag_list[i]
1464 else:
1465 i += 1
1466 pre = '\n\tflags['
1467 post = '] = true;'
1468 code = pre + string.join(flag_list, post + pre) + post
1469 return code
1470
1471 class CodeBlock:
1472 def __init__(self, code):
1473 self.orig_code = code
1474 self.operands = findOperands(code)
1475 self.code = substMungedOpNames(substBitOps(code))
1476 self.constructor = self.operands.concatAttrStrings('constructor')
1477 self.constructor += \
1478 '\n\t_numSrcRegs = %d;' % self.operands.numSrcRegs
1479 self.constructor += \
1480 '\n\t_numDestRegs = %d;' % self.operands.numDestRegs
1481 self.constructor += \
1482 '\n\t_numFPDestRegs = %d;' % self.operands.numFPDestRegs
1483 self.constructor += \
1484 '\n\t_numIntDestRegs = %d;' % self.operands.numIntDestRegs
1485
1486 self.op_decl = self.operands.concatAttrStrings('op_decl')
1487
1488 is_mem = lambda op: op.traits.isMem()
1489 not_mem = lambda op: not op.traits.isMem()
1490
1491 self.op_rd = self.operands.concatAttrStrings('op_rd')
1492 self.op_wb = self.operands.concatAttrStrings('op_wb')
1493 self.op_mem_rd = \
1494 self.operands.concatSomeAttrStrings(is_mem, 'op_rd')
1495 self.op_mem_wb = \
1496 self.operands.concatSomeAttrStrings(is_mem, 'op_wb')
1497 self.op_nonmem_rd = \
1498 self.operands.concatSomeAttrStrings(not_mem, 'op_rd')
1499 self.op_nonmem_wb = \
1500 self.operands.concatSomeAttrStrings(not_mem, 'op_wb')
1501
1502 self.flags = self.operands.concatAttrLists('flags')
1503
1504 # Make a basic guess on the operand class (function unit type).
1505 # These are good enough for most cases, and will be overridden
1506 # later otherwise.
1507 if 'IsStore' in self.flags:
1508 self.op_class = 'MemWriteOp'
1509 elif 'IsLoad' in self.flags or 'IsPrefetch' in self.flags:
1510 self.op_class = 'MemReadOp'
1511 elif 'IsFloating' in self.flags:
1512 self.op_class = 'FloatAddOp'
1513 else:
1514 self.op_class = 'IntAluOp'
1515
1516 # Assume all instruction flags are of the form 'IsFoo'
1517 instFlagRE = re.compile(r'Is.*')
1518
1519 # OpClass constants end in 'Op' except No_OpClass
1520 opClassRE = re.compile(r'.*Op|No_OpClass')
1521
1522 class InstObjParams:
1523 def __init__(self, mnem, class_name, base_class = '',
1524 code_block = None, opt_args = []):
1525 self.mnemonic = mnem
1526 self.class_name = class_name
1527 self.base_class = base_class
1528 if code_block:
1529 for code_attr in code_block.__dict__.keys():
1530 setattr(self, code_attr, getattr(code_block, code_attr))
1531 else:
1532 self.constructor = ''
1533 self.flags = []
1534 # Optional arguments are assumed to be either StaticInst flags
1535 # or an OpClass value. To avoid having to import a complete
1536 # list of these values to match against, we do it ad-hoc
1537 # with regexps.
1538 for oa in opt_args:
1539 if instFlagRE.match(oa):
1540 self.flags.append(oa)
1541 elif opClassRE.match(oa):
1542 self.op_class = oa
1543 else:
1544 error(0, 'InstObjParams: optional arg "%s" not recognized '
1545 'as StaticInst::Flag or OpClass.' % oa)
1546
1547 # add flag initialization to contructor here to include
1548 # any flags added via opt_args
1549 self.constructor += makeFlagConstructor(self.flags)
1550
1551 # if 'IsFloating' is set, add call to the FP enable check
1552 # function (which should be provided by isa_desc via a declare)
1553 if 'IsFloating' in self.flags:
1554 self.fp_enable_check = 'fault = checkFpEnableFault(xc);'
1555 else:
1556 self.fp_enable_check = ''
1557
1558 #######################
1559 #
1560 # Output file template
1561 #
1562
1563 file_template = '''
1564 /*
1565 * DO NOT EDIT THIS FILE!!!
1566 *
1567 * It was automatically generated from the ISA description in %(filename)s
1568 */
1569
1570 %(includes)s
1571
1572 %(global_output)s
1573
1574 namespace %(namespace)s {
1575
1576 %(namespace_output)s
1577
1578 } // namespace %(namespace)s
1579 '''
1580
1581
1582 # Update the output file only if the new contents are different from
1583 # the current contents. Minimizes the files that need to be rebuilt
1584 # after minor changes.
1585 def update_if_needed(file, contents):
1586 update = False
1587 if os.access(file, os.R_OK):
1588 f = open(file, 'r')
1589 old_contents = f.read()
1590 f.close()
1591 if contents != old_contents:
1592 print 'Updating', file
1593 os.remove(file) # in case it's write-protected
1594 update = True
1595 else:
1596 print 'File', file, 'is unchanged'
1597 else:
1598 print 'Generating', file
1599 update = True
1600 if update:
1601 f = open(file, 'w')
1602 f.write(contents)
1603 f.close()
1604
1605 #
1606 # Read in and parse the ISA description.
1607 #
1608 def parse_isa_desc(isa_desc_file, output_dir, include_path):
1609 # set a global var for the input filename... used in error messages
1610 global input_filename
1611 input_filename = isa_desc_file
1612
1613 # Suck the ISA description file in.
1614 input = open(isa_desc_file)
1615 isa_desc = input.read()
1616 input.close()
1617
1618 # Parse it.
1619 (isa_name, namespace, global_code, namespace_code) = yacc.parse(isa_desc)
1620
1621 # grab the last three path components of isa_desc_file to put in
1622 # the output
1623 filename = '/'.join(isa_desc_file.split('/')[-3:])
1624
1625 # generate decoder.hh
1626 includes = '#include "base/bitfield.hh" // for bitfield support'
1627 global_output = global_code.header_output
1628 namespace_output = namespace_code.header_output
1629 update_if_needed(output_dir + '/decoder.hh', file_template % vars())
1630
1631 # generate decoder.cc
1632 includes = '#include "%s/decoder.hh"' % include_path
1633 global_output = global_code.decoder_output
1634 namespace_output = namespace_code.decoder_output
1635 namespace_output += namespace_code.decode_block
1636 update_if_needed(output_dir + '/decoder.cc', file_template % vars())
1637
1638 # generate per-cpu exec files
1639 for cpu in CpuModel.list:
1640 includes = '#include "%s/decoder.hh"\n' % include_path
1641 includes += cpu.includes
1642 global_output = global_code.exec_output[cpu.name]
1643 namespace_output = namespace_code.exec_output[cpu.name]
1644 update_if_needed(output_dir + '/' + cpu.filename,
1645 file_template % vars())
1646
1647 # Called as script: get args from command line.
1648 if __name__ == '__main__':
1649 parse_isa_desc(sys.argv[1], sys.argv[2], sys.argv[3])