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
38 # Prepend the directory where the PLY lex & yacc modules are found
39 # to the search path. Assumes we're compiling in a subdirectory
40 # of 'build' in the current tree.
41 sys
.path
[0:0] = [os
.environ
['M5_PLY']]
46 #####################################################################
50 # The PLY lexer module takes two things as input:
51 # - A list of token names (the string list 'tokens')
52 # - A regular expression describing a match for each token. The
53 # regexp for token FOO can be provided in two ways:
54 # - as a string variable named t_FOO
55 # - as the doc string for a function named t_FOO. In this case,
56 # the function is also executed, allowing an action to be
57 # associated with each token match.
59 #####################################################################
61 # Reserved words. These are listed separately as they are matched
62 # using the same regexp as generic IDs, but distinguished in the
63 # t_ID() function. The PLY documentation suggests this approach.
65 'BITFIELD', 'DECODE', 'DECODER', 'DEFAULT', 'DEF', 'EXEC', 'FORMAT',
66 'HEADER', 'LET', 'NAMESPACE', 'OPERAND_TYPES', 'OPERANDS',
67 'OUTPUT', 'SIGNED', 'TEMPLATE'
70 # List of tokens. The lex module requires this.
84 # ( ) [ ] { } < > , ; : :: *
86 'LBRACKET', 'RBRACKET',
88 'LESS', 'GREATER', 'EQUALS',
89 'COMMA', 'SEMI', 'COLON', 'DBLCOLON',
92 # C preprocessor directives
95 # The following are matched but never returned. commented out to
96 # suppress PLY warning
104 # 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
.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
.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
.lineno
+= t
.value
.count('\n')
159 def t_CPPDIRECTIVE(t
):
161 t
.lineno
+= t
.value
.count('\n')
165 r
'^\#\#newfile\s+"[\w/.-]*"'
166 fileNameStack
.push((t
.value
[11:-1], t
.lineno
))
171 (old_filename
, t
.lineno
) = fileNameStack
.pop()
174 # The functions t_NEWLINE, t_ignore, and t_error are
175 # special for the lex module.
181 t
.lineno
+= t
.value
.count('\n')
187 # Completely ignored characters
192 error(t
.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
273 # Output blocks 'output <foo> {{...}}' (C++ code blocks) are copied
274 # directly to the appropriate output section.
277 # Protect any non-dict-substitution '%'s in a format string
278 # (i.e. those not followed by '(')
279 def protect_non_subst_percents(s
):
280 return re
.sub(r
'%(?!\()', '%%', s
)
282 # Massage output block by substituting in template definitions and bit
283 # operators. We handle '%'s embedded in the string that don't
284 # indicate template substitutions (or CPU-specific symbols, which get
285 # handled in GenCode) by doubling them first so that the format
286 # operation will reduce them back to single '%'s.
287 def process_output(s
):
288 s
= protect_non_subst_percents(s
)
289 # protects cpu-specific symbols too
290 s
= protect_cpu_symbols(s
)
291 return substBitOps(s
% templateMap
)
293 def p_output_header(t
):
294 'output_header : OUTPUT HEADER CODELIT SEMI'
295 t
[0] = GenCode(header_output
= process_output(t
[3]))
297 def p_output_decoder(t
):
298 'output_decoder : OUTPUT DECODER CODELIT SEMI'
299 t
[0] = GenCode(decoder_output
= process_output(t
[3]))
301 def p_output_exec(t
):
302 'output_exec : OUTPUT EXEC CODELIT SEMI'
303 t
[0] = GenCode(exec_output
= process_output(t
[3]))
305 # global let blocks 'let {{...}}' (Python code blocks) are executed
306 # directly when seen. Note that these execute in a special variable
307 # context 'exportContext' to prevent the code from polluting this
308 # script's namespace.
310 'global_let : LET CODELIT SEMI'
311 updateExportContext()
313 exec fixPythonIndentation(t
[2]) in exportContext
314 except Exception, exc
:
316 'error: %s in global let block "%s".' % (exc
, t
[2]))
317 t
[0] = GenCode() # contributes nothing to the output C++ file
319 # Define the mapping from operand type extensions to C++ types and bit
320 # widths (stored in operandTypeMap).
321 def p_def_operand_types(t
):
322 'def_operand_types : DEF OPERAND_TYPES CODELIT SEMI'
324 userDict
= eval('{' + t
[3] + '}')
325 except Exception, exc
:
327 'error: %s in def operand_types block "%s".' % (exc
, t
[3]))
328 buildOperandTypeMap(userDict
, t
.lineno(1))
329 t
[0] = GenCode() # contributes nothing to the output C++ file
331 # Define the mapping from operand names to operand classes and other
332 # traits. Stored in operandNameMap.
333 def p_def_operands(t
):
334 'def_operands : DEF OPERANDS CODELIT SEMI'
335 if not globals().has_key('operandTypeMap'):
337 'error: operand types must be defined before operands')
339 userDict
= eval('{' + t
[3] + '}')
340 except Exception, exc
:
342 'error: %s in def operands block "%s".' % (exc
, t
[3]))
343 buildOperandNameMap(userDict
, t
.lineno(1))
344 t
[0] = GenCode() # contributes nothing to the output C++ file
346 # A bitfield definition looks like:
347 # 'def [signed] bitfield <ID> [<first>:<last>]'
348 # This generates a preprocessor macro in the output file.
349 def p_def_bitfield_0(t
):
350 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT COLON INTLIT GREATER SEMI'
351 expr
= 'bits(machInst, %2d, %2d)' % (t
[6], t
[8])
352 if (t
[2] == 'signed'):
353 expr
= 'sext<%d>(%s)' % (t
[6] - t
[8] + 1, expr
)
354 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
355 t
[0] = GenCode(header_output
= hash_define
)
357 # alternate form for single bit: 'def [signed] bitfield <ID> [<bit>]'
358 def p_def_bitfield_1(t
):
359 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT GREATER SEMI'
360 expr
= 'bits(machInst, %2d, %2d)' % (t
[6], t
[6])
361 if (t
[2] == 'signed'):
362 expr
= 'sext<%d>(%s)' % (1, expr
)
363 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
364 t
[0] = GenCode(header_output
= hash_define
)
366 def p_opt_signed_0(t
):
367 'opt_signed : SIGNED'
370 def p_opt_signed_1(t
):
374 # Global map variable to hold templates
377 def p_def_template(t
):
378 'def_template : DEF TEMPLATE ID CODELIT SEMI'
379 templateMap
[t
[3]] = Template(t
[4])
382 # An instruction format definition looks like
383 # "def format <fmt>(<params>) {{...}};"
385 'def_format : DEF FORMAT ID LPAREN param_list RPAREN CODELIT SEMI'
386 (id, params
, code
) = (t
[3], t
[5], t
[7])
387 defFormat(id, params
, code
, t
.lineno(1))
390 # The formal parameter list for an instruction format is a possibly
391 # empty list of comma-separated parameters. Positional (standard,
392 # non-keyword) parameters must come first, followed by keyword
393 # parameters, followed by a '*foo' parameter that gets excess
394 # positional arguments (as in Python). Each of these three parameter
395 # categories is optional.
397 # Note that we do not support the '**foo' parameter for collecting
398 # otherwise undefined keyword args. Otherwise the parameter list is
399 # (I believe) identical to what is supported in Python.
401 # The param list generates a tuple, where the first element is a list of
402 # the positional params and the second element is a dict containing the
404 def p_param_list_0(t
):
405 'param_list : positional_param_list COMMA nonpositional_param_list'
408 def p_param_list_1(t
):
409 '''param_list : positional_param_list
410 | nonpositional_param_list'''
413 def p_positional_param_list_0(t
):
414 'positional_param_list : empty'
417 def p_positional_param_list_1(t
):
418 'positional_param_list : ID'
421 def p_positional_param_list_2(t
):
422 'positional_param_list : positional_param_list COMMA ID'
425 def p_nonpositional_param_list_0(t
):
426 'nonpositional_param_list : keyword_param_list COMMA excess_args_param'
429 def p_nonpositional_param_list_1(t
):
430 '''nonpositional_param_list : keyword_param_list
431 | excess_args_param'''
434 def p_keyword_param_list_0(t
):
435 'keyword_param_list : keyword_param'
438 def p_keyword_param_list_1(t
):
439 'keyword_param_list : keyword_param_list COMMA keyword_param'
442 def p_keyword_param(t
):
443 'keyword_param : ID EQUALS expr'
444 t
[0] = t
[1] + ' = ' + t
[3].__repr
__()
446 def p_excess_args_param(t
):
447 'excess_args_param : ASTERISK ID'
448 # Just concatenate them: '*ID'. Wrap in list to be consistent
449 # with positional_param_list and keyword_param_list.
452 # End of format definition-related rules.
456 # A decode block looks like:
457 # decode <field1> [, <field2>]* [default <inst>] { ... }
459 def p_decode_block(t
):
460 'decode_block : DECODE ID opt_default LBRACE decode_stmt_list RBRACE'
461 default_defaults
= defaultStack
.pop()
463 # use the "default defaults" only if there was no explicit
464 # default statement in decode_stmt_list
465 if not codeObj
.has_decode_default
:
466 codeObj
+= default_defaults
467 codeObj
.wrap_decode_block('switch (%s) {\n' % t
[2], '}\n')
470 # The opt_default statement serves only to push the "default defaults"
471 # onto defaultStack. This value will be used by nested decode blocks,
472 # and used and popped off when the current decode_block is processed
473 # (in p_decode_block() above).
474 def p_opt_default_0(t
):
475 'opt_default : empty'
476 # no default specified: reuse the one currently at the top of the stack
477 defaultStack
.push(defaultStack
.top())
478 # no meaningful value returned
481 def p_opt_default_1(t
):
482 'opt_default : DEFAULT inst'
483 # push the new default
485 codeObj
.wrap_decode_block('\ndefault:\n', 'break;\n')
486 defaultStack
.push(codeObj
)
487 # no meaningful value returned
490 def p_decode_stmt_list_0(t
):
491 'decode_stmt_list : decode_stmt'
494 def p_decode_stmt_list_1(t
):
495 'decode_stmt_list : decode_stmt decode_stmt_list'
496 if (t
[1].has_decode_default
and t
[2].has_decode_default
):
497 error(t
.lineno(1), 'Two default cases in decode block')
501 # Decode statement rules
503 # There are four types of statements allowed in a decode block:
504 # 1. Format blocks 'format <foo> { ... }'
505 # 2. Nested decode blocks
506 # 3. Instruction definitions.
507 # 4. C preprocessor directives.
510 # Preprocessor directives found in a decode statement list are passed
511 # through to the output, replicated to all of the output code
512 # streams. This works well for ifdefs, so we can ifdef out both the
513 # declarations and the decode cases generated by an instruction
514 # definition. Handling them as part of the grammar makes it easy to
515 # keep them in the right place with respect to the code generated by
516 # the other statements.
517 def p_decode_stmt_cpp(t
):
518 'decode_stmt : CPPDIRECTIVE'
519 t
[0] = GenCode(t
[1], t
[1], t
[1], t
[1])
521 # A format block 'format <foo> { ... }' sets the default instruction
522 # format used to handle instruction definitions inside the block.
523 # This format can be overridden by using an explicit format on the
524 # instruction definition or with a nested format block.
525 def p_decode_stmt_format(t
):
526 'decode_stmt : FORMAT push_format_id LBRACE decode_stmt_list RBRACE'
527 # The format will be pushed on the stack when 'push_format_id' is
528 # processed (see below). Once the parser has recognized the full
529 # production (though the right brace), we're done with the format,
530 # so now we can pop it.
534 # This rule exists so we can set the current format (& push the stack)
535 # when we recognize the format name part of the format block.
536 def p_push_format_id(t
):
537 'push_format_id : ID'
539 formatStack
.push(formatMap
[t
[1]])
540 t
[0] = ('', '// format %s' % t
[1])
542 error(t
.lineno(1), 'instruction format "%s" not defined.' % t
[1])
544 # Nested decode block: if the value of the current field matches the
545 # specified constant, do a nested decode on some other field.
546 def p_decode_stmt_decode(t
):
547 'decode_stmt : case_label COLON decode_block'
550 # just wrap the decoding code from the block as a case in the
551 # outer switch statement.
552 codeObj
.wrap_decode_block('\n%s:\n' % label
)
553 codeObj
.has_decode_default
= (label
== 'default')
556 # Instruction definition (finally!).
557 def p_decode_stmt_inst(t
):
558 'decode_stmt : case_label COLON inst SEMI'
561 codeObj
.wrap_decode_block('\n%s:' % label
, 'break;\n')
562 codeObj
.has_decode_default
= (label
== 'default')
565 # The case label is either a list of one or more constants or 'default'
566 def p_case_label_0(t
):
567 'case_label : intlit_list'
568 t
[0] = ': '.join(map(lambda a
: 'case %#x' % a
, t
[1]))
570 def p_case_label_1(t
):
571 'case_label : DEFAULT'
575 # The constant list for a decode case label must be non-empty, but may have
576 # one or more comma-separated integer literals in it.
578 def p_intlit_list_0(t
):
579 'intlit_list : INTLIT'
582 def p_intlit_list_1(t
):
583 'intlit_list : intlit_list COMMA INTLIT'
587 # Define an instruction using the current instruction format (specified
588 # by an enclosing format block).
589 # "<mnemonic>(<args>)"
591 'inst : ID LPAREN arg_list RPAREN'
592 # Pass the ID and arg list to the current format class to deal with.
593 currentFormat
= formatStack
.top()
594 codeObj
= currentFormat
.defineInst(t
[1], t
[3], t
.lineno(1))
595 args
= ','.join(map(str, t
[3]))
596 args
= re
.sub('(?m)^', '//', args
)
597 args
= re
.sub('^//', '', args
)
598 comment
= '\n// %s::%s(%s)\n' % (currentFormat
.id, t
[1], args
)
599 codeObj
.prepend_all(comment
)
602 # Define an instruction using an explicitly specified format:
603 # "<fmt>::<mnemonic>(<args>)"
605 'inst : ID DBLCOLON ID LPAREN arg_list RPAREN'
607 format
= formatMap
[t
[1]]
609 error(t
.lineno(1), 'instruction format "%s" not defined.' % t
[1])
610 codeObj
= format
.defineInst(t
[3], t
[5], t
.lineno(1))
611 comment
= '\n// %s::%s(%s)\n' % (t
[1], t
[3], t
[5])
612 codeObj
.prepend_all(comment
)
615 # The arg list generates a tuple, where the first element is a list of
616 # the positional args and the second element is a dict containing the
619 'arg_list : positional_arg_list COMMA keyword_arg_list'
620 t
[0] = ( t
[1], t
[3] )
623 'arg_list : positional_arg_list'
627 'arg_list : keyword_arg_list'
630 def p_positional_arg_list_0(t
):
631 'positional_arg_list : empty'
634 def p_positional_arg_list_1(t
):
635 'positional_arg_list : expr'
638 def p_positional_arg_list_2(t
):
639 'positional_arg_list : positional_arg_list COMMA expr'
642 def p_keyword_arg_list_0(t
):
643 'keyword_arg_list : keyword_arg'
646 def p_keyword_arg_list_1(t
):
647 'keyword_arg_list : keyword_arg_list COMMA keyword_arg'
651 def p_keyword_arg(t
):
652 'keyword_arg : ID EQUALS expr'
653 t
[0] = { t
[1] : t
[3] }
656 # Basic expressions. These constitute the argument values of
657 # "function calls" (i.e. instruction definitions in the decode block)
658 # and default values for formal parameters of format functions.
660 # Right now, these are either strings, integers, or (recursively)
661 # lists of exprs (using Python square-bracket list syntax). Note that
662 # bare identifiers are trated as string constants here (since there
663 # isn't really a variable namespace to refer to).
673 '''expr : LBRACKET list_expr RBRACKET'''
676 def p_list_expr_0(t
):
680 def p_list_expr_1(t
):
681 'list_expr : list_expr COMMA expr'
684 def p_list_expr_2(t
):
689 # Empty production... use in other rules for readability.
695 # Parse error handler. Note that the argument here is the offending
696 # *token*, not a grammar symbol (hence the need to use t.value)
699 error(t
.lineno
, "syntax error at '%s'" % t
.value
)
701 error(0, "unknown syntax error", True)
703 # END OF GRAMMAR RULES
705 # Now build the parser.
709 #####################################################################
713 #####################################################################
715 # Expand template with CPU-specific references into a dictionary with
716 # an entry for each CPU model name. The entry key is the model name
717 # and the corresponding value is the template with the CPU-specific
718 # refs substituted for that model.
719 def expand_cpu_symbols_to_dict(template
):
720 # Protect '%'s that don't go with CPU-specific terms
721 t
= re
.sub(r
'%(?!\(CPU_)', '%%', template
)
723 for cpu
in cpu_models
:
724 result
[cpu
.name
] = t
% cpu
.strings
727 # *If* the template has CPU-specific references, return a single
728 # string containing a copy of the template for each CPU model with the
729 # corresponding values substituted in. If the template has no
730 # CPU-specific references, it is returned unmodified.
731 def expand_cpu_symbols_to_string(template
):
732 if template
.find('%(CPU_') != -1:
733 return reduce(lambda x
,y
: x
+y
,
734 expand_cpu_symbols_to_dict(template
).values())
738 # Protect CPU-specific references by doubling the corresponding '%'s
739 # (in preparation for substituting a different set of references into
741 def protect_cpu_symbols(template
):
742 return re
.sub(r
'%(?=\(CPU_)', '%%', template
)
747 # The GenCode class encapsulates generated code destined for various
748 # output files. The header_output and decoder_output attributes are
749 # strings containing code destined for decoder.hh and decoder.cc
750 # respectively. The decode_block attribute contains code to be
751 # incorporated in the decode function itself (that will also end up in
752 # decoder.cc). The exec_output attribute is a dictionary with a key
753 # for each CPU model name; the value associated with a particular key
754 # is the string of code for that CPU model's exec.cc file. The
755 # has_decode_default attribute is used in the decode block to allow
756 # explicit default clauses to override default default clauses.
759 # Constructor. At this point we substitute out all CPU-specific
760 # symbols. For the exec output, these go into the per-model
761 # dictionary. For all other output types they get collapsed into
764 header_output
= '', decoder_output
= '', exec_output
= '',
765 decode_block
= '', has_decode_default
= False):
766 self
.header_output
= expand_cpu_symbols_to_string(header_output
)
767 self
.decoder_output
= expand_cpu_symbols_to_string(decoder_output
)
768 if isinstance(exec_output
, dict):
769 self
.exec_output
= exec_output
770 elif isinstance(exec_output
, str):
771 # If the exec_output arg is a single string, we replicate
772 # it for each of the CPU models, substituting and
773 # %(CPU_foo)s params appropriately.
774 self
.exec_output
= expand_cpu_symbols_to_dict(exec_output
)
775 self
.decode_block
= expand_cpu_symbols_to_string(decode_block
)
776 self
.has_decode_default
= has_decode_default
778 # Override '+' operator: generate a new GenCode object that
779 # concatenates all the individual strings in the operands.
780 def __add__(self
, other
):
782 for cpu
in cpu_models
:
784 exec_output
[n
] = self
.exec_output
[n
] + other
.exec_output
[n
]
785 return GenCode(self
.header_output
+ other
.header_output
,
786 self
.decoder_output
+ other
.decoder_output
,
788 self
.decode_block
+ other
.decode_block
,
789 self
.has_decode_default
or other
.has_decode_default
)
791 # Prepend a string (typically a comment) to all the strings.
792 def prepend_all(self
, pre
):
793 self
.header_output
= pre
+ self
.header_output
794 self
.decoder_output
= pre
+ self
.decoder_output
795 self
.decode_block
= pre
+ self
.decode_block
796 for cpu
in cpu_models
:
797 self
.exec_output
[cpu
.name
] = pre
+ self
.exec_output
[cpu
.name
]
799 # Wrap the decode block in a pair of strings (e.g., 'case foo:'
800 # and 'break;'). Used to build the big nested switch statement.
801 def wrap_decode_block(self
, pre
, post
= ''):
802 self
.decode_block
= pre
+ indent(self
.decode_block
) + post
807 # A format object encapsulates an instruction format. It must provide
808 # a defineInst() method that generates the code for an instruction
811 exportContextSymbols
= ('InstObjParams', 'makeList', 're', 'string')
815 def updateExportContext():
816 exportContext
.update(exportDict(*exportContextSymbols
))
817 exportContext
.update(templateMap
)
819 def exportDict(*symNames
):
820 return dict([(s
, eval(s
)) for s
in symNames
])
824 def __init__(self
, id, params
, code
):
825 # constructor: just save away arguments
828 label
= 'def format ' + id
829 self
.user_code
= compile(fixPythonIndentation(code
), label
, 'exec')
830 param_list
= string
.join(params
, ", ")
831 f
= '''def defInst(_code, _context, %s):
832 my_locals = vars().copy()
833 exec _code in _context, my_locals
834 return my_locals\n''' % param_list
835 c
= compile(f
, label
+ ' wrapper', 'exec')
839 def defineInst(self
, name
, args
, lineno
):
841 updateExportContext()
842 context
.update(exportContext
)
843 context
.update({ 'name': name
, 'Name': string
.capitalize(name
) })
845 vars = self
.func(self
.user_code
, context
, *args
[0], **args
[1])
846 except Exception, exc
:
847 error(lineno
, 'error defining "%s": %s.' % (name
, exc
))
848 for k
in vars.keys():
849 if k
not in ('header_output', 'decoder_output',
850 'exec_output', 'decode_block'):
852 return GenCode(**vars)
854 # Special null format to catch an implicit-format instruction
855 # definition outside of any format block.
858 self
.defaultInst
= ''
860 def defineInst(self
, name
, args
, lineno
):
862 'instruction definition "%s" with no active format!' % name
)
864 # This dictionary maps format name strings to Format objects.
867 # Define a new format
868 def defFormat(id, params
, code
, lineno
):
869 # make sure we haven't already defined this one
870 if formatMap
.get(id, None) != None:
871 error(lineno
, 'format %s redefined.' % id)
872 # create new object and store in global map
873 formatMap
[id] = Format(id, params
, code
)
877 # Stack: a simple stack object. Used for both formats (formatStack)
878 # and default cases (defaultStack). Simply wraps a list to give more
879 # stack-like syntax and enable initialization with an argument list
880 # (as opposed to an argument that's a list).
883 def __init__(self
, *items
):
884 list.__init
__(self
, items
)
886 def push(self
, item
):
892 # The global format stack.
893 formatStack
= Stack(NoFormat())
895 # The global default case stack.
896 defaultStack
= Stack( None )
898 # Global stack that tracks current file and line number.
899 # Each element is a tuple (filename, lineno) that records the
900 # *current* filename and the line number in the *previous* file where
902 fileNameStack
= Stack()
908 # Indent every line in string 's' by two spaces
909 # (except preprocessor directives).
910 # Used to make nested code blocks look pretty.
913 return re
.sub(r
'(?m)^(?!#)', ' ', s
)
916 # Munge a somewhat arbitrarily formatted piece of Python code
917 # (e.g. from a format 'let' block) into something whose indentation
918 # will get by the Python parser.
920 # The two keys here are that Python will give a syntax error if
921 # there's any whitespace at the beginning of the first line, and that
922 # all lines at the same lexical nesting level must have identical
923 # indentation. Unfortunately the way code literals work, an entire
924 # let block tends to have some initial indentation. Rather than
925 # trying to figure out what that is and strip it off, we prepend 'if
926 # 1:' to make the let code the nested block inside the if (and have
927 # the parser automatically deal with the indentation for us).
929 # We don't want to do this if (1) the code block is empty or (2) the
930 # first line of the block doesn't have any whitespace at the front.
932 def fixPythonIndentation(s
):
933 # get rid of blank lines first
934 s
= re
.sub(r
'(?m)^\s*\n', '', s
);
935 if (s
!= '' and re
.match(r
'[ \t]', s
[0])):
939 # Error handler. Just call exit. Output formatted to work under
940 # Emacs compile-mode. Optional 'print_traceback' arg, if set to True,
941 # prints a Python stack backtrace too (can be handy when trying to
942 # debug the parser itself).
943 def error(lineno
, string
, print_traceback
= False):
945 for (filename
, line
) in fileNameStack
[0:-1]:
946 print spaces
+ "In file included from " + filename
+ ":"
948 # Print a Python stack backtrace if requested.
949 if (print_traceback
):
950 traceback
.print_exc()
952 line_str
= "%d:" % lineno
955 sys
.exit(spaces
+ "%s:%s %s" % (fileNameStack
[-1][0], line_str
, string
))
958 #####################################################################
960 # Bitfield Operator Support
962 #####################################################################
964 bitOp1ArgRE
= re
.compile(r
'<\s*(\w+)\s*:\s*>')
966 bitOpWordRE
= re
.compile(r
'(?<![\w\.])([\w\.]+)<\s*(\w+)\s*:\s*(\w+)\s*>')
967 bitOpExprRE
= re
.compile(r
'\)<\s*(\w+)\s*:\s*(\w+)\s*>')
969 def substBitOps(code
):
970 # first convert single-bit selectors to two-index form
971 # i.e., <n> --> <n:n>
972 code
= bitOp1ArgRE
.sub(r
'<\1:\1>', code
)
973 # simple case: selector applied to ID (name)
974 # i.e., foo<a:b> --> bits(foo, a, b)
975 code
= bitOpWordRE
.sub(r
'bits(\1, \2, \3)', code
)
976 # if selector is applied to expression (ending in ')'),
977 # we need to search backward for matching '('
978 match
= bitOpExprRE
.search(code
)
980 exprEnd
= match
.start()
984 if code
[here
] == '(':
986 elif code
[here
] == ')':
990 sys
.exit("Didn't find '('!")
992 newExpr
= r
'bits(%s, %s, %s)' % (code
[exprStart
:exprEnd
+1],
993 match
.group(1), match
.group(2))
994 code
= code
[:exprStart
] + newExpr
+ code
[match
.end():]
995 match
= bitOpExprRE
.search(code
)
1002 # Template objects are format strings that allow substitution from
1003 # the attribute spaces of other objects (e.g. InstObjParams instances).
1005 labelRE
= re
.compile(r
'[^%]%\(([^\)]+)\)[sd]')
1008 def __init__(self
, t
):
1014 # Protect non-Python-dict substitutions (e.g. if there's a printf
1015 # in the templated C++ code)
1016 template
= protect_non_subst_percents(self
.template
)
1017 # CPU-model-specific substitutions are handled later (in GenCode).
1018 template
= protect_cpu_symbols(template
)
1020 # Build a dict ('myDict') to use for the template substitution.
1021 # Start with the template namespace. Make a copy since we're
1022 # going to modify it.
1023 myDict
= templateMap
.copy()
1025 if isinstance(d
, InstObjParams
):
1026 # If we're dealing with an InstObjParams object, we need
1027 # to be a little more sophisticated. The instruction-wide
1028 # parameters are already formed, but the parameters which
1029 # are only function wide still need to be generated.
1032 myDict
.update(d
.__dict
__)
1033 # The "operands" and "snippets" attributes of the InstObjParams
1034 # objects are for internal use and not substitution.
1035 del myDict
['operands']
1036 del myDict
['snippets']
1038 snippetLabels
= [l
for l
in labelRE
.findall(template
)
1039 if d
.snippets
.has_key(l
)]
1041 snippets
= dict([(s
, mungeSnippet(d
.snippets
[s
]))
1042 for s
in snippetLabels
])
1044 myDict
.update(snippets
)
1046 compositeCode
= ' '.join(map(str, snippets
.values()))
1048 # Add in template itself in case it references any
1049 # operands explicitly (like Mem)
1050 compositeCode
+= ' ' + template
1052 operands
= SubOperandList(compositeCode
, d
.operands
)
1054 myDict
['op_decl'] = operands
.concatAttrStrings('op_decl')
1056 is_src
= lambda op
: op
.is_src
1057 is_dest
= lambda op
: op
.is_dest
1059 myDict
['op_src_decl'] = \
1060 operands
.concatSomeAttrStrings(is_src
, 'op_src_decl')
1061 myDict
['op_dest_decl'] = \
1062 operands
.concatSomeAttrStrings(is_dest
, 'op_dest_decl')
1064 myDict
['op_rd'] = operands
.concatAttrStrings('op_rd')
1065 myDict
['op_wb'] = operands
.concatAttrStrings('op_wb')
1067 if d
.operands
.memOperand
:
1068 myDict
['mem_acc_size'] = d
.operands
.memOperand
.mem_acc_size
1069 myDict
['mem_acc_type'] = d
.operands
.memOperand
.mem_acc_type
1071 elif isinstance(d
, dict):
1072 # if the argument is a dictionary, we just use it.
1074 elif hasattr(d
, '__dict__'):
1075 # if the argument is an object, we use its attribute map.
1076 myDict
.update(d
.__dict
__)
1078 raise TypeError, "Template.subst() arg must be or have dictionary"
1079 return template
% myDict
1081 # Convert to string. This handles the case when a template with a
1082 # CPU-specific term gets interpolated into another template or into
1085 return expand_cpu_symbols_to_string(self
.template
)
1087 #####################################################################
1091 # The remaining code is the support for automatically extracting
1092 # instruction characteristics from pseudocode.
1094 #####################################################################
1096 # Force the argument to be a list. Useful for flags, where a caller
1097 # can specify a singleton flag or a list of flags. Also usful for
1098 # converting tuples to lists so they can be modified.
1100 if isinstance(arg
, list):
1102 elif isinstance(arg
, tuple):
1109 # Generate operandTypeMap from the user's 'def operand_types'
1111 def buildOperandTypeMap(userDict
, lineno
):
1112 global operandTypeMap
1114 for (ext
, (desc
, size
)) in userDict
.iteritems():
1115 if desc
== 'signed int':
1116 ctype
= 'int%d_t' % size
1118 elif desc
== 'unsigned int':
1119 ctype
= 'uint%d_t' % size
1121 elif desc
== 'float':
1122 is_signed
= 1 # shouldn't really matter
1127 elif desc
== 'twin64 int':
1130 elif desc
== 'twin32 int':
1134 error(lineno
, 'Unrecognized type description "%s" in userDict')
1135 operandTypeMap
[ext
] = (size
, ctype
, is_signed
)
1140 # Base class for operand descriptors. An instance of this class (or
1141 # actually a class derived from this one) represents a specific
1142 # operand for a code block (e.g, "Rc.sq" as a dest). Intermediate
1143 # derived classes encapsulates the traits of a particular operand type
1144 # (e.g., "32-bit integer register").
1146 class Operand(object):
1147 def __init__(self
, full_name
, ext
, is_src
, is_dest
):
1148 self
.full_name
= full_name
1150 self
.is_src
= is_src
1151 self
.is_dest
= is_dest
1152 # The 'effective extension' (eff_ext) is either the actual
1153 # extension, if one was explicitly provided, or the default.
1157 self
.eff_ext
= self
.dflt_ext
1159 (self
.size
, self
.ctype
, self
.is_signed
) = operandTypeMap
[self
.eff_ext
]
1161 # note that mem_acc_size is undefined for non-mem operands...
1162 # template must be careful not to use it if it doesn't apply.
1164 self
.mem_acc_size
= self
.makeAccSize()
1165 if self
.ctype
in ['Twin32_t', 'Twin64_t']:
1166 self
.mem_acc_type
= 'Twin'
1168 self
.mem_acc_type
= 'uint'
1170 # Finalize additional fields (primarily code fields). This step
1171 # is done separately since some of these fields may depend on the
1172 # register index enumeration that hasn't been performed yet at the
1173 # time of __init__().
1175 self
.flags
= self
.getFlags()
1176 self
.constructor
= self
.makeConstructor()
1177 self
.op_decl
= self
.makeDecl()
1180 self
.op_rd
= self
.makeRead()
1181 self
.op_src_decl
= self
.makeDecl()
1184 self
.op_src_decl
= ''
1187 self
.op_wb
= self
.makeWrite()
1188 self
.op_dest_decl
= self
.makeDecl()
1191 self
.op_dest_decl
= ''
1199 def isFloatReg(self
):
1205 def isControlReg(self
):
1209 # note the empty slice '[:]' gives us a copy of self.flags[0]
1210 # instead of a reference to it
1211 my_flags
= self
.flags
[0][:]
1213 my_flags
+= self
.flags
[1]
1215 my_flags
+= self
.flags
[2]
1219 # Note that initializations in the declarations are solely
1220 # to avoid 'uninitialized variable' errors from the compiler.
1221 return self
.ctype
+ ' ' + self
.base_name
+ ' = 0;\n';
1223 class IntRegOperand(Operand
):
1230 def makeConstructor(self
):
1233 c
+= '\n\t_srcRegIdx[%d] = %s;' % \
1234 (self
.src_reg_idx
, self
.reg_spec
)
1236 c
+= '\n\t_destRegIdx[%d] = %s;' % \
1237 (self
.dest_reg_idx
, self
.reg_spec
)
1241 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1242 error(0, 'Attempt to read integer register as FP')
1243 if (self
.size
== self
.dflt_size
):
1244 return '%s = xc->readIntRegOperand(this, %d);\n' % \
1245 (self
.base_name
, self
.src_reg_idx
)
1246 elif (self
.size
> self
.dflt_size
):
1247 int_reg_val
= 'xc->readIntRegOperand(this, %d)' % \
1249 if (self
.is_signed
):
1250 int_reg_val
= 'sext<%d>(%s)' % (self
.dflt_size
, int_reg_val
)
1251 return '%s = %s;\n' % (self
.base_name
, int_reg_val
)
1253 return '%s = bits(xc->readIntRegOperand(this, %d), %d, 0);\n' % \
1254 (self
.base_name
, self
.src_reg_idx
, self
.size
-1)
1256 def makeWrite(self
):
1257 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1258 error(0, 'Attempt to write integer register as FP')
1259 if (self
.size
!= self
.dflt_size
and self
.is_signed
):
1260 final_val
= 'sext<%d>(%s)' % (self
.size
, self
.base_name
)
1262 final_val
= self
.base_name
1266 xc->setIntRegOperand(this, %d, final_val);\n
1267 if (traceData) { traceData->setData(final_val); }
1268 }''' % (self
.dflt_ctype
, final_val
, self
.dest_reg_idx
)
1271 class FloatRegOperand(Operand
):
1275 def isFloatReg(self
):
1278 def makeConstructor(self
):
1281 c
+= '\n\t_srcRegIdx[%d] = %s + FP_Base_DepTag;' % \
1282 (self
.src_reg_idx
, self
.reg_spec
)
1284 c
+= '\n\t_destRegIdx[%d] = %s + FP_Base_DepTag;' % \
1285 (self
.dest_reg_idx
, self
.reg_spec
)
1291 if (self
.ctype
== 'float'):
1292 func
= 'readFloatRegOperand'
1294 elif (self
.ctype
== 'double'):
1295 func
= 'readFloatRegOperand'
1298 func
= 'readFloatRegOperandBits'
1299 if (self
.ctype
== 'uint32_t'):
1301 elif (self
.ctype
== 'uint64_t'):
1303 if (self
.size
!= self
.dflt_size
):
1306 base
= 'xc->%s(this, %d, %d)' % \
1307 (func
, self
.src_reg_idx
, width
)
1309 base
= 'xc->%s(this, %d)' % \
1310 (func
, self
.src_reg_idx
)
1312 return '%s = bits(%s, %d, 0);\n' % \
1313 (self
.base_name
, base
, self
.size
-1)
1315 return '%s = %s;\n' % (self
.base_name
, base
)
1317 def makeWrite(self
):
1318 final_val
= self
.base_name
1319 final_ctype
= self
.ctype
1322 if (self
.ctype
== 'float'):
1324 func
= 'setFloatRegOperand'
1325 elif (self
.ctype
== 'double'):
1327 func
= 'setFloatRegOperand'
1328 elif (self
.ctype
== 'uint32_t'):
1329 func
= 'setFloatRegOperandBits'
1331 elif (self
.ctype
== 'uint64_t'):
1332 func
= 'setFloatRegOperandBits'
1335 func
= 'setFloatRegOperandBits'
1336 final_ctype
= 'uint%d_t' % self
.dflt_size
1337 if (self
.size
!= self
.dflt_size
and self
.is_signed
):
1338 final_val
= 'sext<%d>(%s)' % (self
.size
, self
.base_name
)
1340 widthSpecifier
= ', %d' % width
1344 xc->%s(this, %d, final_val%s);\n
1345 if (traceData) { traceData->setData(final_val); }
1346 }''' % (final_ctype
, final_val
, func
, self
.dest_reg_idx
,
1350 class ControlRegOperand(Operand
):
1354 def isControlReg(self
):
1357 def makeConstructor(self
):
1360 c
+= '\n\t_srcRegIdx[%d] = %s + Ctrl_Base_DepTag;' % \
1361 (self
.src_reg_idx
, self
.reg_spec
)
1363 c
+= '\n\t_destRegIdx[%d] = %s + Ctrl_Base_DepTag;' % \
1364 (self
.dest_reg_idx
, self
.reg_spec
)
1369 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1370 error(0, 'Attempt to read control register as FP')
1371 base
= 'xc->readMiscRegOperand(this, %s)' % self
.src_reg_idx
1372 if self
.size
== self
.dflt_size
:
1373 return '%s = %s;\n' % (self
.base_name
, base
)
1375 return '%s = bits(%s, %d, 0);\n' % \
1376 (self
.base_name
, base
, self
.size
-1)
1378 def makeWrite(self
):
1379 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1380 error(0, 'Attempt to write control register as FP')
1381 wb
= 'xc->setMiscRegOperand(this, %s, %s);\n' % \
1382 (self
.dest_reg_idx
, self
.base_name
)
1383 wb
+= 'if (traceData) { traceData->setData(%s); }' % \
1387 class MemOperand(Operand
):
1391 def makeConstructor(self
):
1395 # Note that initializations in the declarations are solely
1396 # to avoid 'uninitialized variable' errors from the compiler.
1397 # Declare memory data variable.
1398 if self
.ctype
in ['Twin32_t','Twin64_t']:
1399 return "%s %s; %s.a = 0; %s.b = 0;\n" % (self
.ctype
, self
.base_name
,
1400 self
.base_name
, self
.base_name
)
1401 c
= '%s %s = 0;\n' % (self
.ctype
, self
.base_name
)
1407 def makeWrite(self
):
1410 # Return the memory access size *in bits*, suitable for
1411 # forming a type via "uint%d_t". Divide by 8 if you want bytes.
1412 def makeAccSize(self
):
1416 class NPCOperand(Operand
):
1417 def makeConstructor(self
):
1421 return '%s = xc->readNextPC();\n' % self
.base_name
1423 def makeWrite(self
):
1424 return 'xc->setNextPC(%s);\n' % self
.base_name
1426 class NNPCOperand(Operand
):
1427 def makeConstructor(self
):
1431 return '%s = xc->readNextNPC();\n' % self
.base_name
1433 def makeWrite(self
):
1434 return 'xc->setNextNPC(%s);\n' % self
.base_name
1436 def buildOperandNameMap(userDict
, lineno
):
1437 global operandNameMap
1439 for (op_name
, val
) in userDict
.iteritems():
1440 (base_cls_name
, dflt_ext
, reg_spec
, flags
, sort_pri
) = val
1441 (dflt_size
, dflt_ctype
, dflt_is_signed
) = operandTypeMap
[dflt_ext
]
1442 # Canonical flag structure is a triple of lists, where each list
1443 # indicates the set of flags implied by this operand always, when
1444 # used as a source, and when used as a dest, respectively.
1445 # For simplicity this can be initialized using a variety of fairly
1446 # obvious shortcuts; we convert these to canonical form here.
1448 # no flags specified (e.g., 'None')
1449 flags
= ( [], [], [] )
1450 elif isinstance(flags
, str):
1451 # a single flag: assumed to be unconditional
1452 flags
= ( [ flags
], [], [] )
1453 elif isinstance(flags
, list):
1454 # a list of flags: also assumed to be unconditional
1455 flags
= ( flags
, [], [] )
1456 elif isinstance(flags
, tuple):
1457 # it's a tuple: it should be a triple,
1458 # but each item could be a single string or a list
1459 (uncond_flags
, src_flags
, dest_flags
) = flags
1460 flags
= (makeList(uncond_flags
),
1461 makeList(src_flags
), makeList(dest_flags
))
1462 # Accumulate attributes of new operand class in tmp_dict
1464 for attr
in ('dflt_ext', 'reg_spec', 'flags', 'sort_pri',
1465 'dflt_size', 'dflt_ctype', 'dflt_is_signed'):
1466 tmp_dict
[attr
] = eval(attr
)
1467 tmp_dict
['base_name'] = op_name
1468 # New class name will be e.g. "IntReg_Ra"
1469 cls_name
= base_cls_name
+ '_' + op_name
1470 # Evaluate string arg to get class object. Note that the
1471 # actual base class for "IntReg" is "IntRegOperand", i.e. we
1472 # have to append "Operand".
1474 base_cls
= eval(base_cls_name
+ 'Operand')
1477 'error: unknown operand base class "%s"' % base_cls_name
)
1478 # The following statement creates a new class called
1479 # <cls_name> as a subclass of <base_cls> with the attributes
1480 # in tmp_dict, just as if we evaluated a class declaration.
1481 operandNameMap
[op_name
] = type(cls_name
, (base_cls
,), tmp_dict
)
1483 # Define operand variables.
1484 operands
= userDict
.keys()
1486 operandsREString
= (r
'''
1487 (?<![\w\.]) # neg. lookbehind assertion: prevent partial matches
1488 ((%s)(?:\.(\w+))?) # match: operand with optional '.' then suffix
1489 (?![\w\.]) # neg. lookahead assertion: prevent partial matches
1491 % string
.join(operands
, '|'))
1494 operandsRE
= re
.compile(operandsREString
, re
.MULTILINE|re
.VERBOSE
)
1496 # Same as operandsREString, but extension is mandatory, and only two
1497 # groups are returned (base and ext, not full name as above).
1498 # Used for subtituting '_' for '.' to make C++ identifiers.
1499 operandsWithExtREString
= (r
'(?<![\w\.])(%s)\.(\w+)(?![\w\.])'
1500 % string
.join(operands
, '|'))
1502 global operandsWithExtRE
1503 operandsWithExtRE
= re
.compile(operandsWithExtREString
, re
.MULTILINE
)
1508 # Find all the operands in the given code block. Returns an operand
1509 # descriptor list (instance of class OperandList).
1510 def __init__(self
, code
):
1513 # delete comments so we don't match on reg specifiers inside
1514 code
= commentRE
.sub('', code
)
1515 # search for operands
1518 match
= operandsRE
.search(code
, next_pos
)
1520 # no more matches: we're done
1523 # regexp groups are operand full name, base, and extension
1524 (op_full
, op_base
, op_ext
) = op
1525 # if the token following the operand is an assignment, this is
1526 # a destination (LHS), else it's a source (RHS)
1527 is_dest
= (assignRE
.match(code
, match
.end()) != None)
1528 is_src
= not is_dest
1529 # see if we've already seen this one
1530 op_desc
= self
.find_base(op_base
)
1532 if op_desc
.ext
!= op_ext
:
1533 error(0, 'Inconsistent extensions for operand %s' % \
1535 op_desc
.is_src
= op_desc
.is_src
or is_src
1536 op_desc
.is_dest
= op_desc
.is_dest
or is_dest
1538 # new operand: create new descriptor
1539 op_desc
= operandNameMap
[op_base
](op_full
, op_ext
,
1541 self
.append(op_desc
)
1542 # start next search after end of current match
1543 next_pos
= match
.end()
1545 # enumerate source & dest register operands... used in building
1548 self
.numDestRegs
= 0
1549 self
.numFPDestRegs
= 0
1550 self
.numIntDestRegs
= 0
1551 self
.memOperand
= None
1552 for op_desc
in self
.items
:
1555 op_desc
.src_reg_idx
= self
.numSrcRegs
1556 self
.numSrcRegs
+= 1
1558 op_desc
.dest_reg_idx
= self
.numDestRegs
1559 self
.numDestRegs
+= 1
1560 if op_desc
.isFloatReg():
1561 self
.numFPDestRegs
+= 1
1562 elif op_desc
.isIntReg():
1563 self
.numIntDestRegs
+= 1
1564 elif op_desc
.isMem():
1566 error(0, "Code block has more than one memory operand.")
1567 self
.memOperand
= op_desc
1568 # now make a final pass to finalize op_desc fields that may depend
1569 # on the register enumeration
1570 for op_desc
in self
.items
:
1574 return len(self
.items
)
1576 def __getitem__(self
, index
):
1577 return self
.items
[index
]
1579 def append(self
, op_desc
):
1580 self
.items
.append(op_desc
)
1581 self
.bases
[op_desc
.base_name
] = op_desc
1583 def find_base(self
, base_name
):
1584 # like self.bases[base_name], but returns None if not found
1585 # (rather than raising exception)
1586 return self
.bases
.get(base_name
)
1588 # internal helper function for concat[Some]Attr{Strings|Lists}
1589 def __internalConcatAttrs(self
, attr_name
, filter, result
):
1590 for op_desc
in self
.items
:
1592 result
+= getattr(op_desc
, attr_name
)
1595 # return a single string that is the concatenation of the (string)
1596 # values of the specified attribute for all operands
1597 def concatAttrStrings(self
, attr_name
):
1598 return self
.__internalConcatAttrs
(attr_name
, lambda x
: 1, '')
1600 # like concatAttrStrings, but only include the values for the operands
1601 # for which the provided filter function returns true
1602 def concatSomeAttrStrings(self
, filter, attr_name
):
1603 return self
.__internalConcatAttrs
(attr_name
, filter, '')
1605 # return a single list that is the concatenation of the (list)
1606 # values of the specified attribute for all operands
1607 def concatAttrLists(self
, attr_name
):
1608 return self
.__internalConcatAttrs
(attr_name
, lambda x
: 1, [])
1610 # like concatAttrLists, but only include the values for the operands
1611 # for which the provided filter function returns true
1612 def concatSomeAttrLists(self
, filter, attr_name
):
1613 return self
.__internalConcatAttrs
(attr_name
, filter, [])
1616 self
.items
.sort(lambda a
, b
: a
.sort_pri
- b
.sort_pri
)
1618 class SubOperandList(OperandList
):
1620 # Find all the operands in the given code block. Returns an operand
1621 # descriptor list (instance of class OperandList).
1622 def __init__(self
, code
, master_list
):
1625 # delete comments so we don't match on reg specifiers inside
1626 code
= commentRE
.sub('', code
)
1627 # search for operands
1630 match
= operandsRE
.search(code
, next_pos
)
1632 # no more matches: we're done
1635 # regexp groups are operand full name, base, and extension
1636 (op_full
, op_base
, op_ext
) = op
1637 # find this op in the master list
1638 op_desc
= master_list
.find_base(op_base
)
1640 error(0, 'Found operand %s which is not in the master list!' \
1641 ' This is an internal error' % \
1644 # See if we've already found this operand
1645 op_desc
= self
.find_base(op_base
)
1647 # if not, add a reference to it to this sub list
1648 self
.append(master_list
.bases
[op_base
])
1650 # start next search after end of current match
1651 next_pos
= match
.end()
1653 self
.memOperand
= None
1654 for op_desc
in self
.items
:
1657 error(0, "Code block has more than one memory operand.")
1658 self
.memOperand
= op_desc
1660 # Regular expression object to match C++ comments
1661 # (used in findOperands())
1662 commentRE
= re
.compile(r
'//.*\n')
1664 # Regular expression object to match assignment statements
1665 # (used in findOperands())
1666 assignRE
= re
.compile(r
'\s*=(?!=)', re
.MULTILINE
)
1668 # Munge operand names in code string to make legal C++ variable names.
1669 # This means getting rid of the type extension if any.
1670 # (Will match base_name attribute of Operand object.)
1671 def substMungedOpNames(code
):
1672 return operandsWithExtRE
.sub(r
'\1', code
)
1674 # Fix up code snippets for final substitution in templates.
1675 def mungeSnippet(s
):
1676 if isinstance(s
, str):
1677 return substMungedOpNames(substBitOps(s
))
1681 def makeFlagConstructor(flag_list
):
1682 if len(flag_list
) == 0:
1684 # filter out repeated flags
1687 while i
< len(flag_list
):
1688 if flag_list
[i
] == flag_list
[i
-1]:
1694 code
= pre
+ string
.join(flag_list
, post
+ pre
) + post
1697 # Assume all instruction flags are of the form 'IsFoo'
1698 instFlagRE
= re
.compile(r
'Is.*')
1700 # OpClass constants end in 'Op' except No_OpClass
1701 opClassRE
= re
.compile(r
'.*Op|No_OpClass')
1703 class InstObjParams
:
1704 def __init__(self
, mnem
, class_name
, base_class
= '',
1705 snippets
= {}, opt_args
= []):
1706 self
.mnemonic
= mnem
1707 self
.class_name
= class_name
1708 self
.base_class
= base_class
1709 if not isinstance(snippets
, dict):
1710 snippets
= {'code' : snippets
}
1711 compositeCode
= ' '.join(map(str, snippets
.values()))
1712 self
.snippets
= snippets
1714 self
.operands
= OperandList(compositeCode
)
1715 self
.constructor
= self
.operands
.concatAttrStrings('constructor')
1716 self
.constructor
+= \
1717 '\n\t_numSrcRegs = %d;' % self
.operands
.numSrcRegs
1718 self
.constructor
+= \
1719 '\n\t_numDestRegs = %d;' % self
.operands
.numDestRegs
1720 self
.constructor
+= \
1721 '\n\t_numFPDestRegs = %d;' % self
.operands
.numFPDestRegs
1722 self
.constructor
+= \
1723 '\n\t_numIntDestRegs = %d;' % self
.operands
.numIntDestRegs
1724 self
.flags
= self
.operands
.concatAttrLists('flags')
1726 # Make a basic guess on the operand class (function unit type).
1727 # These are good enough for most cases, and can be overridden
1729 if 'IsStore' in self
.flags
:
1730 self
.op_class
= 'MemWriteOp'
1731 elif 'IsLoad' in self
.flags
or 'IsPrefetch' in self
.flags
:
1732 self
.op_class
= 'MemReadOp'
1733 elif 'IsFloating' in self
.flags
:
1734 self
.op_class
= 'FloatAddOp'
1736 self
.op_class
= 'IntAluOp'
1738 # Optional arguments are assumed to be either StaticInst flags
1739 # or an OpClass value. To avoid having to import a complete
1740 # list of these values to match against, we do it ad-hoc
1743 if instFlagRE
.match(oa
):
1744 self
.flags
.append(oa
)
1745 elif opClassRE
.match(oa
):
1748 error(0, 'InstObjParams: optional arg "%s" not recognized '
1749 'as StaticInst::Flag or OpClass.' % oa
)
1751 # add flag initialization to contructor here to include
1752 # any flags added via opt_args
1753 self
.constructor
+= makeFlagConstructor(self
.flags
)
1755 # if 'IsFloating' is set, add call to the FP enable check
1756 # function (which should be provided by isa_desc via a declare)
1757 if 'IsFloating' in self
.flags
:
1758 self
.fp_enable_check
= 'fault = checkFpEnableFault(xc);'
1760 self
.fp_enable_check
= ''
1762 #######################
1764 # Output file template
1769 * DO NOT EDIT THIS FILE!!!
1771 * It was automatically generated from the ISA description in %(filename)s
1778 namespace %(namespace)s {
1780 %(namespace_output)s
1782 } // namespace %(namespace)s
1788 # Update the output file only if the new contents are different from
1789 # the current contents. Minimizes the files that need to be rebuilt
1790 # after minor changes.
1791 def update_if_needed(file, contents
):
1793 if os
.access(file, os
.R_OK
):
1795 old_contents
= f
.read()
1797 if contents
!= old_contents
:
1798 print 'Updating', file
1799 os
.remove(file) # in case it's write-protected
1802 print 'File', file, 'is unchanged'
1804 print 'Generating', file
1811 # This regular expression matches '##include' directives
1812 includeRE
= re
.compile(r
'^\s*##include\s+"(?P<filename>[\w/.-]*)".*$',
1815 # Function to replace a matched '##include' directive with the
1816 # contents of the specified file (with nested ##includes replaced
1817 # recursively). 'matchobj' is an re match object (from a match of
1818 # includeRE) and 'dirname' is the directory relative to which the file
1819 # path should be resolved.
1820 def replace_include(matchobj
, dirname
):
1821 fname
= matchobj
.group('filename')
1822 full_fname
= os
.path
.normpath(os
.path
.join(dirname
, fname
))
1823 contents
= '##newfile "%s"\n%s\n##endfile\n' % \
1824 (full_fname
, read_and_flatten(full_fname
))
1827 # Read a file and recursively flatten nested '##include' files.
1828 def read_and_flatten(filename
):
1829 current_dir
= os
.path
.dirname(filename
)
1831 contents
= open(filename
).read()
1833 error(0, 'Error including file "%s"' % filename
)
1834 fileNameStack
.push((filename
, 0))
1835 # Find any includes and include them
1836 contents
= includeRE
.sub(lambda m
: replace_include(m
, current_dir
),
1842 # Read in and parse the ISA description.
1844 def parse_isa_desc(isa_desc_file
, output_dir
):
1845 # Read file and (recursively) all included files into a string.
1846 # PLY requires that the input be in a single string so we have to
1848 isa_desc
= read_and_flatten(isa_desc_file
)
1850 # Initialize filename stack with outer file.
1851 fileNameStack
.push((isa_desc_file
, 0))
1854 (isa_name
, namespace
, global_code
, namespace_code
) = yacc
.parse(isa_desc
)
1856 # grab the last three path components of isa_desc_file to put in
1858 filename
= '/'.join(isa_desc_file
.split('/')[-3:])
1860 # generate decoder.hh
1861 includes
= '#include "base/bitfield.hh" // for bitfield support'
1862 global_output
= global_code
.header_output
1863 namespace_output
= namespace_code
.header_output
1864 decode_function
= ''
1865 update_if_needed(output_dir
+ '/decoder.hh', file_template
% vars())
1867 # generate decoder.cc
1868 includes
= '#include "decoder.hh"'
1869 global_output
= global_code
.decoder_output
1870 namespace_output
= namespace_code
.decoder_output
1871 # namespace_output += namespace_code.decode_block
1872 decode_function
= namespace_code
.decode_block
1873 update_if_needed(output_dir
+ '/decoder.cc', file_template
% vars())
1875 # generate per-cpu exec files
1876 for cpu
in cpu_models
:
1877 includes
= '#include "decoder.hh"\n'
1878 includes
+= cpu
.includes
1879 global_output
= global_code
.exec_output
[cpu
.name
]
1880 namespace_output
= namespace_code
.exec_output
[cpu
.name
]
1881 decode_function
= ''
1882 update_if_needed(output_dir
+ '/' + cpu
.filename
,
1883 file_template
% vars())
1885 # global list of CpuModel objects (see cpu_models.py)
1888 # Called as script: get args from command line.
1889 # Args are: <path to cpu_models.py> <isa desc file> <output dir> <cpu models>
1890 if __name__
== '__main__':
1891 execfile(sys
.argv
[1]) # read in CpuModel definitions
1892 cpu_models
= [CpuModel
.dict[cpu
] for cpu
in sys
.argv
[4:]]
1893 parse_isa_desc(sys
.argv
[2], sys
.argv
[3])