1 # Copyright (c) 2003-2005 The Regents of The University of Michigan
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
6 # met: redistributions of source code must retain the above copyright
7 # notice, this list of conditions and the following disclaimer;
8 # redistributions in binary form must reproduce the above copyright
9 # notice, this list of conditions and the following disclaimer in the
10 # documentation and/or other materials provided with the distribution;
11 # neither the name of the copyright holders nor the names of its
12 # contributors may be used to endorse or promote products derived from
13 # this software without specific prior written permission.
15 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 # Authors: Steve Reinhardt
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_PLY']]
45 #####################################################################
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.
58 #####################################################################
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.
64 'BITFIELD', 'DECODE', 'DECODER', 'DEFAULT', 'DEF', 'EXEC', 'FORMAT',
65 'HEADER', 'LET', 'NAMESPACE', 'OPERAND_TYPES', 'OPERANDS',
66 'OUTPUT', 'SIGNED', 'TEMPLATE'
69 # List of tokens. The lex module requires this.
83 # ( ) [ ] { } < > , ; . : :: *
85 'LBRACKET', 'RBRACKET',
87 'LESS', 'GREATER', 'EQUALS',
88 'COMMA', 'SEMI', 'DOT', 'COLON', 'DBLCOLON',
91 # C preprocessor directives
94 # The following are matched but never returned. commented out to
95 # suppress PLY warning
103 # Regular expressions for token matching
120 # Identifiers and reserved words
123 reserved_map
[r
.lower()] = r
127 t
.type = reserved_map
.get(t
.value
,'ID')
132 r
'(0x[\da-fA-F]+)|\d+'
134 t
.value
= int(t
.value
,0)
136 error(t
.lexer
.lineno
, 'Integer value "%s" too large' % t
.value
)
140 # String literal. Note that these use only single quotes, and
141 # can span multiple lines.
145 t
.value
= t
.value
[1:-1]
146 t
.lexer
.lineno
+= t
.value
.count('\n')
150 # "Code literal"... like a string literal, but delimiters are
151 # '{{' and '}}' so they get formatted nicely under emacs c-mode
153 r
"(?m)\{\{([^\}]|}(?!\}))+\}\}"
155 t
.value
= t
.value
[2:-2]
156 t
.lexer
.lineno
+= t
.value
.count('\n')
159 def t_CPPDIRECTIVE(t
):
161 t
.lexer
.lineno
+= t
.value
.count('\n')
165 r
'^\#\#newfile\s+"[\w/.-]*"'
166 fileNameStack
.push((t
.value
[11:-1], t
.lexer
.lineno
))
171 (old_filename
, t
.lexer
.lineno
) = fileNameStack
.pop()
174 # The functions t_NEWLINE, t_ignore, and t_error are
175 # special for the lex module.
181 t
.lexer
.lineno
+= t
.value
.count('\n')
187 # Completely ignored characters
192 error(t
.lexer
.lineno
, "illegal character '%s'" % t
.value
[0])
198 #####################################################################
202 # Every function whose name starts with 'p_' defines a grammar rule.
203 # The rule is encoded in the function's doc string, while the
204 # function body provides the action taken when the rule is matched.
205 # The argument to each function is a list of the values of the
206 # rule's symbols: t[0] for the LHS, and t[1..n] for the symbols
207 # on the RHS. For tokens, the value is copied from the t.value
208 # attribute provided by the lexer. For non-terminals, the value
209 # is assigned by the producing rule; i.e., the job of the grammar
210 # rule function is to set the value for the non-terminal on the LHS
211 # (by assigning to t[0]).
212 #####################################################################
214 # The LHS of the first grammar rule is used as the start symbol
215 # (in this case, 'specification'). Note that this rule enforces
216 # that there will be exactly one namespace declaration, with 0 or more
217 # global defs/decls before and after it. The defs & decls before
218 # the namespace decl will be outside the namespace; those after
219 # will be inside. The decoder function is always inside the namespace.
220 def p_specification(t
):
221 'specification : opt_defs_and_outputs name_decl opt_defs_and_outputs decode_block'
224 namespace
= isa_name
+ "Inst"
225 # wrap the decode block as a function definition
226 t
[4].wrap_decode_block('''
228 %(isa_name)s::decodeInst(%(isa_name)s::ExtMachInst machInst)
230 using namespace %(namespace)s;
232 # both the latter output blocks and the decode block are in the namespace
233 namespace_code
= t
[3] + t
[4]
234 # pass it all back to the caller of yacc.parse()
235 t
[0] = (isa_name
, namespace
, global_code
, namespace_code
)
237 # ISA name declaration looks like "namespace <foo>;"
239 'name_decl : NAMESPACE ID SEMI'
242 # 'opt_defs_and_outputs' is a possibly empty sequence of
243 # def and/or output statements.
244 def p_opt_defs_and_outputs_0(t
):
245 'opt_defs_and_outputs : empty'
248 def p_opt_defs_and_outputs_1(t
):
249 'opt_defs_and_outputs : defs_and_outputs'
252 def p_defs_and_outputs_0(t
):
253 'defs_and_outputs : def_or_output'
256 def p_defs_and_outputs_1(t
):
257 'defs_and_outputs : defs_and_outputs def_or_output'
260 # The list of possible definition/output statements.
261 def p_def_or_output(t
):
262 '''def_or_output : def_format
264 | def_bitfield_struct
274 # Output blocks 'output <foo> {{...}}' (C++ code blocks) are copied
275 # directly to the appropriate output section.
278 # Protect any non-dict-substitution '%'s in a format string
279 # (i.e. those not followed by '(')
280 def protect_non_subst_percents(s
):
281 return re
.sub(r
'%(?!\()', '%%', s
)
283 # Massage output block by substituting in template definitions and bit
284 # operators. We handle '%'s embedded in the string that don't
285 # indicate template substitutions (or CPU-specific symbols, which get
286 # handled in GenCode) by doubling them first so that the format
287 # operation will reduce them back to single '%'s.
288 def process_output(s
):
289 s
= protect_non_subst_percents(s
)
290 # protects cpu-specific symbols too
291 s
= protect_cpu_symbols(s
)
292 return substBitOps(s
% templateMap
)
294 def p_output_header(t
):
295 'output_header : OUTPUT HEADER CODELIT SEMI'
296 t
[0] = GenCode(header_output
= process_output(t
[3]))
298 def p_output_decoder(t
):
299 'output_decoder : OUTPUT DECODER CODELIT SEMI'
300 t
[0] = GenCode(decoder_output
= process_output(t
[3]))
302 def p_output_exec(t
):
303 'output_exec : OUTPUT EXEC CODELIT SEMI'
304 t
[0] = GenCode(exec_output
= process_output(t
[3]))
306 # global let blocks 'let {{...}}' (Python code blocks) are executed
307 # directly when seen. Note that these execute in a special variable
308 # context 'exportContext' to prevent the code from polluting this
309 # script's namespace.
311 'global_let : LET CODELIT SEMI'
312 updateExportContext()
313 exportContext
["header_output"] = ''
314 exportContext
["decoder_output"] = ''
315 exportContext
["exec_output"] = ''
316 exportContext
["decode_block"] = ''
318 exec fixPythonIndentation(t
[2]) in exportContext
319 except Exception, exc
:
320 error(t
.lexer
.lineno
,
321 'error: %s in global let block "%s".' % (exc
, t
[2]))
322 t
[0] = GenCode(header_output
= exportContext
["header_output"],
323 decoder_output
= exportContext
["decoder_output"],
324 exec_output
= exportContext
["exec_output"],
325 decode_block
= exportContext
["decode_block"])
327 # Define the mapping from operand type extensions to C++ types and bit
328 # widths (stored in operandTypeMap).
329 def p_def_operand_types(t
):
330 'def_operand_types : DEF OPERAND_TYPES CODELIT SEMI'
332 userDict
= eval('{' + t
[3] + '}')
333 except Exception, exc
:
334 error(t
.lexer
.lineno
,
335 'error: %s in def operand_types block "%s".' % (exc
, t
[3]))
336 buildOperandTypeMap(userDict
, t
.lexer
.lineno
)
337 t
[0] = GenCode() # contributes nothing to the output C++ file
339 # Define the mapping from operand names to operand classes and other
340 # traits. Stored in operandNameMap.
341 def p_def_operands(t
):
342 'def_operands : DEF OPERANDS CODELIT SEMI'
343 if not globals().has_key('operandTypeMap'):
344 error(t
.lexer
.lineno
,
345 'error: operand types must be defined before operands')
347 userDict
= eval('{' + t
[3] + '}', exportContext
)
348 except Exception, exc
:
349 error(t
.lexer
.lineno
,
350 'error: %s in def operands block "%s".' % (exc
, t
[3]))
351 buildOperandNameMap(userDict
, t
.lexer
.lineno
)
352 t
[0] = GenCode() # contributes nothing to the output C++ file
354 # A bitfield definition looks like:
355 # 'def [signed] bitfield <ID> [<first>:<last>]'
356 # This generates a preprocessor macro in the output file.
357 def p_def_bitfield_0(t
):
358 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT COLON INTLIT GREATER SEMI'
359 expr
= 'bits(machInst, %2d, %2d)' % (t
[6], t
[8])
360 if (t
[2] == 'signed'):
361 expr
= 'sext<%d>(%s)' % (t
[6] - t
[8] + 1, expr
)
362 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
363 t
[0] = GenCode(header_output
= hash_define
)
365 # alternate form for single bit: 'def [signed] bitfield <ID> [<bit>]'
366 def p_def_bitfield_1(t
):
367 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT GREATER SEMI'
368 expr
= 'bits(machInst, %2d, %2d)' % (t
[6], t
[6])
369 if (t
[2] == 'signed'):
370 expr
= 'sext<%d>(%s)' % (1, expr
)
371 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
372 t
[0] = GenCode(header_output
= hash_define
)
374 # alternate form for structure member: 'def bitfield <ID> <ID>'
375 def p_def_bitfield_struct(t
):
376 'def_bitfield_struct : DEF opt_signed BITFIELD ID id_with_dot SEMI'
378 error(t
.lexer
.lineno
, 'error: structure bitfields are always unsigned.')
379 expr
= 'machInst.%s' % t
[5]
380 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
381 t
[0] = GenCode(header_output
= hash_define
)
383 def p_id_with_dot_0(t
):
387 def p_id_with_dot_1(t
):
388 'id_with_dot : ID DOT id_with_dot'
389 t
[0] = t
[1] + t
[2] + t
[3]
391 def p_opt_signed_0(t
):
392 'opt_signed : SIGNED'
395 def p_opt_signed_1(t
):
399 # Global map variable to hold templates
402 def p_def_template(t
):
403 'def_template : DEF TEMPLATE ID CODELIT SEMI'
404 templateMap
[t
[3]] = Template(t
[4])
407 # An instruction format definition looks like
408 # "def format <fmt>(<params>) {{...}};"
410 'def_format : DEF FORMAT ID LPAREN param_list RPAREN CODELIT SEMI'
411 (id, params
, code
) = (t
[3], t
[5], t
[7])
412 defFormat(id, params
, code
, t
.lexer
.lineno
)
415 # The formal parameter list for an instruction format is a possibly
416 # empty list of comma-separated parameters. Positional (standard,
417 # non-keyword) parameters must come first, followed by keyword
418 # parameters, followed by a '*foo' parameter that gets excess
419 # positional arguments (as in Python). Each of these three parameter
420 # categories is optional.
422 # Note that we do not support the '**foo' parameter for collecting
423 # otherwise undefined keyword args. Otherwise the parameter list is
424 # (I believe) identical to what is supported in Python.
426 # The param list generates a tuple, where the first element is a list of
427 # the positional params and the second element is a dict containing the
429 def p_param_list_0(t
):
430 'param_list : positional_param_list COMMA nonpositional_param_list'
433 def p_param_list_1(t
):
434 '''param_list : positional_param_list
435 | nonpositional_param_list'''
438 def p_positional_param_list_0(t
):
439 'positional_param_list : empty'
442 def p_positional_param_list_1(t
):
443 'positional_param_list : ID'
446 def p_positional_param_list_2(t
):
447 'positional_param_list : positional_param_list COMMA ID'
450 def p_nonpositional_param_list_0(t
):
451 'nonpositional_param_list : keyword_param_list COMMA excess_args_param'
454 def p_nonpositional_param_list_1(t
):
455 '''nonpositional_param_list : keyword_param_list
456 | excess_args_param'''
459 def p_keyword_param_list_0(t
):
460 'keyword_param_list : keyword_param'
463 def p_keyword_param_list_1(t
):
464 'keyword_param_list : keyword_param_list COMMA keyword_param'
467 def p_keyword_param(t
):
468 'keyword_param : ID EQUALS expr'
469 t
[0] = t
[1] + ' = ' + t
[3].__repr
__()
471 def p_excess_args_param(t
):
472 'excess_args_param : ASTERISK ID'
473 # Just concatenate them: '*ID'. Wrap in list to be consistent
474 # with positional_param_list and keyword_param_list.
477 # End of format definition-related rules.
481 # A decode block looks like:
482 # decode <field1> [, <field2>]* [default <inst>] { ... }
484 def p_decode_block(t
):
485 'decode_block : DECODE ID opt_default LBRACE decode_stmt_list RBRACE'
486 default_defaults
= defaultStack
.pop()
488 # use the "default defaults" only if there was no explicit
489 # default statement in decode_stmt_list
490 if not codeObj
.has_decode_default
:
491 codeObj
+= default_defaults
492 codeObj
.wrap_decode_block('switch (%s) {\n' % t
[2], '}\n')
495 # The opt_default statement serves only to push the "default defaults"
496 # onto defaultStack. This value will be used by nested decode blocks,
497 # and used and popped off when the current decode_block is processed
498 # (in p_decode_block() above).
499 def p_opt_default_0(t
):
500 'opt_default : empty'
501 # no default specified: reuse the one currently at the top of the stack
502 defaultStack
.push(defaultStack
.top())
503 # no meaningful value returned
506 def p_opt_default_1(t
):
507 'opt_default : DEFAULT inst'
508 # push the new default
510 codeObj
.wrap_decode_block('\ndefault:\n', 'break;\n')
511 defaultStack
.push(codeObj
)
512 # no meaningful value returned
515 def p_decode_stmt_list_0(t
):
516 'decode_stmt_list : decode_stmt'
519 def p_decode_stmt_list_1(t
):
520 'decode_stmt_list : decode_stmt decode_stmt_list'
521 if (t
[1].has_decode_default
and t
[2].has_decode_default
):
522 error(t
.lexer
.lineno
, 'Two default cases in decode block')
526 # Decode statement rules
528 # There are four types of statements allowed in a decode block:
529 # 1. Format blocks 'format <foo> { ... }'
530 # 2. Nested decode blocks
531 # 3. Instruction definitions.
532 # 4. C preprocessor directives.
535 # Preprocessor directives found in a decode statement list are passed
536 # through to the output, replicated to all of the output code
537 # streams. This works well for ifdefs, so we can ifdef out both the
538 # declarations and the decode cases generated by an instruction
539 # definition. Handling them as part of the grammar makes it easy to
540 # keep them in the right place with respect to the code generated by
541 # the other statements.
542 def p_decode_stmt_cpp(t
):
543 'decode_stmt : CPPDIRECTIVE'
544 t
[0] = GenCode(t
[1], t
[1], t
[1], t
[1])
546 # A format block 'format <foo> { ... }' sets the default instruction
547 # format used to handle instruction definitions inside the block.
548 # This format can be overridden by using an explicit format on the
549 # instruction definition or with a nested format block.
550 def p_decode_stmt_format(t
):
551 'decode_stmt : FORMAT push_format_id LBRACE decode_stmt_list RBRACE'
552 # The format will be pushed on the stack when 'push_format_id' is
553 # processed (see below). Once the parser has recognized the full
554 # production (though the right brace), we're done with the format,
555 # so now we can pop it.
559 # This rule exists so we can set the current format (& push the stack)
560 # when we recognize the format name part of the format block.
561 def p_push_format_id(t
):
562 'push_format_id : ID'
564 formatStack
.push(formatMap
[t
[1]])
565 t
[0] = ('', '// format %s' % t
[1])
567 error(t
.lexer
.lineno
, 'instruction format "%s" not defined.' % t
[1])
569 # Nested decode block: if the value of the current field matches the
570 # specified constant, do a nested decode on some other field.
571 def p_decode_stmt_decode(t
):
572 'decode_stmt : case_label COLON decode_block'
575 # just wrap the decoding code from the block as a case in the
576 # outer switch statement.
577 codeObj
.wrap_decode_block('\n%s:\n' % label
)
578 codeObj
.has_decode_default
= (label
== 'default')
581 # Instruction definition (finally!).
582 def p_decode_stmt_inst(t
):
583 'decode_stmt : case_label COLON inst SEMI'
586 codeObj
.wrap_decode_block('\n%s:' % label
, 'break;\n')
587 codeObj
.has_decode_default
= (label
== 'default')
590 # The case label is either a list of one or more constants or 'default'
591 def p_case_label_0(t
):
592 'case_label : intlit_list'
593 t
[0] = ': '.join(map(lambda a
: 'case %#x' % a
, t
[1]))
595 def p_case_label_1(t
):
596 'case_label : DEFAULT'
600 # The constant list for a decode case label must be non-empty, but may have
601 # one or more comma-separated integer literals in it.
603 def p_intlit_list_0(t
):
604 'intlit_list : INTLIT'
607 def p_intlit_list_1(t
):
608 'intlit_list : intlit_list COMMA INTLIT'
612 # Define an instruction using the current instruction format (specified
613 # by an enclosing format block).
614 # "<mnemonic>(<args>)"
616 'inst : ID LPAREN arg_list RPAREN'
617 # Pass the ID and arg list to the current format class to deal with.
618 currentFormat
= formatStack
.top()
619 codeObj
= currentFormat
.defineInst(t
[1], t
[3], t
.lexer
.lineno
)
620 args
= ','.join(map(str, t
[3]))
621 args
= re
.sub('(?m)^', '//', args
)
622 args
= re
.sub('^//', '', args
)
623 comment
= '\n// %s::%s(%s)\n' % (currentFormat
.id, t
[1], args
)
624 codeObj
.prepend_all(comment
)
627 # Define an instruction using an explicitly specified format:
628 # "<fmt>::<mnemonic>(<args>)"
630 'inst : ID DBLCOLON ID LPAREN arg_list RPAREN'
632 format
= formatMap
[t
[1]]
634 error(t
.lexer
.lineno
, 'instruction format "%s" not defined.' % t
[1])
635 codeObj
= format
.defineInst(t
[3], t
[5], t
.lexer
.lineno
)
636 comment
= '\n// %s::%s(%s)\n' % (t
[1], t
[3], t
[5])
637 codeObj
.prepend_all(comment
)
640 # The arg list generates a tuple, where the first element is a list of
641 # the positional args and the second element is a dict containing the
644 'arg_list : positional_arg_list COMMA keyword_arg_list'
645 t
[0] = ( t
[1], t
[3] )
648 'arg_list : positional_arg_list'
652 'arg_list : keyword_arg_list'
655 def p_positional_arg_list_0(t
):
656 'positional_arg_list : empty'
659 def p_positional_arg_list_1(t
):
660 'positional_arg_list : expr'
663 def p_positional_arg_list_2(t
):
664 'positional_arg_list : positional_arg_list COMMA expr'
667 def p_keyword_arg_list_0(t
):
668 'keyword_arg_list : keyword_arg'
671 def p_keyword_arg_list_1(t
):
672 'keyword_arg_list : keyword_arg_list COMMA keyword_arg'
676 def p_keyword_arg(t
):
677 'keyword_arg : ID EQUALS expr'
678 t
[0] = { t
[1] : t
[3] }
681 # Basic expressions. These constitute the argument values of
682 # "function calls" (i.e. instruction definitions in the decode block)
683 # and default values for formal parameters of format functions.
685 # Right now, these are either strings, integers, or (recursively)
686 # lists of exprs (using Python square-bracket list syntax). Note that
687 # bare identifiers are trated as string constants here (since there
688 # isn't really a variable namespace to refer to).
698 '''expr : LBRACKET list_expr RBRACKET'''
701 def p_list_expr_0(t
):
705 def p_list_expr_1(t
):
706 'list_expr : list_expr COMMA expr'
709 def p_list_expr_2(t
):
714 # Empty production... use in other rules for readability.
720 # Parse error handler. Note that the argument here is the offending
721 # *token*, not a grammar symbol (hence the need to use t.value)
724 error(t
.lexer
.lineno
, "syntax error at '%s'" % t
.value
)
726 error(0, "unknown syntax error", True)
728 # END OF GRAMMAR RULES
730 # Now build the parser.
734 #####################################################################
738 #####################################################################
740 # Expand template with CPU-specific references into a dictionary with
741 # an entry for each CPU model name. The entry key is the model name
742 # and the corresponding value is the template with the CPU-specific
743 # refs substituted for that model.
744 def expand_cpu_symbols_to_dict(template
):
745 # Protect '%'s that don't go with CPU-specific terms
746 t
= re
.sub(r
'%(?!\(CPU_)', '%%', template
)
748 for cpu
in cpu_models
:
749 result
[cpu
.name
] = t
% cpu
.strings
752 # *If* the template has CPU-specific references, return a single
753 # string containing a copy of the template for each CPU model with the
754 # corresponding values substituted in. If the template has no
755 # CPU-specific references, it is returned unmodified.
756 def expand_cpu_symbols_to_string(template
):
757 if template
.find('%(CPU_') != -1:
758 return reduce(lambda x
,y
: x
+y
,
759 expand_cpu_symbols_to_dict(template
).values())
763 # Protect CPU-specific references by doubling the corresponding '%'s
764 # (in preparation for substituting a different set of references into
766 def protect_cpu_symbols(template
):
767 return re
.sub(r
'%(?=\(CPU_)', '%%', template
)
772 # The GenCode class encapsulates generated code destined for various
773 # output files. The header_output and decoder_output attributes are
774 # strings containing code destined for decoder.hh and decoder.cc
775 # respectively. The decode_block attribute contains code to be
776 # incorporated in the decode function itself (that will also end up in
777 # decoder.cc). The exec_output attribute is a dictionary with a key
778 # for each CPU model name; the value associated with a particular key
779 # is the string of code for that CPU model's exec.cc file. The
780 # has_decode_default attribute is used in the decode block to allow
781 # explicit default clauses to override default default clauses.
784 # Constructor. At this point we substitute out all CPU-specific
785 # symbols. For the exec output, these go into the per-model
786 # dictionary. For all other output types they get collapsed into
789 header_output
= '', decoder_output
= '', exec_output
= '',
790 decode_block
= '', has_decode_default
= False):
791 self
.header_output
= expand_cpu_symbols_to_string(header_output
)
792 self
.decoder_output
= expand_cpu_symbols_to_string(decoder_output
)
793 if isinstance(exec_output
, dict):
794 self
.exec_output
= exec_output
795 elif isinstance(exec_output
, str):
796 # If the exec_output arg is a single string, we replicate
797 # it for each of the CPU models, substituting and
798 # %(CPU_foo)s params appropriately.
799 self
.exec_output
= expand_cpu_symbols_to_dict(exec_output
)
800 self
.decode_block
= expand_cpu_symbols_to_string(decode_block
)
801 self
.has_decode_default
= has_decode_default
803 # Override '+' operator: generate a new GenCode object that
804 # concatenates all the individual strings in the operands.
805 def __add__(self
, other
):
807 for cpu
in cpu_models
:
809 exec_output
[n
] = self
.exec_output
[n
] + other
.exec_output
[n
]
810 return GenCode(self
.header_output
+ other
.header_output
,
811 self
.decoder_output
+ other
.decoder_output
,
813 self
.decode_block
+ other
.decode_block
,
814 self
.has_decode_default
or other
.has_decode_default
)
816 # Prepend a string (typically a comment) to all the strings.
817 def prepend_all(self
, pre
):
818 self
.header_output
= pre
+ self
.header_output
819 self
.decoder_output
= pre
+ self
.decoder_output
820 self
.decode_block
= pre
+ self
.decode_block
821 for cpu
in cpu_models
:
822 self
.exec_output
[cpu
.name
] = pre
+ self
.exec_output
[cpu
.name
]
824 # Wrap the decode block in a pair of strings (e.g., 'case foo:'
825 # and 'break;'). Used to build the big nested switch statement.
826 def wrap_decode_block(self
, pre
, post
= ''):
827 self
.decode_block
= pre
+ indent(self
.decode_block
) + post
832 # A format object encapsulates an instruction format. It must provide
833 # a defineInst() method that generates the code for an instruction
836 exportContextSymbols
= ('InstObjParams', 'makeList', 're', 'string')
840 def updateExportContext():
841 exportContext
.update(exportDict(*exportContextSymbols
))
842 exportContext
.update(templateMap
)
844 def exportDict(*symNames
):
845 return dict([(s
, eval(s
)) for s
in symNames
])
849 def __init__(self
, id, params
, code
):
850 # constructor: just save away arguments
853 label
= 'def format ' + id
854 self
.user_code
= compile(fixPythonIndentation(code
), label
, 'exec')
855 param_list
= string
.join(params
, ", ")
856 f
= '''def defInst(_code, _context, %s):
857 my_locals = vars().copy()
858 exec _code in _context, my_locals
859 return my_locals\n''' % param_list
860 c
= compile(f
, label
+ ' wrapper', 'exec')
864 def defineInst(self
, name
, args
, lineno
):
866 updateExportContext()
867 context
.update(exportContext
)
869 Name
= name
[0].upper()
872 context
.update({ 'name': name
, 'Name': Name
})
874 vars = self
.func(self
.user_code
, context
, *args
[0], **args
[1])
875 except Exception, exc
:
876 error(lineno
, 'error defining "%s": %s.' % (name
, exc
))
877 for k
in vars.keys():
878 if k
not in ('header_output', 'decoder_output',
879 'exec_output', 'decode_block'):
881 return GenCode(**vars)
883 # Special null format to catch an implicit-format instruction
884 # definition outside of any format block.
887 self
.defaultInst
= ''
889 def defineInst(self
, name
, args
, lineno
):
891 'instruction definition "%s" with no active format!' % name
)
893 # This dictionary maps format name strings to Format objects.
896 # Define a new format
897 def defFormat(id, params
, code
, lineno
):
898 # make sure we haven't already defined this one
899 if formatMap
.get(id, None) != None:
900 error(lineno
, 'format %s redefined.' % id)
901 # create new object and store in global map
902 formatMap
[id] = Format(id, params
, code
)
906 # Stack: a simple stack object. Used for both formats (formatStack)
907 # and default cases (defaultStack). Simply wraps a list to give more
908 # stack-like syntax and enable initialization with an argument list
909 # (as opposed to an argument that's a list).
912 def __init__(self
, *items
):
913 list.__init
__(self
, items
)
915 def push(self
, item
):
921 # The global format stack.
922 formatStack
= Stack(NoFormat())
924 # The global default case stack.
925 defaultStack
= Stack( None )
927 # Global stack that tracks current file and line number.
928 # Each element is a tuple (filename, lineno) that records the
929 # *current* filename and the line number in the *previous* file where
931 fileNameStack
= Stack()
937 # Indent every line in string 's' by two spaces
938 # (except preprocessor directives).
939 # Used to make nested code blocks look pretty.
942 return re
.sub(r
'(?m)^(?!#)', ' ', s
)
945 # Munge a somewhat arbitrarily formatted piece of Python code
946 # (e.g. from a format 'let' block) into something whose indentation
947 # will get by the Python parser.
949 # The two keys here are that Python will give a syntax error if
950 # there's any whitespace at the beginning of the first line, and that
951 # all lines at the same lexical nesting level must have identical
952 # indentation. Unfortunately the way code literals work, an entire
953 # let block tends to have some initial indentation. Rather than
954 # trying to figure out what that is and strip it off, we prepend 'if
955 # 1:' to make the let code the nested block inside the if (and have
956 # the parser automatically deal with the indentation for us).
958 # We don't want to do this if (1) the code block is empty or (2) the
959 # first line of the block doesn't have any whitespace at the front.
961 def fixPythonIndentation(s
):
962 # get rid of blank lines first
963 s
= re
.sub(r
'(?m)^\s*\n', '', s
);
964 if (s
!= '' and re
.match(r
'[ \t]', s
[0])):
968 # Error handler. Just call exit. Output formatted to work under
969 # Emacs compile-mode. Optional 'print_traceback' arg, if set to True,
970 # prints a Python stack backtrace too (can be handy when trying to
971 # debug the parser itself).
972 def error(lineno
, string
, print_traceback
= False):
974 for (filename
, line
) in fileNameStack
[0:-1]:
975 print spaces
+ "In file included from " + filename
+ ":"
977 # Print a Python stack backtrace if requested.
978 if (print_traceback
):
979 traceback
.print_exc()
981 line_str
= "%d:" % lineno
984 sys
.exit(spaces
+ "%s:%s %s" % (fileNameStack
[-1][0], line_str
, string
))
987 #####################################################################
989 # Bitfield Operator Support
991 #####################################################################
993 bitOp1ArgRE
= re
.compile(r
'<\s*(\w+)\s*:\s*>')
995 bitOpWordRE
= re
.compile(r
'(?<![\w\.])([\w\.]+)<\s*(\w+)\s*:\s*(\w+)\s*>')
996 bitOpExprRE
= re
.compile(r
'\)<\s*(\w+)\s*:\s*(\w+)\s*>')
998 def substBitOps(code
):
999 # first convert single-bit selectors to two-index form
1000 # i.e., <n> --> <n:n>
1001 code
= bitOp1ArgRE
.sub(r
'<\1:\1>', code
)
1002 # simple case: selector applied to ID (name)
1003 # i.e., foo<a:b> --> bits(foo, a, b)
1004 code
= bitOpWordRE
.sub(r
'bits(\1, \2, \3)', code
)
1005 # if selector is applied to expression (ending in ')'),
1006 # we need to search backward for matching '('
1007 match
= bitOpExprRE
.search(code
)
1009 exprEnd
= match
.start()
1012 while nestLevel
> 0:
1013 if code
[here
] == '(':
1015 elif code
[here
] == ')':
1019 sys
.exit("Didn't find '('!")
1021 newExpr
= r
'bits(%s, %s, %s)' % (code
[exprStart
:exprEnd
+1],
1022 match
.group(1), match
.group(2))
1023 code
= code
[:exprStart
] + newExpr
+ code
[match
.end():]
1024 match
= bitOpExprRE
.search(code
)
1028 ####################
1031 # Template objects are format strings that allow substitution from
1032 # the attribute spaces of other objects (e.g. InstObjParams instances).
1034 labelRE
= re
.compile(r
'(?<!%)%\(([^\)]+)\)[sd]')
1037 def __init__(self
, t
):
1043 # Protect non-Python-dict substitutions (e.g. if there's a printf
1044 # in the templated C++ code)
1045 template
= protect_non_subst_percents(self
.template
)
1046 # CPU-model-specific substitutions are handled later (in GenCode).
1047 template
= protect_cpu_symbols(template
)
1049 # Build a dict ('myDict') to use for the template substitution.
1050 # Start with the template namespace. Make a copy since we're
1051 # going to modify it.
1052 myDict
= templateMap
.copy()
1054 if isinstance(d
, InstObjParams
):
1055 # If we're dealing with an InstObjParams object, we need
1056 # to be a little more sophisticated. The instruction-wide
1057 # parameters are already formed, but the parameters which
1058 # are only function wide still need to be generated.
1061 myDict
.update(d
.__dict
__)
1062 # The "operands" and "snippets" attributes of the InstObjParams
1063 # objects are for internal use and not substitution.
1064 del myDict
['operands']
1065 del myDict
['snippets']
1067 snippetLabels
= [l
for l
in labelRE
.findall(template
)
1068 if d
.snippets
.has_key(l
)]
1070 snippets
= dict([(s
, mungeSnippet(d
.snippets
[s
]))
1071 for s
in snippetLabels
])
1073 myDict
.update(snippets
)
1075 compositeCode
= ' '.join(map(str, snippets
.values()))
1077 # Add in template itself in case it references any
1078 # operands explicitly (like Mem)
1079 compositeCode
+= ' ' + template
1081 operands
= SubOperandList(compositeCode
, d
.operands
)
1083 myDict
['op_decl'] = operands
.concatAttrStrings('op_decl')
1085 is_src
= lambda op
: op
.is_src
1086 is_dest
= lambda op
: op
.is_dest
1088 myDict
['op_src_decl'] = \
1089 operands
.concatSomeAttrStrings(is_src
, 'op_src_decl')
1090 myDict
['op_dest_decl'] = \
1091 operands
.concatSomeAttrStrings(is_dest
, 'op_dest_decl')
1093 myDict
['op_rd'] = operands
.concatAttrStrings('op_rd')
1094 myDict
['op_wb'] = operands
.concatAttrStrings('op_wb')
1096 if d
.operands
.memOperand
:
1097 myDict
['mem_acc_size'] = d
.operands
.memOperand
.mem_acc_size
1098 myDict
['mem_acc_type'] = d
.operands
.memOperand
.mem_acc_type
1100 elif isinstance(d
, dict):
1101 # if the argument is a dictionary, we just use it.
1103 elif hasattr(d
, '__dict__'):
1104 # if the argument is an object, we use its attribute map.
1105 myDict
.update(d
.__dict
__)
1107 raise TypeError, "Template.subst() arg must be or have dictionary"
1108 return template
% myDict
1110 # Convert to string. This handles the case when a template with a
1111 # CPU-specific term gets interpolated into another template or into
1114 return expand_cpu_symbols_to_string(self
.template
)
1116 #####################################################################
1120 # The remaining code is the support for automatically extracting
1121 # instruction characteristics from pseudocode.
1123 #####################################################################
1125 # Force the argument to be a list. Useful for flags, where a caller
1126 # can specify a singleton flag or a list of flags. Also usful for
1127 # converting tuples to lists so they can be modified.
1129 if isinstance(arg
, list):
1131 elif isinstance(arg
, tuple):
1138 # Generate operandTypeMap from the user's 'def operand_types'
1140 def buildOperandTypeMap(userDict
, lineno
):
1141 global operandTypeMap
1143 for (ext
, (desc
, size
)) in userDict
.iteritems():
1144 if desc
== 'signed int':
1145 ctype
= 'int%d_t' % size
1147 elif desc
== 'unsigned int':
1148 ctype
= 'uint%d_t' % size
1150 elif desc
== 'float':
1151 is_signed
= 1 # shouldn't really matter
1156 elif desc
== 'twin64 int':
1159 elif desc
== 'twin32 int':
1163 error(lineno
, 'Unrecognized type description "%s" in userDict')
1164 operandTypeMap
[ext
] = (size
, ctype
, is_signed
)
1169 # Base class for operand descriptors. An instance of this class (or
1170 # actually a class derived from this one) represents a specific
1171 # operand for a code block (e.g, "Rc.sq" as a dest). Intermediate
1172 # derived classes encapsulates the traits of a particular operand type
1173 # (e.g., "32-bit integer register").
1175 class Operand(object):
1176 def buildReadCode(self
, func
= None):
1177 code
= self
.read_code
% {"name": self
.base_name
,
1179 "op_idx": self
.src_reg_idx
,
1180 "reg_idx": self
.reg_spec
,
1182 "ctype": self
.ctype
}
1183 if self
.size
!= self
.dflt_size
:
1184 return '%s = bits(%s, %d, 0);\n' % \
1185 (self
.base_name
, code
, self
.size
-1)
1187 return '%s = %s;\n' % \
1188 (self
.base_name
, code
)
1190 def buildWriteCode(self
, func
= None):
1191 if (self
.size
!= self
.dflt_size
and self
.is_signed
):
1192 final_val
= 'sext<%d>(%s)' % (self
.size
, self
.base_name
)
1194 final_val
= self
.base_name
1195 code
= self
.write_code
% {"name": self
.base_name
,
1197 "op_idx": self
.dest_reg_idx
,
1198 "reg_idx": self
.reg_spec
,
1200 "ctype": self
.ctype
,
1201 "final_val": final_val
}
1206 if (traceData) { traceData->setData(final_val); }
1207 }''' % (self
.dflt_ctype
, final_val
, code
)
1209 def __init__(self
, full_name
, ext
, is_src
, is_dest
):
1210 self
.full_name
= full_name
1212 self
.is_src
= is_src
1213 self
.is_dest
= is_dest
1214 # The 'effective extension' (eff_ext) is either the actual
1215 # extension, if one was explicitly provided, or the default.
1219 self
.eff_ext
= self
.dflt_ext
1221 (self
.size
, self
.ctype
, self
.is_signed
) = operandTypeMap
[self
.eff_ext
]
1223 # note that mem_acc_size is undefined for non-mem operands...
1224 # template must be careful not to use it if it doesn't apply.
1226 self
.mem_acc_size
= self
.makeAccSize()
1227 if self
.ctype
in ['Twin32_t', 'Twin64_t']:
1228 self
.mem_acc_type
= 'Twin'
1230 self
.mem_acc_type
= 'uint'
1232 # Finalize additional fields (primarily code fields). This step
1233 # is done separately since some of these fields may depend on the
1234 # register index enumeration that hasn't been performed yet at the
1235 # time of __init__().
1237 self
.flags
= self
.getFlags()
1238 self
.constructor
= self
.makeConstructor()
1239 self
.op_decl
= self
.makeDecl()
1242 self
.op_rd
= self
.makeRead()
1243 self
.op_src_decl
= self
.makeDecl()
1246 self
.op_src_decl
= ''
1249 self
.op_wb
= self
.makeWrite()
1250 self
.op_dest_decl
= self
.makeDecl()
1253 self
.op_dest_decl
= ''
1261 def isFloatReg(self
):
1267 def isControlReg(self
):
1271 # note the empty slice '[:]' gives us a copy of self.flags[0]
1272 # instead of a reference to it
1273 my_flags
= self
.flags
[0][:]
1275 my_flags
+= self
.flags
[1]
1277 my_flags
+= self
.flags
[2]
1281 # Note that initializations in the declarations are solely
1282 # to avoid 'uninitialized variable' errors from the compiler.
1283 return self
.ctype
+ ' ' + self
.base_name
+ ' = 0;\n';
1285 class IntRegOperand(Operand
):
1292 def makeConstructor(self
):
1295 c
+= '\n\t_srcRegIdx[%d] = %s;' % \
1296 (self
.src_reg_idx
, self
.reg_spec
)
1298 c
+= '\n\t_destRegIdx[%d] = %s;' % \
1299 (self
.dest_reg_idx
, self
.reg_spec
)
1303 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1304 error(0, 'Attempt to read integer register as FP')
1305 if self
.read_code
!= None:
1306 return self
.buildReadCode('readIntRegOperand')
1307 if (self
.size
== self
.dflt_size
):
1308 return '%s = xc->readIntRegOperand(this, %d);\n' % \
1309 (self
.base_name
, self
.src_reg_idx
)
1310 elif (self
.size
> self
.dflt_size
):
1311 int_reg_val
= 'xc->readIntRegOperand(this, %d)' % \
1313 if (self
.is_signed
):
1314 int_reg_val
= 'sext<%d>(%s)' % (self
.dflt_size
, int_reg_val
)
1315 return '%s = %s;\n' % (self
.base_name
, int_reg_val
)
1317 return '%s = bits(xc->readIntRegOperand(this, %d), %d, 0);\n' % \
1318 (self
.base_name
, self
.src_reg_idx
, self
.size
-1)
1320 def makeWrite(self
):
1321 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1322 error(0, 'Attempt to write integer register as FP')
1323 if self
.write_code
!= None:
1324 return self
.buildWriteCode('setIntRegOperand')
1325 if (self
.size
!= self
.dflt_size
and self
.is_signed
):
1326 final_val
= 'sext<%d>(%s)' % (self
.size
, self
.base_name
)
1328 final_val
= self
.base_name
1332 xc->setIntRegOperand(this, %d, final_val);\n
1333 if (traceData) { traceData->setData(final_val); }
1334 }''' % (self
.dflt_ctype
, final_val
, self
.dest_reg_idx
)
1337 class FloatRegOperand(Operand
):
1341 def isFloatReg(self
):
1344 def makeConstructor(self
):
1347 c
+= '\n\t_srcRegIdx[%d] = %s + FP_Base_DepTag;' % \
1348 (self
.src_reg_idx
, self
.reg_spec
)
1350 c
+= '\n\t_destRegIdx[%d] = %s + FP_Base_DepTag;' % \
1351 (self
.dest_reg_idx
, self
.reg_spec
)
1356 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1357 func
= 'readFloatRegOperand'
1359 func
= 'readFloatRegOperandBits'
1360 if (self
.size
!= self
.dflt_size
):
1362 base
= 'xc->%s(this, %d)' % (func
, self
.src_reg_idx
)
1363 if self
.read_code
!= None:
1364 return self
.buildReadCode(func
)
1366 return '%s = bits(%s, %d, 0);\n' % \
1367 (self
.base_name
, base
, self
.size
-1)
1369 return '%s = %s;\n' % (self
.base_name
, base
)
1371 def makeWrite(self
):
1372 final_val
= self
.base_name
1373 final_ctype
= self
.ctype
1374 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1375 func
= 'setFloatRegOperand'
1376 elif (self
.ctype
== 'uint32_t' or self
.ctype
== 'uint64_t'):
1377 func
= 'setFloatRegOperandBits'
1379 func
= 'setFloatRegOperandBits'
1380 final_ctype
= 'uint%d_t' % self
.dflt_size
1381 if (self
.size
!= self
.dflt_size
and self
.is_signed
):
1382 final_val
= 'sext<%d>(%s)' % (self
.size
, self
.base_name
)
1383 if self
.write_code
!= None:
1384 return self
.buildWriteCode(func
)
1388 xc->%s(this, %d, final_val);\n
1389 if (traceData) { traceData->setData(final_val); }
1390 }''' % (final_ctype
, final_val
, func
, self
.dest_reg_idx
)
1393 class ControlRegOperand(Operand
):
1397 def isControlReg(self
):
1400 def makeConstructor(self
):
1403 c
+= '\n\t_srcRegIdx[%d] = %s + Ctrl_Base_DepTag;' % \
1404 (self
.src_reg_idx
, self
.reg_spec
)
1406 c
+= '\n\t_destRegIdx[%d] = %s + Ctrl_Base_DepTag;' % \
1407 (self
.dest_reg_idx
, self
.reg_spec
)
1412 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1413 error(0, 'Attempt to read control register as FP')
1414 if self
.read_code
!= None:
1415 return self
.buildReadCode('readMiscRegOperand')
1416 base
= 'xc->readMiscRegOperand(this, %s)' % self
.src_reg_idx
1417 if self
.size
== self
.dflt_size
:
1418 return '%s = %s;\n' % (self
.base_name
, base
)
1420 return '%s = bits(%s, %d, 0);\n' % \
1421 (self
.base_name
, base
, self
.size
-1)
1423 def makeWrite(self
):
1424 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1425 error(0, 'Attempt to write control register as FP')
1426 if self
.write_code
!= None:
1427 return self
.buildWriteCode('setMiscRegOperand')
1428 wb
= 'xc->setMiscRegOperand(this, %s, %s);\n' % \
1429 (self
.dest_reg_idx
, self
.base_name
)
1430 wb
+= 'if (traceData) { traceData->setData(%s); }' % \
1434 class MemOperand(Operand
):
1438 def makeConstructor(self
):
1442 # Note that initializations in the declarations are solely
1443 # to avoid 'uninitialized variable' errors from the compiler.
1444 # Declare memory data variable.
1445 if self
.ctype
in ['Twin32_t','Twin64_t']:
1446 return "%s %s; %s.a = 0; %s.b = 0;\n" % (self
.ctype
, self
.base_name
,
1447 self
.base_name
, self
.base_name
)
1448 c
= '%s %s = 0;\n' % (self
.ctype
, self
.base_name
)
1452 if self
.read_code
!= None:
1453 return self
.buildReadCode()
1456 def makeWrite(self
):
1457 if self
.write_code
!= None:
1458 return self
.buildWriteCode()
1461 # Return the memory access size *in bits*, suitable for
1462 # forming a type via "uint%d_t". Divide by 8 if you want bytes.
1463 def makeAccSize(self
):
1466 class UPCOperand(Operand
):
1467 def makeConstructor(self
):
1471 if self
.read_code
!= None:
1472 return self
.buildReadCode('readMicroPC')
1473 return '%s = xc->readMicroPC();\n' % self
.base_name
1475 def makeWrite(self
):
1476 if self
.write_code
!= None:
1477 return self
.buildWriteCode('setMicroPC')
1478 return 'xc->setMicroPC(%s);\n' % self
.base_name
1480 class NUPCOperand(Operand
):
1481 def makeConstructor(self
):
1485 if self
.read_code
!= None:
1486 return self
.buildReadCode('readNextMicroPC')
1487 return '%s = xc->readNextMicroPC();\n' % self
.base_name
1489 def makeWrite(self
):
1490 if self
.write_code
!= None:
1491 return self
.buildWriteCode('setNextMicroPC')
1492 return 'xc->setNextMicroPC(%s);\n' % self
.base_name
1494 class NPCOperand(Operand
):
1495 def makeConstructor(self
):
1499 if self
.read_code
!= None:
1500 return self
.buildReadCode('readNextPC')
1501 return '%s = xc->readNextPC();\n' % self
.base_name
1503 def makeWrite(self
):
1504 if self
.write_code
!= None:
1505 return self
.buildWriteCode('setNextPC')
1506 return 'xc->setNextPC(%s);\n' % self
.base_name
1508 class NNPCOperand(Operand
):
1509 def makeConstructor(self
):
1513 if self
.read_code
!= None:
1514 return self
.buildReadCode('readNextNPC')
1515 return '%s = xc->readNextNPC();\n' % self
.base_name
1517 def makeWrite(self
):
1518 if self
.write_code
!= None:
1519 return self
.buildWriteCode('setNextNPC')
1520 return 'xc->setNextNPC(%s);\n' % self
.base_name
1522 def buildOperandNameMap(userDict
, lineno
):
1523 global operandNameMap
1525 for (op_name
, val
) in userDict
.iteritems():
1526 (base_cls_name
, dflt_ext
, reg_spec
, flags
, sort_pri
) = val
[:5]
1537 'error: too many attributes for operand "%s"' %
1540 (dflt_size
, dflt_ctype
, dflt_is_signed
) = operandTypeMap
[dflt_ext
]
1541 # Canonical flag structure is a triple of lists, where each list
1542 # indicates the set of flags implied by this operand always, when
1543 # used as a source, and when used as a dest, respectively.
1544 # For simplicity this can be initialized using a variety of fairly
1545 # obvious shortcuts; we convert these to canonical form here.
1547 # no flags specified (e.g., 'None')
1548 flags
= ( [], [], [] )
1549 elif isinstance(flags
, str):
1550 # a single flag: assumed to be unconditional
1551 flags
= ( [ flags
], [], [] )
1552 elif isinstance(flags
, list):
1553 # a list of flags: also assumed to be unconditional
1554 flags
= ( flags
, [], [] )
1555 elif isinstance(flags
, tuple):
1556 # it's a tuple: it should be a triple,
1557 # but each item could be a single string or a list
1558 (uncond_flags
, src_flags
, dest_flags
) = flags
1559 flags
= (makeList(uncond_flags
),
1560 makeList(src_flags
), makeList(dest_flags
))
1561 # Accumulate attributes of new operand class in tmp_dict
1563 for attr
in ('dflt_ext', 'reg_spec', 'flags', 'sort_pri',
1564 'dflt_size', 'dflt_ctype', 'dflt_is_signed',
1565 'read_code', 'write_code'):
1566 tmp_dict
[attr
] = eval(attr
)
1567 tmp_dict
['base_name'] = op_name
1568 # New class name will be e.g. "IntReg_Ra"
1569 cls_name
= base_cls_name
+ '_' + op_name
1570 # Evaluate string arg to get class object. Note that the
1571 # actual base class for "IntReg" is "IntRegOperand", i.e. we
1572 # have to append "Operand".
1574 base_cls
= eval(base_cls_name
+ 'Operand')
1577 'error: unknown operand base class "%s"' % base_cls_name
)
1578 # The following statement creates a new class called
1579 # <cls_name> as a subclass of <base_cls> with the attributes
1580 # in tmp_dict, just as if we evaluated a class declaration.
1581 operandNameMap
[op_name
] = type(cls_name
, (base_cls
,), tmp_dict
)
1583 # Define operand variables.
1584 operands
= userDict
.keys()
1586 operandsREString
= (r
'''
1587 (?<![\w\.]) # neg. lookbehind assertion: prevent partial matches
1588 ((%s)(?:\.(\w+))?) # match: operand with optional '.' then suffix
1589 (?![\w\.]) # neg. lookahead assertion: prevent partial matches
1591 % string
.join(operands
, '|'))
1594 operandsRE
= re
.compile(operandsREString
, re
.MULTILINE|re
.VERBOSE
)
1596 # Same as operandsREString, but extension is mandatory, and only two
1597 # groups are returned (base and ext, not full name as above).
1598 # Used for subtituting '_' for '.' to make C++ identifiers.
1599 operandsWithExtREString
= (r
'(?<![\w\.])(%s)\.(\w+)(?![\w\.])'
1600 % string
.join(operands
, '|'))
1602 global operandsWithExtRE
1603 operandsWithExtRE
= re
.compile(operandsWithExtREString
, re
.MULTILINE
)
1610 # Find all the operands in the given code block. Returns an operand
1611 # descriptor list (instance of class OperandList).
1612 def __init__(self
, code
):
1615 # delete comments so we don't match on reg specifiers inside
1616 code
= commentRE
.sub('', code
)
1617 # search for operands
1620 match
= operandsRE
.search(code
, next_pos
)
1622 # no more matches: we're done
1625 # regexp groups are operand full name, base, and extension
1626 (op_full
, op_base
, op_ext
) = op
1627 # if the token following the operand is an assignment, this is
1628 # a destination (LHS), else it's a source (RHS)
1629 is_dest
= (assignRE
.match(code
, match
.end()) != None)
1630 is_src
= not is_dest
1631 # see if we've already seen this one
1632 op_desc
= self
.find_base(op_base
)
1634 if op_desc
.ext
!= op_ext
:
1635 error(0, 'Inconsistent extensions for operand %s' % \
1637 op_desc
.is_src
= op_desc
.is_src
or is_src
1638 op_desc
.is_dest
= op_desc
.is_dest
or is_dest
1640 # new operand: create new descriptor
1641 op_desc
= operandNameMap
[op_base
](op_full
, op_ext
,
1643 self
.append(op_desc
)
1644 # start next search after end of current match
1645 next_pos
= match
.end()
1647 # enumerate source & dest register operands... used in building
1650 self
.numDestRegs
= 0
1651 self
.numFPDestRegs
= 0
1652 self
.numIntDestRegs
= 0
1653 self
.memOperand
= None
1654 for op_desc
in self
.items
:
1657 op_desc
.src_reg_idx
= self
.numSrcRegs
1658 self
.numSrcRegs
+= 1
1660 op_desc
.dest_reg_idx
= self
.numDestRegs
1661 self
.numDestRegs
+= 1
1662 if op_desc
.isFloatReg():
1663 self
.numFPDestRegs
+= 1
1664 elif op_desc
.isIntReg():
1665 self
.numIntDestRegs
+= 1
1666 elif op_desc
.isMem():
1668 error(0, "Code block has more than one memory operand.")
1669 self
.memOperand
= op_desc
1670 global maxInstSrcRegs
1671 global maxInstDestRegs
1672 if maxInstSrcRegs
< self
.numSrcRegs
:
1673 maxInstSrcRegs
= self
.numSrcRegs
1674 if maxInstDestRegs
< self
.numDestRegs
:
1675 maxInstDestRegs
= self
.numDestRegs
1676 # now make a final pass to finalize op_desc fields that may depend
1677 # on the register enumeration
1678 for op_desc
in self
.items
:
1682 return len(self
.items
)
1684 def __getitem__(self
, index
):
1685 return self
.items
[index
]
1687 def append(self
, op_desc
):
1688 self
.items
.append(op_desc
)
1689 self
.bases
[op_desc
.base_name
] = op_desc
1691 def find_base(self
, base_name
):
1692 # like self.bases[base_name], but returns None if not found
1693 # (rather than raising exception)
1694 return self
.bases
.get(base_name
)
1696 # internal helper function for concat[Some]Attr{Strings|Lists}
1697 def __internalConcatAttrs(self
, attr_name
, filter, result
):
1698 for op_desc
in self
.items
:
1700 result
+= getattr(op_desc
, attr_name
)
1703 # return a single string that is the concatenation of the (string)
1704 # values of the specified attribute for all operands
1705 def concatAttrStrings(self
, attr_name
):
1706 return self
.__internalConcatAttrs
(attr_name
, lambda x
: 1, '')
1708 # like concatAttrStrings, but only include the values for the operands
1709 # for which the provided filter function returns true
1710 def concatSomeAttrStrings(self
, filter, attr_name
):
1711 return self
.__internalConcatAttrs
(attr_name
, filter, '')
1713 # return a single list that is the concatenation of the (list)
1714 # values of the specified attribute for all operands
1715 def concatAttrLists(self
, attr_name
):
1716 return self
.__internalConcatAttrs
(attr_name
, lambda x
: 1, [])
1718 # like concatAttrLists, but only include the values for the operands
1719 # for which the provided filter function returns true
1720 def concatSomeAttrLists(self
, filter, attr_name
):
1721 return self
.__internalConcatAttrs
(attr_name
, filter, [])
1724 self
.items
.sort(lambda a
, b
: a
.sort_pri
- b
.sort_pri
)
1726 class SubOperandList(OperandList
):
1728 # Find all the operands in the given code block. Returns an operand
1729 # descriptor list (instance of class OperandList).
1730 def __init__(self
, code
, master_list
):
1733 # delete comments so we don't match on reg specifiers inside
1734 code
= commentRE
.sub('', code
)
1735 # search for operands
1738 match
= operandsRE
.search(code
, next_pos
)
1740 # no more matches: we're done
1743 # regexp groups are operand full name, base, and extension
1744 (op_full
, op_base
, op_ext
) = op
1745 # find this op in the master list
1746 op_desc
= master_list
.find_base(op_base
)
1748 error(0, 'Found operand %s which is not in the master list!' \
1749 ' This is an internal error' % \
1752 # See if we've already found this operand
1753 op_desc
= self
.find_base(op_base
)
1755 # if not, add a reference to it to this sub list
1756 self
.append(master_list
.bases
[op_base
])
1758 # start next search after end of current match
1759 next_pos
= match
.end()
1761 self
.memOperand
= None
1762 for op_desc
in self
.items
:
1765 error(0, "Code block has more than one memory operand.")
1766 self
.memOperand
= op_desc
1768 # Regular expression object to match C++ comments
1769 # (used in findOperands())
1770 commentRE
= re
.compile(r
'//.*\n')
1772 # Regular expression object to match assignment statements
1773 # (used in findOperands())
1774 assignRE
= re
.compile(r
'\s*=(?!=)', re
.MULTILINE
)
1776 # Munge operand names in code string to make legal C++ variable names.
1777 # This means getting rid of the type extension if any.
1778 # (Will match base_name attribute of Operand object.)
1779 def substMungedOpNames(code
):
1780 return operandsWithExtRE
.sub(r
'\1', code
)
1782 # Fix up code snippets for final substitution in templates.
1783 def mungeSnippet(s
):
1784 if isinstance(s
, str):
1785 return substMungedOpNames(substBitOps(s
))
1789 def makeFlagConstructor(flag_list
):
1790 if len(flag_list
) == 0:
1792 # filter out repeated flags
1795 while i
< len(flag_list
):
1796 if flag_list
[i
] == flag_list
[i
-1]:
1802 code
= pre
+ string
.join(flag_list
, post
+ pre
) + post
1805 # Assume all instruction flags are of the form 'IsFoo'
1806 instFlagRE
= re
.compile(r
'Is.*')
1808 # OpClass constants end in 'Op' except No_OpClass
1809 opClassRE
= re
.compile(r
'.*Op|No_OpClass')
1811 class InstObjParams
:
1812 def __init__(self
, mnem
, class_name
, base_class
= '',
1813 snippets
= {}, opt_args
= []):
1814 self
.mnemonic
= mnem
1815 self
.class_name
= class_name
1816 self
.base_class
= base_class
1817 if not isinstance(snippets
, dict):
1818 snippets
= {'code' : snippets
}
1819 compositeCode
= ' '.join(map(str, snippets
.values()))
1820 self
.snippets
= snippets
1822 self
.operands
= OperandList(compositeCode
)
1823 self
.constructor
= self
.operands
.concatAttrStrings('constructor')
1824 self
.constructor
+= \
1825 '\n\t_numSrcRegs = %d;' % self
.operands
.numSrcRegs
1826 self
.constructor
+= \
1827 '\n\t_numDestRegs = %d;' % self
.operands
.numDestRegs
1828 self
.constructor
+= \
1829 '\n\t_numFPDestRegs = %d;' % self
.operands
.numFPDestRegs
1830 self
.constructor
+= \
1831 '\n\t_numIntDestRegs = %d;' % self
.operands
.numIntDestRegs
1832 self
.flags
= self
.operands
.concatAttrLists('flags')
1834 # Make a basic guess on the operand class (function unit type).
1835 # These are good enough for most cases, and can be overridden
1837 if 'IsStore' in self
.flags
:
1838 self
.op_class
= 'MemWriteOp'
1839 elif 'IsLoad' in self
.flags
or 'IsPrefetch' in self
.flags
:
1840 self
.op_class
= 'MemReadOp'
1841 elif 'IsFloating' in self
.flags
:
1842 self
.op_class
= 'FloatAddOp'
1844 self
.op_class
= 'IntAluOp'
1846 # Optional arguments are assumed to be either StaticInst flags
1847 # or an OpClass value. To avoid having to import a complete
1848 # list of these values to match against, we do it ad-hoc
1851 if instFlagRE
.match(oa
):
1852 self
.flags
.append(oa
)
1853 elif opClassRE
.match(oa
):
1856 error(0, 'InstObjParams: optional arg "%s" not recognized '
1857 'as StaticInst::Flag or OpClass.' % oa
)
1859 # add flag initialization to contructor here to include
1860 # any flags added via opt_args
1861 self
.constructor
+= makeFlagConstructor(self
.flags
)
1863 # if 'IsFloating' is set, add call to the FP enable check
1864 # function (which should be provided by isa_desc via a declare)
1865 if 'IsFloating' in self
.flags
:
1866 self
.fp_enable_check
= 'fault = checkFpEnableFault(xc);'
1868 self
.fp_enable_check
= ''
1870 #######################
1872 # Output file template
1877 * DO NOT EDIT THIS FILE!!!
1879 * It was automatically generated from the ISA description in %(filename)s
1886 namespace %(namespace)s {
1888 %(namespace_output)s
1890 } // namespace %(namespace)s
1895 max_inst_regs_template
= '''
1897 * DO NOT EDIT THIS FILE!!!
1899 * It was automatically generated from the ISA description in %(filename)s
1902 namespace %(namespace)s {
1904 const int MaxInstSrcRegs = %(MaxInstSrcRegs)d;
1905 const int MaxInstDestRegs = %(MaxInstDestRegs)d;
1907 } // namespace %(namespace)s
1912 # Update the output file only if the new contents are different from
1913 # the current contents. Minimizes the files that need to be rebuilt
1914 # after minor changes.
1915 def update_if_needed(file, contents
):
1917 if os
.access(file, os
.R_OK
):
1919 old_contents
= f
.read()
1921 if contents
!= old_contents
:
1922 print 'Updating', file
1923 os
.remove(file) # in case it's write-protected
1926 print 'File', file, 'is unchanged'
1928 print 'Generating', file
1935 # This regular expression matches '##include' directives
1936 includeRE
= re
.compile(r
'^\s*##include\s+"(?P<filename>[\w/.-]*)".*$',
1939 # Function to replace a matched '##include' directive with the
1940 # contents of the specified file (with nested ##includes replaced
1941 # recursively). 'matchobj' is an re match object (from a match of
1942 # includeRE) and 'dirname' is the directory relative to which the file
1943 # path should be resolved.
1944 def replace_include(matchobj
, dirname
):
1945 fname
= matchobj
.group('filename')
1946 full_fname
= os
.path
.normpath(os
.path
.join(dirname
, fname
))
1947 contents
= '##newfile "%s"\n%s\n##endfile\n' % \
1948 (full_fname
, read_and_flatten(full_fname
))
1951 # Read a file and recursively flatten nested '##include' files.
1952 def read_and_flatten(filename
):
1953 current_dir
= os
.path
.dirname(filename
)
1955 contents
= open(filename
).read()
1957 error(0, 'Error including file "%s"' % filename
)
1958 fileNameStack
.push((filename
, 0))
1959 # Find any includes and include them
1960 contents
= includeRE
.sub(lambda m
: replace_include(m
, current_dir
),
1966 # Read in and parse the ISA description.
1968 def parse_isa_desc(isa_desc_file
, output_dir
):
1969 # Read file and (recursively) all included files into a string.
1970 # PLY requires that the input be in a single string so we have to
1972 isa_desc
= read_and_flatten(isa_desc_file
)
1974 # Initialize filename stack with outer file.
1975 fileNameStack
.push((isa_desc_file
, 0))
1978 (isa_name
, namespace
, global_code
, namespace_code
) = \
1979 parser
.parse(isa_desc
, lexer
=lexer
)
1981 # grab the last three path components of isa_desc_file to put in
1983 filename
= '/'.join(isa_desc_file
.split('/')[-3:])
1985 # generate decoder.hh
1986 includes
= '#include "base/bitfield.hh" // for bitfield support'
1987 global_output
= global_code
.header_output
1988 namespace_output
= namespace_code
.header_output
1989 decode_function
= ''
1990 update_if_needed(output_dir
+ '/decoder.hh', file_template
% vars())
1992 # generate decoder.cc
1993 includes
= '#include "decoder.hh"'
1994 global_output
= global_code
.decoder_output
1995 namespace_output
= namespace_code
.decoder_output
1996 # namespace_output += namespace_code.decode_block
1997 decode_function
= namespace_code
.decode_block
1998 update_if_needed(output_dir
+ '/decoder.cc', file_template
% vars())
2000 # generate per-cpu exec files
2001 for cpu
in cpu_models
:
2002 includes
= '#include "decoder.hh"\n'
2003 includes
+= cpu
.includes
2004 global_output
= global_code
.exec_output
[cpu
.name
]
2005 namespace_output
= namespace_code
.exec_output
[cpu
.name
]
2006 decode_function
= ''
2007 update_if_needed(output_dir
+ '/' + cpu
.filename
,
2008 file_template
% vars())
2010 # The variable names here are hacky, but this will creat local variables
2011 # which will be referenced in vars() which have the value of the globals.
2012 global maxInstSrcRegs
2013 MaxInstSrcRegs
= maxInstSrcRegs
2014 global maxInstDestRegs
2015 MaxInstDestRegs
= maxInstDestRegs
2017 update_if_needed(output_dir
+ '/max_inst_regs.hh', \
2018 max_inst_regs_template
% vars())
2020 # global list of CpuModel objects (see cpu_models.py)
2023 # Called as script: get args from command line.
2024 # Args are: <path to cpu_models.py> <isa desc file> <output dir> <cpu models>
2025 if __name__
== '__main__':
2026 execfile(sys
.argv
[1]) # read in CpuModel definitions
2027 cpu_models
= [CpuModel
.dict[cpu
] for cpu
in sys
.argv
[4:]]
2028 parse_isa_desc(sys
.argv
[2], sys
.argv
[3])