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', 'DOT', '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
121 # Identifiers and reserved words
124 reserved_map
[r
.lower()] = r
128 t
.type = reserved_map
.get(t
.value
,'ID')
133 r
'(0x[\da-fA-F]+)|\d+'
135 t
.value
= int(t
.value
,0)
137 error(t
.lexer
.lineno
, 'Integer value "%s" too large' % t
.value
)
141 # String literal. Note that these use only single quotes, and
142 # can span multiple lines.
146 t
.value
= t
.value
[1:-1]
147 t
.lexer
.lineno
+= t
.value
.count('\n')
151 # "Code literal"... like a string literal, but delimiters are
152 # '{{' and '}}' so they get formatted nicely under emacs c-mode
154 r
"(?m)\{\{([^\}]|}(?!\}))+\}\}"
156 t
.value
= t
.value
[2:-2]
157 t
.lexer
.lineno
+= t
.value
.count('\n')
160 def t_CPPDIRECTIVE(t
):
162 t
.lexer
.lineno
+= t
.value
.count('\n')
166 r
'^\#\#newfile\s+"[\w/.-]*"'
167 fileNameStack
.push((t
.value
[11:-1], t
.lexer
.lineno
))
172 (old_filename
, t
.lexer
.lineno
) = fileNameStack
.pop()
175 # The functions t_NEWLINE, t_ignore, and t_error are
176 # special for the lex module.
182 t
.lexer
.lineno
+= t
.value
.count('\n')
188 # Completely ignored characters
193 error(t
.lexer
.lineno
, "illegal character '%s'" % t
.value
[0])
199 #####################################################################
203 # Every function whose name starts with 'p_' defines a grammar rule.
204 # The rule is encoded in the function's doc string, while the
205 # function body provides the action taken when the rule is matched.
206 # The argument to each function is a list of the values of the
207 # rule's symbols: t[0] for the LHS, and t[1..n] for the symbols
208 # on the RHS. For tokens, the value is copied from the t.value
209 # attribute provided by the lexer. For non-terminals, the value
210 # is assigned by the producing rule; i.e., the job of the grammar
211 # rule function is to set the value for the non-terminal on the LHS
212 # (by assigning to t[0]).
213 #####################################################################
215 # The LHS of the first grammar rule is used as the start symbol
216 # (in this case, 'specification'). Note that this rule enforces
217 # that there will be exactly one namespace declaration, with 0 or more
218 # global defs/decls before and after it. The defs & decls before
219 # the namespace decl will be outside the namespace; those after
220 # will be inside. The decoder function is always inside the namespace.
221 def p_specification(t
):
222 'specification : opt_defs_and_outputs name_decl opt_defs_and_outputs decode_block'
225 namespace
= isa_name
+ "Inst"
226 # wrap the decode block as a function definition
227 t
[4].wrap_decode_block('''
229 %(isa_name)s::decodeInst(%(isa_name)s::ExtMachInst machInst)
231 using namespace %(namespace)s;
233 # both the latter output blocks and the decode block are in the namespace
234 namespace_code
= t
[3] + t
[4]
235 # pass it all back to the caller of yacc.parse()
236 t
[0] = (isa_name
, namespace
, global_code
, namespace_code
)
238 # ISA name declaration looks like "namespace <foo>;"
240 'name_decl : NAMESPACE ID SEMI'
243 # 'opt_defs_and_outputs' is a possibly empty sequence of
244 # def and/or output statements.
245 def p_opt_defs_and_outputs_0(t
):
246 'opt_defs_and_outputs : empty'
249 def p_opt_defs_and_outputs_1(t
):
250 'opt_defs_and_outputs : defs_and_outputs'
253 def p_defs_and_outputs_0(t
):
254 'defs_and_outputs : def_or_output'
257 def p_defs_and_outputs_1(t
):
258 'defs_and_outputs : defs_and_outputs def_or_output'
261 # The list of possible definition/output statements.
262 def p_def_or_output(t
):
263 '''def_or_output : def_format
265 | def_bitfield_struct
275 # Output blocks 'output <foo> {{...}}' (C++ code blocks) are copied
276 # directly to the appropriate output section.
279 # Protect any non-dict-substitution '%'s in a format string
280 # (i.e. those not followed by '(')
281 def protect_non_subst_percents(s
):
282 return re
.sub(r
'%(?!\()', '%%', s
)
284 # Massage output block by substituting in template definitions and bit
285 # operators. We handle '%'s embedded in the string that don't
286 # indicate template substitutions (or CPU-specific symbols, which get
287 # handled in GenCode) by doubling them first so that the format
288 # operation will reduce them back to single '%'s.
289 def process_output(s
):
290 s
= protect_non_subst_percents(s
)
291 # protects cpu-specific symbols too
292 s
= protect_cpu_symbols(s
)
293 return substBitOps(s
% templateMap
)
295 def p_output_header(t
):
296 'output_header : OUTPUT HEADER CODELIT SEMI'
297 t
[0] = GenCode(header_output
= process_output(t
[3]))
299 def p_output_decoder(t
):
300 'output_decoder : OUTPUT DECODER CODELIT SEMI'
301 t
[0] = GenCode(decoder_output
= process_output(t
[3]))
303 def p_output_exec(t
):
304 'output_exec : OUTPUT EXEC CODELIT SEMI'
305 t
[0] = GenCode(exec_output
= process_output(t
[3]))
307 # global let blocks 'let {{...}}' (Python code blocks) are executed
308 # directly when seen. Note that these execute in a special variable
309 # context 'exportContext' to prevent the code from polluting this
310 # script's namespace.
312 'global_let : LET CODELIT SEMI'
313 updateExportContext()
314 exportContext
["header_output"] = ''
315 exportContext
["decoder_output"] = ''
316 exportContext
["exec_output"] = ''
317 exportContext
["decode_block"] = ''
319 exec fixPythonIndentation(t
[2]) in exportContext
320 except Exception, exc
:
321 error(t
.lexer
.lineno
,
322 'error: %s in global let block "%s".' % (exc
, t
[2]))
323 t
[0] = GenCode(header_output
= exportContext
["header_output"],
324 decoder_output
= exportContext
["decoder_output"],
325 exec_output
= exportContext
["exec_output"],
326 decode_block
= exportContext
["decode_block"])
328 # Define the mapping from operand type extensions to C++ types and bit
329 # widths (stored in operandTypeMap).
330 def p_def_operand_types(t
):
331 'def_operand_types : DEF OPERAND_TYPES CODELIT SEMI'
333 userDict
= eval('{' + t
[3] + '}')
334 except Exception, exc
:
335 error(t
.lexer
.lineno
,
336 'error: %s in def operand_types block "%s".' % (exc
, t
[3]))
337 buildOperandTypeMap(userDict
, t
.lexer
.lineno
)
338 t
[0] = GenCode() # contributes nothing to the output C++ file
340 # Define the mapping from operand names to operand classes and other
341 # traits. Stored in operandNameMap.
342 def p_def_operands(t
):
343 'def_operands : DEF OPERANDS CODELIT SEMI'
344 if not globals().has_key('operandTypeMap'):
345 error(t
.lexer
.lineno
,
346 'error: operand types must be defined before operands')
348 userDict
= eval('{' + t
[3] + '}')
349 except Exception, exc
:
350 error(t
.lexer
.lineno
,
351 'error: %s in def operands block "%s".' % (exc
, t
[3]))
352 buildOperandNameMap(userDict
, t
.lexer
.lineno
)
353 t
[0] = GenCode() # contributes nothing to the output C++ file
355 # A bitfield definition looks like:
356 # 'def [signed] bitfield <ID> [<first>:<last>]'
357 # This generates a preprocessor macro in the output file.
358 def p_def_bitfield_0(t
):
359 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT COLON INTLIT GREATER SEMI'
360 expr
= 'bits(machInst, %2d, %2d)' % (t
[6], t
[8])
361 if (t
[2] == 'signed'):
362 expr
= 'sext<%d>(%s)' % (t
[6] - t
[8] + 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 # alternate form for single bit: 'def [signed] bitfield <ID> [<bit>]'
367 def p_def_bitfield_1(t
):
368 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT GREATER SEMI'
369 expr
= 'bits(machInst, %2d, %2d)' % (t
[6], t
[6])
370 if (t
[2] == 'signed'):
371 expr
= 'sext<%d>(%s)' % (1, expr
)
372 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
373 t
[0] = GenCode(header_output
= hash_define
)
375 # alternate form for structure member: 'def bitfield <ID> <ID>'
376 def p_def_bitfield_struct(t
):
377 'def_bitfield_struct : DEF opt_signed BITFIELD ID id_with_dot SEMI'
379 error(t
.lexer
.lineno
, 'error: structure bitfields are always unsigned.')
380 expr
= 'machInst.%s' % t
[5]
381 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
382 t
[0] = GenCode(header_output
= hash_define
)
384 def p_id_with_dot_0(t
):
388 def p_id_with_dot_1(t
):
389 'id_with_dot : ID DOT id_with_dot'
390 t
[0] = t
[1] + t
[2] + t
[3]
392 def p_opt_signed_0(t
):
393 'opt_signed : SIGNED'
396 def p_opt_signed_1(t
):
400 # Global map variable to hold templates
403 def p_def_template(t
):
404 'def_template : DEF TEMPLATE ID CODELIT SEMI'
405 templateMap
[t
[3]] = Template(t
[4])
408 # An instruction format definition looks like
409 # "def format <fmt>(<params>) {{...}};"
411 'def_format : DEF FORMAT ID LPAREN param_list RPAREN CODELIT SEMI'
412 (id, params
, code
) = (t
[3], t
[5], t
[7])
413 defFormat(id, params
, code
, t
.lexer
.lineno
)
416 # The formal parameter list for an instruction format is a possibly
417 # empty list of comma-separated parameters. Positional (standard,
418 # non-keyword) parameters must come first, followed by keyword
419 # parameters, followed by a '*foo' parameter that gets excess
420 # positional arguments (as in Python). Each of these three parameter
421 # categories is optional.
423 # Note that we do not support the '**foo' parameter for collecting
424 # otherwise undefined keyword args. Otherwise the parameter list is
425 # (I believe) identical to what is supported in Python.
427 # The param list generates a tuple, where the first element is a list of
428 # the positional params and the second element is a dict containing the
430 def p_param_list_0(t
):
431 'param_list : positional_param_list COMMA nonpositional_param_list'
434 def p_param_list_1(t
):
435 '''param_list : positional_param_list
436 | nonpositional_param_list'''
439 def p_positional_param_list_0(t
):
440 'positional_param_list : empty'
443 def p_positional_param_list_1(t
):
444 'positional_param_list : ID'
447 def p_positional_param_list_2(t
):
448 'positional_param_list : positional_param_list COMMA ID'
451 def p_nonpositional_param_list_0(t
):
452 'nonpositional_param_list : keyword_param_list COMMA excess_args_param'
455 def p_nonpositional_param_list_1(t
):
456 '''nonpositional_param_list : keyword_param_list
457 | excess_args_param'''
460 def p_keyword_param_list_0(t
):
461 'keyword_param_list : keyword_param'
464 def p_keyword_param_list_1(t
):
465 'keyword_param_list : keyword_param_list COMMA keyword_param'
468 def p_keyword_param(t
):
469 'keyword_param : ID EQUALS expr'
470 t
[0] = t
[1] + ' = ' + t
[3].__repr
__()
472 def p_excess_args_param(t
):
473 'excess_args_param : ASTERISK ID'
474 # Just concatenate them: '*ID'. Wrap in list to be consistent
475 # with positional_param_list and keyword_param_list.
478 # End of format definition-related rules.
482 # A decode block looks like:
483 # decode <field1> [, <field2>]* [default <inst>] { ... }
485 def p_decode_block(t
):
486 'decode_block : DECODE ID opt_default LBRACE decode_stmt_list RBRACE'
487 default_defaults
= defaultStack
.pop()
489 # use the "default defaults" only if there was no explicit
490 # default statement in decode_stmt_list
491 if not codeObj
.has_decode_default
:
492 codeObj
+= default_defaults
493 codeObj
.wrap_decode_block('switch (%s) {\n' % t
[2], '}\n')
496 # The opt_default statement serves only to push the "default defaults"
497 # onto defaultStack. This value will be used by nested decode blocks,
498 # and used and popped off when the current decode_block is processed
499 # (in p_decode_block() above).
500 def p_opt_default_0(t
):
501 'opt_default : empty'
502 # no default specified: reuse the one currently at the top of the stack
503 defaultStack
.push(defaultStack
.top())
504 # no meaningful value returned
507 def p_opt_default_1(t
):
508 'opt_default : DEFAULT inst'
509 # push the new default
511 codeObj
.wrap_decode_block('\ndefault:\n', 'break;\n')
512 defaultStack
.push(codeObj
)
513 # no meaningful value returned
516 def p_decode_stmt_list_0(t
):
517 'decode_stmt_list : decode_stmt'
520 def p_decode_stmt_list_1(t
):
521 'decode_stmt_list : decode_stmt decode_stmt_list'
522 if (t
[1].has_decode_default
and t
[2].has_decode_default
):
523 error(t
.lexer
.lineno
, 'Two default cases in decode block')
527 # Decode statement rules
529 # There are four types of statements allowed in a decode block:
530 # 1. Format blocks 'format <foo> { ... }'
531 # 2. Nested decode blocks
532 # 3. Instruction definitions.
533 # 4. C preprocessor directives.
536 # Preprocessor directives found in a decode statement list are passed
537 # through to the output, replicated to all of the output code
538 # streams. This works well for ifdefs, so we can ifdef out both the
539 # declarations and the decode cases generated by an instruction
540 # definition. Handling them as part of the grammar makes it easy to
541 # keep them in the right place with respect to the code generated by
542 # the other statements.
543 def p_decode_stmt_cpp(t
):
544 'decode_stmt : CPPDIRECTIVE'
545 t
[0] = GenCode(t
[1], t
[1], t
[1], t
[1])
547 # A format block 'format <foo> { ... }' sets the default instruction
548 # format used to handle instruction definitions inside the block.
549 # This format can be overridden by using an explicit format on the
550 # instruction definition or with a nested format block.
551 def p_decode_stmt_format(t
):
552 'decode_stmt : FORMAT push_format_id LBRACE decode_stmt_list RBRACE'
553 # The format will be pushed on the stack when 'push_format_id' is
554 # processed (see below). Once the parser has recognized the full
555 # production (though the right brace), we're done with the format,
556 # so now we can pop it.
560 # This rule exists so we can set the current format (& push the stack)
561 # when we recognize the format name part of the format block.
562 def p_push_format_id(t
):
563 'push_format_id : ID'
565 formatStack
.push(formatMap
[t
[1]])
566 t
[0] = ('', '// format %s' % t
[1])
568 error(t
.lexer
.lineno
, 'instruction format "%s" not defined.' % t
[1])
570 # Nested decode block: if the value of the current field matches the
571 # specified constant, do a nested decode on some other field.
572 def p_decode_stmt_decode(t
):
573 'decode_stmt : case_label COLON decode_block'
576 # just wrap the decoding code from the block as a case in the
577 # outer switch statement.
578 codeObj
.wrap_decode_block('\n%s:\n' % label
)
579 codeObj
.has_decode_default
= (label
== 'default')
582 # Instruction definition (finally!).
583 def p_decode_stmt_inst(t
):
584 'decode_stmt : case_label COLON inst SEMI'
587 codeObj
.wrap_decode_block('\n%s:' % label
, 'break;\n')
588 codeObj
.has_decode_default
= (label
== 'default')
591 # The case label is either a list of one or more constants or 'default'
592 def p_case_label_0(t
):
593 'case_label : intlit_list'
594 t
[0] = ': '.join(map(lambda a
: 'case %#x' % a
, t
[1]))
596 def p_case_label_1(t
):
597 'case_label : DEFAULT'
601 # The constant list for a decode case label must be non-empty, but may have
602 # one or more comma-separated integer literals in it.
604 def p_intlit_list_0(t
):
605 'intlit_list : INTLIT'
608 def p_intlit_list_1(t
):
609 'intlit_list : intlit_list COMMA INTLIT'
613 # Define an instruction using the current instruction format (specified
614 # by an enclosing format block).
615 # "<mnemonic>(<args>)"
617 'inst : ID LPAREN arg_list RPAREN'
618 # Pass the ID and arg list to the current format class to deal with.
619 currentFormat
= formatStack
.top()
620 codeObj
= currentFormat
.defineInst(t
[1], t
[3], t
.lexer
.lineno
)
621 args
= ','.join(map(str, t
[3]))
622 args
= re
.sub('(?m)^', '//', args
)
623 args
= re
.sub('^//', '', args
)
624 comment
= '\n// %s::%s(%s)\n' % (currentFormat
.id, t
[1], args
)
625 codeObj
.prepend_all(comment
)
628 # Define an instruction using an explicitly specified format:
629 # "<fmt>::<mnemonic>(<args>)"
631 'inst : ID DBLCOLON ID LPAREN arg_list RPAREN'
633 format
= formatMap
[t
[1]]
635 error(t
.lexer
.lineno
, 'instruction format "%s" not defined.' % t
[1])
636 codeObj
= format
.defineInst(t
[3], t
[5], t
.lexer
.lineno
)
637 comment
= '\n// %s::%s(%s)\n' % (t
[1], t
[3], t
[5])
638 codeObj
.prepend_all(comment
)
641 # The arg list generates a tuple, where the first element is a list of
642 # the positional args and the second element is a dict containing the
645 'arg_list : positional_arg_list COMMA keyword_arg_list'
646 t
[0] = ( t
[1], t
[3] )
649 'arg_list : positional_arg_list'
653 'arg_list : keyword_arg_list'
656 def p_positional_arg_list_0(t
):
657 'positional_arg_list : empty'
660 def p_positional_arg_list_1(t
):
661 'positional_arg_list : expr'
664 def p_positional_arg_list_2(t
):
665 'positional_arg_list : positional_arg_list COMMA expr'
668 def p_keyword_arg_list_0(t
):
669 'keyword_arg_list : keyword_arg'
672 def p_keyword_arg_list_1(t
):
673 'keyword_arg_list : keyword_arg_list COMMA keyword_arg'
677 def p_keyword_arg(t
):
678 'keyword_arg : ID EQUALS expr'
679 t
[0] = { t
[1] : t
[3] }
682 # Basic expressions. These constitute the argument values of
683 # "function calls" (i.e. instruction definitions in the decode block)
684 # and default values for formal parameters of format functions.
686 # Right now, these are either strings, integers, or (recursively)
687 # lists of exprs (using Python square-bracket list syntax). Note that
688 # bare identifiers are trated as string constants here (since there
689 # isn't really a variable namespace to refer to).
699 '''expr : LBRACKET list_expr RBRACKET'''
702 def p_list_expr_0(t
):
706 def p_list_expr_1(t
):
707 'list_expr : list_expr COMMA expr'
710 def p_list_expr_2(t
):
715 # Empty production... use in other rules for readability.
721 # Parse error handler. Note that the argument here is the offending
722 # *token*, not a grammar symbol (hence the need to use t.value)
725 error(t
.lexer
.lineno
, "syntax error at '%s'" % t
.value
)
727 error(0, "unknown syntax error", True)
729 # END OF GRAMMAR RULES
731 # Now build the parser.
735 #####################################################################
739 #####################################################################
741 # Expand template with CPU-specific references into a dictionary with
742 # an entry for each CPU model name. The entry key is the model name
743 # and the corresponding value is the template with the CPU-specific
744 # refs substituted for that model.
745 def expand_cpu_symbols_to_dict(template
):
746 # Protect '%'s that don't go with CPU-specific terms
747 t
= re
.sub(r
'%(?!\(CPU_)', '%%', template
)
749 for cpu
in cpu_models
:
750 result
[cpu
.name
] = t
% cpu
.strings
753 # *If* the template has CPU-specific references, return a single
754 # string containing a copy of the template for each CPU model with the
755 # corresponding values substituted in. If the template has no
756 # CPU-specific references, it is returned unmodified.
757 def expand_cpu_symbols_to_string(template
):
758 if template
.find('%(CPU_') != -1:
759 return reduce(lambda x
,y
: x
+y
,
760 expand_cpu_symbols_to_dict(template
).values())
764 # Protect CPU-specific references by doubling the corresponding '%'s
765 # (in preparation for substituting a different set of references into
767 def protect_cpu_symbols(template
):
768 return re
.sub(r
'%(?=\(CPU_)', '%%', template
)
773 # The GenCode class encapsulates generated code destined for various
774 # output files. The header_output and decoder_output attributes are
775 # strings containing code destined for decoder.hh and decoder.cc
776 # respectively. The decode_block attribute contains code to be
777 # incorporated in the decode function itself (that will also end up in
778 # decoder.cc). The exec_output attribute is a dictionary with a key
779 # for each CPU model name; the value associated with a particular key
780 # is the string of code for that CPU model's exec.cc file. The
781 # has_decode_default attribute is used in the decode block to allow
782 # explicit default clauses to override default default clauses.
785 # Constructor. At this point we substitute out all CPU-specific
786 # symbols. For the exec output, these go into the per-model
787 # dictionary. For all other output types they get collapsed into
790 header_output
= '', decoder_output
= '', exec_output
= '',
791 decode_block
= '', has_decode_default
= False):
792 self
.header_output
= expand_cpu_symbols_to_string(header_output
)
793 self
.decoder_output
= expand_cpu_symbols_to_string(decoder_output
)
794 if isinstance(exec_output
, dict):
795 self
.exec_output
= exec_output
796 elif isinstance(exec_output
, str):
797 # If the exec_output arg is a single string, we replicate
798 # it for each of the CPU models, substituting and
799 # %(CPU_foo)s params appropriately.
800 self
.exec_output
= expand_cpu_symbols_to_dict(exec_output
)
801 self
.decode_block
= expand_cpu_symbols_to_string(decode_block
)
802 self
.has_decode_default
= has_decode_default
804 # Override '+' operator: generate a new GenCode object that
805 # concatenates all the individual strings in the operands.
806 def __add__(self
, other
):
808 for cpu
in cpu_models
:
810 exec_output
[n
] = self
.exec_output
[n
] + other
.exec_output
[n
]
811 return GenCode(self
.header_output
+ other
.header_output
,
812 self
.decoder_output
+ other
.decoder_output
,
814 self
.decode_block
+ other
.decode_block
,
815 self
.has_decode_default
or other
.has_decode_default
)
817 # Prepend a string (typically a comment) to all the strings.
818 def prepend_all(self
, pre
):
819 self
.header_output
= pre
+ self
.header_output
820 self
.decoder_output
= pre
+ self
.decoder_output
821 self
.decode_block
= pre
+ self
.decode_block
822 for cpu
in cpu_models
:
823 self
.exec_output
[cpu
.name
] = pre
+ self
.exec_output
[cpu
.name
]
825 # Wrap the decode block in a pair of strings (e.g., 'case foo:'
826 # and 'break;'). Used to build the big nested switch statement.
827 def wrap_decode_block(self
, pre
, post
= ''):
828 self
.decode_block
= pre
+ indent(self
.decode_block
) + post
833 # A format object encapsulates an instruction format. It must provide
834 # a defineInst() method that generates the code for an instruction
837 exportContextSymbols
= ('InstObjParams', 'makeList', 're', 'string')
841 def updateExportContext():
842 exportContext
.update(exportDict(*exportContextSymbols
))
843 exportContext
.update(templateMap
)
845 def exportDict(*symNames
):
846 return dict([(s
, eval(s
)) for s
in symNames
])
850 def __init__(self
, id, params
, code
):
851 # constructor: just save away arguments
854 label
= 'def format ' + id
855 self
.user_code
= compile(fixPythonIndentation(code
), label
, 'exec')
856 param_list
= string
.join(params
, ", ")
857 f
= '''def defInst(_code, _context, %s):
858 my_locals = vars().copy()
859 exec _code in _context, my_locals
860 return my_locals\n''' % param_list
861 c
= compile(f
, label
+ ' wrapper', 'exec')
865 def defineInst(self
, name
, args
, lineno
):
867 updateExportContext()
868 context
.update(exportContext
)
870 Name
= name
[0].upper()
873 context
.update({ 'name': name
, 'Name': Name
})
875 vars = self
.func(self
.user_code
, context
, *args
[0], **args
[1])
876 except Exception, exc
:
877 error(lineno
, 'error defining "%s": %s.' % (name
, exc
))
878 for k
in vars.keys():
879 if k
not in ('header_output', 'decoder_output',
880 'exec_output', 'decode_block'):
882 return GenCode(**vars)
884 # Special null format to catch an implicit-format instruction
885 # definition outside of any format block.
888 self
.defaultInst
= ''
890 def defineInst(self
, name
, args
, lineno
):
892 'instruction definition "%s" with no active format!' % name
)
894 # This dictionary maps format name strings to Format objects.
897 # Define a new format
898 def defFormat(id, params
, code
, lineno
):
899 # make sure we haven't already defined this one
900 if formatMap
.get(id, None) != None:
901 error(lineno
, 'format %s redefined.' % id)
902 # create new object and store in global map
903 formatMap
[id] = Format(id, params
, code
)
907 # Stack: a simple stack object. Used for both formats (formatStack)
908 # and default cases (defaultStack). Simply wraps a list to give more
909 # stack-like syntax and enable initialization with an argument list
910 # (as opposed to an argument that's a list).
913 def __init__(self
, *items
):
914 list.__init
__(self
, items
)
916 def push(self
, item
):
922 # The global format stack.
923 formatStack
= Stack(NoFormat())
925 # The global default case stack.
926 defaultStack
= Stack( None )
928 # Global stack that tracks current file and line number.
929 # Each element is a tuple (filename, lineno) that records the
930 # *current* filename and the line number in the *previous* file where
932 fileNameStack
= Stack()
938 # Indent every line in string 's' by two spaces
939 # (except preprocessor directives).
940 # Used to make nested code blocks look pretty.
943 return re
.sub(r
'(?m)^(?!#)', ' ', s
)
946 # Munge a somewhat arbitrarily formatted piece of Python code
947 # (e.g. from a format 'let' block) into something whose indentation
948 # will get by the Python parser.
950 # The two keys here are that Python will give a syntax error if
951 # there's any whitespace at the beginning of the first line, and that
952 # all lines at the same lexical nesting level must have identical
953 # indentation. Unfortunately the way code literals work, an entire
954 # let block tends to have some initial indentation. Rather than
955 # trying to figure out what that is and strip it off, we prepend 'if
956 # 1:' to make the let code the nested block inside the if (and have
957 # the parser automatically deal with the indentation for us).
959 # We don't want to do this if (1) the code block is empty or (2) the
960 # first line of the block doesn't have any whitespace at the front.
962 def fixPythonIndentation(s
):
963 # get rid of blank lines first
964 s
= re
.sub(r
'(?m)^\s*\n', '', s
);
965 if (s
!= '' and re
.match(r
'[ \t]', s
[0])):
969 # Error handler. Just call exit. Output formatted to work under
970 # Emacs compile-mode. Optional 'print_traceback' arg, if set to True,
971 # prints a Python stack backtrace too (can be handy when trying to
972 # debug the parser itself).
973 def error(lineno
, string
, print_traceback
= False):
975 for (filename
, line
) in fileNameStack
[0:-1]:
976 print spaces
+ "In file included from " + filename
+ ":"
978 # Print a Python stack backtrace if requested.
979 if (print_traceback
):
980 traceback
.print_exc()
982 line_str
= "%d:" % lineno
985 sys
.exit(spaces
+ "%s:%s %s" % (fileNameStack
[-1][0], line_str
, string
))
988 #####################################################################
990 # Bitfield Operator Support
992 #####################################################################
994 bitOp1ArgRE
= re
.compile(r
'<\s*(\w+)\s*:\s*>')
996 bitOpWordRE
= re
.compile(r
'(?<![\w\.])([\w\.]+)<\s*(\w+)\s*:\s*(\w+)\s*>')
997 bitOpExprRE
= re
.compile(r
'\)<\s*(\w+)\s*:\s*(\w+)\s*>')
999 def substBitOps(code
):
1000 # first convert single-bit selectors to two-index form
1001 # i.e., <n> --> <n:n>
1002 code
= bitOp1ArgRE
.sub(r
'<\1:\1>', code
)
1003 # simple case: selector applied to ID (name)
1004 # i.e., foo<a:b> --> bits(foo, a, b)
1005 code
= bitOpWordRE
.sub(r
'bits(\1, \2, \3)', code
)
1006 # if selector is applied to expression (ending in ')'),
1007 # we need to search backward for matching '('
1008 match
= bitOpExprRE
.search(code
)
1010 exprEnd
= match
.start()
1013 while nestLevel
> 0:
1014 if code
[here
] == '(':
1016 elif code
[here
] == ')':
1020 sys
.exit("Didn't find '('!")
1022 newExpr
= r
'bits(%s, %s, %s)' % (code
[exprStart
:exprEnd
+1],
1023 match
.group(1), match
.group(2))
1024 code
= code
[:exprStart
] + newExpr
+ code
[match
.end():]
1025 match
= bitOpExprRE
.search(code
)
1029 ####################
1032 # Template objects are format strings that allow substitution from
1033 # the attribute spaces of other objects (e.g. InstObjParams instances).
1035 labelRE
= re
.compile(r
'(?<!%)%\(([^\)]+)\)[sd]')
1038 def __init__(self
, t
):
1044 # Protect non-Python-dict substitutions (e.g. if there's a printf
1045 # in the templated C++ code)
1046 template
= protect_non_subst_percents(self
.template
)
1047 # CPU-model-specific substitutions are handled later (in GenCode).
1048 template
= protect_cpu_symbols(template
)
1050 # Build a dict ('myDict') to use for the template substitution.
1051 # Start with the template namespace. Make a copy since we're
1052 # going to modify it.
1053 myDict
= templateMap
.copy()
1055 if isinstance(d
, InstObjParams
):
1056 # If we're dealing with an InstObjParams object, we need
1057 # to be a little more sophisticated. The instruction-wide
1058 # parameters are already formed, but the parameters which
1059 # are only function wide still need to be generated.
1062 myDict
.update(d
.__dict
__)
1063 # The "operands" and "snippets" attributes of the InstObjParams
1064 # objects are for internal use and not substitution.
1065 del myDict
['operands']
1066 del myDict
['snippets']
1068 snippetLabels
= [l
for l
in labelRE
.findall(template
)
1069 if d
.snippets
.has_key(l
)]
1071 snippets
= dict([(s
, mungeSnippet(d
.snippets
[s
]))
1072 for s
in snippetLabels
])
1074 myDict
.update(snippets
)
1076 compositeCode
= ' '.join(map(str, snippets
.values()))
1078 # Add in template itself in case it references any
1079 # operands explicitly (like Mem)
1080 compositeCode
+= ' ' + template
1082 operands
= SubOperandList(compositeCode
, d
.operands
)
1084 myDict
['op_decl'] = operands
.concatAttrStrings('op_decl')
1086 is_src
= lambda op
: op
.is_src
1087 is_dest
= lambda op
: op
.is_dest
1089 myDict
['op_src_decl'] = \
1090 operands
.concatSomeAttrStrings(is_src
, 'op_src_decl')
1091 myDict
['op_dest_decl'] = \
1092 operands
.concatSomeAttrStrings(is_dest
, 'op_dest_decl')
1094 myDict
['op_rd'] = operands
.concatAttrStrings('op_rd')
1095 myDict
['op_wb'] = operands
.concatAttrStrings('op_wb')
1097 if d
.operands
.memOperand
:
1098 myDict
['mem_acc_size'] = d
.operands
.memOperand
.mem_acc_size
1099 myDict
['mem_acc_type'] = d
.operands
.memOperand
.mem_acc_type
1101 elif isinstance(d
, dict):
1102 # if the argument is a dictionary, we just use it.
1104 elif hasattr(d
, '__dict__'):
1105 # if the argument is an object, we use its attribute map.
1106 myDict
.update(d
.__dict
__)
1108 raise TypeError, "Template.subst() arg must be or have dictionary"
1109 return template
% myDict
1111 # Convert to string. This handles the case when a template with a
1112 # CPU-specific term gets interpolated into another template or into
1115 return expand_cpu_symbols_to_string(self
.template
)
1117 #####################################################################
1121 # The remaining code is the support for automatically extracting
1122 # instruction characteristics from pseudocode.
1124 #####################################################################
1126 # Force the argument to be a list. Useful for flags, where a caller
1127 # can specify a singleton flag or a list of flags. Also usful for
1128 # converting tuples to lists so they can be modified.
1130 if isinstance(arg
, list):
1132 elif isinstance(arg
, tuple):
1139 # Generate operandTypeMap from the user's 'def operand_types'
1141 def buildOperandTypeMap(userDict
, lineno
):
1142 global operandTypeMap
1144 for (ext
, (desc
, size
)) in userDict
.iteritems():
1145 if desc
== 'signed int':
1146 ctype
= 'int%d_t' % size
1148 elif desc
== 'unsigned int':
1149 ctype
= 'uint%d_t' % size
1151 elif desc
== 'float':
1152 is_signed
= 1 # shouldn't really matter
1157 elif desc
== 'twin64 int':
1160 elif desc
== 'twin32 int':
1164 error(lineno
, 'Unrecognized type description "%s" in userDict')
1165 operandTypeMap
[ext
] = (size
, ctype
, is_signed
)
1170 # Base class for operand descriptors. An instance of this class (or
1171 # actually a class derived from this one) represents a specific
1172 # operand for a code block (e.g, "Rc.sq" as a dest). Intermediate
1173 # derived classes encapsulates the traits of a particular operand type
1174 # (e.g., "32-bit integer register").
1176 class Operand(object):
1177 def __init__(self
, full_name
, ext
, is_src
, is_dest
):
1178 self
.full_name
= full_name
1180 self
.is_src
= is_src
1181 self
.is_dest
= is_dest
1182 # The 'effective extension' (eff_ext) is either the actual
1183 # extension, if one was explicitly provided, or the default.
1187 self
.eff_ext
= self
.dflt_ext
1189 (self
.size
, self
.ctype
, self
.is_signed
) = operandTypeMap
[self
.eff_ext
]
1191 # note that mem_acc_size is undefined for non-mem operands...
1192 # template must be careful not to use it if it doesn't apply.
1194 self
.mem_acc_size
= self
.makeAccSize()
1195 if self
.ctype
in ['Twin32_t', 'Twin64_t']:
1196 self
.mem_acc_type
= 'Twin'
1198 self
.mem_acc_type
= 'uint'
1200 # Finalize additional fields (primarily code fields). This step
1201 # is done separately since some of these fields may depend on the
1202 # register index enumeration that hasn't been performed yet at the
1203 # time of __init__().
1205 self
.flags
= self
.getFlags()
1206 self
.constructor
= self
.makeConstructor()
1207 self
.op_decl
= self
.makeDecl()
1210 self
.op_rd
= self
.makeRead()
1211 self
.op_src_decl
= self
.makeDecl()
1214 self
.op_src_decl
= ''
1217 self
.op_wb
= self
.makeWrite()
1218 self
.op_dest_decl
= self
.makeDecl()
1221 self
.op_dest_decl
= ''
1229 def isFloatReg(self
):
1235 def isControlReg(self
):
1239 # note the empty slice '[:]' gives us a copy of self.flags[0]
1240 # instead of a reference to it
1241 my_flags
= self
.flags
[0][:]
1243 my_flags
+= self
.flags
[1]
1245 my_flags
+= self
.flags
[2]
1249 # Note that initializations in the declarations are solely
1250 # to avoid 'uninitialized variable' errors from the compiler.
1251 return self
.ctype
+ ' ' + self
.base_name
+ ' = 0;\n';
1253 class IntRegOperand(Operand
):
1260 def makeConstructor(self
):
1263 c
+= '\n\t_srcRegIdx[%d] = %s;' % \
1264 (self
.src_reg_idx
, self
.reg_spec
)
1266 c
+= '\n\t_destRegIdx[%d] = %s;' % \
1267 (self
.dest_reg_idx
, self
.reg_spec
)
1271 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1272 error(0, 'Attempt to read integer register as FP')
1273 if (self
.size
== self
.dflt_size
):
1274 return '%s = xc->readIntRegOperand(this, %d);\n' % \
1275 (self
.base_name
, self
.src_reg_idx
)
1276 elif (self
.size
> self
.dflt_size
):
1277 int_reg_val
= 'xc->readIntRegOperand(this, %d)' % \
1279 if (self
.is_signed
):
1280 int_reg_val
= 'sext<%d>(%s)' % (self
.dflt_size
, int_reg_val
)
1281 return '%s = %s;\n' % (self
.base_name
, int_reg_val
)
1283 return '%s = bits(xc->readIntRegOperand(this, %d), %d, 0);\n' % \
1284 (self
.base_name
, self
.src_reg_idx
, self
.size
-1)
1286 def makeWrite(self
):
1287 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1288 error(0, 'Attempt to write integer register as FP')
1289 if (self
.size
!= self
.dflt_size
and self
.is_signed
):
1290 final_val
= 'sext<%d>(%s)' % (self
.size
, self
.base_name
)
1292 final_val
= self
.base_name
1296 xc->setIntRegOperand(this, %d, final_val);\n
1297 if (traceData) { traceData->setData(final_val); }
1298 }''' % (self
.dflt_ctype
, final_val
, self
.dest_reg_idx
)
1301 class FloatRegOperand(Operand
):
1305 def isFloatReg(self
):
1308 def makeConstructor(self
):
1311 c
+= '\n\t_srcRegIdx[%d] = %s + FP_Base_DepTag;' % \
1312 (self
.src_reg_idx
, self
.reg_spec
)
1314 c
+= '\n\t_destRegIdx[%d] = %s + FP_Base_DepTag;' % \
1315 (self
.dest_reg_idx
, self
.reg_spec
)
1321 if (self
.ctype
== 'float'):
1322 func
= 'readFloatRegOperand'
1324 elif (self
.ctype
== 'double'):
1325 func
= 'readFloatRegOperand'
1328 func
= 'readFloatRegOperandBits'
1329 if (self
.ctype
== 'uint32_t'):
1331 elif (self
.ctype
== 'uint64_t'):
1333 if (self
.size
!= self
.dflt_size
):
1336 base
= 'xc->%s(this, %d, %d)' % \
1337 (func
, self
.src_reg_idx
, width
)
1339 base
= 'xc->%s(this, %d)' % \
1340 (func
, self
.src_reg_idx
)
1342 return '%s = bits(%s, %d, 0);\n' % \
1343 (self
.base_name
, base
, self
.size
-1)
1345 return '%s = %s;\n' % (self
.base_name
, base
)
1347 def makeWrite(self
):
1348 final_val
= self
.base_name
1349 final_ctype
= self
.ctype
1352 if (self
.ctype
== 'float'):
1354 func
= 'setFloatRegOperand'
1355 elif (self
.ctype
== 'double'):
1357 func
= 'setFloatRegOperand'
1358 elif (self
.ctype
== 'uint32_t'):
1359 func
= 'setFloatRegOperandBits'
1361 elif (self
.ctype
== 'uint64_t'):
1362 func
= 'setFloatRegOperandBits'
1365 func
= 'setFloatRegOperandBits'
1366 final_ctype
= 'uint%d_t' % self
.dflt_size
1367 if (self
.size
!= self
.dflt_size
and self
.is_signed
):
1368 final_val
= 'sext<%d>(%s)' % (self
.size
, self
.base_name
)
1370 widthSpecifier
= ', %d' % width
1374 xc->%s(this, %d, final_val%s);\n
1375 if (traceData) { traceData->setData(final_val); }
1376 }''' % (final_ctype
, final_val
, func
, self
.dest_reg_idx
,
1380 class ControlRegOperand(Operand
):
1384 def isControlReg(self
):
1387 def makeConstructor(self
):
1390 c
+= '\n\t_srcRegIdx[%d] = %s + Ctrl_Base_DepTag;' % \
1391 (self
.src_reg_idx
, self
.reg_spec
)
1393 c
+= '\n\t_destRegIdx[%d] = %s + Ctrl_Base_DepTag;' % \
1394 (self
.dest_reg_idx
, self
.reg_spec
)
1399 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1400 error(0, 'Attempt to read control register as FP')
1401 base
= 'xc->readMiscRegOperand(this, %s)' % self
.src_reg_idx
1402 if self
.size
== self
.dflt_size
:
1403 return '%s = %s;\n' % (self
.base_name
, base
)
1405 return '%s = bits(%s, %d, 0);\n' % \
1406 (self
.base_name
, base
, self
.size
-1)
1408 def makeWrite(self
):
1409 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1410 error(0, 'Attempt to write control register as FP')
1411 wb
= 'xc->setMiscRegOperand(this, %s, %s);\n' % \
1412 (self
.dest_reg_idx
, self
.base_name
)
1413 wb
+= 'if (traceData) { traceData->setData(%s); }' % \
1417 class ControlBitfieldOperand(ControlRegOperand
):
1420 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1421 error(0, 'Attempt to read control register as FP')
1422 base
= 'xc->readMiscReg(%s)' % self
.reg_spec
1423 name
= self
.base_name
1424 return '%s = bits(%s, %s_HI, %s_LO);' % \
1425 (name
, base
, name
, name
)
1427 def makeWrite(self
):
1428 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1429 error(0, 'Attempt to write control register as FP')
1430 base
= 'xc->readMiscReg(%s)' % self
.reg_spec
1431 name
= self
.base_name
1432 wb_val
= 'insertBits(%s, %s_HI, %s_LO, %s)' % \
1433 (base
, name
, name
, self
.base_name
)
1434 wb
= 'xc->setMiscRegOperand(this, %s, %s );\n' % (self
.dest_reg_idx
, wb_val
)
1435 wb
+= 'if (traceData) { traceData->setData(%s); }' % \
1439 class MemOperand(Operand
):
1443 def makeConstructor(self
):
1447 # Note that initializations in the declarations are solely
1448 # to avoid 'uninitialized variable' errors from the compiler.
1449 # Declare memory data variable.
1450 if self
.ctype
in ['Twin32_t','Twin64_t']:
1451 return "%s %s; %s.a = 0; %s.b = 0;\n" % (self
.ctype
, self
.base_name
,
1452 self
.base_name
, self
.base_name
)
1453 c
= '%s %s = 0;\n' % (self
.ctype
, self
.base_name
)
1459 def makeWrite(self
):
1462 # Return the memory access size *in bits*, suitable for
1463 # forming a type via "uint%d_t". Divide by 8 if you want bytes.
1464 def makeAccSize(self
):
1468 class NPCOperand(Operand
):
1469 def makeConstructor(self
):
1473 return '%s = xc->readNextPC();\n' % self
.base_name
1475 def makeWrite(self
):
1476 return 'xc->setNextPC(%s);\n' % self
.base_name
1478 class NNPCOperand(Operand
):
1479 def makeConstructor(self
):
1483 return '%s = xc->readNextNPC();\n' % self
.base_name
1485 def makeWrite(self
):
1486 return 'xc->setNextNPC(%s);\n' % self
.base_name
1488 def buildOperandNameMap(userDict
, lineno
):
1489 global operandNameMap
1491 for (op_name
, val
) in userDict
.iteritems():
1492 (base_cls_name
, dflt_ext
, reg_spec
, flags
, sort_pri
) = val
1493 (dflt_size
, dflt_ctype
, dflt_is_signed
) = operandTypeMap
[dflt_ext
]
1494 # Canonical flag structure is a triple of lists, where each list
1495 # indicates the set of flags implied by this operand always, when
1496 # used as a source, and when used as a dest, respectively.
1497 # For simplicity this can be initialized using a variety of fairly
1498 # obvious shortcuts; we convert these to canonical form here.
1500 # no flags specified (e.g., 'None')
1501 flags
= ( [], [], [] )
1502 elif isinstance(flags
, str):
1503 # a single flag: assumed to be unconditional
1504 flags
= ( [ flags
], [], [] )
1505 elif isinstance(flags
, list):
1506 # a list of flags: also assumed to be unconditional
1507 flags
= ( flags
, [], [] )
1508 elif isinstance(flags
, tuple):
1509 # it's a tuple: it should be a triple,
1510 # but each item could be a single string or a list
1511 (uncond_flags
, src_flags
, dest_flags
) = flags
1512 flags
= (makeList(uncond_flags
),
1513 makeList(src_flags
), makeList(dest_flags
))
1514 # Accumulate attributes of new operand class in tmp_dict
1516 for attr
in ('dflt_ext', 'reg_spec', 'flags', 'sort_pri',
1517 'dflt_size', 'dflt_ctype', 'dflt_is_signed'):
1518 tmp_dict
[attr
] = eval(attr
)
1519 tmp_dict
['base_name'] = op_name
1520 # New class name will be e.g. "IntReg_Ra"
1521 cls_name
= base_cls_name
+ '_' + op_name
1522 # Evaluate string arg to get class object. Note that the
1523 # actual base class for "IntReg" is "IntRegOperand", i.e. we
1524 # have to append "Operand".
1526 base_cls
= eval(base_cls_name
+ 'Operand')
1529 'error: unknown operand base class "%s"' % base_cls_name
)
1530 # The following statement creates a new class called
1531 # <cls_name> as a subclass of <base_cls> with the attributes
1532 # in tmp_dict, just as if we evaluated a class declaration.
1533 operandNameMap
[op_name
] = type(cls_name
, (base_cls
,), tmp_dict
)
1535 # Define operand variables.
1536 operands
= userDict
.keys()
1538 operandsREString
= (r
'''
1539 (?<![\w\.]) # neg. lookbehind assertion: prevent partial matches
1540 ((%s)(?:\.(\w+))?) # match: operand with optional '.' then suffix
1541 (?![\w\.]) # neg. lookahead assertion: prevent partial matches
1543 % string
.join(operands
, '|'))
1546 operandsRE
= re
.compile(operandsREString
, re
.MULTILINE|re
.VERBOSE
)
1548 # Same as operandsREString, but extension is mandatory, and only two
1549 # groups are returned (base and ext, not full name as above).
1550 # Used for subtituting '_' for '.' to make C++ identifiers.
1551 operandsWithExtREString
= (r
'(?<![\w\.])(%s)\.(\w+)(?![\w\.])'
1552 % string
.join(operands
, '|'))
1554 global operandsWithExtRE
1555 operandsWithExtRE
= re
.compile(operandsWithExtREString
, re
.MULTILINE
)
1560 # Find all the operands in the given code block. Returns an operand
1561 # descriptor list (instance of class OperandList).
1562 def __init__(self
, code
):
1565 # delete comments so we don't match on reg specifiers inside
1566 code
= commentRE
.sub('', code
)
1567 # search for operands
1570 match
= operandsRE
.search(code
, next_pos
)
1572 # no more matches: we're done
1575 # regexp groups are operand full name, base, and extension
1576 (op_full
, op_base
, op_ext
) = op
1577 # if the token following the operand is an assignment, this is
1578 # a destination (LHS), else it's a source (RHS)
1579 is_dest
= (assignRE
.match(code
, match
.end()) != None)
1580 is_src
= not is_dest
1581 # see if we've already seen this one
1582 op_desc
= self
.find_base(op_base
)
1584 if op_desc
.ext
!= op_ext
:
1585 error(0, 'Inconsistent extensions for operand %s' % \
1587 op_desc
.is_src
= op_desc
.is_src
or is_src
1588 op_desc
.is_dest
= op_desc
.is_dest
or is_dest
1590 # new operand: create new descriptor
1591 op_desc
= operandNameMap
[op_base
](op_full
, op_ext
,
1593 self
.append(op_desc
)
1594 # start next search after end of current match
1595 next_pos
= match
.end()
1597 # enumerate source & dest register operands... used in building
1600 self
.numDestRegs
= 0
1601 self
.numFPDestRegs
= 0
1602 self
.numIntDestRegs
= 0
1603 self
.memOperand
= None
1604 for op_desc
in self
.items
:
1607 op_desc
.src_reg_idx
= self
.numSrcRegs
1608 self
.numSrcRegs
+= 1
1610 op_desc
.dest_reg_idx
= self
.numDestRegs
1611 self
.numDestRegs
+= 1
1612 if op_desc
.isFloatReg():
1613 self
.numFPDestRegs
+= 1
1614 elif op_desc
.isIntReg():
1615 self
.numIntDestRegs
+= 1
1616 elif op_desc
.isMem():
1618 error(0, "Code block has more than one memory operand.")
1619 self
.memOperand
= op_desc
1620 # now make a final pass to finalize op_desc fields that may depend
1621 # on the register enumeration
1622 for op_desc
in self
.items
:
1626 return len(self
.items
)
1628 def __getitem__(self
, index
):
1629 return self
.items
[index
]
1631 def append(self
, op_desc
):
1632 self
.items
.append(op_desc
)
1633 self
.bases
[op_desc
.base_name
] = op_desc
1635 def find_base(self
, base_name
):
1636 # like self.bases[base_name], but returns None if not found
1637 # (rather than raising exception)
1638 return self
.bases
.get(base_name
)
1640 # internal helper function for concat[Some]Attr{Strings|Lists}
1641 def __internalConcatAttrs(self
, attr_name
, filter, result
):
1642 for op_desc
in self
.items
:
1644 result
+= getattr(op_desc
, attr_name
)
1647 # return a single string that is the concatenation of the (string)
1648 # values of the specified attribute for all operands
1649 def concatAttrStrings(self
, attr_name
):
1650 return self
.__internalConcatAttrs
(attr_name
, lambda x
: 1, '')
1652 # like concatAttrStrings, but only include the values for the operands
1653 # for which the provided filter function returns true
1654 def concatSomeAttrStrings(self
, filter, attr_name
):
1655 return self
.__internalConcatAttrs
(attr_name
, filter, '')
1657 # return a single list that is the concatenation of the (list)
1658 # values of the specified attribute for all operands
1659 def concatAttrLists(self
, attr_name
):
1660 return self
.__internalConcatAttrs
(attr_name
, lambda x
: 1, [])
1662 # like concatAttrLists, but only include the values for the operands
1663 # for which the provided filter function returns true
1664 def concatSomeAttrLists(self
, filter, attr_name
):
1665 return self
.__internalConcatAttrs
(attr_name
, filter, [])
1668 self
.items
.sort(lambda a
, b
: a
.sort_pri
- b
.sort_pri
)
1670 class SubOperandList(OperandList
):
1672 # Find all the operands in the given code block. Returns an operand
1673 # descriptor list (instance of class OperandList).
1674 def __init__(self
, code
, master_list
):
1677 # delete comments so we don't match on reg specifiers inside
1678 code
= commentRE
.sub('', code
)
1679 # search for operands
1682 match
= operandsRE
.search(code
, next_pos
)
1684 # no more matches: we're done
1687 # regexp groups are operand full name, base, and extension
1688 (op_full
, op_base
, op_ext
) = op
1689 # find this op in the master list
1690 op_desc
= master_list
.find_base(op_base
)
1692 error(0, 'Found operand %s which is not in the master list!' \
1693 ' This is an internal error' % \
1696 # See if we've already found this operand
1697 op_desc
= self
.find_base(op_base
)
1699 # if not, add a reference to it to this sub list
1700 self
.append(master_list
.bases
[op_base
])
1702 # start next search after end of current match
1703 next_pos
= match
.end()
1705 self
.memOperand
= None
1706 for op_desc
in self
.items
:
1709 error(0, "Code block has more than one memory operand.")
1710 self
.memOperand
= op_desc
1712 # Regular expression object to match C++ comments
1713 # (used in findOperands())
1714 commentRE
= re
.compile(r
'//.*\n')
1716 # Regular expression object to match assignment statements
1717 # (used in findOperands())
1718 assignRE
= re
.compile(r
'\s*=(?!=)', re
.MULTILINE
)
1720 # Munge operand names in code string to make legal C++ variable names.
1721 # This means getting rid of the type extension if any.
1722 # (Will match base_name attribute of Operand object.)
1723 def substMungedOpNames(code
):
1724 return operandsWithExtRE
.sub(r
'\1', code
)
1726 # Fix up code snippets for final substitution in templates.
1727 def mungeSnippet(s
):
1728 if isinstance(s
, str):
1729 return substMungedOpNames(substBitOps(s
))
1733 def makeFlagConstructor(flag_list
):
1734 if len(flag_list
) == 0:
1736 # filter out repeated flags
1739 while i
< len(flag_list
):
1740 if flag_list
[i
] == flag_list
[i
-1]:
1746 code
= pre
+ string
.join(flag_list
, post
+ pre
) + post
1749 # Assume all instruction flags are of the form 'IsFoo'
1750 instFlagRE
= re
.compile(r
'Is.*')
1752 # OpClass constants end in 'Op' except No_OpClass
1753 opClassRE
= re
.compile(r
'.*Op|No_OpClass')
1755 class InstObjParams
:
1756 def __init__(self
, mnem
, class_name
, base_class
= '',
1757 snippets
= {}, opt_args
= []):
1758 self
.mnemonic
= mnem
1759 self
.class_name
= class_name
1760 self
.base_class
= base_class
1761 if not isinstance(snippets
, dict):
1762 snippets
= {'code' : snippets
}
1763 compositeCode
= ' '.join(map(str, snippets
.values()))
1764 self
.snippets
= snippets
1766 self
.operands
= OperandList(compositeCode
)
1767 self
.constructor
= self
.operands
.concatAttrStrings('constructor')
1768 self
.constructor
+= \
1769 '\n\t_numSrcRegs = %d;' % self
.operands
.numSrcRegs
1770 self
.constructor
+= \
1771 '\n\t_numDestRegs = %d;' % self
.operands
.numDestRegs
1772 self
.constructor
+= \
1773 '\n\t_numFPDestRegs = %d;' % self
.operands
.numFPDestRegs
1774 self
.constructor
+= \
1775 '\n\t_numIntDestRegs = %d;' % self
.operands
.numIntDestRegs
1776 self
.flags
= self
.operands
.concatAttrLists('flags')
1778 # Make a basic guess on the operand class (function unit type).
1779 # These are good enough for most cases, and can be overridden
1781 if 'IsStore' in self
.flags
:
1782 self
.op_class
= 'MemWriteOp'
1783 elif 'IsLoad' in self
.flags
or 'IsPrefetch' in self
.flags
:
1784 self
.op_class
= 'MemReadOp'
1785 elif 'IsFloating' in self
.flags
:
1786 self
.op_class
= 'FloatAddOp'
1788 self
.op_class
= 'IntAluOp'
1790 # Optional arguments are assumed to be either StaticInst flags
1791 # or an OpClass value. To avoid having to import a complete
1792 # list of these values to match against, we do it ad-hoc
1795 if instFlagRE
.match(oa
):
1796 self
.flags
.append(oa
)
1797 elif opClassRE
.match(oa
):
1800 error(0, 'InstObjParams: optional arg "%s" not recognized '
1801 'as StaticInst::Flag or OpClass.' % oa
)
1803 # add flag initialization to contructor here to include
1804 # any flags added via opt_args
1805 self
.constructor
+= makeFlagConstructor(self
.flags
)
1807 # if 'IsFloating' is set, add call to the FP enable check
1808 # function (which should be provided by isa_desc via a declare)
1809 if 'IsFloating' in self
.flags
:
1810 self
.fp_enable_check
= 'fault = checkFpEnableFault(xc);'
1812 self
.fp_enable_check
= ''
1814 #######################
1816 # Output file template
1821 * DO NOT EDIT THIS FILE!!!
1823 * It was automatically generated from the ISA description in %(filename)s
1830 namespace %(namespace)s {
1832 %(namespace_output)s
1834 } // namespace %(namespace)s
1840 # Update the output file only if the new contents are different from
1841 # the current contents. Minimizes the files that need to be rebuilt
1842 # after minor changes.
1843 def update_if_needed(file, contents
):
1845 if os
.access(file, os
.R_OK
):
1847 old_contents
= f
.read()
1849 if contents
!= old_contents
:
1850 print 'Updating', file
1851 os
.remove(file) # in case it's write-protected
1854 print 'File', file, 'is unchanged'
1856 print 'Generating', file
1863 # This regular expression matches '##include' directives
1864 includeRE
= re
.compile(r
'^\s*##include\s+"(?P<filename>[\w/.-]*)".*$',
1867 # Function to replace a matched '##include' directive with the
1868 # contents of the specified file (with nested ##includes replaced
1869 # recursively). 'matchobj' is an re match object (from a match of
1870 # includeRE) and 'dirname' is the directory relative to which the file
1871 # path should be resolved.
1872 def replace_include(matchobj
, dirname
):
1873 fname
= matchobj
.group('filename')
1874 full_fname
= os
.path
.normpath(os
.path
.join(dirname
, fname
))
1875 contents
= '##newfile "%s"\n%s\n##endfile\n' % \
1876 (full_fname
, read_and_flatten(full_fname
))
1879 # Read a file and recursively flatten nested '##include' files.
1880 def read_and_flatten(filename
):
1881 current_dir
= os
.path
.dirname(filename
)
1883 contents
= open(filename
).read()
1885 error(0, 'Error including file "%s"' % filename
)
1886 fileNameStack
.push((filename
, 0))
1887 # Find any includes and include them
1888 contents
= includeRE
.sub(lambda m
: replace_include(m
, current_dir
),
1894 # Read in and parse the ISA description.
1896 def parse_isa_desc(isa_desc_file
, output_dir
):
1897 # Read file and (recursively) all included files into a string.
1898 # PLY requires that the input be in a single string so we have to
1900 isa_desc
= read_and_flatten(isa_desc_file
)
1902 # Initialize filename stack with outer file.
1903 fileNameStack
.push((isa_desc_file
, 0))
1906 (isa_name
, namespace
, global_code
, namespace_code
) = \
1907 parser
.parse(isa_desc
, lexer
=lexer
)
1909 # grab the last three path components of isa_desc_file to put in
1911 filename
= '/'.join(isa_desc_file
.split('/')[-3:])
1913 # generate decoder.hh
1914 includes
= '#include "base/bitfield.hh" // for bitfield support'
1915 global_output
= global_code
.header_output
1916 namespace_output
= namespace_code
.header_output
1917 decode_function
= ''
1918 update_if_needed(output_dir
+ '/decoder.hh', file_template
% vars())
1920 # generate decoder.cc
1921 includes
= '#include "decoder.hh"'
1922 global_output
= global_code
.decoder_output
1923 namespace_output
= namespace_code
.decoder_output
1924 # namespace_output += namespace_code.decode_block
1925 decode_function
= namespace_code
.decode_block
1926 update_if_needed(output_dir
+ '/decoder.cc', file_template
% vars())
1928 # generate per-cpu exec files
1929 for cpu
in cpu_models
:
1930 includes
= '#include "decoder.hh"\n'
1931 includes
+= cpu
.includes
1932 global_output
= global_code
.exec_output
[cpu
.name
]
1933 namespace_output
= namespace_code
.exec_output
[cpu
.name
]
1934 decode_function
= ''
1935 update_if_needed(output_dir
+ '/' + cpu
.filename
,
1936 file_template
% vars())
1938 # global list of CpuModel objects (see cpu_models.py)
1941 # Called as script: get args from command line.
1942 # Args are: <path to cpu_models.py> <isa desc file> <output dir> <cpu models>
1943 if __name__
== '__main__':
1944 execfile(sys
.argv
[1]) # read in CpuModel definitions
1945 cpu_models
= [CpuModel
.dict[cpu
] for cpu
in sys
.argv
[4:]]
1946 parse_isa_desc(sys
.argv
[2], sys
.argv
[3])