5 # Copyright (c) 2003 The Regents of The University of Michigan
8 # Redistribution and use in source and binary forms, with or without
9 # modification, are permitted provided that the following conditions are
10 # met: redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer;
12 # redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in the
14 # documentation and/or other materials provided with the distribution;
15 # neither the name of the copyright holders nor the names of its
16 # contributors may be used to endorse or promote products derived from
17 # this software without specific prior written permission.
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 # Prepend the directory where the PLY lex & yacc modules are found
40 # to the search path. Assumes we're compiling in a subdirectory
41 # of 'build' in the current tree.
42 sys
.path
[0:0] = [os
.environ
['M5_EXT'] + '/ply']
47 #####################################################################
51 # The PLY lexer module takes two things as input:
52 # - A list of token names (the string list 'tokens')
53 # - A regular expression describing a match for each token. The
54 # regexp for token FOO can be provided in two ways:
55 # - as a string variable named t_FOO
56 # - as the doc string for a function named t_FOO. In this case,
57 # the function is also executed, allowing an action to be
58 # associated with each token match.
60 #####################################################################
62 # Reserved words. These are listed separately as they are matched
63 # using the same regexp as generic IDs, but distinguished in the
64 # t_ID() function. The PLY documentation suggests this approach.
66 'BITFIELD', 'DECODE', 'DECODER', 'DEFAULT', 'DEF', 'EXEC', 'FORMAT',
67 'HEADER', 'LET', 'NAMESPACE', 'OPERAND_TYPES', 'OPERANDS',
68 'OUTPUT', 'SIGNED', 'TEMPLATE'
71 # List of tokens. The lex module requires this.
85 # ( ) [ ] { } < > , ; : :: *
87 # not used any more... commented out to suppress PLY warning
88 # 'LBRACKET', 'RBRACKET',
91 'COMMA', 'SEMI', 'COLON', 'DBLCOLON',
94 # C preprocessor directives
98 # Regular expressions for token matching
101 # not used any more... commented out to suppress PLY warning
114 # Identifiers and reserved words
117 reserved_map
[r
.lower()] = r
121 t
.type = reserved_map
.get(t
.value
,'ID')
126 r
'(0x[\da-fA-F]+)|\d+'
128 t
.value
= int(t
.value
,0)
130 error(t
.lineno
, 'Integer value "%s" too large' % t
.value
)
134 # String literal. Note that these use only single quotes, and
135 # can span multiple lines.
139 t
.value
= t
.value
[1:-1]
140 t
.lineno
+= t
.value
.count('\n')
144 # "Code literal"... like a string literal, but delimiters are
145 # '{{' and '}}' so they get formatted nicely under emacs c-mode
147 r
"(?m)\{\{([^\}]|}(?!\}))+\}\}"
149 t
.value
= t
.value
[2:-2]
150 t
.lineno
+= t
.value
.count('\n')
153 def t_CPPDIRECTIVE(t
):
155 t
.lineno
+= t
.value
.count('\n')
159 # The functions t_NEWLINE, t_ignore, and t_error are
160 # special for the lex module.
166 t
.lineno
+= t
.value
.count('\n')
172 # Completely ignored characters
177 error(t
.lineno
, "illegal character '%s'" % t
.value
[0])
183 #####################################################################
187 # Every function whose name starts with 'p_' defines a grammar rule.
188 # The rule is encoded in the function's doc string, while the
189 # function body provides the action taken when the rule is matched.
190 # The argument to each function is a list of the values of the
191 # rule's symbols: t[0] for the LHS, and t[1..n] for the symbols
192 # on the RHS. For tokens, the value is copied from the t.value
193 # attribute provided by the lexer. For non-terminals, the value
194 # is assigned by the producing rule; i.e., the job of the grammar
195 # rule function is to set the value for the non-terminal on the LHS
196 # (by assigning to t[0]).
197 #####################################################################
199 # The LHS of the first grammar rule is used as the start symbol
200 # (in this case, 'specification'). Note that this rule enforces
201 # that there will be exactly one namespace declaration, with 0 or more
202 # global defs/decls before and after it. The defs & decls before
203 # the namespace decl will be outside the namespace; those after
204 # will be inside. The decoder function is always inside the namespace.
205 def p_specification(t
):
206 'specification : opt_defs_and_outputs name_decl opt_defs_and_outputs decode_block'
209 namespace
= isa_name
+ "Inst"
210 # wrap the decode block as a function definition
211 t
[4].wrap_decode_block('''
212 StaticInstPtr<%(isa_name)s>
213 %(isa_name)s::decodeInst(%(isa_name)s::MachInst machInst)
215 using namespace %(namespace)s;
217 # both the latter output blocks and the decode block are in the namespace
218 namespace_code
= t
[3] + t
[4]
219 # pass it all back to the caller of yacc.parse()
220 t
[0] = (isa_name
, namespace
, global_code
, namespace_code
)
222 # ISA name declaration looks like "namespace <foo>;"
224 'name_decl : NAMESPACE ID SEMI'
227 # 'opt_defs_and_outputs' is a possibly empty sequence of
228 # def and/or output statements.
229 def p_opt_defs_and_outputs_0(t
):
230 'opt_defs_and_outputs : empty'
233 def p_opt_defs_and_outputs_1(t
):
234 'opt_defs_and_outputs : defs_and_outputs'
237 def p_defs_and_outputs_0(t
):
238 'defs_and_outputs : def_or_output'
241 def p_defs_and_outputs_1(t
):
242 'defs_and_outputs : defs_and_outputs def_or_output'
245 # The list of possible definition/output statements.
246 def p_def_or_output(t
):
247 '''def_or_output : def_format
258 # Output blocks 'output <foo> {{...}}' (C++ code blocks) are copied
259 # directly to the appropriate output section.
261 # Massage output block by substituting in template definitions and bit
262 # operators. We handle '%'s embedded in the string that don't
263 # indicate template substitutions (or CPU-specific symbols, which get
264 # handled in GenCode) by doubling them first so that the format
265 # operation will reduce them back to single '%'s.
266 def process_output(s
):
267 # protect any non-substitution '%'s (not followed by '(')
268 s
= re
.sub(r
'%(?!\()', '%%', s
)
269 # protects cpu-specific symbols too
270 s
= protect_cpu_symbols(s
)
271 return substBitOps(s
% templateMap
)
273 def p_output_header(t
):
274 'output_header : OUTPUT HEADER CODELIT SEMI'
275 t
[0] = GenCode(header_output
= process_output(t
[3]))
277 def p_output_decoder(t
):
278 'output_decoder : OUTPUT DECODER CODELIT SEMI'
279 t
[0] = GenCode(decoder_output
= process_output(t
[3]))
281 def p_output_exec(t
):
282 'output_exec : OUTPUT EXEC CODELIT SEMI'
283 t
[0] = GenCode(exec_output
= process_output(t
[3]))
285 # global let blocks 'let {{...}}' (Python code blocks) are executed
286 # directly when seen. Note that these execute in a special variable
287 # context 'exportContext' to prevent the code from polluting this
288 # script's namespace.
290 'global_let : LET CODELIT SEMI'
291 updateExportContext()
293 exec fixPythonIndentation(t
[2]) in exportContext
294 except Exception, exc
:
296 'error: %s in global let block "%s".' % (exc
, t
[2]))
297 t
[0] = GenCode() # contributes nothing to the output C++ file
299 # Define the mapping from operand type extensions to C++ types and bit
300 # widths (stored in operandTypeMap).
301 def p_def_operand_types(t
):
302 'def_operand_types : DEF OPERAND_TYPES CODELIT SEMI'
303 s
= 'global operandTypeMap; operandTypeMap = {' + t
[3] + '}'
306 except Exception, exc
:
308 'error: %s in def operand_types block "%s".' % (exc
, t
[3]))
309 t
[0] = GenCode() # contributes nothing to the output C++ file
311 # Define the mapping from operand names to operand classes and other
312 # traits. Stored in operandTraitsMap.
313 def p_def_operands(t
):
314 'def_operands : DEF OPERANDS CODELIT SEMI'
315 s
= 'global operandTraitsMap; operandTraitsMap = {' + t
[3] + '}'
318 except Exception, exc
:
320 'error: %s in def operands block "%s".' % (exc
, t
[3]))
321 defineDerivedOperandVars()
322 t
[0] = GenCode() # contributes nothing to the output C++ file
324 # A bitfield definition looks like:
325 # 'def [signed] bitfield <ID> [<first>:<last>]'
326 # This generates a preprocessor macro in the output file.
327 def p_def_bitfield_0(t
):
328 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT COLON INTLIT GREATER SEMI'
329 expr
= 'bits(machInst, %2d, %2d)' % (t
[6], t
[8])
330 if (t
[2] == 'signed'):
331 expr
= 'sext<%d>(%s)' % (t
[6] - t
[8] + 1, expr
)
332 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
333 t
[0] = GenCode(header_output
= hash_define
)
335 # alternate form for single bit: 'def [signed] bitfield <ID> [<bit>]'
336 def p_def_bitfield_1(t
):
337 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT GREATER SEMI'
338 expr
= 'bits(machInst, %2d, %2d)' % (t
[6], t
[6])
339 if (t
[2] == 'signed'):
340 expr
= 'sext<%d>(%s)' % (1, expr
)
341 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
342 t
[0] = GenCode(header_output
= hash_define
)
344 def p_opt_signed_0(t
):
345 'opt_signed : SIGNED'
348 def p_opt_signed_1(t
):
352 # Global map variable to hold templates
355 def p_def_template(t
):
356 'def_template : DEF TEMPLATE ID CODELIT SEMI'
357 templateMap
[t
[3]] = Template(t
[4])
360 # An instruction format definition looks like
361 # "def format <fmt>(<params>) {{...}};"
363 'def_format : DEF FORMAT ID LPAREN param_list RPAREN CODELIT SEMI'
364 (id, params
, code
) = (t
[3], t
[5], t
[7])
365 defFormat(id, params
, code
, t
.lineno(1))
368 # The formal parameter list for an instruction format is a possibly
369 # empty list of comma-separated parameters.
370 def p_param_list_0(t
):
374 def p_param_list_1(t
):
378 def p_param_list_2(t
):
379 'param_list : param_list COMMA param'
383 # Each formal parameter is either an identifier or an identifier
384 # preceded by an asterisk. As in Python, the latter (if present) gets
385 # a tuple containing all the excess positional arguments, allowing
392 'param : ASTERISK ID'
393 # just concatenate them: '*ID'
396 # End of format definition-related rules.
400 # A decode block looks like:
401 # decode <field1> [, <field2>]* [default <inst>] { ... }
403 def p_decode_block(t
):
404 'decode_block : DECODE ID opt_default LBRACE decode_stmt_list RBRACE'
405 default_defaults
= defaultStack
.pop()
407 # use the "default defaults" only if there was no explicit
408 # default statement in decode_stmt_list
409 if not codeObj
.has_decode_default
:
410 codeObj
+= default_defaults
411 codeObj
.wrap_decode_block('switch (%s) {\n' % t
[2], '}\n')
414 # The opt_default statement serves only to push the "default defaults"
415 # onto defaultStack. This value will be used by nested decode blocks,
416 # and used and popped off when the current decode_block is processed
417 # (in p_decode_block() above).
418 def p_opt_default_0(t
):
419 'opt_default : empty'
420 # no default specified: reuse the one currently at the top of the stack
421 defaultStack
.push(defaultStack
.top())
422 # no meaningful value returned
425 def p_opt_default_1(t
):
426 'opt_default : DEFAULT inst'
427 # push the new default
429 codeObj
.wrap_decode_block('\ndefault:\n', 'break;\n')
430 defaultStack
.push(codeObj
)
431 # no meaningful value returned
434 def p_decode_stmt_list_0(t
):
435 'decode_stmt_list : decode_stmt'
438 def p_decode_stmt_list_1(t
):
439 'decode_stmt_list : decode_stmt decode_stmt_list'
440 if (t
[1].has_decode_default
and t
[2].has_decode_default
):
441 error(t
.lineno(1), 'Two default cases in decode block')
445 # Decode statement rules
447 # There are four types of statements allowed in a decode block:
448 # 1. Format blocks 'format <foo> { ... }'
449 # 2. Nested decode blocks
450 # 3. Instruction definitions.
451 # 4. C preprocessor directives.
454 # Preprocessor directives found in a decode statement list are passed
455 # through to the output, replicated to all of the output code
456 # streams. This works well for ifdefs, so we can ifdef out both the
457 # declarations and the decode cases generated by an instruction
458 # definition. Handling them as part of the grammar makes it easy to
459 # keep them in the right place with respect to the code generated by
460 # the other statements.
461 def p_decode_stmt_cpp(t
):
462 'decode_stmt : CPPDIRECTIVE'
463 t
[0] = GenCode(t
[1], t
[1], t
[1], t
[1])
465 # A format block 'format <foo> { ... }' sets the default instruction
466 # format used to handle instruction definitions inside the block.
467 # This format can be overridden by using an explicit format on the
468 # instruction definition or with a nested format block.
469 def p_decode_stmt_format(t
):
470 'decode_stmt : FORMAT push_format_id LBRACE decode_stmt_list RBRACE'
471 # The format will be pushed on the stack when 'push_format_id' is
472 # processed (see below). Once the parser has recognized the full
473 # production (though the right brace), we're done with the format,
474 # so now we can pop it.
478 # This rule exists so we can set the current format (& push the stack)
479 # when we recognize the format name part of the format block.
480 def p_push_format_id(t
):
481 'push_format_id : ID'
483 formatStack
.push(formatMap
[t
[1]])
484 t
[0] = ('', '// format %s' % t
[1])
486 error(t
.lineno(1), 'instruction format "%s" not defined.' % t
[1])
488 # Nested decode block: if the value of the current field matches the
489 # specified constant, do a nested decode on some other field.
490 def p_decode_stmt_decode(t
):
491 'decode_stmt : case_label COLON decode_block'
494 # just wrap the decoding code from the block as a case in the
495 # outer switch statement.
496 codeObj
.wrap_decode_block('\n%s:\n' % label
)
497 codeObj
.has_decode_default
= (label
== 'default')
500 # Instruction definition (finally!).
501 def p_decode_stmt_inst(t
):
502 'decode_stmt : case_label COLON inst SEMI'
505 codeObj
.wrap_decode_block('\n%s:' % label
, 'break;\n')
506 codeObj
.has_decode_default
= (label
== 'default')
509 # The case label is either a list of one or more constants or 'default'
510 def p_case_label_0(t
):
511 'case_label : intlit_list'
512 t
[0] = ': '.join(map(lambda a
: 'case %#x' % a
, t
[1]))
514 def p_case_label_1(t
):
515 'case_label : DEFAULT'
519 # The constant list for a decode case label must be non-empty, but may have
520 # one or more comma-separated integer literals in it.
522 def p_intlit_list_0(t
):
523 'intlit_list : INTLIT'
526 def p_intlit_list_1(t
):
527 'intlit_list : intlit_list COMMA INTLIT'
531 # Define an instruction using the current instruction format (specified
532 # by an enclosing format block).
533 # "<mnemonic>(<args>)"
535 'inst : ID LPAREN arg_list RPAREN'
536 # Pass the ID and arg list to the current format class to deal with.
537 currentFormat
= formatStack
.top()
538 codeObj
= currentFormat
.defineInst(t
[1], t
[3], t
.lineno(1))
539 args
= ','.join(map(str, t
[3]))
540 args
= re
.sub('(?m)^', '//', args
)
541 args
= re
.sub('^//', '', args
)
542 comment
= '\n// %s::%s(%s)\n' % (currentFormat
.id, t
[1], args
)
543 codeObj
.prepend_all(comment
)
546 # Define an instruction using an explicitly specified format:
547 # "<fmt>::<mnemonic>(<args>)"
549 'inst : ID DBLCOLON ID LPAREN arg_list RPAREN'
551 format
= formatMap
[t
[1]]
553 error(t
.lineno(1), 'instruction format "%s" not defined.' % t
[1])
554 codeObj
= format
.defineInst(t
[3], t
[5], t
.lineno(1))
555 comment
= '\n// %s::%s(%s)\n' % (t
[1], t
[3], t
[5])
556 codeObj
.prepend_all(comment
)
568 'arg_list : arg_list COMMA arg'
580 # Empty production... use in other rules for readability.
586 # Parse error handler. Note that the argument here is the offending
587 # *token*, not a grammar symbol (hence the need to use t.value)
590 error(t
.lineno
, "syntax error at '%s'" % t
.value
)
592 error_bt(0, "unknown syntax error")
594 # END OF GRAMMAR RULES
596 # Now build the parser.
600 #####################################################################
604 #####################################################################
609 # The CpuModel class encapsulates everything we need to know about a
610 # particular CPU model.
613 # List of all CPU models. Accessible as CpuModel.list.
616 # Constructor. Automatically adds models to CpuModel.list.
617 def __init__(self
, name
, filename
, includes
, strings
):
619 self
.filename
= filename
# filename for output exec code
620 self
.includes
= includes
# include files needed in exec file
621 # The 'strings' dict holds all the per-CPU symbols we can
622 # substitute into templates etc.
623 self
.strings
= strings
625 CpuModel
.list.append(self
)
627 # Define CPU models. The following lines should contain the only
628 # CPU-model-specific information in this file. Note that the ISA
629 # description itself should have *no* CPU-model-specific content.
630 CpuModel('InorderCPU', 'inorder_cpu_exec.cc',
631 '#include "cpu/inorder_cpu/inorder_cpu.hh"',
632 { 'CPU_exec_context': 'InorderCPU' })
633 CpuModel('SimpleCPU', 'simple_cpu_exec.cc',
634 '#include "cpu/simple_cpu/simple_cpu.hh"',
635 { 'CPU_exec_context': 'SimpleCPU' })
636 CpuModel('FastCPU', 'fast_cpu_exec.cc',
637 '#include "cpu/fast_cpu/fast_cpu.hh"',
638 { 'CPU_exec_context': 'FastCPU' })
639 CpuModel('FullCPU', 'full_cpu_exec.cc',
640 '#include "cpu/full_cpu/dyn_inst.hh"',
641 { 'CPU_exec_context': 'DynInst' })
643 # Expand template with CPU-specific references into a dictionary with
644 # an entry for each CPU model name. The entry key is the model name
645 # and the corresponding value is the template with the CPU-specific
646 # refs substituted for that model.
647 def expand_cpu_symbols_to_dict(template
):
648 # Protect '%'s that don't go with CPU-specific terms
649 t
= re
.sub(r
'%(?!\(CPU_)', '%%', template
)
651 for cpu
in CpuModel
.list:
652 result
[cpu
.name
] = t
% cpu
.strings
655 # *If* the template has CPU-specific references, return a single
656 # string containing a copy of the template for each CPU model with the
657 # corresponding values substituted in. If the template has no
658 # CPU-specific references, it is returned unmodified.
659 def expand_cpu_symbols_to_string(template
):
660 if template
.find('%(CPU_') != -1:
661 return reduce(lambda x
,y
: x
+y
,
662 expand_cpu_symbols_to_dict(template
).values())
666 # Protect CPU-specific references by doubling the corresponding '%'s
667 # (in preparation for substituting a different set of references into
669 def protect_cpu_symbols(template
):
670 return re
.sub(r
'%(?=\(CPU_)', '%%', template
)
675 # The GenCode class encapsulates generated code destined for various
676 # output files. The header_output and decoder_output attributes are
677 # strings containing code destined for decoder.hh and decoder.cc
678 # respectively. The decode_block attribute contains code to be
679 # incorporated in the decode function itself (that will also end up in
680 # decoder.cc). The exec_output attribute is a dictionary with a key
681 # for each CPU model name; the value associated with a particular key
682 # is the string of code for that CPU model's exec.cc file. The
683 # has_decode_default attribute is used in the decode block to allow
684 # explicit default clauses to override default default clauses.
687 # Constructor. At this point we substitute out all CPU-specific
688 # symbols. For the exec output, these go into the per-model
689 # dictionary. For all other output types they get collapsed into
692 header_output
= '', decoder_output
= '', exec_output
= '',
693 decode_block
= '', has_decode_default
= False):
694 self
.header_output
= expand_cpu_symbols_to_string(header_output
)
695 self
.decoder_output
= expand_cpu_symbols_to_string(decoder_output
)
696 if isinstance(exec_output
, dict):
697 self
.exec_output
= exec_output
698 elif isinstance(exec_output
, str):
699 # If the exec_output arg is a single string, we replicate
700 # it for each of the CPU models, substituting and
701 # %(CPU_foo)s params appropriately.
702 self
.exec_output
= expand_cpu_symbols_to_dict(exec_output
)
703 self
.decode_block
= expand_cpu_symbols_to_string(decode_block
)
704 self
.has_decode_default
= has_decode_default
706 # Override '+' operator: generate a new GenCode object that
707 # concatenates all the individual strings in the operands.
708 def __add__(self
, other
):
710 for cpu
in CpuModel
.list:
712 exec_output
[n
] = self
.exec_output
[n
] + other
.exec_output
[n
]
713 return GenCode(self
.header_output
+ other
.header_output
,
714 self
.decoder_output
+ other
.decoder_output
,
716 self
.decode_block
+ other
.decode_block
,
717 self
.has_decode_default
or other
.has_decode_default
)
719 # Prepend a string (typically a comment) to all the strings.
720 def prepend_all(self
, pre
):
721 self
.header_output
= pre
+ self
.header_output
722 self
.decoder_output
= pre
+ self
.decoder_output
723 self
.decode_block
= pre
+ self
.decode_block
724 for cpu
in CpuModel
.list:
725 self
.exec_output
[cpu
.name
] = pre
+ self
.exec_output
[cpu
.name
]
727 # Wrap the decode block in a pair of strings (e.g., 'case foo:'
728 # and 'break;'). Used to build the big nested switch statement.
729 def wrap_decode_block(self
, pre
, post
= ''):
730 self
.decode_block
= pre
+ indent(self
.decode_block
) + post
735 # A format object encapsulates an instruction format. It must provide
736 # a defineInst() method that generates the code for an instruction
740 def __init__(self
, id, params
, code
):
741 # constructor: just save away arguments
744 label
= 'def format ' + id
745 self
.user_code
= compile(fixPythonIndentation(code
), label
, 'exec')
746 param_list
= string
.join(params
, ", ")
747 f
= '''def defInst(_code, _context, %s):
748 my_locals = vars().copy()
749 exec _code in _context, my_locals
750 return my_locals\n''' % param_list
751 c
= compile(f
, label
+ ' wrapper', 'exec')
755 def defineInst(self
, name
, args
, lineno
):
757 updateExportContext()
758 context
.update(exportContext
)
759 context
.update({ 'name': name
, 'Name': string
.capitalize(name
) })
761 vars = self
.func(self
.user_code
, context
, *args
)
762 except Exception, exc
:
763 error(lineno
, 'error defining "%s": %s.' % (name
, exc
))
764 for k
in vars.keys():
765 if k
not in ('header_output', 'decoder_output',
766 'exec_output', 'decode_block'):
768 return GenCode(**vars)
770 # Special null format to catch an implicit-format instruction
771 # definition outside of any format block.
774 self
.defaultInst
= ''
776 def defineInst(self
, name
, args
, lineno
):
778 'instruction definition "%s" with no active format!' % name
)
780 # This dictionary maps format name strings to Format objects.
783 # Define a new format
784 def defFormat(id, params
, code
, lineno
):
785 # make sure we haven't already defined this one
786 if formatMap
.get(id, None) != None:
787 error(lineno
, 'format %s redefined.' % id)
788 # create new object and store in global map
789 formatMap
[id] = Format(id, params
, code
)
793 # Stack: a simple stack object. Used for both formats (formatStack)
794 # and default cases (defaultStack).
797 def __init__(self
, initItem
):
798 self
.stack
= [ initItem
]
800 def push(self
, item
):
801 self
.stack
.append(item
);
804 return self
.stack
.pop()
807 return self
.stack
[-1]
809 # The global format stack.
810 formatStack
= Stack(NoFormat())
812 # The global default case stack.
813 defaultStack
= Stack( None )
819 # Indent every line in string 's' by two spaces
820 # (except preprocessor directives).
821 # Used to make nested code blocks look pretty.
824 return re
.sub(r
'(?m)^(?!\#)', ' ', s
)
827 # Munge a somewhat arbitrarily formatted piece of Python code
828 # (e.g. from a format 'let' block) into something whose indentation
829 # will get by the Python parser.
831 # The two keys here are that Python will give a syntax error if
832 # there's any whitespace at the beginning of the first line, and that
833 # all lines at the same lexical nesting level must have identical
834 # indentation. Unfortunately the way code literals work, an entire
835 # let block tends to have some initial indentation. Rather than
836 # trying to figure out what that is and strip it off, we prepend 'if
837 # 1:' to make the let code the nested block inside the if (and have
838 # the parser automatically deal with the indentation for us).
840 # We don't want to do this if (1) the code block is empty or (2) the
841 # first line of the block doesn't have any whitespace at the front.
843 def fixPythonIndentation(s
):
844 # get rid of blank lines first
845 s
= re
.sub(r
'(?m)^\s*\n', '', s
);
846 if (s
!= '' and re
.match(r
'[ \t]', s
[0])):
850 # Error handler. Just call exit. Output formatted to work under
851 # Emacs compile-mode.
852 def error(lineno
, string
):
853 sys
.exit("%s:%d: %s" % (input_filename
, lineno
, string
))
855 # Like error(), but include a Python stack backtrace (for processing
856 # Python exceptions).
857 def error_bt(lineno
, string
):
858 traceback
.print_exc()
859 print >> sys
.stderr
, "%s:%d: %s" % (input_filename
, lineno
, string
)
863 #####################################################################
865 # Bitfield Operator Support
867 #####################################################################
869 bitOp1ArgRE
= re
.compile(r
'<\s*(\w+)\s*:\s*>')
871 bitOpWordRE
= re
.compile(r
'(?<![\w\.])([\w\.]+)<\s*(\w+)\s*:\s*(\w+)\s*>')
872 bitOpExprRE
= re
.compile(r
'\)<\s*(\w+)\s*:\s*(\w+)\s*>')
874 def substBitOps(code
):
875 # first convert single-bit selectors to two-index form
876 # i.e., <n> --> <n:n>
877 code
= bitOp1ArgRE
.sub(r
'<\1:\1>', code
)
878 # simple case: selector applied to ID (name)
879 # i.e., foo<a:b> --> bits(foo, a, b)
880 code
= bitOpWordRE
.sub(r
'bits(\1, \2, \3)', code
)
881 # if selector is applied to expression (ending in ')'),
882 # we need to search backward for matching '('
883 match
= bitOpExprRE
.search(code
)
885 exprEnd
= match
.start()
889 if code
[here
] == '(':
891 elif code
[here
] == ')':
895 sys
.exit("Didn't find '('!")
897 newExpr
= r
'bits(%s, %s, %s)' % (code
[exprStart
:exprEnd
+1],
898 match
.group(1), match
.group(2))
899 code
= code
[:exprStart
] + newExpr
+ code
[match
.end():]
900 match
= bitOpExprRE
.search(code
)
907 # Template objects are format strings that allow substitution from
908 # the attribute spaces of other objects (e.g. InstObjParams instances).
911 def __init__(self
, t
):
915 # Start with the template namespace. Make a copy since we're
916 # going to modify it.
917 myDict
= templateMap
.copy()
918 # if the argument is a dictionary, we just use it.
919 if isinstance(d
, dict):
921 # if the argument is an object, we use its attribute map.
922 elif hasattr(d
, '__dict__'):
923 myDict
.update(d
.__dict
__)
925 raise TypeError, "Template.subst() arg must be or have dictionary"
926 # CPU-model-specific substitutions are handled later (in GenCode).
927 return protect_cpu_symbols(self
.template
) % myDict
929 # Convert to string. This handles the case when a template with a
930 # CPU-specific term gets interpolated into another template or into
933 return expand_cpu_symbols_to_string(self
.template
)
935 #####################################################################
939 # The remaining code is the support for automatically extracting
940 # instruction characteristics from pseudocode.
942 #####################################################################
944 # Force the argument to be a list
945 def makeList(list_or_item
):
948 elif type(list_or_item
) == ListType
:
951 return [ list_or_item
]
953 # generate operandSizeMap based on provided operandTypeMap:
954 # basically generate equiv. C++ type and make is_signed flag
955 def buildOperandSizeMap():
956 global operandSizeMap
958 for ext
in operandTypeMap
.keys():
959 (desc
, size
) = operandTypeMap
[ext
]
960 if desc
== 'signed int':
961 type = 'int%d_t' % size
963 elif desc
== 'unsigned int':
964 type = 'uint%d_t' % size
966 elif desc
== 'float':
967 is_signed
= 1 # shouldn't really matter
973 error(0, 'Unrecognized type description "%s" in operandTypeMap')
974 operandSizeMap
[ext
] = (size
, type, is_signed
)
977 # Base class for operand traits. An instance of this class (or actually
978 # a class derived from this one) encapsulates the traits of a particular
979 # operand type (e.g., "32-bit integer register").
982 def __init__(self
, dflt_ext
, reg_spec
, flags
, sort_pri
):
983 # Force construction of operandSizeMap from operandTypeMap
984 # if it hasn't happened yet
985 if not globals().has_key('operandSizeMap'):
986 buildOperandSizeMap()
987 self
.dflt_ext
= dflt_ext
988 (self
.dflt_size
, self
.dflt_type
, self
.dflt_is_signed
) = \
989 operandSizeMap
[dflt_ext
]
990 self
.reg_spec
= reg_spec
991 # Canonical flag structure is a triple of lists, where each list
992 # indicates the set of flags implied by this operand always, when
993 # used as a source, and when used as a dest, respectively.
994 # For simplicity this can be initialized using a variety of fairly
995 # obvious shortcuts; we convert these to canonical form here.
997 # no flags specified (e.g., 'None')
998 self
.flags
= ( [], [], [] )
999 elif type(flags
) == StringType
:
1000 # a single flag: assumed to be unconditional
1001 self
.flags
= ( [ flags
], [], [] )
1002 elif type(flags
) == ListType
:
1003 # a list of flags: also assumed to be unconditional
1004 self
.flags
= ( flags
, [], [] )
1005 elif type(flags
) == TupleType
:
1006 # it's a tuple: it should be a triple,
1007 # but each item could be a single string or a list
1008 (uncond_flags
, src_flags
, dest_flags
) = flags
1009 self
.flags
= (makeList(uncond_flags
),
1010 makeList(src_flags
), makeList(dest_flags
))
1011 self
.sort_pri
= sort_pri
1019 def isFloatReg(self
):
1025 def isControlReg(self
):
1028 def getFlags(self
, op_desc
):
1029 # note the empty slice '[:]' gives us a copy of self.flags[0]
1030 # instead of a reference to it
1031 my_flags
= self
.flags
[0][:]
1033 my_flags
+= self
.flags
[1]
1035 my_flags
+= self
.flags
[2]
1038 def makeDecl(self
, op_desc
):
1039 (size
, type, is_signed
) = operandSizeMap
[op_desc
.eff_ext
]
1040 # Note that initializations in the declarations are solely
1041 # to avoid 'uninitialized variable' errors from the compiler.
1042 return type + ' ' + op_desc
.munged_name
+ ' = 0;\n';
1044 class IntRegOperandTraits(OperandTraits
):
1051 def makeConstructor(self
, op_desc
):
1054 c
+= '\n\t_srcRegIdx[%d] = %s;' % \
1055 (op_desc
.src_reg_idx
, self
.reg_spec
)
1057 c
+= '\n\t_destRegIdx[%d] = %s;' % \
1058 (op_desc
.dest_reg_idx
, self
.reg_spec
)
1061 def makeRead(self
, op_desc
):
1062 (size
, type, is_signed
) = operandSizeMap
[op_desc
.eff_ext
]
1063 if (type == 'float' or type == 'double'):
1064 error(0, 'Attempt to read integer register as FP')
1065 if (size
== self
.dflt_size
):
1066 return '%s = xc->readIntReg(this, %d);\n' % \
1067 (op_desc
.munged_name
, op_desc
.src_reg_idx
)
1069 return '%s = bits(xc->readIntReg(this, %d), %d, 0);\n' % \
1070 (op_desc
.munged_name
, op_desc
.src_reg_idx
, size
-1)
1072 def makeWrite(self
, op_desc
):
1073 (size
, type, is_signed
) = operandSizeMap
[op_desc
.eff_ext
]
1074 if (type == 'float' or type == 'double'):
1075 error(0, 'Attempt to write integer register as FP')
1076 if (size
!= self
.dflt_size
and is_signed
):
1077 final_val
= 'sext<%d>(%s)' % (size
, op_desc
.munged_name
)
1079 final_val
= op_desc
.munged_name
1083 xc->setIntReg(this, %d, final_val);\n
1084 if (traceData) { traceData->setData(final_val); }
1085 }''' % (self
.dflt_type
, final_val
, op_desc
.dest_reg_idx
)
1088 class FloatRegOperandTraits(OperandTraits
):
1092 def isFloatReg(self
):
1095 def makeConstructor(self
, op_desc
):
1098 c
+= '\n\t_srcRegIdx[%d] = %s + FP_Base_DepTag;' % \
1099 (op_desc
.src_reg_idx
, self
.reg_spec
)
1101 c
+= '\n\t_destRegIdx[%d] = %s + FP_Base_DepTag;' % \
1102 (op_desc
.dest_reg_idx
, self
.reg_spec
)
1105 def makeRead(self
, op_desc
):
1106 (size
, type, is_signed
) = operandSizeMap
[op_desc
.eff_ext
]
1108 if (type == 'float'):
1109 func
= 'readFloatRegSingle'
1110 elif (type == 'double'):
1111 func
= 'readFloatRegDouble'
1113 func
= 'readFloatRegInt'
1114 if (size
!= self
.dflt_size
):
1116 base
= 'xc->%s(this, %d)' % \
1117 (func
, op_desc
.src_reg_idx
)
1119 return '%s = bits(%s, %d, 0);\n' % \
1120 (op_desc
.munged_name
, base
, size
-1)
1122 return '%s = %s;\n' % (op_desc
.munged_name
, base
)
1124 def makeWrite(self
, op_desc
):
1125 (size
, type, is_signed
) = operandSizeMap
[op_desc
.eff_ext
]
1126 final_val
= op_desc
.munged_name
1127 if (type == 'float'):
1128 func
= 'setFloatRegSingle'
1129 elif (type == 'double'):
1130 func
= 'setFloatRegDouble'
1132 func
= 'setFloatRegInt'
1133 type = 'uint%d_t' % self
.dflt_size
1134 if (size
!= self
.dflt_size
and is_signed
):
1135 final_val
= 'sext<%d>(%s)' % (size
, op_desc
.munged_name
)
1139 xc->%s(this, %d, final_val);\n
1140 if (traceData) { traceData->setData(final_val); }
1141 }''' % (type, final_val
, func
, op_desc
.dest_reg_idx
)
1144 class ControlRegOperandTraits(OperandTraits
):
1148 def isControlReg(self
):
1151 def makeConstructor(self
, op_desc
):
1154 c
+= '\n\t_srcRegIdx[%d] = %s_DepTag;' % \
1155 (op_desc
.src_reg_idx
, self
.reg_spec
)
1157 c
+= '\n\t_destRegIdx[%d] = %s_DepTag;' % \
1158 (op_desc
.dest_reg_idx
, self
.reg_spec
)
1161 def makeRead(self
, op_desc
):
1162 (size
, type, is_signed
) = operandSizeMap
[op_desc
.eff_ext
]
1164 if (type == 'float' or type == 'double'):
1165 error(0, 'Attempt to read control register as FP')
1166 base
= 'xc->read%s()' % self
.reg_spec
1167 if size
== self
.dflt_size
:
1168 return '%s = %s;\n' % (op_desc
.munged_name
, base
)
1170 return '%s = bits(%s, %d, 0);\n' % \
1171 (op_desc
.munged_name
, base
, size
-1)
1173 def makeWrite(self
, op_desc
):
1174 (size
, type, is_signed
) = operandSizeMap
[op_desc
.eff_ext
]
1175 if (type == 'float' or type == 'double'):
1176 error(0, 'Attempt to write control register as FP')
1177 wb
= 'xc->set%s(%s);\n' % (self
.reg_spec
, op_desc
.munged_name
)
1178 wb
+= 'if (traceData) { traceData->setData(%s); }' % \
1182 class MemOperandTraits(OperandTraits
):
1186 def makeConstructor(self
, op_desc
):
1189 def makeDecl(self
, op_desc
):
1190 (size
, type, is_signed
) = operandSizeMap
[op_desc
.eff_ext
]
1191 # Note that initializations in the declarations are solely
1192 # to avoid 'uninitialized variable' errors from the compiler.
1193 # Declare memory data variable.
1194 c
= '%s %s = 0;\n' % (type, op_desc
.munged_name
)
1195 # Declare var to hold memory access flags.
1196 c
+= 'unsigned %s_flags = memAccessFlags;\n' % op_desc
.base_name
1197 # If this operand is a dest (i.e., it's a store operation),
1198 # then we need to declare a variable for the write result code
1201 c
+= 'uint64_t %s_write_result = 0;\n' % op_desc
.base_name
1204 def makeRead(self
, op_desc
):
1205 (size
, type, is_signed
) = operandSizeMap
[op_desc
.eff_ext
]
1206 eff_type
= 'uint%d_t' % size
1207 return 'fault = xc->read(EA, (%s&)%s, %s_flags);\n' \
1208 % (eff_type
, op_desc
.munged_name
, op_desc
.base_name
)
1210 def makeWrite(self
, op_desc
):
1211 (size
, type, is_signed
) = operandSizeMap
[op_desc
.eff_ext
]
1212 eff_type
= 'uint%d_t' % size
1213 wb
= 'fault = xc->write((%s&)%s, EA, %s_flags, &%s_write_result);\n' \
1214 % (eff_type
, op_desc
.munged_name
, op_desc
.base_name
,
1216 wb
+= 'if (traceData) { traceData->setData(%s); }' % \
1220 class NPCOperandTraits(OperandTraits
):
1221 def makeConstructor(self
, op_desc
):
1224 def makeRead(self
, op_desc
):
1225 return '%s = xc->readPC() + 4;\n' % op_desc
.munged_name
1227 def makeWrite(self
, op_desc
):
1228 return 'xc->setNextPC(%s);\n' % op_desc
.munged_name
1231 exportContextSymbols
= ('IntRegOperandTraits', 'FloatRegOperandTraits',
1232 'ControlRegOperandTraits', 'MemOperandTraits',
1233 'NPCOperandTraits', 'InstObjParams', 'CodeBlock',
1238 def updateExportContext():
1239 exportContext
.update(exportDict(*exportContextSymbols
))
1240 exportContext
.update(templateMap
)
1243 def exportDict(*symNames
):
1244 return dict([(s
, eval(s
)) for s
in symNames
])
1248 # Define operand variables that get derived from the basic declaration
1249 # of ISA-specific operands in operandTraitsMap. This function must be
1250 # called by the ISA description file explicitly after defining
1251 # operandTraitsMap (in a 'let' block).
1253 def defineDerivedOperandVars():
1255 operands
= operandTraitsMap
.keys()
1257 operandsREString
= (r
'''
1258 (?<![\w\.]) # neg. lookbehind assertion: prevent partial matches
1259 ((%s)(?:\.(\w+))?) # match: operand with optional '.' then suffix
1260 (?![\w\.]) # neg. lookahead assertion: prevent partial matches
1262 % string
.join(operands
, '|'))
1265 operandsRE
= re
.compile(operandsREString
, re
.MULTILINE|re
.VERBOSE
)
1267 # Same as operandsREString, but extension is mandatory, and only two
1268 # groups are returned (base and ext, not full name as above).
1269 # Used for subtituting '_' for '.' to make C++ identifiers.
1270 operandsWithExtREString
= (r
'(?<![\w\.])(%s)\.(\w+)(?![\w\.])'
1271 % string
.join(operands
, '|'))
1273 global operandsWithExtRE
1274 operandsWithExtRE
= re
.compile(operandsWithExtREString
, re
.MULTILINE
)
1278 # Operand descriptor class. An instance of this class represents
1279 # a specific operand for a code block.
1281 class OperandDescriptor
:
1282 def __init__(self
, full_name
, base_name
, ext
, is_src
, is_dest
):
1283 self
.full_name
= full_name
1284 self
.base_name
= base_name
1286 self
.is_src
= is_src
1287 self
.is_dest
= is_dest
1288 self
.traits
= operandTraitsMap
[base_name
]
1289 # The 'effective extension' (eff_ext) is either the actual
1290 # extension, if one was explicitly provided, or the default.
1291 # The 'munged name' replaces the '.' between the base and
1292 # extension (if any) with a '_' to make a legal C++ variable name.
1295 self
.munged_name
= base_name
+ '_' + ext
1297 self
.eff_ext
= self
.traits
.dflt_ext
1298 self
.munged_name
= base_name
1300 # Finalize additional fields (primarily code fields). This step
1301 # is done separately since some of these fields may depend on the
1302 # register index enumeration that hasn't been performed yet at the
1303 # time of __init__().
1305 self
.flags
= self
.traits
.getFlags(self
)
1306 self
.constructor
= self
.traits
.makeConstructor(self
)
1307 self
.op_decl
= self
.traits
.makeDecl(self
)
1310 self
.op_rd
= self
.traits
.makeRead(self
)
1315 self
.op_wb
= self
.traits
.makeWrite(self
)
1319 class OperandDescriptorList
:
1325 return len(self
.items
)
1327 def __getitem__(self
, index
):
1328 return self
.items
[index
]
1330 def append(self
, op_desc
):
1331 self
.items
.append(op_desc
)
1332 self
.bases
[op_desc
.base_name
] = op_desc
1334 def find_base(self
, base_name
):
1335 # like self.bases[base_name], but returns None if not found
1336 # (rather than raising exception)
1337 return self
.bases
.get(base_name
)
1339 # internal helper function for concat[Some]Attr{Strings|Lists}
1340 def __internalConcatAttrs(self
, attr_name
, filter, result
):
1341 for op_desc
in self
.items
:
1343 result
+= getattr(op_desc
, attr_name
)
1346 # return a single string that is the concatenation of the (string)
1347 # values of the specified attribute for all operands
1348 def concatAttrStrings(self
, attr_name
):
1349 return self
.__internalConcatAttrs
(attr_name
, lambda x
: 1, '')
1351 # like concatAttrStrings, but only include the values for the operands
1352 # for which the provided filter function returns true
1353 def concatSomeAttrStrings(self
, filter, attr_name
):
1354 return self
.__internalConcatAttrs
(attr_name
, filter, '')
1356 # return a single list that is the concatenation of the (list)
1357 # values of the specified attribute for all operands
1358 def concatAttrLists(self
, attr_name
):
1359 return self
.__internalConcatAttrs
(attr_name
, lambda x
: 1, [])
1361 # like concatAttrLists, but only include the values for the operands
1362 # for which the provided filter function returns true
1363 def concatSomeAttrLists(self
, filter, attr_name
):
1364 return self
.__internalConcatAttrs
(attr_name
, filter, [])
1367 self
.items
.sort(lambda a
, b
: a
.traits
.sort_pri
- b
.traits
.sort_pri
)
1369 # Regular expression object to match C++ comments
1370 # (used in findOperands())
1371 commentRE
= re
.compile(r
'//.*\n')
1373 # Regular expression object to match assignment statements
1374 # (used in findOperands())
1375 assignRE
= re
.compile(r
'\s*=(?!=)', re
.MULTILINE
)
1378 # Find all the operands in the given code block. Returns an operand
1379 # descriptor list (instance of class OperandDescriptorList).
1381 def findOperands(code
):
1382 operands
= OperandDescriptorList()
1383 # delete comments so we don't accidentally match on reg specifiers inside
1384 code
= commentRE
.sub('', code
)
1385 # search for operands
1388 match
= operandsRE
.search(code
, next_pos
)
1390 # no more matches: we're done
1393 # regexp groups are operand full name, base, and extension
1394 (op_full
, op_base
, op_ext
) = op
1395 # if the token following the operand is an assignment, this is
1396 # a destination (LHS), else it's a source (RHS)
1397 is_dest
= (assignRE
.match(code
, match
.end()) != None)
1398 is_src
= not is_dest
1399 # see if we've already seen this one
1400 op_desc
= operands
.find_base(op_base
)
1402 if op_desc
.ext
!= op_ext
:
1403 error(0, 'Inconsistent extensions for operand %s' % op_base
)
1404 op_desc
.is_src
= op_desc
.is_src
or is_src
1405 op_desc
.is_dest
= op_desc
.is_dest
or is_dest
1407 # new operand: create new descriptor
1408 op_desc
= OperandDescriptor(op_full
, op_base
, op_ext
,
1410 operands
.append(op_desc
)
1411 # start next search after end of current match
1412 next_pos
= match
.end()
1414 # enumerate source & dest register operands... used in building
1418 operands
.numFPDestRegs
= 0
1419 operands
.numIntDestRegs
= 0
1420 for op_desc
in operands
:
1421 if op_desc
.traits
.isReg():
1423 op_desc
.src_reg_idx
= srcRegs
1426 op_desc
.dest_reg_idx
= destRegs
1428 if op_desc
.traits
.isFloatReg():
1429 operands
.numFPDestRegs
+= 1
1430 elif op_desc
.traits
.isIntReg():
1431 operands
.numIntDestRegs
+= 1
1432 operands
.numSrcRegs
= srcRegs
1433 operands
.numDestRegs
= destRegs
1434 # now make a final pass to finalize op_desc fields that may depend
1435 # on the register enumeration
1436 for op_desc
in operands
:
1440 # Munge operand names in code string to make legal C++ variable names.
1441 # (Will match munged_name attribute of OperandDescriptor object.)
1442 def substMungedOpNames(code
):
1443 return operandsWithExtRE
.sub(r
'\1_\2', code
)
1446 return map(string
.join
, t
)
1448 def makeFlagConstructor(flag_list
):
1449 if len(flag_list
) == 0:
1451 # filter out repeated flags
1454 while i
< len(flag_list
):
1455 if flag_list
[i
] == flag_list
[i
-1]:
1461 code
= pre
+ string
.join(flag_list
, post
+ pre
) + post
1465 def __init__(self
, code
):
1466 self
.orig_code
= code
1467 self
.operands
= findOperands(code
)
1468 self
.code
= substMungedOpNames(substBitOps(code
))
1469 self
.constructor
= self
.operands
.concatAttrStrings('constructor')
1470 self
.constructor
+= \
1471 '\n\t_numSrcRegs = %d;' % self
.operands
.numSrcRegs
1472 self
.constructor
+= \
1473 '\n\t_numDestRegs = %d;' % self
.operands
.numDestRegs
1474 self
.constructor
+= \
1475 '\n\t_numFPDestRegs = %d;' % self
.operands
.numFPDestRegs
1476 self
.constructor
+= \
1477 '\n\t_numIntDestRegs = %d;' % self
.operands
.numIntDestRegs
1479 self
.op_decl
= self
.operands
.concatAttrStrings('op_decl')
1481 is_mem
= lambda op
: op
.traits
.isMem()
1482 not_mem
= lambda op
: not op
.traits
.isMem()
1484 self
.op_rd
= self
.operands
.concatAttrStrings('op_rd')
1485 self
.op_wb
= self
.operands
.concatAttrStrings('op_wb')
1487 self
.operands
.concatSomeAttrStrings(is_mem
, 'op_rd')
1489 self
.operands
.concatSomeAttrStrings(is_mem
, 'op_wb')
1490 self
.op_nonmem_rd
= \
1491 self
.operands
.concatSomeAttrStrings(not_mem
, 'op_rd')
1492 self
.op_nonmem_wb
= \
1493 self
.operands
.concatSomeAttrStrings(not_mem
, 'op_wb')
1495 self
.flags
= self
.operands
.concatAttrLists('flags')
1497 # Make a basic guess on the operand class (function unit type).
1498 # These are good enough for most cases, and will be overridden
1500 if 'IsStore' in self
.flags
:
1501 self
.op_class
= 'MemWriteOp'
1502 elif 'IsLoad' in self
.flags
or 'IsPrefetch' in self
.flags
:
1503 self
.op_class
= 'MemReadOp'
1504 elif 'IsFloating' in self
.flags
:
1505 self
.op_class
= 'FloatAddOp'
1507 self
.op_class
= 'IntAluOp'
1509 # Assume all instruction flags are of the form 'IsFoo'
1510 instFlagRE
= re
.compile(r
'Is.*')
1512 # OpClass constants end in 'Op' except No_OpClass
1513 opClassRE
= re
.compile(r
'.*Op|No_OpClass')
1515 class InstObjParams
:
1516 def __init__(self
, mnem
, class_name
, base_class
= '',
1517 code_block
= None, opt_args
= []):
1518 self
.mnemonic
= mnem
1519 self
.class_name
= class_name
1520 self
.base_class
= base_class
1522 for code_attr
in code_block
.__dict
__.keys():
1523 setattr(self
, code_attr
, getattr(code_block
, code_attr
))
1525 self
.constructor
= ''
1527 # Optional arguments are assumed to be either StaticInst flags
1528 # or an OpClass value. To avoid having to import a complete
1529 # list of these values to match against, we do it ad-hoc
1532 if instFlagRE
.match(oa
):
1533 self
.flags
.append(oa
)
1534 elif opClassRE
.match(oa
):
1537 error(0, 'InstObjParams: optional arg "%s" not recognized '
1538 'as StaticInst::Flag or OpClass.' % oa
)
1540 # add flag initialization to contructor here to include
1541 # any flags added via opt_args
1542 self
.constructor
+= makeFlagConstructor(self
.flags
)
1544 # if 'IsFloating' is set, add call to the FP enable check
1545 # function (which should be provided by isa_desc via a declare)
1546 if 'IsFloating' in self
.flags
:
1547 self
.fp_enable_check
= 'fault = checkFpEnableFault(xc);'
1549 self
.fp_enable_check
= ''
1551 #######################
1553 # Output file template
1558 * Copyright (c) 2003
1559 * The Regents of The University of Michigan
1560 * All Rights Reserved
1562 * This code is part of the M5 simulator, developed by Nathan Binkert,
1563 * Erik Hallnor, Steve Raasch, and Steve Reinhardt, with contributions
1564 * from Ron Dreslinski, Dave Greene, and Lisa Hsu.
1566 * Permission is granted to use, copy, create derivative works and
1567 * redistribute this software and such derivative works for any
1568 * purpose, so long as the copyright notice above, this grant of
1569 * permission, and the disclaimer below appear in all copies made; and
1570 * so long as the name of The University of Michigan is not used in
1571 * any advertising or publicity pertaining to the use or distribution
1572 * of this software without specific, written prior authorization.
1574 * THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION FROM THE
1575 * UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY PURPOSE, AND
1576 * WITHOUT WARRANTY BY THE UNIVERSITY OF MICHIGAN OF ANY KIND, EITHER
1577 * EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
1578 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
1579 * PURPOSE. THE REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE
1580 * LIABLE FOR ANY DAMAGES, INCLUDING DIRECT, SPECIAL, INDIRECT,
1581 * INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM
1582 * ARISING OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
1583 * IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF SUCH
1588 * DO NOT EDIT THIS FILE!!!
1590 * It was automatically generated from the ISA description in %(filename)s
1597 namespace %(namespace)s {
1599 %(namespace_output)s
1601 } // namespace %(namespace)s
1605 # Update the output file only if the new contents are different from
1606 # the current contents. Minimizes the files that need to be rebuilt
1607 # after minor changes.
1608 def update_if_needed(file, contents
):
1610 if os
.access(file, os
.R_OK
):
1612 old_contents
= f
.read()
1614 if contents
!= old_contents
:
1615 print 'Updating', file
1616 os
.remove(file) # in case it's write-protected
1619 print 'File', file, 'is unchanged'
1621 print 'Generating', file
1629 # Read in and parse the ISA description.
1631 def parse_isa_desc(isa_desc_file
, output_dir
, include_path
):
1632 # set a global var for the input filename... used in error messages
1633 global input_filename
1634 input_filename
= isa_desc_file
1636 # Suck the ISA description file in.
1637 input = open(isa_desc_file
)
1638 isa_desc
= input.read()
1642 (isa_name
, namespace
, global_code
, namespace_code
) = yacc
.parse(isa_desc
)
1644 # grab the last three path components of isa_desc_file to put in
1646 filename
= '/'.join(isa_desc_file
.split('/')[-3:])
1648 # generate decoder.hh
1649 includes
= '#include "base/bitfield.hh" // for bitfield support'
1650 global_output
= global_code
.header_output
1651 namespace_output
= namespace_code
.header_output
1652 update_if_needed(output_dir
+ '/decoder.hh', file_template
% vars())
1654 # generate decoder.cc
1655 includes
= '#include "%s/decoder.hh"' % include_path
1656 global_output
= global_code
.decoder_output
1657 namespace_output
= namespace_code
.decoder_output
1658 namespace_output
+= namespace_code
.decode_block
1659 update_if_needed(output_dir
+ '/decoder.cc', file_template
% vars())
1661 # generate per-cpu exec files
1662 for cpu
in CpuModel
.list:
1663 includes
= '#include "%s/decoder.hh"\n' % include_path
1664 includes
+= cpu
.includes
1665 global_output
= global_code
.exec_output
[cpu
.name
]
1666 namespace_output
= namespace_code
.exec_output
[cpu
.name
]
1667 update_if_needed(output_dir
+ '/' + cpu
.filename
,
1668 file_template
% vars())
1670 # Called as script: get args from command line.
1671 if __name__
== '__main__':
1672 parse_isa_desc(sys
.argv
[1], sys
.argv
[2], sys
.argv
[3])