8d0fee22ded16128f75d75c6d9a2caee7efba4ea
1 # Copyright (c) 2014, 2016, 2018-2019 ARM Limited
4 # The license below extends only to copyright in the software and shall
5 # not be construed as granting a license to any other intellectual
6 # property including but not limited to intellectual property relating
7 # to a hardware implementation of the functionality of the software
8 # licensed hereunder. You may use the software subject to the license
9 # terms below provided that you ensure that this notice is replicated
10 # unmodified and in its entirety in all distributions of the software,
11 # modified or unmodified, in source code or in binary form.
13 # Copyright (c) 2003-2005 The Regents of The University of Michigan
14 # Copyright (c) 2013,2015 Advanced Micro Devices, Inc.
15 # All rights reserved.
17 # Redistribution and use in source and binary forms, with or without
18 # modification, are permitted provided that the following conditions are
19 # met: redistributions of source code must retain the above copyright
20 # notice, this list of conditions and the following disclaimer;
21 # redistributions in binary form must reproduce the above copyright
22 # notice, this list of conditions and the following disclaimer in the
23 # documentation and/or other materials provided with the distribution;
24 # neither the name of the copyright holders nor the names of its
25 # contributors may be used to endorse or promote products derived from
26 # this software without specific prior written permission.
28 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 from __future__
import with_statement
, print_function
45 import inspect
, traceback
49 from m5
.util
.grammar
import Grammar
57 # Indent every line in string 's' by two spaces
58 # (except preprocessor directives).
59 # Used to make nested code blocks look pretty.
62 return re
.sub(r
'(?m)^(?!#)', ' ', s
)
65 # Munge a somewhat arbitrarily formatted piece of Python code
66 # (e.g. from a format 'let' block) into something whose indentation
67 # will get by the Python parser.
69 # The two keys here are that Python will give a syntax error if
70 # there's any whitespace at the beginning of the first line, and that
71 # all lines at the same lexical nesting level must have identical
72 # indentation. Unfortunately the way code literals work, an entire
73 # let block tends to have some initial indentation. Rather than
74 # trying to figure out what that is and strip it off, we prepend 'if
75 # 1:' to make the let code the nested block inside the if (and have
76 # the parser automatically deal with the indentation for us).
78 # We don't want to do this if (1) the code block is empty or (2) the
79 # first line of the block doesn't have any whitespace at the front.
81 def fixPythonIndentation(s
):
82 # get rid of blank lines first
83 s
= re
.sub(r
'(?m)^\s*\n', '', s
);
84 if (s
!= '' and re
.match(r
'[ \t]', s
[0])):
88 class ISAParserError(Exception):
89 """Exception class for parser errors"""
90 def __init__(self
, first
, second
=None):
102 raise ISAParserError(*args
)
107 # Template objects are format strings that allow substitution from
108 # the attribute spaces of other objects (e.g. InstObjParams instances).
110 labelRE
= re
.compile(r
'(?<!%)%\(([^\)]+)\)[sd]')
112 class Template(object):
113 def __init__(self
, parser
, t
):
120 # Protect non-Python-dict substitutions (e.g. if there's a printf
121 # in the templated C++ code)
122 template
= self
.parser
.protectNonSubstPercents(self
.template
)
124 # Build a dict ('myDict') to use for the template substitution.
125 # Start with the template namespace. Make a copy since we're
126 # going to modify it.
127 myDict
= self
.parser
.templateMap
.copy()
129 if isinstance(d
, InstObjParams
):
130 # If we're dealing with an InstObjParams object, we need
131 # to be a little more sophisticated. The instruction-wide
132 # parameters are already formed, but the parameters which
133 # are only function wide still need to be generated.
136 myDict
.update(d
.__dict
__)
137 # The "operands" and "snippets" attributes of the InstObjParams
138 # objects are for internal use and not substitution.
139 del myDict
['operands']
140 del myDict
['snippets']
142 snippetLabels
= [l
for l
in labelRE
.findall(template
)
145 snippets
= dict([(s
, self
.parser
.mungeSnippet(d
.snippets
[s
]))
146 for s
in snippetLabels
])
148 myDict
.update(snippets
)
150 compositeCode
= ' '.join(map(str, snippets
.values()))
152 # Add in template itself in case it references any
153 # operands explicitly (like Mem)
154 compositeCode
+= ' ' + template
156 operands
= SubOperandList(self
.parser
, compositeCode
, d
.operands
)
158 myDict
['op_decl'] = operands
.concatAttrStrings('op_decl')
159 if operands
.readPC
or operands
.setPC
:
160 myDict
['op_decl'] += 'TheISA::PCState __parserAutoPCState;\n'
162 # In case there are predicated register reads and write, declare
163 # the variables for register indicies. It is being assumed that
164 # all the operands in the OperandList are also in the
165 # SubOperandList and in the same order. Otherwise, it is
166 # expected that predication would not be used for the operands.
167 if operands
.predRead
:
168 myDict
['op_decl'] += 'uint8_t _sourceIndex = 0;\n'
169 if operands
.predWrite
:
170 myDict
['op_decl'] += 'uint8_t M5_VAR_USED _destIndex = 0;\n'
172 is_src
= lambda op
: op
.is_src
173 is_dest
= lambda op
: op
.is_dest
175 myDict
['op_src_decl'] = \
176 operands
.concatSomeAttrStrings(is_src
, 'op_src_decl')
177 myDict
['op_dest_decl'] = \
178 operands
.concatSomeAttrStrings(is_dest
, 'op_dest_decl')
180 myDict
['op_src_decl'] += \
181 'TheISA::PCState __parserAutoPCState;\n'
183 myDict
['op_dest_decl'] += \
184 'TheISA::PCState __parserAutoPCState;\n'
186 myDict
['op_rd'] = operands
.concatAttrStrings('op_rd')
188 myDict
['op_rd'] = '__parserAutoPCState = xc->pcState();\n' + \
191 # Compose the op_wb string. If we're going to write back the
192 # PC state because we changed some of its elements, we'll need to
193 # do that as early as possible. That allows later uncoordinated
194 # modifications to the PC to layer appropriately.
195 reordered
= list(operands
.items
)
198 pcWbStr
= 'xc->pcState(__parserAutoPCState);\n'
199 for op_desc
in reordered
:
200 if op_desc
.isPCPart() and op_desc
.is_dest
:
201 op_wb_str
= op_desc
.op_wb
+ pcWbStr
+ op_wb_str
204 op_wb_str
= op_desc
.op_wb
+ op_wb_str
205 myDict
['op_wb'] = op_wb_str
207 elif isinstance(d
, dict):
208 # if the argument is a dictionary, we just use it.
210 elif hasattr(d
, '__dict__'):
211 # if the argument is an object, we use its attribute map.
212 myDict
.update(d
.__dict
__)
214 raise TypeError, "Template.subst() arg must be or have dictionary"
215 return template
% myDict
224 # A format object encapsulates an instruction format. It must provide
225 # a defineInst() method that generates the code for an instruction
228 class Format(object):
229 def __init__(self
, id, params
, code
):
232 label
= 'def format ' + id
233 self
.user_code
= compile(fixPythonIndentation(code
), label
, 'exec')
234 param_list
= string
.join(params
, ", ")
235 f
= '''def defInst(_code, _context, %s):
236 my_locals = vars().copy()
237 exec _code in _context, my_locals
238 return my_locals\n''' % param_list
239 c
= compile(f
, label
+ ' wrapper', 'exec')
243 def defineInst(self
, parser
, name
, args
, lineno
):
244 parser
.updateExportContext()
245 context
= parser
.exportContext
.copy()
247 Name
= name
[0].upper()
250 context
.update({ 'name' : name
, 'Name' : Name
})
252 vars = self
.func(self
.user_code
, context
, *args
[0], **args
[1])
253 except Exception, exc
:
256 error(lineno
, 'error defining "%s": %s.' % (name
, exc
))
257 for k
in vars.keys():
258 if k
not in ('header_output', 'decoder_output',
259 'exec_output', 'decode_block'):
261 return GenCode(parser
, **vars)
263 # Special null format to catch an implicit-format instruction
264 # definition outside of any format block.
265 class NoFormat(object):
267 self
.defaultInst
= ''
269 def defineInst(self
, parser
, name
, args
, lineno
):
271 'instruction definition "%s" with no active format!' % name
)
276 # The GenCode class encapsulates generated code destined for various
277 # output files. The header_output and decoder_output attributes are
278 # strings containing code destined for decoder.hh and decoder.cc
279 # respectively. The decode_block attribute contains code to be
280 # incorporated in the decode function itself (that will also end up in
281 # decoder.cc). The exec_output attribute is the string of code for the
282 # exec.cc file. The has_decode_default attribute is used in the decode block
283 # to allow explicit default clauses to override default default clauses.
285 class GenCode(object):
287 def __init__(self
, parser
,
288 header_output
= '', decoder_output
= '', exec_output
= '',
289 decode_block
= '', has_decode_default
= False):
291 self
.header_output
= header_output
292 self
.decoder_output
= decoder_output
293 self
.exec_output
= exec_output
294 self
.decode_block
= decode_block
295 self
.has_decode_default
= has_decode_default
297 # Write these code chunks out to the filesystem. They will be properly
298 # interwoven by the write_top_level_files().
300 if self
.header_output
:
301 self
.parser
.get_file('header').write(self
.header_output
)
302 if self
.decoder_output
:
303 self
.parser
.get_file('decoder').write(self
.decoder_output
)
305 self
.parser
.get_file('exec').write(self
.exec_output
)
306 if self
.decode_block
:
307 self
.parser
.get_file('decode_block').write(self
.decode_block
)
309 # Override '+' operator: generate a new GenCode object that
310 # concatenates all the individual strings in the operands.
311 def __add__(self
, other
):
312 return GenCode(self
.parser
,
313 self
.header_output
+ other
.header_output
,
314 self
.decoder_output
+ other
.decoder_output
,
315 self
.exec_output
+ other
.exec_output
,
316 self
.decode_block
+ other
.decode_block
,
317 self
.has_decode_default
or other
.has_decode_default
)
319 # Prepend a string (typically a comment) to all the strings.
320 def prepend_all(self
, pre
):
321 self
.header_output
= pre
+ self
.header_output
322 self
.decoder_output
= pre
+ self
.decoder_output
323 self
.decode_block
= pre
+ self
.decode_block
324 self
.exec_output
= pre
+ self
.exec_output
326 # Wrap the decode block in a pair of strings (e.g., 'case foo:'
327 # and 'break;'). Used to build the big nested switch statement.
328 def wrap_decode_block(self
, pre
, post
= ''):
329 self
.decode_block
= pre
+ indent(self
.decode_block
) + post
331 #####################################################################
333 # Bitfield Operator Support
335 #####################################################################
337 bitOp1ArgRE
= re
.compile(r
'<\s*(\w+)\s*:\s*>')
339 bitOpWordRE
= re
.compile(r
'(?<![\w\.])([\w\.]+)<\s*(\w+)\s*:\s*(\w+)\s*>')
340 bitOpExprRE
= re
.compile(r
'\)<\s*(\w+)\s*:\s*(\w+)\s*>')
342 def substBitOps(code
):
343 # first convert single-bit selectors to two-index form
344 # i.e., <n> --> <n:n>
345 code
= bitOp1ArgRE
.sub(r
'<\1:\1>', code
)
346 # simple case: selector applied to ID (name)
347 # i.e., foo<a:b> --> bits(foo, a, b)
348 code
= bitOpWordRE
.sub(r
'bits(\1, \2, \3)', code
)
349 # if selector is applied to expression (ending in ')'),
350 # we need to search backward for matching '('
351 match
= bitOpExprRE
.search(code
)
353 exprEnd
= match
.start()
357 if code
[here
] == '(':
359 elif code
[here
] == ')':
363 sys
.exit("Didn't find '('!")
365 newExpr
= r
'bits(%s, %s, %s)' % (code
[exprStart
:exprEnd
+1],
366 match
.group(1), match
.group(2))
367 code
= code
[:exprStart
] + newExpr
+ code
[match
.end():]
368 match
= bitOpExprRE
.search(code
)
372 #####################################################################
376 # The remaining code is the support for automatically extracting
377 # instruction characteristics from pseudocode.
379 #####################################################################
381 # Force the argument to be a list. Useful for flags, where a caller
382 # can specify a singleton flag or a list of flags. Also usful for
383 # converting tuples to lists so they can be modified.
385 if isinstance(arg
, list):
387 elif isinstance(arg
, tuple):
394 class Operand(object):
395 '''Base class for operand descriptors. An instance of this class
396 (or actually a class derived from this one) represents a specific
397 operand for a code block (e.g, "Rc.sq" as a dest). Intermediate
398 derived classes encapsulates the traits of a particular operand
399 type (e.g., "32-bit integer register").'''
401 def buildReadCode(self
, func
= None):
402 subst_dict
= {"name": self
.base_name
,
404 "reg_idx": self
.reg_spec
,
406 if hasattr(self
, 'src_reg_idx'):
407 subst_dict
['op_idx'] = self
.src_reg_idx
408 code
= self
.read_code
% subst_dict
409 return '%s = %s;\n' % (self
.base_name
, code
)
411 def buildWriteCode(self
, func
= None):
412 subst_dict
= {"name": self
.base_name
,
414 "reg_idx": self
.reg_spec
,
416 "final_val": self
.base_name
}
417 if hasattr(self
, 'dest_reg_idx'):
418 subst_dict
['op_idx'] = self
.dest_reg_idx
419 code
= self
.write_code
% subst_dict
424 if (traceData) { traceData->setData(final_val); }
425 }''' % (self
.dflt_ctype
, self
.base_name
, code
)
427 def __init__(self
, parser
, full_name
, ext
, is_src
, is_dest
):
428 self
.full_name
= full_name
431 self
.is_dest
= is_dest
432 # The 'effective extension' (eff_ext) is either the actual
433 # extension, if one was explicitly provided, or the default.
436 elif hasattr(self
, 'dflt_ext'):
437 self
.eff_ext
= self
.dflt_ext
439 if hasattr(self
, 'eff_ext'):
440 self
.ctype
= parser
.operandTypeMap
[self
.eff_ext
]
442 # Finalize additional fields (primarily code fields). This step
443 # is done separately since some of these fields may depend on the
444 # register index enumeration that hasn't been performed yet at the
445 # time of __init__(). The register index enumeration is affected
446 # by predicated register reads/writes. Hence, we forward the flags
447 # that indicate whether or not predication is in use.
448 def finalize(self
, predRead
, predWrite
):
449 self
.flags
= self
.getFlags()
450 self
.constructor
= self
.makeConstructor(predRead
, predWrite
)
451 self
.op_decl
= self
.makeDecl()
454 self
.op_rd
= self
.makeRead(predRead
)
455 self
.op_src_decl
= self
.makeDecl()
458 self
.op_src_decl
= ''
461 self
.op_wb
= self
.makeWrite(predWrite
)
462 self
.op_dest_decl
= self
.makeDecl()
465 self
.op_dest_decl
= ''
473 def isFloatReg(self
):
482 def isControlReg(self
):
491 def isVecPredReg(self
):
498 return self
.isPCState() and self
.reg_spec
500 def hasReadPred(self
):
501 return self
.read_predicate
!= None
503 def hasWritePred(self
):
504 return self
.write_predicate
!= None
507 # note the empty slice '[:]' gives us a copy of self.flags[0]
508 # instead of a reference to it
509 my_flags
= self
.flags
[0][:]
511 my_flags
+= self
.flags
[1]
513 my_flags
+= self
.flags
[2]
517 # Note that initializations in the declarations are solely
518 # to avoid 'uninitialized variable' errors from the compiler.
519 return self
.ctype
+ ' ' + self
.base_name
+ ' = 0;\n';
522 src_reg_constructor
= '\n\t_srcRegIdx[_numSrcRegs++] = RegId(%s, %s);'
523 dst_reg_constructor
= '\n\t_destRegIdx[_numDestRegs++] = RegId(%s, %s);'
526 class IntRegOperand(Operand
):
527 reg_class
= 'IntRegClass'
535 def makeConstructor(self
, predRead
, predWrite
):
540 c_src
= src_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
541 if self
.hasReadPred():
542 c_src
= '\n\tif (%s) {%s\n\t}' % \
543 (self
.read_predicate
, c_src
)
546 c_dest
= dst_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
547 c_dest
+= '\n\t_numIntDestRegs++;'
548 if self
.hasWritePred():
549 c_dest
= '\n\tif (%s) {%s\n\t}' % \
550 (self
.write_predicate
, c_dest
)
552 return c_src
+ c_dest
554 def makeRead(self
, predRead
):
555 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
556 error('Attempt to read integer register as FP')
557 if self
.read_code
!= None:
558 return self
.buildReadCode('readIntRegOperand')
562 int_reg_val
= 'xc->readIntRegOperand(this, _sourceIndex++)'
563 if self
.hasReadPred():
564 int_reg_val
= '(%s) ? %s : 0' % \
565 (self
.read_predicate
, int_reg_val
)
567 int_reg_val
= 'xc->readIntRegOperand(this, %d)' % self
.src_reg_idx
569 return '%s = %s;\n' % (self
.base_name
, int_reg_val
)
571 def makeWrite(self
, predWrite
):
572 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
573 error('Attempt to write integer register as FP')
574 if self
.write_code
!= None:
575 return self
.buildWriteCode('setIntRegOperand')
579 if self
.hasWritePred():
580 wp
= self
.write_predicate
582 wcond
= 'if (%s)' % (wp
)
583 windex
= '_destIndex++'
586 windex
= '%d' % self
.dest_reg_idx
592 xc->setIntRegOperand(this, %s, final_val);\n
593 if (traceData) { traceData->setData(final_val); }
594 }''' % (wcond
, self
.ctype
, self
.base_name
, windex
)
598 class FloatRegOperand(Operand
):
599 reg_class
= 'FloatRegClass'
604 def isFloatReg(self
):
607 def makeConstructor(self
, predRead
, predWrite
):
612 c_src
= src_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
615 c_dest
= dst_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
616 c_dest
+= '\n\t_numFPDestRegs++;'
618 return c_src
+ c_dest
620 def makeRead(self
, predRead
):
621 if self
.read_code
!= None:
622 return self
.buildReadCode('readFloatRegOperandBits')
625 rindex
= '_sourceIndex++'
627 rindex
= '%d' % self
.src_reg_idx
629 code
= 'xc->readFloatRegOperandBits(this, %s)' % rindex
630 if self
.ctype
== 'float':
631 code
= 'bitsToFloat32(%s)' % code
632 elif self
.ctype
== 'double':
633 code
= 'bitsToFloat64(%s)' % code
634 return '%s = %s;\n' % (self
.base_name
, code
)
636 def makeWrite(self
, predWrite
):
637 if self
.write_code
!= None:
638 return self
.buildWriteCode('setFloatRegOperandBits')
643 wp
= '%d' % self
.dest_reg_idx
646 if self
.ctype
== 'float':
647 val
= 'floatToBits32(%s)' % val
648 elif self
.ctype
== 'double':
649 val
= 'floatToBits64(%s)' % val
651 wp
= 'xc->setFloatRegOperandBits(this, %s, %s);' % (wp
, val
)
657 if (traceData) { traceData->setData(final_val); }
658 }''' % (self
.ctype
, self
.base_name
, wp
)
661 class VecRegOperand(Operand
):
662 reg_class
= 'VecRegClass'
664 def __init__(self
, parser
, full_name
, ext
, is_src
, is_dest
):
665 Operand
.__init
__(self
, parser
, full_name
, ext
, is_src
, is_dest
)
675 def makeDeclElem(self
, elem_op
):
676 (elem_name
, elem_ext
) = elem_op
677 (elem_spec
, dflt_elem_ext
, zeroing
) = self
.elems
[elem_name
]
682 ctype
= self
.parser
.operandTypeMap
[ext
]
683 return '\n\t%s %s = 0;' % (ctype
, elem_name
)
686 if not self
.is_dest
and self
.is_src
:
687 c_decl
= '\t/* Vars for %s*/' % (self
.base_name
)
688 if hasattr(self
, 'active_elems'):
689 if self
.active_elems
:
690 for elem
in self
.active_elems
:
691 c_decl
+= self
.makeDeclElem(elem
)
692 return c_decl
+ '\t/* End vars for %s */\n' % (self
.base_name
)
696 def makeConstructor(self
, predRead
, predWrite
):
703 c_src
= src_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
706 c_dest
= dst_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
707 c_dest
+= '\n\t_numVecDestRegs++;'
709 return c_src
+ c_dest
711 # Read destination register to write
712 def makeReadWElem(self
, elem_op
):
713 (elem_name
, elem_ext
) = elem_op
714 (elem_spec
, dflt_elem_ext
, zeroing
) = self
.elems
[elem_name
]
719 ctype
= self
.parser
.operandTypeMap
[ext
]
720 c_read
= '\t\t%s& %s = %s[%s];\n' % \
721 (ctype
, elem_name
, self
.base_name
, elem_spec
)
724 def makeReadW(self
, predWrite
):
725 func
= 'getWritableVecRegOperand'
726 if self
.read_code
!= None:
727 return self
.buildReadCode(func
)
730 rindex
= '_destIndex++'
732 rindex
= '%d' % self
.dest_reg_idx
734 c_readw
= '\t\t%s& tmp_d%s = xc->%s(this, %s);\n'\
735 % ('TheISA::VecRegContainer', rindex
, func
, rindex
)
737 c_readw
+= '\t\tauto %s = tmp_d%s.as<%s>();\n' % (self
.base_name
,
738 rindex
, self
.parser
.operandTypeMap
[self
.elemExt
])
740 c_readw
+= '\t\tauto %s = tmp_d%s.as<%s>();\n' % (self
.base_name
,
741 rindex
, self
.parser
.operandTypeMap
[self
.ext
])
742 if hasattr(self
, 'active_elems'):
743 if self
.active_elems
:
744 for elem
in self
.active_elems
:
745 c_readw
+= self
.makeReadWElem(elem
)
748 # Normal source operand read
749 def makeReadElem(self
, elem_op
, name
):
750 (elem_name
, elem_ext
) = elem_op
751 (elem_spec
, dflt_elem_ext
, zeroing
) = self
.elems
[elem_name
]
757 ctype
= self
.parser
.operandTypeMap
[ext
]
758 c_read
= '\t\t%s = %s[%s];\n' % \
759 (elem_name
, name
, elem_spec
)
762 def makeRead(self
, predRead
):
763 func
= 'readVecRegOperand'
764 if self
.read_code
!= None:
765 return self
.buildReadCode(func
)
768 rindex
= '_sourceIndex++'
770 rindex
= '%d' % self
.src_reg_idx
772 name
= self
.base_name
773 if self
.is_dest
and self
.is_src
:
776 c_read
= '\t\t%s& tmp_s%s = xc->%s(this, %s);\n' \
777 % ('const TheISA::VecRegContainer', rindex
, func
, rindex
)
778 # If the parser has detected that elements are being access, create
779 # the appropriate view
781 c_read
+= '\t\tauto %s = tmp_s%s.as<%s>();\n' % \
782 (name
, rindex
, self
.parser
.operandTypeMap
[self
.elemExt
])
784 c_read
+= '\t\tauto %s = tmp_s%s.as<%s>();\n' % \
785 (name
, rindex
, self
.parser
.operandTypeMap
[self
.ext
])
786 if hasattr(self
, 'active_elems'):
787 if self
.active_elems
:
788 for elem
in self
.active_elems
:
789 c_read
+= self
.makeReadElem(elem
, name
)
792 def makeWrite(self
, predWrite
):
793 func
= 'setVecRegOperand'
794 if self
.write_code
!= None:
795 return self
.buildWriteCode(func
)
799 traceData->setData(tmp_d%d);
801 ''' % self
.dest_reg_idx
804 def finalize(self
, predRead
, predWrite
):
805 super(VecRegOperand
, self
).finalize(predRead
, predWrite
)
807 self
.op_rd
= self
.makeReadW(predWrite
) + self
.op_rd
809 class VecElemOperand(Operand
):
810 reg_class
= 'VecElemClass'
819 if self
.is_dest
and not self
.is_src
:
820 return '\n\t%s %s;' % (self
.ctype
, self
.base_name
)
824 def makeConstructor(self
, predRead
, predWrite
):
831 c_src
= ('\n\t_srcRegIdx[_numSrcRegs++] = RegId(%s, %s, %s);' %
832 (self
.reg_class
, self
.reg_spec
, self
.elem_spec
))
835 c_dest
= ('\n\t_destRegIdx[_numDestRegs++] = RegId(%s, %s, %s);' %
836 (self
.reg_class
, self
.reg_spec
, self
.elem_spec
))
837 c_dest
+= '\n\t_numVecElemDestRegs++;'
838 return c_src
+ c_dest
840 def makeRead(self
, predRead
):
841 c_read
= 'xc->readVecElemOperand(this, %d)' % self
.src_reg_idx
843 if self
.ctype
== 'float':
844 c_read
= 'bitsToFloat32(%s)' % c_read
845 elif self
.ctype
== 'double':
846 c_read
= 'bitsToFloat64(%s)' % c_read
848 return '\n\t%s %s = %s;\n' % (self
.ctype
, self
.base_name
, c_read
)
850 def makeWrite(self
, predWrite
):
851 if self
.ctype
== 'float':
852 c_write
= 'floatToBits32(%s)' % self
.base_name
853 elif self
.ctype
== 'double':
854 c_write
= 'floatToBits64(%s)' % self
.base_name
856 c_write
= self
.base_name
858 c_write
= ('\n\txc->setVecElemOperand(this, %d, %s);' %
859 (self
.dest_reg_idx
, c_write
))
863 class VecPredRegOperand(Operand
):
864 reg_class
= 'VecPredRegClass'
866 def __init__(self
, parser
, full_name
, ext
, is_src
, is_dest
):
867 Operand
.__init
__(self
, parser
, full_name
, ext
, is_src
, is_dest
)
873 def isVecPredReg(self
):
879 def makeConstructor(self
, predRead
, predWrite
):
884 c_src
= src_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
887 c_dest
= dst_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
888 c_dest
+= '\n\t_numVecPredDestRegs++;'
890 return c_src
+ c_dest
892 def makeRead(self
, predRead
):
893 func
= 'readVecPredRegOperand'
894 if self
.read_code
!= None:
895 return self
.buildReadCode(func
)
898 rindex
= '_sourceIndex++'
900 rindex
= '%d' % self
.src_reg_idx
902 c_read
= '\t\t%s& tmp_s%s = xc->%s(this, %s);\n' % (
903 'const TheISA::VecPredRegContainer', rindex
, func
, rindex
)
905 c_read
+= '\t\tauto %s = tmp_s%s.as<%s>();\n' % (
906 self
.base_name
, rindex
,
907 self
.parser
.operandTypeMap
[self
.ext
])
910 def makeReadW(self
, predWrite
):
911 func
= 'getWritableVecPredRegOperand'
912 if self
.read_code
!= None:
913 return self
.buildReadCode(func
)
916 rindex
= '_destIndex++'
918 rindex
= '%d' % self
.dest_reg_idx
920 c_readw
= '\t\t%s& tmp_d%s = xc->%s(this, %s);\n' % (
921 'TheISA::VecPredRegContainer', rindex
, func
, rindex
)
923 c_readw
+= '\t\tauto %s = tmp_d%s.as<%s>();\n' % (
924 self
.base_name
, rindex
,
925 self
.parser
.operandTypeMap
[self
.ext
])
928 def makeWrite(self
, predWrite
):
929 func
= 'setVecPredRegOperand'
930 if self
.write_code
!= None:
931 return self
.buildWriteCode(func
)
935 traceData->setData(tmp_d%d);
937 ''' % self
.dest_reg_idx
940 def finalize(self
, predRead
, predWrite
):
941 super(VecPredRegOperand
, self
).finalize(predRead
, predWrite
)
943 self
.op_rd
= self
.makeReadW(predWrite
) + self
.op_rd
945 class CCRegOperand(Operand
):
946 reg_class
= 'CCRegClass'
954 def makeConstructor(self
, predRead
, predWrite
):
959 c_src
= src_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
960 if self
.hasReadPred():
961 c_src
= '\n\tif (%s) {%s\n\t}' % \
962 (self
.read_predicate
, c_src
)
965 c_dest
= dst_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
966 c_dest
+= '\n\t_numCCDestRegs++;'
967 if self
.hasWritePred():
968 c_dest
= '\n\tif (%s) {%s\n\t}' % \
969 (self
.write_predicate
, c_dest
)
971 return c_src
+ c_dest
973 def makeRead(self
, predRead
):
974 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
975 error('Attempt to read condition-code register as FP')
976 if self
.read_code
!= None:
977 return self
.buildReadCode('readCCRegOperand')
981 int_reg_val
= 'xc->readCCRegOperand(this, _sourceIndex++)'
982 if self
.hasReadPred():
983 int_reg_val
= '(%s) ? %s : 0' % \
984 (self
.read_predicate
, int_reg_val
)
986 int_reg_val
= 'xc->readCCRegOperand(this, %d)' % self
.src_reg_idx
988 return '%s = %s;\n' % (self
.base_name
, int_reg_val
)
990 def makeWrite(self
, predWrite
):
991 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
992 error('Attempt to write condition-code register as FP')
993 if self
.write_code
!= None:
994 return self
.buildWriteCode('setCCRegOperand')
998 if self
.hasWritePred():
999 wp
= self
.write_predicate
1001 wcond
= 'if (%s)' % (wp
)
1002 windex
= '_destIndex++'
1005 windex
= '%d' % self
.dest_reg_idx
1011 xc->setCCRegOperand(this, %s, final_val);\n
1012 if (traceData) { traceData->setData(final_val); }
1013 }''' % (wcond
, self
.ctype
, self
.base_name
, windex
)
1017 class ControlRegOperand(Operand
):
1018 reg_class
= 'MiscRegClass'
1023 def isControlReg(self
):
1026 def makeConstructor(self
, predRead
, predWrite
):
1031 c_src
= src_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
1034 c_dest
= dst_reg_constructor
% (self
.reg_class
, self
.reg_spec
)
1036 return c_src
+ c_dest
1038 def makeRead(self
, predRead
):
1040 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1041 error('Attempt to read control register as FP')
1042 if self
.read_code
!= None:
1043 return self
.buildReadCode('readMiscRegOperand')
1046 rindex
= '_sourceIndex++'
1048 rindex
= '%d' % self
.src_reg_idx
1050 return '%s = xc->readMiscRegOperand(this, %s);\n' % \
1051 (self
.base_name
, rindex
)
1053 def makeWrite(self
, predWrite
):
1054 if (self
.ctype
== 'float' or self
.ctype
== 'double'):
1055 error('Attempt to write control register as FP')
1056 if self
.write_code
!= None:
1057 return self
.buildWriteCode('setMiscRegOperand')
1060 windex
= '_destIndex++'
1062 windex
= '%d' % self
.dest_reg_idx
1064 wb
= 'xc->setMiscRegOperand(this, %s, %s);\n' % \
1065 (windex
, self
.base_name
)
1066 wb
+= 'if (traceData) { traceData->setData(%s); }' % \
1071 class MemOperand(Operand
):
1075 def makeConstructor(self
, predRead
, predWrite
):
1079 # Declare memory data variable.
1080 return '%s %s;\n' % (self
.ctype
, self
.base_name
)
1082 def makeRead(self
, predRead
):
1083 if self
.read_code
!= None:
1084 return self
.buildReadCode()
1087 def makeWrite(self
, predWrite
):
1088 if self
.write_code
!= None:
1089 return self
.buildWriteCode()
1092 class PCStateOperand(Operand
):
1093 def makeConstructor(self
, predRead
, predWrite
):
1096 def makeRead(self
, predRead
):
1098 # A component of the PC state.
1099 return '%s = __parserAutoPCState.%s();\n' % \
1100 (self
.base_name
, self
.reg_spec
)
1102 # The whole PC state itself.
1103 return '%s = xc->pcState();\n' % self
.base_name
1105 def makeWrite(self
, predWrite
):
1107 # A component of the PC state.
1108 return '__parserAutoPCState.%s(%s);\n' % \
1109 (self
.reg_spec
, self
.base_name
)
1111 # The whole PC state itself.
1112 return 'xc->pcState(%s);\n' % self
.base_name
1115 ctype
= 'TheISA::PCState'
1118 # Note that initializations in the declarations are solely
1119 # to avoid 'uninitialized variable' errors from the compiler.
1120 return '%s %s = 0;\n' % (ctype
, self
.base_name
)
1122 def isPCState(self
):
1125 class OperandList(object):
1126 '''Find all the operands in the given code block. Returns an operand
1127 descriptor list (instance of class OperandList).'''
1128 def __init__(self
, parser
, code
):
1131 # delete strings and comments so we don't match on operands inside
1132 for regEx
in (stringRE
, commentRE
):
1133 code
= regEx
.sub('', code
)
1134 # search for operands
1137 match
= parser
.operandsRE
.search(code
, next_pos
)
1139 # no more matches: we're done
1142 # regexp groups are operand full name, base, and extension
1143 (op_full
, op_base
, op_ext
) = op
1144 # If is a elem operand, define or update the corresponding
1147 if op_base
in parser
.elemToVector
:
1149 elem_op
= (op_base
, op_ext
)
1150 op_base
= parser
.elemToVector
[op_base
]
1151 op_ext
= '' # use the default one
1152 # if the token following the operand is an assignment, this is
1153 # a destination (LHS), else it's a source (RHS)
1154 is_dest
= (assignRE
.match(code
, match
.end()) != None)
1155 is_src
= not is_dest
1157 # see if we've already seen this one
1158 op_desc
= self
.find_base(op_base
)
1160 if op_ext
and op_ext
!= '' and op_desc
.ext
!= op_ext
:
1161 error ('Inconsistent extensions for operand %s: %s - %s' \
1162 % (op_base
, op_desc
.ext
, op_ext
))
1163 op_desc
.is_src
= op_desc
.is_src
or is_src
1164 op_desc
.is_dest
= op_desc
.is_dest
or is_dest
1166 (elem_base
, elem_ext
) = elem_op
1168 for ae
in op_desc
.active_elems
:
1169 (ae_base
, ae_ext
) = ae
1170 if ae_base
== elem_base
:
1171 if ae_ext
!= elem_ext
:
1172 error('Inconsistent extensions for elem'
1173 ' operand %s' % elem_base
)
1177 op_desc
.active_elems
.append(elem_op
)
1179 # new operand: create new descriptor
1180 op_desc
= parser
.operandNameMap
[op_base
](parser
,
1181 op_full
, op_ext
, is_src
, is_dest
)
1182 # if operand is a vector elem, add the corresponding vector
1183 # operand if not already done
1185 op_desc
.elemExt
= elem_op
[1]
1186 op_desc
.active_elems
= [elem_op
]
1187 self
.append(op_desc
)
1188 # start next search after end of current match
1189 next_pos
= match
.end()
1191 # enumerate source & dest register operands... used in building
1194 self
.numDestRegs
= 0
1195 self
.numFPDestRegs
= 0
1196 self
.numIntDestRegs
= 0
1197 self
.numVecDestRegs
= 0
1198 self
.numVecPredDestRegs
= 0
1199 self
.numCCDestRegs
= 0
1200 self
.numMiscDestRegs
= 0
1201 self
.memOperand
= None
1203 # Flags to keep track if one or more operands are to be read/written
1205 self
.predRead
= False
1206 self
.predWrite
= False
1208 for op_desc
in self
.items
:
1211 op_desc
.src_reg_idx
= self
.numSrcRegs
1212 self
.numSrcRegs
+= 1
1214 op_desc
.dest_reg_idx
= self
.numDestRegs
1215 self
.numDestRegs
+= 1
1216 if op_desc
.isFloatReg():
1217 self
.numFPDestRegs
+= 1
1218 elif op_desc
.isIntReg():
1219 self
.numIntDestRegs
+= 1
1220 elif op_desc
.isVecReg():
1221 self
.numVecDestRegs
+= 1
1222 elif op_desc
.isVecPredReg():
1223 self
.numVecPredDestRegs
+= 1
1224 elif op_desc
.isCCReg():
1225 self
.numCCDestRegs
+= 1
1226 elif op_desc
.isControlReg():
1227 self
.numMiscDestRegs
+= 1
1228 elif op_desc
.isMem():
1230 error("Code block has more than one memory operand.")
1231 self
.memOperand
= op_desc
1233 # Check if this operand has read/write predication. If true, then
1234 # the microop will dynamically index source/dest registers.
1235 self
.predRead
= self
.predRead
or op_desc
.hasReadPred()
1236 self
.predWrite
= self
.predWrite
or op_desc
.hasWritePred()
1238 if parser
.maxInstSrcRegs
< self
.numSrcRegs
:
1239 parser
.maxInstSrcRegs
= self
.numSrcRegs
1240 if parser
.maxInstDestRegs
< self
.numDestRegs
:
1241 parser
.maxInstDestRegs
= self
.numDestRegs
1242 if parser
.maxMiscDestRegs
< self
.numMiscDestRegs
:
1243 parser
.maxMiscDestRegs
= self
.numMiscDestRegs
1245 # now make a final pass to finalize op_desc fields that may depend
1246 # on the register enumeration
1247 for op_desc
in self
.items
:
1248 op_desc
.finalize(self
.predRead
, self
.predWrite
)
1251 return len(self
.items
)
1253 def __getitem__(self
, index
):
1254 return self
.items
[index
]
1256 def append(self
, op_desc
):
1257 self
.items
.append(op_desc
)
1258 self
.bases
[op_desc
.base_name
] = op_desc
1260 def find_base(self
, base_name
):
1261 # like self.bases[base_name], but returns None if not found
1262 # (rather than raising exception)
1263 return self
.bases
.get(base_name
)
1265 # internal helper function for concat[Some]Attr{Strings|Lists}
1266 def __internalConcatAttrs(self
, attr_name
, filter, result
):
1267 for op_desc
in self
.items
:
1269 result
+= getattr(op_desc
, attr_name
)
1272 # return a single string that is the concatenation of the (string)
1273 # values of the specified attribute for all operands
1274 def concatAttrStrings(self
, attr_name
):
1275 return self
.__internalConcatAttrs
(attr_name
, lambda x
: 1, '')
1277 # like concatAttrStrings, but only include the values for the operands
1278 # for which the provided filter function returns true
1279 def concatSomeAttrStrings(self
, filter, attr_name
):
1280 return self
.__internalConcatAttrs
(attr_name
, filter, '')
1282 # return a single list that is the concatenation of the (list)
1283 # values of the specified attribute for all operands
1284 def concatAttrLists(self
, attr_name
):
1285 return self
.__internalConcatAttrs
(attr_name
, lambda x
: 1, [])
1287 # like concatAttrLists, but only include the values for the operands
1288 # for which the provided filter function returns true
1289 def concatSomeAttrLists(self
, filter, attr_name
):
1290 return self
.__internalConcatAttrs
(attr_name
, filter, [])
1293 self
.items
.sort(lambda a
, b
: a
.sort_pri
- b
.sort_pri
)
1295 class SubOperandList(OperandList
):
1296 '''Find all the operands in the given code block. Returns an operand
1297 descriptor list (instance of class OperandList).'''
1298 def __init__(self
, parser
, code
, master_list
):
1301 # delete strings and comments so we don't match on operands inside
1302 for regEx
in (stringRE
, commentRE
):
1303 code
= regEx
.sub('', code
)
1304 # search for operands
1307 match
= parser
.operandsRE
.search(code
, next_pos
)
1309 # no more matches: we're done
1312 # regexp groups are operand full name, base, and extension
1313 (op_full
, op_base
, op_ext
) = op
1314 # If is a elem operand, define or update the corresponding
1316 if op_base
in parser
.elemToVector
:
1318 op_base
= parser
.elemToVector
[elem_op
]
1319 # find this op in the master list
1320 op_desc
= master_list
.find_base(op_base
)
1322 error('Found operand %s which is not in the master list!'
1325 # See if we've already found this operand
1326 op_desc
= self
.find_base(op_base
)
1328 # if not, add a reference to it to this sub list
1329 self
.append(master_list
.bases
[op_base
])
1331 # start next search after end of current match
1332 next_pos
= match
.end()
1334 self
.memOperand
= None
1335 # Whether the whole PC needs to be read so parts of it can be accessed
1337 # Whether the whole PC needs to be written after parts of it were
1340 # Whether this instruction manipulates the whole PC or parts of it.
1341 # Mixing the two is a bad idea and flagged as an error.
1344 # Flags to keep track if one or more operands are to be read/written
1346 self
.predRead
= False
1347 self
.predWrite
= False
1349 for op_desc
in self
.items
:
1350 if op_desc
.isPCPart():
1355 if op_desc
.isPCState():
1356 if self
.pcPart
is not None:
1357 if self
.pcPart
and not op_desc
.isPCPart() or \
1358 not self
.pcPart
and op_desc
.isPCPart():
1359 error("Mixed whole and partial PC state operands.")
1360 self
.pcPart
= op_desc
.isPCPart()
1364 error("Code block has more than one memory operand.")
1365 self
.memOperand
= op_desc
1367 # Check if this operand has read/write predication. If true, then
1368 # the microop will dynamically index source/dest registers.
1369 self
.predRead
= self
.predRead
or op_desc
.hasReadPred()
1370 self
.predWrite
= self
.predWrite
or op_desc
.hasWritePred()
1372 # Regular expression object to match C++ strings
1373 stringRE
= re
.compile(r
'"([^"\\]|\\.)*"')
1375 # Regular expression object to match C++ comments
1376 # (used in findOperands())
1377 commentRE
= re
.compile(r
'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
1378 re
.DOTALL | re
.MULTILINE
)
1380 # Regular expression object to match assignment statements (used in
1381 # findOperands()). If the code immediately following the first
1382 # appearance of the operand matches this regex, then the operand
1383 # appears to be on the LHS of an assignment, and is thus a
1384 # destination. basically we're looking for an '=' that's not '=='.
1385 # The heinous tangle before that handles the case where the operand
1386 # has an array subscript.
1387 assignRE
= re
.compile(r
'(\[[^\]]+\])?\s*=(?!=)', re
.MULTILINE
)
1389 def makeFlagConstructor(flag_list
):
1390 if len(flag_list
) == 0:
1392 # filter out repeated flags
1395 while i
< len(flag_list
):
1396 if flag_list
[i
] == flag_list
[i
-1]:
1402 code
= pre
+ string
.join(flag_list
, post
+ pre
) + post
1405 # Assume all instruction flags are of the form 'IsFoo'
1406 instFlagRE
= re
.compile(r
'Is.*')
1408 # OpClass constants end in 'Op' except No_OpClass
1409 opClassRE
= re
.compile(r
'.*Op|No_OpClass')
1411 class InstObjParams(object):
1412 def __init__(self
, parser
, mnem
, class_name
, base_class
= '',
1413 snippets
= {}, opt_args
= []):
1414 self
.mnemonic
= mnem
1415 self
.class_name
= class_name
1416 self
.base_class
= base_class
1417 if not isinstance(snippets
, dict):
1418 snippets
= {'code' : snippets
}
1419 compositeCode
= ' '.join(map(str, snippets
.values()))
1420 self
.snippets
= snippets
1422 self
.operands
= OperandList(parser
, compositeCode
)
1424 # The header of the constructor declares the variables to be used
1425 # in the body of the constructor.
1427 header
+= '\n\t_numSrcRegs = 0;'
1428 header
+= '\n\t_numDestRegs = 0;'
1429 header
+= '\n\t_numFPDestRegs = 0;'
1430 header
+= '\n\t_numVecDestRegs = 0;'
1431 header
+= '\n\t_numVecElemDestRegs = 0;'
1432 header
+= '\n\t_numVecPredDestRegs = 0;'
1433 header
+= '\n\t_numIntDestRegs = 0;'
1434 header
+= '\n\t_numCCDestRegs = 0;'
1436 self
.constructor
= header
+ \
1437 self
.operands
.concatAttrStrings('constructor')
1439 self
.flags
= self
.operands
.concatAttrLists('flags')
1441 self
.op_class
= None
1443 # Optional arguments are assumed to be either StaticInst flags
1444 # or an OpClass value. To avoid having to import a complete
1445 # list of these values to match against, we do it ad-hoc
1448 if instFlagRE
.match(oa
):
1449 self
.flags
.append(oa
)
1450 elif opClassRE
.match(oa
):
1453 error('InstObjParams: optional arg "%s" not recognized '
1454 'as StaticInst::Flag or OpClass.' % oa
)
1456 # Make a basic guess on the operand class if not set.
1457 # These are good enough for most cases.
1458 if not self
.op_class
:
1459 if 'IsStore' in self
.flags
:
1460 # The order matters here: 'IsFloating' and 'IsInteger' are
1461 # usually set in FP instructions because of the base
1463 if 'IsFloating' in self
.flags
:
1464 self
.op_class
= 'FloatMemWriteOp'
1466 self
.op_class
= 'MemWriteOp'
1467 elif 'IsLoad' in self
.flags
or 'IsPrefetch' in self
.flags
:
1468 # The order matters here: 'IsFloating' and 'IsInteger' are
1469 # usually set in FP instructions because of the base
1471 if 'IsFloating' in self
.flags
:
1472 self
.op_class
= 'FloatMemReadOp'
1474 self
.op_class
= 'MemReadOp'
1475 elif 'IsFloating' in self
.flags
:
1476 self
.op_class
= 'FloatAddOp'
1477 elif 'IsVector' in self
.flags
:
1478 self
.op_class
= 'SimdAddOp'
1480 self
.op_class
= 'IntAluOp'
1482 # add flag initialization to contructor here to include
1483 # any flags added via opt_args
1484 self
.constructor
+= makeFlagConstructor(self
.flags
)
1486 # if 'IsFloating' is set, add call to the FP enable check
1487 # function (which should be provided by isa_desc via a declare)
1488 # if 'IsVector' is set, add call to the Vector enable check
1489 # function (which should be provided by isa_desc via a declare)
1490 if 'IsFloating' in self
.flags
:
1491 self
.fp_enable_check
= 'fault = checkFpEnableFault(xc);'
1492 elif 'IsVector' in self
.flags
:
1493 self
.fp_enable_check
= 'fault = checkVecEnableFault(xc);'
1495 self
.fp_enable_check
= ''
1498 # Stack: a simple stack object. Used for both formats (formatStack)
1499 # and default cases (defaultStack). Simply wraps a list to give more
1500 # stack-like syntax and enable initialization with an argument list
1501 # (as opposed to an argument that's a list).
1504 def __init__(self
, *items
):
1505 list.__init
__(self
, items
)
1507 def push(self
, item
):
1513 # Format a file include stack backtrace as a string
1514 def backtrace(filename_stack
):
1515 fmt
= "In file included from %s:"
1516 return "\n".join([fmt
% f
for f
in filename_stack
])
1519 #######################
1521 # LineTracker: track filenames along with line numbers in PLY lineno fields
1522 # PLY explicitly doesn't do anything with 'lineno' except propagate
1523 # it. This class lets us tie filenames with the line numbers with a
1524 # minimum of disruption to existing increment code.
1527 class LineTracker(object):
1528 def __init__(self
, filename
, lineno
=1):
1529 self
.filename
= filename
1530 self
.lineno
= lineno
1532 # Overload '+=' for increments. We need to create a new object on
1533 # each update else every token ends up referencing the same
1534 # constantly incrementing instance.
1535 def __iadd__(self
, incr
):
1536 return LineTracker(self
.filename
, self
.lineno
+ incr
)
1539 return "%s:%d" % (self
.filename
, self
.lineno
)
1541 # In case there are places where someone really expects a number
1546 #######################
1549 # parses ISA DSL and emits C++ headers and source
1552 class ISAParser(Grammar
):
1553 def __init__(self
, output_dir
):
1554 super(ISAParser
, self
).__init
__()
1555 self
.output_dir
= output_dir
1557 self
.filename
= None # for output file watermarking/scaremongering
1559 # variable to hold templates
1560 self
.templateMap
= {}
1562 # This dictionary maps format name strings to Format objects.
1565 # Track open files and, if applicable, how many chunks it has been
1566 # split into so far.
1570 # isa_name / namespace identifier from namespace declaration.
1571 # before the namespace declaration, None.
1572 self
.isa_name
= None
1573 self
.namespace
= None
1576 self
.formatStack
= Stack(NoFormat())
1578 # The default case stack.
1579 self
.defaultStack
= Stack(None)
1581 # Stack that tracks current file and line number. Each
1582 # element is a tuple (filename, lineno) that records the
1583 # *current* filename and the line number in the *previous*
1584 # file where it was included.
1585 self
.fileNameStack
= Stack()
1587 symbols
= ('makeList', 're', 'string')
1588 self
.exportContext
= dict([(s
, eval(s
)) for s
in symbols
])
1590 self
.maxInstSrcRegs
= 0
1591 self
.maxInstDestRegs
= 0
1592 self
.maxMiscDestRegs
= 0
1594 def __getitem__(self
, i
): # Allow object (self) to be
1595 return getattr(self
, i
) # passed to %-substitutions
1597 # Change the file suffix of a base filename:
1598 # (e.g.) decoder.cc -> decoder-g.cc.inc for 'global' outputs
1599 def suffixize(self
, s
, sec
):
1600 extn
= re
.compile('(\.[^\.]+)$') # isolate extension
1602 return extn
.sub(r
'-ns\1.inc', s
) # insert some text on either side
1604 return extn
.sub(r
'-g\1.inc', s
)
1606 # Get the file object for emitting code into the specified section
1607 # (header, decoder, exec, decode_block).
1608 def get_file(self
, section
):
1609 if section
== 'decode_block':
1610 filename
= 'decode-method.cc.inc'
1612 if section
== 'header':
1615 file = '%s.cc' % section
1616 filename
= self
.suffixize(file, section
)
1618 return self
.files
[filename
]
1619 except KeyError: pass
1621 f
= self
.open(filename
)
1622 self
.files
[filename
] = f
1624 # The splittable files are the ones with many independent
1625 # per-instruction functions - the decoder's instruction constructors
1626 # and the instruction execution (execute()) methods. These both have
1627 # the suffix -ns.cc.inc, meaning they are within the namespace part
1628 # of the ISA, contain object-emitting C++ source, and are included
1629 # into other top-level files. These are the files that need special
1630 # #define's to allow parts of them to be compiled separately. Rather
1631 # than splitting the emissions into separate files, the monolithic
1632 # output of the ISA parser is maintained, but the value (or lack
1633 # thereof) of the __SPLIT definition during C preprocessing will
1634 # select the different chunks. If no 'split' directives are used,
1635 # the cpp emissions have no effect.
1636 if re
.search('-ns.cc.inc$', filename
):
1637 print('#if !defined(__SPLIT) || (__SPLIT == 1)', file=f
)
1639 # ensure requisite #include's
1640 elif filename
== 'decoder-g.hh.inc':
1641 print('#include "base/bitfield.hh"', file=f
)
1645 # Weave together the parts of the different output sections by
1646 # #include'ing them into some very short top-level .cc/.hh files.
1647 # These small files make it much clearer how this tool works, since
1648 # you directly see the chunks emitted as files that are #include'd.
1649 def write_top_level_files(self
):
1650 # decoder header - everything depends on this
1652 with self
.open(file) as f
:
1653 f
.write('#ifndef __ARCH_%(isa)s_GENERATED_DECODER_HH__\n'
1654 '#define __ARCH_%(isa)s_GENERATED_DECODER_HH__\n\n' %
1655 {'isa': self
.isa_name
.upper()})
1656 fn
= 'decoder-g.hh.inc'
1657 assert(fn
in self
.files
)
1658 f
.write('#include "%s"\n' % fn
)
1660 fn
= 'decoder-ns.hh.inc'
1661 assert(fn
in self
.files
)
1662 f
.write('namespace %s {\n#include "%s"\n}\n'
1663 % (self
.namespace
, fn
))
1664 f
.write('\n#endif // __ARCH_%s_GENERATED_DECODER_HH__\n' %
1665 self
.isa_name
.upper())
1667 # decoder method - cannot be split
1669 with self
.open(file) as f
:
1670 fn
= 'base/compiler.hh'
1671 f
.write('#include "%s"\n' % fn
)
1673 fn
= 'decoder-g.cc.inc'
1674 assert(fn
in self
.files
)
1675 f
.write('#include "%s"\n' % fn
)
1678 f
.write('#include "%s"\n' % fn
)
1680 fn
= 'decode-method.cc.inc'
1681 # is guaranteed to have been written for parse to complete
1682 f
.write('#include "%s"\n' % fn
)
1684 extn
= re
.compile('(\.[^\.]+)$')
1686 # instruction constructors
1687 splits
= self
.splits
[self
.get_file('decoder')]
1688 file_
= 'inst-constrs.cc'
1689 for i
in range(1, splits
+1):
1691 file = extn
.sub(r
'-%d\1' % i
, file_
)
1694 with self
.open(file) as f
:
1695 fn
= 'decoder-g.cc.inc'
1696 assert(fn
in self
.files
)
1697 f
.write('#include "%s"\n' % fn
)
1700 f
.write('#include "%s"\n' % fn
)
1702 fn
= 'decoder-ns.cc.inc'
1703 assert(fn
in self
.files
)
1704 print('namespace %s {' % self
.namespace
, file=f
)
1706 print('#define __SPLIT %u' % i
, file=f
)
1707 print('#include "%s"' % fn
, file=f
)
1710 # instruction execution
1711 splits
= self
.splits
[self
.get_file('exec')]
1712 for i
in range(1, splits
+1):
1713 file = 'generic_cpu_exec.cc'
1715 file = extn
.sub(r
'_%d\1' % i
, file)
1716 with self
.open(file) as f
:
1717 fn
= 'exec-g.cc.inc'
1718 assert(fn
in self
.files
)
1719 f
.write('#include "%s"\n' % fn
)
1720 f
.write('#include "cpu/exec_context.hh"\n')
1721 f
.write('#include "decoder.hh"\n')
1723 fn
= 'exec-ns.cc.inc'
1724 assert(fn
in self
.files
)
1725 print('namespace %s {' % self
.namespace
, file=f
)
1727 print('#define __SPLIT %u' % i
, file=f
)
1728 print('#include "%s"' % fn
, file=f
)
1732 self
.update('max_inst_regs.hh',
1733 '''namespace %(namespace)s {
1734 const int MaxInstSrcRegs = %(maxInstSrcRegs)d;
1735 const int MaxInstDestRegs = %(maxInstDestRegs)d;
1736 const int MaxMiscDestRegs = %(maxMiscDestRegs)d;\n}\n''' % self
)
1738 scaremonger_template
='''// DO NOT EDIT
1739 // This file was automatically generated from an ISA description:
1744 #####################################################################
1748 # The PLY lexer module takes two things as input:
1749 # - A list of token names (the string list 'tokens')
1750 # - A regular expression describing a match for each token. The
1751 # regexp for token FOO can be provided in two ways:
1752 # - as a string variable named t_FOO
1753 # - as the doc string for a function named t_FOO. In this case,
1754 # the function is also executed, allowing an action to be
1755 # associated with each token match.
1757 #####################################################################
1759 # Reserved words. These are listed separately as they are matched
1760 # using the same regexp as generic IDs, but distinguished in the
1761 # t_ID() function. The PLY documentation suggests this approach.
1763 'BITFIELD', 'DECODE', 'DECODER', 'DEFAULT', 'DEF', 'EXEC', 'FORMAT',
1764 'HEADER', 'LET', 'NAMESPACE', 'OPERAND_TYPES', 'OPERANDS',
1765 'OUTPUT', 'SIGNED', 'SPLIT', 'TEMPLATE'
1768 # List of tokens. The lex module requires this.
1769 tokens
= reserved
+ (
1782 # ( ) [ ] { } < > , ; . : :: *
1784 'LBRACKET', 'RBRACKET',
1786 'LESS', 'GREATER', 'EQUALS',
1787 'COMMA', 'SEMI', 'DOT', 'COLON', 'DBLCOLON',
1790 # C preprocessor directives
1793 # The following are matched but never returned. commented out to
1794 # suppress PLY warning
1802 # Regular expressions for token matching
1819 # Identifiers and reserved words
1822 reserved_map
[r
.lower()] = r
1826 t
.type = self
.reserved_map
.get(t
.value
, 'ID')
1830 def t_INTLIT(self
, t
):
1831 r
'-?(0x[\da-fA-F]+)|\d+'
1833 t
.value
= int(t
.value
,0)
1835 error(t
.lexer
.lineno
, 'Integer value "%s" too large' % t
.value
)
1839 # String literal. Note that these use only single quotes, and
1840 # can span multiple lines.
1841 def t_STRLIT(self
, t
):
1844 t
.value
= t
.value
[1:-1]
1845 t
.lexer
.lineno
+= t
.value
.count('\n')
1849 # "Code literal"... like a string literal, but delimiters are
1850 # '{{' and '}}' so they get formatted nicely under emacs c-mode
1851 def t_CODELIT(self
, t
):
1852 r
"(?m)\{\{([^\}]|}(?!\}))+\}\}"
1854 t
.value
= t
.value
[2:-2]
1855 t
.lexer
.lineno
+= t
.value
.count('\n')
1858 def t_CPPDIRECTIVE(self
, t
):
1860 t
.lexer
.lineno
+= t
.value
.count('\n')
1863 def t_NEWFILE(self
, t
):
1864 r
'^\#\#newfile\s+"[^"]*"\n'
1865 self
.fileNameStack
.push(t
.lexer
.lineno
)
1866 t
.lexer
.lineno
= LineTracker(t
.value
[11:-2])
1868 def t_ENDFILE(self
, t
):
1870 t
.lexer
.lineno
= self
.fileNameStack
.pop()
1873 # The functions t_NEWLINE, t_ignore, and t_error are
1874 # special for the lex module.
1878 def t_NEWLINE(self
, t
):
1880 t
.lexer
.lineno
+= t
.value
.count('\n')
1883 def t_comment(self
, t
):
1886 # Completely ignored characters
1887 t_ignore
= ' \t\x0c'
1890 def t_error(self
, t
):
1891 error(t
.lexer
.lineno
, "illegal character '%s'" % t
.value
[0])
1894 #####################################################################
1898 # Every function whose name starts with 'p_' defines a grammar
1899 # rule. The rule is encoded in the function's doc string, while
1900 # the function body provides the action taken when the rule is
1901 # matched. The argument to each function is a list of the values
1902 # of the rule's symbols: t[0] for the LHS, and t[1..n] for the
1903 # symbols on the RHS. For tokens, the value is copied from the
1904 # t.value attribute provided by the lexer. For non-terminals, the
1905 # value is assigned by the producing rule; i.e., the job of the
1906 # grammar rule function is to set the value for the non-terminal
1907 # on the LHS (by assigning to t[0]).
1908 #####################################################################
1910 # The LHS of the first grammar rule is used as the start symbol
1911 # (in this case, 'specification'). Note that this rule enforces
1912 # that there will be exactly one namespace declaration, with 0 or
1913 # more global defs/decls before and after it. The defs & decls
1914 # before the namespace decl will be outside the namespace; those
1915 # after will be inside. The decoder function is always inside the
1917 def p_specification(self
, t
):
1918 'specification : opt_defs_and_outputs top_level_decode_block'
1920 for f
in self
.splits
.iterkeys():
1921 f
.write('\n#endif\n')
1923 for f
in self
.files
.itervalues(): # close ALL the files;
1924 f
.close() # not doing so can cause compilation to fail
1926 self
.write_top_level_files()
1930 # 'opt_defs_and_outputs' is a possibly empty sequence of def and/or
1931 # output statements. Its productions do the hard work of eventually
1932 # instantiating a GenCode, which are generally emitted (written to disk)
1933 # as soon as possible, except for the decode_block, which has to be
1934 # accumulated into one large function of nested switch/case blocks.
1935 def p_opt_defs_and_outputs_0(self
, t
):
1936 'opt_defs_and_outputs : empty'
1938 def p_opt_defs_and_outputs_1(self
, t
):
1939 'opt_defs_and_outputs : defs_and_outputs'
1941 def p_defs_and_outputs_0(self
, t
):
1942 'defs_and_outputs : def_or_output'
1944 def p_defs_and_outputs_1(self
, t
):
1945 'defs_and_outputs : defs_and_outputs def_or_output'
1947 # The list of possible definition/output statements.
1948 # They are all processed as they are seen.
1949 def p_def_or_output(self
, t
):
1950 '''def_or_output : name_decl
1953 | def_bitfield_struct
1961 # Utility function used by both invocations of splitting - explicit
1962 # 'split' keyword and split() function inside "let {{ }};" blocks.
1963 def split(self
, sec
, write
=False):
1964 assert(sec
!= 'header' and "header cannot be split")
1966 f
= self
.get_file(sec
)
1968 s
= '\n#endif\n#if __SPLIT == %u\n' % self
.splits
[f
]
1974 # split output file to reduce compilation time
1975 def p_split(self
, t
):
1976 'split : SPLIT output_type SEMI'
1977 assert(self
.isa_name
and "'split' not allowed before namespace decl")
1979 self
.split(t
[2], True)
1981 def p_output_type(self
, t
):
1982 '''output_type : DECODER
1987 # ISA name declaration looks like "namespace <foo>;"
1988 def p_name_decl(self
, t
):
1989 'name_decl : NAMESPACE ID SEMI'
1990 assert(self
.isa_name
== None and "Only 1 namespace decl permitted")
1991 self
.isa_name
= t
[2]
1992 self
.namespace
= t
[2] + 'Inst'
1994 # Output blocks 'output <foo> {{...}}' (C++ code blocks) are copied
1995 # directly to the appropriate output section.
1997 # Massage output block by substituting in template definitions and
1998 # bit operators. We handle '%'s embedded in the string that don't
1999 # indicate template substitutions by doubling them first so that the
2000 # format operation will reduce them back to single '%'s.
2001 def process_output(self
, s
):
2002 s
= self
.protectNonSubstPercents(s
)
2003 return substBitOps(s
% self
.templateMap
)
2005 def p_output(self
, t
):
2006 'output : OUTPUT output_type CODELIT SEMI'
2007 kwargs
= { t
[2]+'_output' : self
.process_output(t
[3]) }
2008 GenCode(self
, **kwargs
).emit()
2010 # global let blocks 'let {{...}}' (Python code blocks) are
2011 # executed directly when seen. Note that these execute in a
2012 # special variable context 'exportContext' to prevent the code
2013 # from polluting this script's namespace.
2014 def p_global_let(self
, t
):
2015 'global_let : LET CODELIT SEMI'
2017 return self
.split(sec
)
2018 self
.updateExportContext()
2019 self
.exportContext
["header_output"] = ''
2020 self
.exportContext
["decoder_output"] = ''
2021 self
.exportContext
["exec_output"] = ''
2022 self
.exportContext
["decode_block"] = ''
2023 self
.exportContext
["split"] = _split
2027 globals()[sec + '_output'] += func(sec)
2032 # This tricky setup (immediately above) allows us to just write
2033 # (e.g.) "split('exec')" in the Python code and the split #ifdef's
2034 # will automatically be added to the exec_output variable. The inner
2035 # Python execution environment doesn't know about the split points,
2036 # so we carefully inject and wrap a closure that can retrieve the
2037 # next split's #define from the parser and add it to the current
2038 # emission-in-progress.
2040 exec split_setup
+fixPythonIndentation(t
[2]) in self
.exportContext
2041 except Exception, exc
:
2042 traceback
.print_exc(file=sys
.stdout
)
2045 error(t
.lineno(1), 'In global let block: %s' % exc
)
2047 header_output
=self
.exportContext
["header_output"],
2048 decoder_output
=self
.exportContext
["decoder_output"],
2049 exec_output
=self
.exportContext
["exec_output"],
2050 decode_block
=self
.exportContext
["decode_block"]).emit()
2052 # Define the mapping from operand type extensions to C++ types and
2053 # bit widths (stored in operandTypeMap).
2054 def p_def_operand_types(self
, t
):
2055 'def_operand_types : DEF OPERAND_TYPES CODELIT SEMI'
2057 self
.operandTypeMap
= eval('{' + t
[3] + '}')
2058 except Exception, exc
:
2062 'In def operand_types: %s' % exc
)
2064 # Define the mapping from operand names to operand classes and
2065 # other traits. Stored in operandNameMap.
2066 def p_def_operands(self
, t
):
2067 'def_operands : DEF OPERANDS CODELIT SEMI'
2068 if not hasattr(self
, 'operandTypeMap'):
2070 'error: operand types must be defined before operands')
2072 user_dict
= eval('{' + t
[3] + '}', self
.exportContext
)
2073 except Exception, exc
:
2076 error(t
.lineno(1), 'In def operands: %s' % exc
)
2077 self
.buildOperandNameMap(user_dict
, t
.lexer
.lineno
)
2079 # A bitfield definition looks like:
2080 # 'def [signed] bitfield <ID> [<first>:<last>]'
2081 # This generates a preprocessor macro in the output file.
2082 def p_def_bitfield_0(self
, t
):
2083 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT COLON INTLIT GREATER SEMI'
2084 expr
= 'bits(machInst, %2d, %2d)' % (t
[6], t
[8])
2085 if (t
[2] == 'signed'):
2086 expr
= 'sext<%d>(%s)' % (t
[6] - t
[8] + 1, expr
)
2087 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
2088 GenCode(self
, header_output
=hash_define
).emit()
2090 # alternate form for single bit: 'def [signed] bitfield <ID> [<bit>]'
2091 def p_def_bitfield_1(self
, t
):
2092 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT GREATER SEMI'
2093 expr
= 'bits(machInst, %2d, %2d)' % (t
[6], t
[6])
2094 if (t
[2] == 'signed'):
2095 expr
= 'sext<%d>(%s)' % (1, expr
)
2096 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
2097 GenCode(self
, header_output
=hash_define
).emit()
2099 # alternate form for structure member: 'def bitfield <ID> <ID>'
2100 def p_def_bitfield_struct(self
, t
):
2101 'def_bitfield_struct : DEF opt_signed BITFIELD ID id_with_dot SEMI'
2104 'error: structure bitfields are always unsigned.')
2105 expr
= 'machInst.%s' % t
[5]
2106 hash_define
= '#undef %s\n#define %s\t%s\n' % (t
[4], t
[4], expr
)
2107 GenCode(self
, header_output
=hash_define
).emit()
2109 def p_id_with_dot_0(self
, t
):
2113 def p_id_with_dot_1(self
, t
):
2114 'id_with_dot : ID DOT id_with_dot'
2115 t
[0] = t
[1] + t
[2] + t
[3]
2117 def p_opt_signed_0(self
, t
):
2118 'opt_signed : SIGNED'
2121 def p_opt_signed_1(self
, t
):
2122 'opt_signed : empty'
2125 def p_def_template(self
, t
):
2126 'def_template : DEF TEMPLATE ID CODELIT SEMI'
2127 if t
[3] in self
.templateMap
:
2128 print("warning: template %s already defined" % t
[3])
2129 self
.templateMap
[t
[3]] = Template(self
, t
[4])
2131 # An instruction format definition looks like
2132 # "def format <fmt>(<params>) {{...}};"
2133 def p_def_format(self
, t
):
2134 'def_format : DEF FORMAT ID LPAREN param_list RPAREN CODELIT SEMI'
2135 (id, params
, code
) = (t
[3], t
[5], t
[7])
2136 self
.defFormat(id, params
, code
, t
.lexer
.lineno
)
2138 # The formal parameter list for an instruction format is a
2139 # possibly empty list of comma-separated parameters. Positional
2140 # (standard, non-keyword) parameters must come first, followed by
2141 # keyword parameters, followed by a '*foo' parameter that gets
2142 # excess positional arguments (as in Python). Each of these three
2143 # parameter categories is optional.
2145 # Note that we do not support the '**foo' parameter for collecting
2146 # otherwise undefined keyword args. Otherwise the parameter list
2147 # is (I believe) identical to what is supported in Python.
2149 # The param list generates a tuple, where the first element is a
2150 # list of the positional params and the second element is a dict
2151 # containing the keyword params.
2152 def p_param_list_0(self
, t
):
2153 'param_list : positional_param_list COMMA nonpositional_param_list'
2156 def p_param_list_1(self
, t
):
2157 '''param_list : positional_param_list
2158 | nonpositional_param_list'''
2161 def p_positional_param_list_0(self
, t
):
2162 'positional_param_list : empty'
2165 def p_positional_param_list_1(self
, t
):
2166 'positional_param_list : ID'
2169 def p_positional_param_list_2(self
, t
):
2170 'positional_param_list : positional_param_list COMMA ID'
2171 t
[0] = t
[1] + [t
[3]]
2173 def p_nonpositional_param_list_0(self
, t
):
2174 'nonpositional_param_list : keyword_param_list COMMA excess_args_param'
2177 def p_nonpositional_param_list_1(self
, t
):
2178 '''nonpositional_param_list : keyword_param_list
2179 | excess_args_param'''
2182 def p_keyword_param_list_0(self
, t
):
2183 'keyword_param_list : keyword_param'
2186 def p_keyword_param_list_1(self
, t
):
2187 'keyword_param_list : keyword_param_list COMMA keyword_param'
2188 t
[0] = t
[1] + [t
[3]]
2190 def p_keyword_param(self
, t
):
2191 'keyword_param : ID EQUALS expr'
2192 t
[0] = t
[1] + ' = ' + t
[3].__repr
__()
2194 def p_excess_args_param(self
, t
):
2195 'excess_args_param : ASTERISK ID'
2196 # Just concatenate them: '*ID'. Wrap in list to be consistent
2197 # with positional_param_list and keyword_param_list.
2198 t
[0] = [t
[1] + t
[2]]
2200 # End of format definition-related rules.
2204 # A decode block looks like:
2205 # decode <field1> [, <field2>]* [default <inst>] { ... }
2207 def p_top_level_decode_block(self
, t
):
2208 'top_level_decode_block : decode_block'
2210 codeObj
.wrap_decode_block('''
2212 %(isa_name)s::Decoder::decodeInst(%(isa_name)s::ExtMachInst machInst)
2214 using namespace %(namespace)s;
2219 def p_decode_block(self
, t
):
2220 'decode_block : DECODE ID opt_default LBRACE decode_stmt_list RBRACE'
2221 default_defaults
= self
.defaultStack
.pop()
2223 # use the "default defaults" only if there was no explicit
2224 # default statement in decode_stmt_list
2225 if not codeObj
.has_decode_default
:
2226 codeObj
+= default_defaults
2227 codeObj
.wrap_decode_block('switch (%s) {\n' % t
[2], '}\n')
2230 # The opt_default statement serves only to push the "default
2231 # defaults" onto defaultStack. This value will be used by nested
2232 # decode blocks, and used and popped off when the current
2233 # decode_block is processed (in p_decode_block() above).
2234 def p_opt_default_0(self
, t
):
2235 'opt_default : empty'
2236 # no default specified: reuse the one currently at the top of
2238 self
.defaultStack
.push(self
.defaultStack
.top())
2239 # no meaningful value returned
2242 def p_opt_default_1(self
, t
):
2243 'opt_default : DEFAULT inst'
2244 # push the new default
2246 codeObj
.wrap_decode_block('\ndefault:\n', 'break;\n')
2247 self
.defaultStack
.push(codeObj
)
2248 # no meaningful value returned
2251 def p_decode_stmt_list_0(self
, t
):
2252 'decode_stmt_list : decode_stmt'
2255 def p_decode_stmt_list_1(self
, t
):
2256 'decode_stmt_list : decode_stmt decode_stmt_list'
2257 if (t
[1].has_decode_default
and t
[2].has_decode_default
):
2258 error(t
.lineno(1), 'Two default cases in decode block')
2262 # Decode statement rules
2264 # There are four types of statements allowed in a decode block:
2265 # 1. Format blocks 'format <foo> { ... }'
2266 # 2. Nested decode blocks
2267 # 3. Instruction definitions.
2268 # 4. C preprocessor directives.
2271 # Preprocessor directives found in a decode statement list are
2272 # passed through to the output, replicated to all of the output
2273 # code streams. This works well for ifdefs, so we can ifdef out
2274 # both the declarations and the decode cases generated by an
2275 # instruction definition. Handling them as part of the grammar
2276 # makes it easy to keep them in the right place with respect to
2277 # the code generated by the other statements.
2278 def p_decode_stmt_cpp(self
, t
):
2279 'decode_stmt : CPPDIRECTIVE'
2280 t
[0] = GenCode(self
, t
[1], t
[1], t
[1], t
[1])
2282 # A format block 'format <foo> { ... }' sets the default
2283 # instruction format used to handle instruction definitions inside
2284 # the block. This format can be overridden by using an explicit
2285 # format on the instruction definition or with a nested format
2287 def p_decode_stmt_format(self
, t
):
2288 'decode_stmt : FORMAT push_format_id LBRACE decode_stmt_list RBRACE'
2289 # The format will be pushed on the stack when 'push_format_id'
2290 # is processed (see below). Once the parser has recognized
2291 # the full production (though the right brace), we're done
2292 # with the format, so now we can pop it.
2293 self
.formatStack
.pop()
2296 # This rule exists so we can set the current format (& push the
2297 # stack) when we recognize the format name part of the format
2299 def p_push_format_id(self
, t
):
2300 'push_format_id : ID'
2302 self
.formatStack
.push(self
.formatMap
[t
[1]])
2303 t
[0] = ('', '// format %s' % t
[1])
2305 error(t
.lineno(1), 'instruction format "%s" not defined.' % t
[1])
2307 # Nested decode block: if the value of the current field matches
2308 # the specified constant(s), do a nested decode on some other field.
2309 def p_decode_stmt_decode(self
, t
):
2310 'decode_stmt : case_list COLON decode_block'
2313 # just wrap the decoding code from the block as a case in the
2314 # outer switch statement.
2315 codeObj
.wrap_decode_block('\n%s\n' % ''.join(case_list
),
2316 'M5_UNREACHABLE;\n')
2317 codeObj
.has_decode_default
= (case_list
== ['default:'])
2320 # Instruction definition (finally!).
2321 def p_decode_stmt_inst(self
, t
):
2322 'decode_stmt : case_list COLON inst SEMI'
2325 codeObj
.wrap_decode_block('\n%s' % ''.join(case_list
), 'break;\n')
2326 codeObj
.has_decode_default
= (case_list
== ['default:'])
2329 # The constant list for a decode case label must be non-empty, and must
2330 # either be the keyword 'default', or made up of one or more
2331 # comma-separated integer literals or strings which evaluate to
2332 # constants when compiled as C++.
2333 def p_case_list_0(self
, t
):
2334 'case_list : DEFAULT'
2337 def prep_int_lit_case_label(self
, lit
):
2339 return 'case ULL(%#x): ' % lit
2341 return 'case %#x: ' % lit
2343 def prep_str_lit_case_label(self
, lit
):
2344 return 'case %s: ' % lit
2346 def p_case_list_1(self
, t
):
2347 'case_list : INTLIT'
2348 t
[0] = [self
.prep_int_lit_case_label(t
[1])]
2350 def p_case_list_2(self
, t
):
2351 'case_list : STRLIT'
2352 t
[0] = [self
.prep_str_lit_case_label(t
[1])]
2354 def p_case_list_3(self
, t
):
2355 'case_list : case_list COMMA INTLIT'
2357 t
[0].append(self
.prep_int_lit_case_label(t
[3]))
2359 def p_case_list_4(self
, t
):
2360 'case_list : case_list COMMA STRLIT'
2362 t
[0].append(self
.prep_str_lit_case_label(t
[3]))
2364 # Define an instruction using the current instruction format
2365 # (specified by an enclosing format block).
2366 # "<mnemonic>(<args>)"
2367 def p_inst_0(self
, t
):
2368 'inst : ID LPAREN arg_list RPAREN'
2369 # Pass the ID and arg list to the current format class to deal with.
2370 currentFormat
= self
.formatStack
.top()
2371 codeObj
= currentFormat
.defineInst(self
, t
[1], t
[3], t
.lexer
.lineno
)
2372 args
= ','.join(map(str, t
[3]))
2373 args
= re
.sub('(?m)^', '//', args
)
2374 args
= re
.sub('^//', '', args
)
2375 comment
= '\n// %s::%s(%s)\n' % (currentFormat
.id, t
[1], args
)
2376 codeObj
.prepend_all(comment
)
2379 # Define an instruction using an explicitly specified format:
2380 # "<fmt>::<mnemonic>(<args>)"
2381 def p_inst_1(self
, t
):
2382 'inst : ID DBLCOLON ID LPAREN arg_list RPAREN'
2384 format
= self
.formatMap
[t
[1]]
2386 error(t
.lineno(1), 'instruction format "%s" not defined.' % t
[1])
2388 codeObj
= format
.defineInst(self
, t
[3], t
[5], t
.lexer
.lineno
)
2389 comment
= '\n// %s::%s(%s)\n' % (t
[1], t
[3], t
[5])
2390 codeObj
.prepend_all(comment
)
2393 # The arg list generates a tuple, where the first element is a
2394 # list of the positional args and the second element is a dict
2395 # containing the keyword args.
2396 def p_arg_list_0(self
, t
):
2397 'arg_list : positional_arg_list COMMA keyword_arg_list'
2398 t
[0] = ( t
[1], t
[3] )
2400 def p_arg_list_1(self
, t
):
2401 'arg_list : positional_arg_list'
2404 def p_arg_list_2(self
, t
):
2405 'arg_list : keyword_arg_list'
2408 def p_positional_arg_list_0(self
, t
):
2409 'positional_arg_list : empty'
2412 def p_positional_arg_list_1(self
, t
):
2413 'positional_arg_list : expr'
2416 def p_positional_arg_list_2(self
, t
):
2417 'positional_arg_list : positional_arg_list COMMA expr'
2418 t
[0] = t
[1] + [t
[3]]
2420 def p_keyword_arg_list_0(self
, t
):
2421 'keyword_arg_list : keyword_arg'
2424 def p_keyword_arg_list_1(self
, t
):
2425 'keyword_arg_list : keyword_arg_list COMMA keyword_arg'
2429 def p_keyword_arg(self
, t
):
2430 'keyword_arg : ID EQUALS expr'
2431 t
[0] = { t
[1] : t
[3] }
2434 # Basic expressions. These constitute the argument values of
2435 # "function calls" (i.e. instruction definitions in the decode
2436 # block) and default values for formal parameters of format
2439 # Right now, these are either strings, integers, or (recursively)
2440 # lists of exprs (using Python square-bracket list syntax). Note
2441 # that bare identifiers are trated as string constants here (since
2442 # there isn't really a variable namespace to refer to).
2444 def p_expr_0(self
, t
):
2451 def p_expr_1(self
, t
):
2452 '''expr : LBRACKET list_expr RBRACKET'''
2455 def p_list_expr_0(self
, t
):
2459 def p_list_expr_1(self
, t
):
2460 'list_expr : list_expr COMMA expr'
2461 t
[0] = t
[1] + [t
[3]]
2463 def p_list_expr_2(self
, t
):
2468 # Empty production... use in other rules for readability.
2470 def p_empty(self
, t
):
2474 # Parse error handler. Note that the argument here is the
2475 # offending *token*, not a grammar symbol (hence the need to use
2477 def p_error(self
, t
):
2479 error(t
.lexer
.lineno
, "syntax error at '%s'" % t
.value
)
2481 error("unknown syntax error")
2483 # END OF GRAMMAR RULES
2485 def updateExportContext(self
):
2487 # create a continuation that allows us to grab the current parser
2488 def wrapInstObjParams(*args
):
2489 return InstObjParams(self
, *args
)
2490 self
.exportContext
['InstObjParams'] = wrapInstObjParams
2491 self
.exportContext
.update(self
.templateMap
)
2493 def defFormat(self
, id, params
, code
, lineno
):
2494 '''Define a new format'''
2496 # make sure we haven't already defined this one
2497 if id in self
.formatMap
:
2498 error(lineno
, 'format %s redefined.' % id)
2500 # create new object and store in global map
2501 self
.formatMap
[id] = Format(id, params
, code
)
2503 def protectNonSubstPercents(self
, s
):
2504 '''Protect any non-dict-substitution '%'s in a format string
2505 (i.e. those not followed by '(')'''
2507 return re
.sub(r
'%(?!\()', '%%', s
)
2509 def buildOperandNameMap(self
, user_dict
, lineno
):
2511 for op_name
, val
in user_dict
.iteritems():
2513 # Check if extra attributes have been specified.
2515 error(lineno
, 'error: too many attributes for operand "%s"' %
2518 # Pad val with None in case optional args are missing
2519 val
+= (None, None, None, None)
2520 base_cls_name
, dflt_ext
, reg_spec
, flags
, sort_pri
, \
2521 read_code
, write_code
, read_predicate
, write_predicate
= val
[:9]
2523 # Canonical flag structure is a triple of lists, where each list
2524 # indicates the set of flags implied by this operand always, when
2525 # used as a source, and when used as a dest, respectively.
2526 # For simplicity this can be initialized using a variety of fairly
2527 # obvious shortcuts; we convert these to canonical form here.
2529 # no flags specified (e.g., 'None')
2530 flags
= ( [], [], [] )
2531 elif isinstance(flags
, str):
2532 # a single flag: assumed to be unconditional
2533 flags
= ( [ flags
], [], [] )
2534 elif isinstance(flags
, list):
2535 # a list of flags: also assumed to be unconditional
2536 flags
= ( flags
, [], [] )
2537 elif isinstance(flags
, tuple):
2538 # it's a tuple: it should be a triple,
2539 # but each item could be a single string or a list
2540 (uncond_flags
, src_flags
, dest_flags
) = flags
2541 flags
= (makeList(uncond_flags
),
2542 makeList(src_flags
), makeList(dest_flags
))
2544 # Accumulate attributes of new operand class in tmp_dict
2546 attrList
= ['reg_spec', 'flags', 'sort_pri',
2547 'read_code', 'write_code',
2548 'read_predicate', 'write_predicate']
2550 dflt_ctype
= self
.operandTypeMap
[dflt_ext
]
2551 attrList
.extend(['dflt_ctype', 'dflt_ext'])
2552 # reg_spec is either just a string or a dictionary
2553 # (for elems of vector)
2554 if isinstance(reg_spec
, tuple):
2555 (reg_spec
, elem_spec
) = reg_spec
2556 if isinstance(elem_spec
, str):
2557 attrList
.append('elem_spec')
2559 assert(isinstance(elem_spec
, dict))
2561 attrList
.append('elems')
2562 for attr
in attrList
:
2563 tmp_dict
[attr
] = eval(attr
)
2564 tmp_dict
['base_name'] = op_name
2566 # New class name will be e.g. "IntReg_Ra"
2567 cls_name
= base_cls_name
+ '_' + op_name
2568 # Evaluate string arg to get class object. Note that the
2569 # actual base class for "IntReg" is "IntRegOperand", i.e. we
2570 # have to append "Operand".
2572 base_cls
= eval(base_cls_name
+ 'Operand')
2575 'error: unknown operand base class "%s"' % base_cls_name
)
2576 # The following statement creates a new class called
2577 # <cls_name> as a subclass of <base_cls> with the attributes
2578 # in tmp_dict, just as if we evaluated a class declaration.
2579 operand_name
[op_name
] = type(cls_name
, (base_cls
,), tmp_dict
)
2581 self
.operandNameMap
= operand_name
2583 # Define operand variables.
2584 operands
= user_dict
.keys()
2585 # Add the elems defined in the vector operands and
2586 # build a map elem -> vector (used in OperandList)
2588 for op
in user_dict
.keys():
2589 if hasattr(self
.operandNameMap
[op
], 'elems'):
2590 for elem
in self
.operandNameMap
[op
].elems
.keys():
2591 operands
.append(elem
)
2592 elem_to_vec
[elem
] = op
2593 self
.elemToVector
= elem_to_vec
2594 extensions
= self
.operandTypeMap
.keys()
2596 operandsREString
= r
'''
2597 (?<!\w) # neg. lookbehind assertion: prevent partial matches
2598 ((%s)(?:_(%s))?) # match: operand with optional '_' then suffix
2599 (?!\w) # neg. lookahead assertion: prevent partial matches
2600 ''' % (string
.join(operands
, '|'), string
.join(extensions
, '|'))
2602 self
.operandsRE
= re
.compile(operandsREString
, re
.MULTILINE|re
.VERBOSE
)
2604 # Same as operandsREString, but extension is mandatory, and only two
2605 # groups are returned (base and ext, not full name as above).
2606 # Used for subtituting '_' for '.' to make C++ identifiers.
2607 operandsWithExtREString
= r
'(?<!\w)(%s)_(%s)(?!\w)' \
2608 % (string
.join(operands
, '|'), string
.join(extensions
, '|'))
2610 self
.operandsWithExtRE
= \
2611 re
.compile(operandsWithExtREString
, re
.MULTILINE
)
2613 def substMungedOpNames(self
, code
):
2614 '''Munge operand names in code string to make legal C++
2615 variable names. This means getting rid of the type extension
2616 if any. Will match base_name attribute of Operand object.)'''
2617 return self
.operandsWithExtRE
.sub(r
'\1', code
)
2619 def mungeSnippet(self
, s
):
2620 '''Fix up code snippets for final substitution in templates.'''
2621 if isinstance(s
, str):
2622 return self
.substMungedOpNames(substBitOps(s
))
2626 def open(self
, name
, bare
=False):
2627 '''Open the output file for writing and include scary warning.'''
2628 filename
= os
.path
.join(self
.output_dir
, name
)
2629 f
= open(filename
, 'w')
2632 f
.write(ISAParser
.scaremonger_template
% self
)
2635 def update(self
, file, contents
):
2636 '''Update the output file only. Scons should handle the case when
2637 the new contents are unchanged using its built-in hash feature.'''
2642 # This regular expression matches '##include' directives
2643 includeRE
= re
.compile(r
'^\s*##include\s+"(?P<filename>[^"]*)".*$',
2646 def replace_include(self
, matchobj
, dirname
):
2647 """Function to replace a matched '##include' directive with the
2648 contents of the specified file (with nested ##includes
2649 replaced recursively). 'matchobj' is an re match object
2650 (from a match of includeRE) and 'dirname' is the directory
2651 relative to which the file path should be resolved."""
2653 fname
= matchobj
.group('filename')
2654 full_fname
= os
.path
.normpath(os
.path
.join(dirname
, fname
))
2655 contents
= '##newfile "%s"\n%s\n##endfile\n' % \
2656 (full_fname
, self
.read_and_flatten(full_fname
))
2659 def read_and_flatten(self
, filename
):
2660 """Read a file and recursively flatten nested '##include' files."""
2662 current_dir
= os
.path
.dirname(filename
)
2664 contents
= open(filename
).read()
2666 error('Error including file "%s"' % filename
)
2668 self
.fileNameStack
.push(LineTracker(filename
))
2670 # Find any includes and include them
2671 def replace(matchobj
):
2672 return self
.replace_include(matchobj
, current_dir
)
2673 contents
= self
.includeRE
.sub(replace
, contents
)
2675 self
.fileNameStack
.pop()
2678 AlreadyGenerated
= {}
2680 def _parse_isa_desc(self
, isa_desc_file
):
2681 '''Read in and parse the ISA description.'''
2683 # The build system can end up running the ISA parser twice: once to
2684 # finalize the build dependencies, and then to actually generate
2685 # the files it expects (in src/arch/$ARCH/generated). This code
2686 # doesn't do anything different either time, however; the SCons
2687 # invocations just expect different things. Since this code runs
2688 # within SCons, we can just remember that we've already run and
2689 # not perform a completely unnecessary run, since the ISA parser's
2690 # effect is idempotent.
2691 if isa_desc_file
in ISAParser
.AlreadyGenerated
:
2694 # grab the last three path components of isa_desc_file
2695 self
.filename
= '/'.join(isa_desc_file
.split('/')[-3:])
2697 # Read file and (recursively) all included files into a string.
2698 # PLY requires that the input be in a single string so we have to
2700 isa_desc
= self
.read_and_flatten(isa_desc_file
)
2702 # Initialize lineno tracker
2703 self
.lex
.lineno
= LineTracker(isa_desc_file
)
2706 self
.parse_string(isa_desc
)
2708 ISAParser
.AlreadyGenerated
[isa_desc_file
] = None
2710 def parse_isa_desc(self
, *args
, **kwargs
):
2712 self
._parse
_isa
_desc
(*args
, **kwargs
)
2713 except ISAParserError
, e
:
2714 print(backtrace(self
.fileNameStack
))
2715 print("At %s:" % e
.lineno
)
2719 # Called as script: get args from command line.
2720 # Args are: <isa desc file> <output dir>
2721 if __name__
== '__main__':
2722 ISAParser(sys
.argv
[2]).parse_isa_desc(sys
.argv
[1])