isa_parser.py revision 13595:d673075b3204
1# Copyright (c) 2014, 2016 ARM Limited 2# All rights reserved 3# 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. 12# 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. 16# 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. 27# 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. 39# 40# Authors: Steve Reinhardt 41 42from __future__ import with_statement, print_function 43import os 44import sys 45import re 46import string 47import inspect, traceback 48# get type names 49from types import * 50 51from m5.util.grammar import Grammar 52 53debug=False 54 55################### 56# Utility functions 57 58# 59# Indent every line in string 's' by two spaces 60# (except preprocessor directives). 61# Used to make nested code blocks look pretty. 62# 63def indent(s): 64 return re.sub(r'(?m)^(?!#)', ' ', s) 65 66# 67# Munge a somewhat arbitrarily formatted piece of Python code 68# (e.g. from a format 'let' block) into something whose indentation 69# will get by the Python parser. 70# 71# The two keys here are that Python will give a syntax error if 72# there's any whitespace at the beginning of the first line, and that 73# all lines at the same lexical nesting level must have identical 74# indentation. Unfortunately the way code literals work, an entire 75# let block tends to have some initial indentation. Rather than 76# trying to figure out what that is and strip it off, we prepend 'if 77# 1:' to make the let code the nested block inside the if (and have 78# the parser automatically deal with the indentation for us). 79# 80# We don't want to do this if (1) the code block is empty or (2) the 81# first line of the block doesn't have any whitespace at the front. 82 83def fixPythonIndentation(s): 84 # get rid of blank lines first 85 s = re.sub(r'(?m)^\s*\n', '', s); 86 if (s != '' and re.match(r'[ \t]', s[0])): 87 s = 'if 1:\n' + s 88 return s 89 90class ISAParserError(Exception): 91 """Exception class for parser errors""" 92 def __init__(self, first, second=None): 93 if second is None: 94 self.lineno = 0 95 self.string = first 96 else: 97 self.lineno = first 98 self.string = second 99 100 def __str__(self): 101 return self.string 102 103def error(*args): 104 raise ISAParserError(*args) 105 106#################### 107# Template objects. 108# 109# Template objects are format strings that allow substitution from 110# the attribute spaces of other objects (e.g. InstObjParams instances). 111 112labelRE = re.compile(r'(?<!%)%\(([^\)]+)\)[sd]') 113 114class Template(object): 115 def __init__(self, parser, t): 116 self.parser = parser 117 self.template = t 118 119 def subst(self, d): 120 myDict = None 121 122 # Protect non-Python-dict substitutions (e.g. if there's a printf 123 # in the templated C++ code) 124 template = self.parser.protectNonSubstPercents(self.template) 125 126 # Build a dict ('myDict') to use for the template substitution. 127 # Start with the template namespace. Make a copy since we're 128 # going to modify it. 129 myDict = self.parser.templateMap.copy() 130 131 if isinstance(d, InstObjParams): 132 # If we're dealing with an InstObjParams object, we need 133 # to be a little more sophisticated. The instruction-wide 134 # parameters are already formed, but the parameters which 135 # are only function wide still need to be generated. 136 compositeCode = '' 137 138 myDict.update(d.__dict__) 139 # The "operands" and "snippets" attributes of the InstObjParams 140 # objects are for internal use and not substitution. 141 del myDict['operands'] 142 del myDict['snippets'] 143 144 snippetLabels = [l for l in labelRE.findall(template) 145 if d.snippets.has_key(l)] 146 147 snippets = dict([(s, self.parser.mungeSnippet(d.snippets[s])) 148 for s in snippetLabels]) 149 150 myDict.update(snippets) 151 152 compositeCode = ' '.join(map(str, snippets.values())) 153 154 # Add in template itself in case it references any 155 # operands explicitly (like Mem) 156 compositeCode += ' ' + template 157 158 operands = SubOperandList(self.parser, compositeCode, d.operands) 159 160 myDict['op_decl'] = operands.concatAttrStrings('op_decl') 161 if operands.readPC or operands.setPC: 162 myDict['op_decl'] += 'TheISA::PCState __parserAutoPCState;\n' 163 164 # In case there are predicated register reads and write, declare 165 # the variables for register indicies. It is being assumed that 166 # all the operands in the OperandList are also in the 167 # SubOperandList and in the same order. Otherwise, it is 168 # expected that predication would not be used for the operands. 169 if operands.predRead: 170 myDict['op_decl'] += 'uint8_t _sourceIndex = 0;\n' 171 if operands.predWrite: 172 myDict['op_decl'] += 'uint8_t M5_VAR_USED _destIndex = 0;\n' 173 174 is_src = lambda op: op.is_src 175 is_dest = lambda op: op.is_dest 176 177 myDict['op_src_decl'] = \ 178 operands.concatSomeAttrStrings(is_src, 'op_src_decl') 179 myDict['op_dest_decl'] = \ 180 operands.concatSomeAttrStrings(is_dest, 'op_dest_decl') 181 if operands.readPC: 182 myDict['op_src_decl'] += \ 183 'TheISA::PCState __parserAutoPCState;\n' 184 if operands.setPC: 185 myDict['op_dest_decl'] += \ 186 'TheISA::PCState __parserAutoPCState;\n' 187 188 myDict['op_rd'] = operands.concatAttrStrings('op_rd') 189 if operands.readPC: 190 myDict['op_rd'] = '__parserAutoPCState = xc->pcState();\n' + \ 191 myDict['op_rd'] 192 193 # Compose the op_wb string. If we're going to write back the 194 # PC state because we changed some of its elements, we'll need to 195 # do that as early as possible. That allows later uncoordinated 196 # modifications to the PC to layer appropriately. 197 reordered = list(operands.items) 198 reordered.reverse() 199 op_wb_str = '' 200 pcWbStr = 'xc->pcState(__parserAutoPCState);\n' 201 for op_desc in reordered: 202 if op_desc.isPCPart() and op_desc.is_dest: 203 op_wb_str = op_desc.op_wb + pcWbStr + op_wb_str 204 pcWbStr = '' 205 else: 206 op_wb_str = op_desc.op_wb + op_wb_str 207 myDict['op_wb'] = op_wb_str 208 209 elif isinstance(d, dict): 210 # if the argument is a dictionary, we just use it. 211 myDict.update(d) 212 elif hasattr(d, '__dict__'): 213 # if the argument is an object, we use its attribute map. 214 myDict.update(d.__dict__) 215 else: 216 raise TypeError, "Template.subst() arg must be or have dictionary" 217 return template % myDict 218 219 # Convert to string. 220 def __str__(self): 221 return self.template 222 223################ 224# Format object. 225# 226# A format object encapsulates an instruction format. It must provide 227# a defineInst() method that generates the code for an instruction 228# definition. 229 230class Format(object): 231 def __init__(self, id, params, code): 232 self.id = id 233 self.params = params 234 label = 'def format ' + id 235 self.user_code = compile(fixPythonIndentation(code), label, 'exec') 236 param_list = string.join(params, ", ") 237 f = '''def defInst(_code, _context, %s): 238 my_locals = vars().copy() 239 exec _code in _context, my_locals 240 return my_locals\n''' % param_list 241 c = compile(f, label + ' wrapper', 'exec') 242 exec c 243 self.func = defInst 244 245 def defineInst(self, parser, name, args, lineno): 246 parser.updateExportContext() 247 context = parser.exportContext.copy() 248 if len(name): 249 Name = name[0].upper() 250 if len(name) > 1: 251 Name += name[1:] 252 context.update({ 'name' : name, 'Name' : Name }) 253 try: 254 vars = self.func(self.user_code, context, *args[0], **args[1]) 255 except Exception, exc: 256 if debug: 257 raise 258 error(lineno, 'error defining "%s": %s.' % (name, exc)) 259 for k in vars.keys(): 260 if k not in ('header_output', 'decoder_output', 261 'exec_output', 'decode_block'): 262 del vars[k] 263 return GenCode(parser, **vars) 264 265# Special null format to catch an implicit-format instruction 266# definition outside of any format block. 267class NoFormat(object): 268 def __init__(self): 269 self.defaultInst = '' 270 271 def defineInst(self, parser, name, args, lineno): 272 error(lineno, 273 'instruction definition "%s" with no active format!' % name) 274 275############### 276# GenCode class 277# 278# The GenCode class encapsulates generated code destined for various 279# output files. The header_output and decoder_output attributes are 280# strings containing code destined for decoder.hh and decoder.cc 281# respectively. The decode_block attribute contains code to be 282# incorporated in the decode function itself (that will also end up in 283# decoder.cc). The exec_output attribute is the string of code for the 284# exec.cc file. The has_decode_default attribute is used in the decode block 285# to allow explicit default clauses to override default default clauses. 286 287class GenCode(object): 288 # Constructor. 289 def __init__(self, parser, 290 header_output = '', decoder_output = '', exec_output = '', 291 decode_block = '', has_decode_default = False): 292 self.parser = parser 293 self.header_output = header_output 294 self.decoder_output = decoder_output 295 self.exec_output = exec_output 296 self.decode_block = decode_block 297 self.has_decode_default = has_decode_default 298 299 # Write these code chunks out to the filesystem. They will be properly 300 # interwoven by the write_top_level_files(). 301 def emit(self): 302 if self.header_output: 303 self.parser.get_file('header').write(self.header_output) 304 if self.decoder_output: 305 self.parser.get_file('decoder').write(self.decoder_output) 306 if self.exec_output: 307 self.parser.get_file('exec').write(self.exec_output) 308 if self.decode_block: 309 self.parser.get_file('decode_block').write(self.decode_block) 310 311 # Override '+' operator: generate a new GenCode object that 312 # concatenates all the individual strings in the operands. 313 def __add__(self, other): 314 return GenCode(self.parser, 315 self.header_output + other.header_output, 316 self.decoder_output + other.decoder_output, 317 self.exec_output + other.exec_output, 318 self.decode_block + other.decode_block, 319 self.has_decode_default or other.has_decode_default) 320 321 # Prepend a string (typically a comment) to all the strings. 322 def prepend_all(self, pre): 323 self.header_output = pre + self.header_output 324 self.decoder_output = pre + self.decoder_output 325 self.decode_block = pre + self.decode_block 326 self.exec_output = pre + self.exec_output 327 328 # Wrap the decode block in a pair of strings (e.g., 'case foo:' 329 # and 'break;'). Used to build the big nested switch statement. 330 def wrap_decode_block(self, pre, post = ''): 331 self.decode_block = pre + indent(self.decode_block) + post 332 333##################################################################### 334# 335# Bitfield Operator Support 336# 337##################################################################### 338 339bitOp1ArgRE = re.compile(r'<\s*(\w+)\s*:\s*>') 340 341bitOpWordRE = re.compile(r'(?<![\w\.])([\w\.]+)<\s*(\w+)\s*:\s*(\w+)\s*>') 342bitOpExprRE = re.compile(r'\)<\s*(\w+)\s*:\s*(\w+)\s*>') 343 344def substBitOps(code): 345 # first convert single-bit selectors to two-index form 346 # i.e., <n> --> <n:n> 347 code = bitOp1ArgRE.sub(r'<\1:\1>', code) 348 # simple case: selector applied to ID (name) 349 # i.e., foo<a:b> --> bits(foo, a, b) 350 code = bitOpWordRE.sub(r'bits(\1, \2, \3)', code) 351 # if selector is applied to expression (ending in ')'), 352 # we need to search backward for matching '(' 353 match = bitOpExprRE.search(code) 354 while match: 355 exprEnd = match.start() 356 here = exprEnd - 1 357 nestLevel = 1 358 while nestLevel > 0: 359 if code[here] == '(': 360 nestLevel -= 1 361 elif code[here] == ')': 362 nestLevel += 1 363 here -= 1 364 if here < 0: 365 sys.exit("Didn't find '('!") 366 exprStart = here+1 367 newExpr = r'bits(%s, %s, %s)' % (code[exprStart:exprEnd+1], 368 match.group(1), match.group(2)) 369 code = code[:exprStart] + newExpr + code[match.end():] 370 match = bitOpExprRE.search(code) 371 return code 372 373 374##################################################################### 375# 376# Code Parser 377# 378# The remaining code is the support for automatically extracting 379# instruction characteristics from pseudocode. 380# 381##################################################################### 382 383# Force the argument to be a list. Useful for flags, where a caller 384# can specify a singleton flag or a list of flags. Also usful for 385# converting tuples to lists so they can be modified. 386def makeList(arg): 387 if isinstance(arg, list): 388 return arg 389 elif isinstance(arg, tuple): 390 return list(arg) 391 elif not arg: 392 return [] 393 else: 394 return [ arg ] 395 396class Operand(object): 397 '''Base class for operand descriptors. An instance of this class 398 (or actually a class derived from this one) represents a specific 399 operand for a code block (e.g, "Rc.sq" as a dest). Intermediate 400 derived classes encapsulates the traits of a particular operand 401 type (e.g., "32-bit integer register").''' 402 403 def buildReadCode(self, func = None): 404 subst_dict = {"name": self.base_name, 405 "func": func, 406 "reg_idx": self.reg_spec, 407 "ctype": self.ctype} 408 if hasattr(self, 'src_reg_idx'): 409 subst_dict['op_idx'] = self.src_reg_idx 410 code = self.read_code % subst_dict 411 return '%s = %s;\n' % (self.base_name, code) 412 413 def buildWriteCode(self, func = None): 414 subst_dict = {"name": self.base_name, 415 "func": func, 416 "reg_idx": self.reg_spec, 417 "ctype": self.ctype, 418 "final_val": self.base_name} 419 if hasattr(self, 'dest_reg_idx'): 420 subst_dict['op_idx'] = self.dest_reg_idx 421 code = self.write_code % subst_dict 422 return ''' 423 { 424 %s final_val = %s; 425 %s; 426 if (traceData) { traceData->setData(final_val); } 427 }''' % (self.dflt_ctype, self.base_name, code) 428 429 def __init__(self, parser, full_name, ext, is_src, is_dest): 430 self.full_name = full_name 431 self.ext = ext 432 self.is_src = is_src 433 self.is_dest = is_dest 434 # The 'effective extension' (eff_ext) is either the actual 435 # extension, if one was explicitly provided, or the default. 436 if ext: 437 self.eff_ext = ext 438 elif hasattr(self, 'dflt_ext'): 439 self.eff_ext = self.dflt_ext 440 441 if hasattr(self, 'eff_ext'): 442 self.ctype = parser.operandTypeMap[self.eff_ext] 443 444 # Finalize additional fields (primarily code fields). This step 445 # is done separately since some of these fields may depend on the 446 # register index enumeration that hasn't been performed yet at the 447 # time of __init__(). The register index enumeration is affected 448 # by predicated register reads/writes. Hence, we forward the flags 449 # that indicate whether or not predication is in use. 450 def finalize(self, predRead, predWrite): 451 self.flags = self.getFlags() 452 self.constructor = self.makeConstructor(predRead, predWrite) 453 self.op_decl = self.makeDecl() 454 455 if self.is_src: 456 self.op_rd = self.makeRead(predRead) 457 self.op_src_decl = self.makeDecl() 458 else: 459 self.op_rd = '' 460 self.op_src_decl = '' 461 462 if self.is_dest: 463 self.op_wb = self.makeWrite(predWrite) 464 self.op_dest_decl = self.makeDecl() 465 else: 466 self.op_wb = '' 467 self.op_dest_decl = '' 468 469 def isMem(self): 470 return 0 471 472 def isReg(self): 473 return 0 474 475 def isFloatReg(self): 476 return 0 477 478 def isIntReg(self): 479 return 0 480 481 def isCCReg(self): 482 return 0 483 484 def isControlReg(self): 485 return 0 486 487 def isVecReg(self): 488 return 0 489 490 def isVecElem(self): 491 return 0 492 493 def isPCState(self): 494 return 0 495 496 def isPCPart(self): 497 return self.isPCState() and self.reg_spec 498 499 def hasReadPred(self): 500 return self.read_predicate != None 501 502 def hasWritePred(self): 503 return self.write_predicate != None 504 505 def getFlags(self): 506 # note the empty slice '[:]' gives us a copy of self.flags[0] 507 # instead of a reference to it 508 my_flags = self.flags[0][:] 509 if self.is_src: 510 my_flags += self.flags[1] 511 if self.is_dest: 512 my_flags += self.flags[2] 513 return my_flags 514 515 def makeDecl(self): 516 # Note that initializations in the declarations are solely 517 # to avoid 'uninitialized variable' errors from the compiler. 518 return self.ctype + ' ' + self.base_name + ' = 0;\n'; 519 520 521src_reg_constructor = '\n\t_srcRegIdx[_numSrcRegs++] = RegId(%s, %s);' 522dst_reg_constructor = '\n\t_destRegIdx[_numDestRegs++] = RegId(%s, %s);' 523 524 525class IntRegOperand(Operand): 526 reg_class = 'IntRegClass' 527 528 def isReg(self): 529 return 1 530 531 def isIntReg(self): 532 return 1 533 534 def makeConstructor(self, predRead, predWrite): 535 c_src = '' 536 c_dest = '' 537 538 if self.is_src: 539 c_src = src_reg_constructor % (self.reg_class, self.reg_spec) 540 if self.hasReadPred(): 541 c_src = '\n\tif (%s) {%s\n\t}' % \ 542 (self.read_predicate, c_src) 543 544 if self.is_dest: 545 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec) 546 c_dest += '\n\t_numIntDestRegs++;' 547 if self.hasWritePred(): 548 c_dest = '\n\tif (%s) {%s\n\t}' % \ 549 (self.write_predicate, c_dest) 550 551 return c_src + c_dest 552 553 def makeRead(self, predRead): 554 if (self.ctype == 'float' or self.ctype == 'double'): 555 error('Attempt to read integer register as FP') 556 if self.read_code != None: 557 return self.buildReadCode('readIntRegOperand') 558 559 int_reg_val = '' 560 if predRead: 561 int_reg_val = 'xc->readIntRegOperand(this, _sourceIndex++)' 562 if self.hasReadPred(): 563 int_reg_val = '(%s) ? %s : 0' % \ 564 (self.read_predicate, int_reg_val) 565 else: 566 int_reg_val = 'xc->readIntRegOperand(this, %d)' % self.src_reg_idx 567 568 return '%s = %s;\n' % (self.base_name, int_reg_val) 569 570 def makeWrite(self, predWrite): 571 if (self.ctype == 'float' or self.ctype == 'double'): 572 error('Attempt to write integer register as FP') 573 if self.write_code != None: 574 return self.buildWriteCode('setIntRegOperand') 575 576 if predWrite: 577 wp = 'true' 578 if self.hasWritePred(): 579 wp = self.write_predicate 580 581 wcond = 'if (%s)' % (wp) 582 windex = '_destIndex++' 583 else: 584 wcond = '' 585 windex = '%d' % self.dest_reg_idx 586 587 wb = ''' 588 %s 589 { 590 %s final_val = %s; 591 xc->setIntRegOperand(this, %s, final_val);\n 592 if (traceData) { traceData->setData(final_val); } 593 }''' % (wcond, self.ctype, self.base_name, windex) 594 595 return wb 596 597class FloatRegOperand(Operand): 598 reg_class = 'FloatRegClass' 599 600 def isReg(self): 601 return 1 602 603 def isFloatReg(self): 604 return 1 605 606 def makeConstructor(self, predRead, predWrite): 607 c_src = '' 608 c_dest = '' 609 610 if self.is_src: 611 c_src = src_reg_constructor % (self.reg_class, self.reg_spec) 612 613 if self.is_dest: 614 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec) 615 c_dest += '\n\t_numFPDestRegs++;' 616 617 return c_src + c_dest 618 619 def makeRead(self, predRead): 620 if self.read_code != None: 621 return self.buildReadCode('readFloatRegOperandBits') 622 623 if predRead: 624 rindex = '_sourceIndex++' 625 else: 626 rindex = '%d' % self.src_reg_idx 627 628 code = 'xc->readFloatRegOperandBits(this, %s)' % rindex 629 if self.ctype == 'float': 630 code = 'bitsToFloat32(%s)' % code 631 elif self.ctype == 'double': 632 code = 'bitsToFloat64(%s)' % code 633 return '%s = %s;\n' % (self.base_name, code) 634 635 def makeWrite(self, predWrite): 636 if self.write_code != None: 637 return self.buildWriteCode('setFloatRegOperandBits') 638 639 if predWrite: 640 wp = '_destIndex++' 641 else: 642 wp = '%d' % self.dest_reg_idx 643 644 val = 'final_val' 645 if self.ctype == 'float': 646 val = 'floatToBits32(%s)' % val 647 elif self.ctype == 'double': 648 val = 'floatToBits64(%s)' % val 649 650 wp = 'xc->setFloatRegOperandBits(this, %s, %s);' % (wp, val) 651 652 wb = ''' 653 { 654 %s final_val = %s; 655 %s\n 656 if (traceData) { traceData->setData(final_val); } 657 }''' % (self.ctype, self.base_name, wp) 658 return wb 659 660class VecRegOperand(Operand): 661 reg_class = 'VecRegClass' 662 663 def __init__(self, parser, full_name, ext, is_src, is_dest): 664 Operand.__init__(self, parser, full_name, ext, is_src, is_dest) 665 self.elemExt = None 666 self.parser = parser 667 668 def isReg(self): 669 return 1 670 671 def isVecReg(self): 672 return 1 673 674 def makeDeclElem(self, elem_op): 675 (elem_name, elem_ext) = elem_op 676 (elem_spec, dflt_elem_ext, zeroing) = self.elems[elem_name] 677 if elem_ext: 678 ext = elem_ext 679 else: 680 ext = dflt_elem_ext 681 ctype = self.parser.operandTypeMap[ext] 682 return '\n\t%s %s = 0;' % (ctype, elem_name) 683 684 def makeDecl(self): 685 if not self.is_dest and self.is_src: 686 c_decl = '\t/* Vars for %s*/' % (self.base_name) 687 if hasattr(self, 'active_elems'): 688 if self.active_elems: 689 for elem in self.active_elems: 690 c_decl += self.makeDeclElem(elem) 691 return c_decl + '\t/* End vars for %s */\n' % (self.base_name) 692 else: 693 return '' 694 695 def makeConstructor(self, predRead, predWrite): 696 c_src = '' 697 c_dest = '' 698 699 numAccessNeeded = 1 700 701 if self.is_src: 702 c_src = src_reg_constructor % (self.reg_class, self.reg_spec) 703 704 if self.is_dest: 705 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec) 706 c_dest += '\n\t_numVecDestRegs++;' 707 708 return c_src + c_dest 709 710 # Read destination register to write 711 def makeReadWElem(self, elem_op): 712 (elem_name, elem_ext) = elem_op 713 (elem_spec, dflt_elem_ext, zeroing) = self.elems[elem_name] 714 if elem_ext: 715 ext = elem_ext 716 else: 717 ext = dflt_elem_ext 718 ctype = self.parser.operandTypeMap[ext] 719 c_read = '\t\t%s& %s = %s[%s];\n' % \ 720 (ctype, elem_name, self.base_name, elem_spec) 721 return c_read 722 723 def makeReadW(self, predWrite): 724 func = 'getWritableVecRegOperand' 725 if self.read_code != None: 726 return self.buildReadCode(func) 727 728 if predWrite: 729 rindex = '_destIndex++' 730 else: 731 rindex = '%d' % self.dest_reg_idx 732 733 c_readw = '\t\t%s& tmp_d%s = xc->%s(this, %s);\n'\ 734 % ('TheISA::VecRegContainer', rindex, func, rindex) 735 if self.elemExt: 736 c_readw += '\t\tauto %s = tmp_d%s.as<%s>();\n' % (self.base_name, 737 rindex, self.parser.operandTypeMap[self.elemExt]) 738 if self.ext: 739 c_readw += '\t\tauto %s = tmp_d%s.as<%s>();\n' % (self.base_name, 740 rindex, self.parser.operandTypeMap[self.ext]) 741 if hasattr(self, 'active_elems'): 742 if self.active_elems: 743 for elem in self.active_elems: 744 c_readw += self.makeReadWElem(elem) 745 return c_readw 746 747 # Normal source operand read 748 def makeReadElem(self, elem_op, name): 749 (elem_name, elem_ext) = elem_op 750 (elem_spec, dflt_elem_ext, zeroing) = self.elems[elem_name] 751 752 if elem_ext: 753 ext = elem_ext 754 else: 755 ext = dflt_elem_ext 756 ctype = self.parser.operandTypeMap[ext] 757 c_read = '\t\t%s = %s[%s];\n' % \ 758 (elem_name, name, elem_spec) 759 return c_read 760 761 def makeRead(self, predRead): 762 func = 'readVecRegOperand' 763 if self.read_code != None: 764 return self.buildReadCode(func) 765 766 if predRead: 767 rindex = '_sourceIndex++' 768 else: 769 rindex = '%d' % self.src_reg_idx 770 771 name = self.base_name 772 if self.is_dest and self.is_src: 773 name += '_merger' 774 775 c_read = '\t\t%s& tmp_s%s = xc->%s(this, %s);\n' \ 776 % ('const TheISA::VecRegContainer', rindex, func, rindex) 777 # If the parser has detected that elements are being access, create 778 # the appropriate view 779 if self.elemExt: 780 c_read += '\t\tauto %s = tmp_s%s.as<%s>();\n' % \ 781 (name, rindex, self.parser.operandTypeMap[self.elemExt]) 782 if self.ext: 783 c_read += '\t\tauto %s = tmp_s%s.as<%s>();\n' % \ 784 (name, rindex, self.parser.operandTypeMap[self.ext]) 785 if hasattr(self, 'active_elems'): 786 if self.active_elems: 787 for elem in self.active_elems: 788 c_read += self.makeReadElem(elem, name) 789 return c_read 790 791 def makeWrite(self, predWrite): 792 func = 'setVecRegOperand' 793 if self.write_code != None: 794 return self.buildWriteCode(func) 795 796 wb = ''' 797 if (traceData) { 798 warn_once("Vectors not supported yet in tracedata"); 799 /*traceData->setData(final_val);*/ 800 } 801 ''' 802 return wb 803 804 def finalize(self, predRead, predWrite): 805 super(VecRegOperand, self).finalize(predRead, predWrite) 806 if self.is_dest: 807 self.op_rd = self.makeReadW(predWrite) + self.op_rd 808 809class VecElemOperand(Operand): 810 reg_class = 'VectorElemClass' 811 812 def isReg(self): 813 return 1 814 815 def isVecElem(self): 816 return 1 817 818 def makeDecl(self): 819 if self.is_dest and not self.is_src: 820 return '\n\t%s %s;' % (self.ctype, self.base_name) 821 else: 822 return '' 823 824 def makeConstructor(self, predRead, predWrite): 825 c_src = '' 826 c_dest = '' 827 828 numAccessNeeded = 1 829 regId = 'RegId(%s, %s * numVecElemPerVecReg + elemIdx, %s)' % \ 830 (self.reg_class, self.reg_spec) 831 832 if self.is_src: 833 c_src = ('\n\t_srcRegIdx[_numSrcRegs++] = RegId(%s, %s, %s);' % 834 (self.reg_class, self.reg_spec, self.elem_spec)) 835 836 if self.is_dest: 837 c_dest = ('\n\t_destRegIdx[_numDestRegs++] = RegId(%s, %s, %s);' % 838 (self.reg_class, self.reg_spec, self.elem_spec)) 839 c_dest += '\n\t_numVecElemDestRegs++;' 840 return c_src + c_dest 841 842 def makeRead(self, predRead): 843 c_read = ('\n/* Elem is kept inside the operand description */' + 844 '\n\tVecElem %s = xc->readVecElemOperand(this, %d);' % 845 (self.base_name, self.src_reg_idx)) 846 return c_read 847 848 def makeWrite(self, predWrite): 849 c_write = ('\n/* Elem is kept inside the operand description */' + 850 '\n\txc->setVecElemOperand(this, %d, %s);' % 851 (self.dest_reg_idx, self.base_name)) 852 return c_write 853 854class CCRegOperand(Operand): 855 reg_class = 'CCRegClass' 856 857 def isReg(self): 858 return 1 859 860 def isCCReg(self): 861 return 1 862 863 def makeConstructor(self, predRead, predWrite): 864 c_src = '' 865 c_dest = '' 866 867 if self.is_src: 868 c_src = src_reg_constructor % (self.reg_class, self.reg_spec) 869 if self.hasReadPred(): 870 c_src = '\n\tif (%s) {%s\n\t}' % \ 871 (self.read_predicate, c_src) 872 873 if self.is_dest: 874 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec) 875 c_dest += '\n\t_numCCDestRegs++;' 876 if self.hasWritePred(): 877 c_dest = '\n\tif (%s) {%s\n\t}' % \ 878 (self.write_predicate, c_dest) 879 880 return c_src + c_dest 881 882 def makeRead(self, predRead): 883 if (self.ctype == 'float' or self.ctype == 'double'): 884 error('Attempt to read condition-code register as FP') 885 if self.read_code != None: 886 return self.buildReadCode('readCCRegOperand') 887 888 int_reg_val = '' 889 if predRead: 890 int_reg_val = 'xc->readCCRegOperand(this, _sourceIndex++)' 891 if self.hasReadPred(): 892 int_reg_val = '(%s) ? %s : 0' % \ 893 (self.read_predicate, int_reg_val) 894 else: 895 int_reg_val = 'xc->readCCRegOperand(this, %d)' % self.src_reg_idx 896 897 return '%s = %s;\n' % (self.base_name, int_reg_val) 898 899 def makeWrite(self, predWrite): 900 if (self.ctype == 'float' or self.ctype == 'double'): 901 error('Attempt to write condition-code register as FP') 902 if self.write_code != None: 903 return self.buildWriteCode('setCCRegOperand') 904 905 if predWrite: 906 wp = 'true' 907 if self.hasWritePred(): 908 wp = self.write_predicate 909 910 wcond = 'if (%s)' % (wp) 911 windex = '_destIndex++' 912 else: 913 wcond = '' 914 windex = '%d' % self.dest_reg_idx 915 916 wb = ''' 917 %s 918 { 919 %s final_val = %s; 920 xc->setCCRegOperand(this, %s, final_val);\n 921 if (traceData) { traceData->setData(final_val); } 922 }''' % (wcond, self.ctype, self.base_name, windex) 923 924 return wb 925 926class ControlRegOperand(Operand): 927 reg_class = 'MiscRegClass' 928 929 def isReg(self): 930 return 1 931 932 def isControlReg(self): 933 return 1 934 935 def makeConstructor(self, predRead, predWrite): 936 c_src = '' 937 c_dest = '' 938 939 if self.is_src: 940 c_src = src_reg_constructor % (self.reg_class, self.reg_spec) 941 942 if self.is_dest: 943 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec) 944 945 return c_src + c_dest 946 947 def makeRead(self, predRead): 948 bit_select = 0 949 if (self.ctype == 'float' or self.ctype == 'double'): 950 error('Attempt to read control register as FP') 951 if self.read_code != None: 952 return self.buildReadCode('readMiscRegOperand') 953 954 if predRead: 955 rindex = '_sourceIndex++' 956 else: 957 rindex = '%d' % self.src_reg_idx 958 959 return '%s = xc->readMiscRegOperand(this, %s);\n' % \ 960 (self.base_name, rindex) 961 962 def makeWrite(self, predWrite): 963 if (self.ctype == 'float' or self.ctype == 'double'): 964 error('Attempt to write control register as FP') 965 if self.write_code != None: 966 return self.buildWriteCode('setMiscRegOperand') 967 968 if predWrite: 969 windex = '_destIndex++' 970 else: 971 windex = '%d' % self.dest_reg_idx 972 973 wb = 'xc->setMiscRegOperand(this, %s, %s);\n' % \ 974 (windex, self.base_name) 975 wb += 'if (traceData) { traceData->setData(%s); }' % \ 976 self.base_name 977 978 return wb 979 980class MemOperand(Operand): 981 def isMem(self): 982 return 1 983 984 def makeConstructor(self, predRead, predWrite): 985 return '' 986 987 def makeDecl(self): 988 # Declare memory data variable. 989 return '%s %s;\n' % (self.ctype, self.base_name) 990 991 def makeRead(self, predRead): 992 if self.read_code != None: 993 return self.buildReadCode() 994 return '' 995 996 def makeWrite(self, predWrite): 997 if self.write_code != None: 998 return self.buildWriteCode() 999 return '' 1000 1001class PCStateOperand(Operand): 1002 def makeConstructor(self, predRead, predWrite): 1003 return '' 1004 1005 def makeRead(self, predRead): 1006 if self.reg_spec: 1007 # A component of the PC state. 1008 return '%s = __parserAutoPCState.%s();\n' % \ 1009 (self.base_name, self.reg_spec) 1010 else: 1011 # The whole PC state itself. 1012 return '%s = xc->pcState();\n' % self.base_name 1013 1014 def makeWrite(self, predWrite): 1015 if self.reg_spec: 1016 # A component of the PC state. 1017 return '__parserAutoPCState.%s(%s);\n' % \ 1018 (self.reg_spec, self.base_name) 1019 else: 1020 # The whole PC state itself. 1021 return 'xc->pcState(%s);\n' % self.base_name 1022 1023 def makeDecl(self): 1024 ctype = 'TheISA::PCState' 1025 if self.isPCPart(): 1026 ctype = self.ctype 1027 # Note that initializations in the declarations are solely 1028 # to avoid 'uninitialized variable' errors from the compiler. 1029 return '%s %s = 0;\n' % (ctype, self.base_name) 1030 1031 def isPCState(self): 1032 return 1 1033 1034class OperandList(object): 1035 '''Find all the operands in the given code block. Returns an operand 1036 descriptor list (instance of class OperandList).''' 1037 def __init__(self, parser, code): 1038 self.items = [] 1039 self.bases = {} 1040 # delete strings and comments so we don't match on operands inside 1041 for regEx in (stringRE, commentRE): 1042 code = regEx.sub('', code) 1043 # search for operands 1044 next_pos = 0 1045 while 1: 1046 match = parser.operandsRE.search(code, next_pos) 1047 if not match: 1048 # no more matches: we're done 1049 break 1050 op = match.groups() 1051 # regexp groups are operand full name, base, and extension 1052 (op_full, op_base, op_ext) = op 1053 # If is a elem operand, define or update the corresponding 1054 # vector operand 1055 isElem = False 1056 if op_base in parser.elemToVector: 1057 isElem = True 1058 elem_op = (op_base, op_ext) 1059 op_base = parser.elemToVector[op_base] 1060 op_ext = '' # use the default one 1061 # if the token following the operand is an assignment, this is 1062 # a destination (LHS), else it's a source (RHS) 1063 is_dest = (assignRE.match(code, match.end()) != None) 1064 is_src = not is_dest 1065 1066 # see if we've already seen this one 1067 op_desc = self.find_base(op_base) 1068 if op_desc: 1069 if op_ext and op_ext != '' and op_desc.ext != op_ext: 1070 error ('Inconsistent extensions for operand %s: %s - %s' \ 1071 % (op_base, op_desc.ext, op_ext)) 1072 op_desc.is_src = op_desc.is_src or is_src 1073 op_desc.is_dest = op_desc.is_dest or is_dest 1074 if isElem: 1075 (elem_base, elem_ext) = elem_op 1076 found = False 1077 for ae in op_desc.active_elems: 1078 (ae_base, ae_ext) = ae 1079 if ae_base == elem_base: 1080 if ae_ext != elem_ext: 1081 error('Inconsistent extensions for elem' 1082 ' operand %s' % elem_base) 1083 else: 1084 found = True 1085 if not found: 1086 op_desc.active_elems.append(elem_op) 1087 else: 1088 # new operand: create new descriptor 1089 op_desc = parser.operandNameMap[op_base](parser, 1090 op_full, op_ext, is_src, is_dest) 1091 # if operand is a vector elem, add the corresponding vector 1092 # operand if not already done 1093 if isElem: 1094 op_desc.elemExt = elem_op[1] 1095 op_desc.active_elems = [elem_op] 1096 self.append(op_desc) 1097 # start next search after end of current match 1098 next_pos = match.end() 1099 self.sort() 1100 # enumerate source & dest register operands... used in building 1101 # constructor later 1102 self.numSrcRegs = 0 1103 self.numDestRegs = 0 1104 self.numFPDestRegs = 0 1105 self.numIntDestRegs = 0 1106 self.numVecDestRegs = 0 1107 self.numCCDestRegs = 0 1108 self.numMiscDestRegs = 0 1109 self.memOperand = None 1110 1111 # Flags to keep track if one or more operands are to be read/written 1112 # conditionally. 1113 self.predRead = False 1114 self.predWrite = False 1115 1116 for op_desc in self.items: 1117 if op_desc.isReg(): 1118 if op_desc.is_src: 1119 op_desc.src_reg_idx = self.numSrcRegs 1120 self.numSrcRegs += 1 1121 if op_desc.is_dest: 1122 op_desc.dest_reg_idx = self.numDestRegs 1123 self.numDestRegs += 1 1124 if op_desc.isFloatReg(): 1125 self.numFPDestRegs += 1 1126 elif op_desc.isIntReg(): 1127 self.numIntDestRegs += 1 1128 elif op_desc.isVecReg(): 1129 self.numVecDestRegs += 1 1130 elif op_desc.isCCReg(): 1131 self.numCCDestRegs += 1 1132 elif op_desc.isControlReg(): 1133 self.numMiscDestRegs += 1 1134 elif op_desc.isMem(): 1135 if self.memOperand: 1136 error("Code block has more than one memory operand.") 1137 self.memOperand = op_desc 1138 1139 # Check if this operand has read/write predication. If true, then 1140 # the microop will dynamically index source/dest registers. 1141 self.predRead = self.predRead or op_desc.hasReadPred() 1142 self.predWrite = self.predWrite or op_desc.hasWritePred() 1143 1144 if parser.maxInstSrcRegs < self.numSrcRegs: 1145 parser.maxInstSrcRegs = self.numSrcRegs 1146 if parser.maxInstDestRegs < self.numDestRegs: 1147 parser.maxInstDestRegs = self.numDestRegs 1148 if parser.maxMiscDestRegs < self.numMiscDestRegs: 1149 parser.maxMiscDestRegs = self.numMiscDestRegs 1150 1151 # now make a final pass to finalize op_desc fields that may depend 1152 # on the register enumeration 1153 for op_desc in self.items: 1154 op_desc.finalize(self.predRead, self.predWrite) 1155 1156 def __len__(self): 1157 return len(self.items) 1158 1159 def __getitem__(self, index): 1160 return self.items[index] 1161 1162 def append(self, op_desc): 1163 self.items.append(op_desc) 1164 self.bases[op_desc.base_name] = op_desc 1165 1166 def find_base(self, base_name): 1167 # like self.bases[base_name], but returns None if not found 1168 # (rather than raising exception) 1169 return self.bases.get(base_name) 1170 1171 # internal helper function for concat[Some]Attr{Strings|Lists} 1172 def __internalConcatAttrs(self, attr_name, filter, result): 1173 for op_desc in self.items: 1174 if filter(op_desc): 1175 result += getattr(op_desc, attr_name) 1176 return result 1177 1178 # return a single string that is the concatenation of the (string) 1179 # values of the specified attribute for all operands 1180 def concatAttrStrings(self, attr_name): 1181 return self.__internalConcatAttrs(attr_name, lambda x: 1, '') 1182 1183 # like concatAttrStrings, but only include the values for the operands 1184 # for which the provided filter function returns true 1185 def concatSomeAttrStrings(self, filter, attr_name): 1186 return self.__internalConcatAttrs(attr_name, filter, '') 1187 1188 # return a single list that is the concatenation of the (list) 1189 # values of the specified attribute for all operands 1190 def concatAttrLists(self, attr_name): 1191 return self.__internalConcatAttrs(attr_name, lambda x: 1, []) 1192 1193 # like concatAttrLists, but only include the values for the operands 1194 # for which the provided filter function returns true 1195 def concatSomeAttrLists(self, filter, attr_name): 1196 return self.__internalConcatAttrs(attr_name, filter, []) 1197 1198 def sort(self): 1199 self.items.sort(lambda a, b: a.sort_pri - b.sort_pri) 1200 1201class SubOperandList(OperandList): 1202 '''Find all the operands in the given code block. Returns an operand 1203 descriptor list (instance of class OperandList).''' 1204 def __init__(self, parser, code, master_list): 1205 self.items = [] 1206 self.bases = {} 1207 # delete strings and comments so we don't match on operands inside 1208 for regEx in (stringRE, commentRE): 1209 code = regEx.sub('', code) 1210 # search for operands 1211 next_pos = 0 1212 while 1: 1213 match = parser.operandsRE.search(code, next_pos) 1214 if not match: 1215 # no more matches: we're done 1216 break 1217 op = match.groups() 1218 # regexp groups are operand full name, base, and extension 1219 (op_full, op_base, op_ext) = op 1220 # If is a elem operand, define or update the corresponding 1221 # vector operand 1222 if op_base in parser.elemToVector: 1223 elem_op = op_base 1224 op_base = parser.elemToVector[elem_op] 1225 # find this op in the master list 1226 op_desc = master_list.find_base(op_base) 1227 if not op_desc: 1228 error('Found operand %s which is not in the master list!' 1229 % op_base) 1230 else: 1231 # See if we've already found this operand 1232 op_desc = self.find_base(op_base) 1233 if not op_desc: 1234 # if not, add a reference to it to this sub list 1235 self.append(master_list.bases[op_base]) 1236 1237 # start next search after end of current match 1238 next_pos = match.end() 1239 self.sort() 1240 self.memOperand = None 1241 # Whether the whole PC needs to be read so parts of it can be accessed 1242 self.readPC = False 1243 # Whether the whole PC needs to be written after parts of it were 1244 # changed 1245 self.setPC = False 1246 # Whether this instruction manipulates the whole PC or parts of it. 1247 # Mixing the two is a bad idea and flagged as an error. 1248 self.pcPart = None 1249 1250 # Flags to keep track if one or more operands are to be read/written 1251 # conditionally. 1252 self.predRead = False 1253 self.predWrite = False 1254 1255 for op_desc in self.items: 1256 if op_desc.isPCPart(): 1257 self.readPC = True 1258 if op_desc.is_dest: 1259 self.setPC = True 1260 1261 if op_desc.isPCState(): 1262 if self.pcPart is not None: 1263 if self.pcPart and not op_desc.isPCPart() or \ 1264 not self.pcPart and op_desc.isPCPart(): 1265 error("Mixed whole and partial PC state operands.") 1266 self.pcPart = op_desc.isPCPart() 1267 1268 if op_desc.isMem(): 1269 if self.memOperand: 1270 error("Code block has more than one memory operand.") 1271 self.memOperand = op_desc 1272 1273 # Check if this operand has read/write predication. If true, then 1274 # the microop will dynamically index source/dest registers. 1275 self.predRead = self.predRead or op_desc.hasReadPred() 1276 self.predWrite = self.predWrite or op_desc.hasWritePred() 1277 1278# Regular expression object to match C++ strings 1279stringRE = re.compile(r'"([^"\\]|\\.)*"') 1280 1281# Regular expression object to match C++ comments 1282# (used in findOperands()) 1283commentRE = re.compile(r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?', 1284 re.DOTALL | re.MULTILINE) 1285 1286# Regular expression object to match assignment statements (used in 1287# findOperands()). If the code immediately following the first 1288# appearance of the operand matches this regex, then the operand 1289# appears to be on the LHS of an assignment, and is thus a 1290# destination. basically we're looking for an '=' that's not '=='. 1291# The heinous tangle before that handles the case where the operand 1292# has an array subscript. 1293assignRE = re.compile(r'(\[[^\]]+\])?\s*=(?!=)', re.MULTILINE) 1294 1295def makeFlagConstructor(flag_list): 1296 if len(flag_list) == 0: 1297 return '' 1298 # filter out repeated flags 1299 flag_list.sort() 1300 i = 1 1301 while i < len(flag_list): 1302 if flag_list[i] == flag_list[i-1]: 1303 del flag_list[i] 1304 else: 1305 i += 1 1306 pre = '\n\tflags[' 1307 post = '] = true;' 1308 code = pre + string.join(flag_list, post + pre) + post 1309 return code 1310 1311# Assume all instruction flags are of the form 'IsFoo' 1312instFlagRE = re.compile(r'Is.*') 1313 1314# OpClass constants end in 'Op' except No_OpClass 1315opClassRE = re.compile(r'.*Op|No_OpClass') 1316 1317class InstObjParams(object): 1318 def __init__(self, parser, mnem, class_name, base_class = '', 1319 snippets = {}, opt_args = []): 1320 self.mnemonic = mnem 1321 self.class_name = class_name 1322 self.base_class = base_class 1323 if not isinstance(snippets, dict): 1324 snippets = {'code' : snippets} 1325 compositeCode = ' '.join(map(str, snippets.values())) 1326 self.snippets = snippets 1327 1328 self.operands = OperandList(parser, compositeCode) 1329 1330 # The header of the constructor declares the variables to be used 1331 # in the body of the constructor. 1332 header = '' 1333 header += '\n\t_numSrcRegs = 0;' 1334 header += '\n\t_numDestRegs = 0;' 1335 header += '\n\t_numFPDestRegs = 0;' 1336 header += '\n\t_numVecDestRegs = 0;' 1337 header += '\n\t_numVecElemDestRegs = 0;' 1338 header += '\n\t_numIntDestRegs = 0;' 1339 header += '\n\t_numCCDestRegs = 0;' 1340 1341 self.constructor = header + \ 1342 self.operands.concatAttrStrings('constructor') 1343 1344 self.flags = self.operands.concatAttrLists('flags') 1345 1346 self.op_class = None 1347 1348 # Optional arguments are assumed to be either StaticInst flags 1349 # or an OpClass value. To avoid having to import a complete 1350 # list of these values to match against, we do it ad-hoc 1351 # with regexps. 1352 for oa in opt_args: 1353 if instFlagRE.match(oa): 1354 self.flags.append(oa) 1355 elif opClassRE.match(oa): 1356 self.op_class = oa 1357 else: 1358 error('InstObjParams: optional arg "%s" not recognized ' 1359 'as StaticInst::Flag or OpClass.' % oa) 1360 1361 # Make a basic guess on the operand class if not set. 1362 # These are good enough for most cases. 1363 if not self.op_class: 1364 if 'IsStore' in self.flags: 1365 # The order matters here: 'IsFloating' and 'IsInteger' are 1366 # usually set in FP instructions because of the base 1367 # register 1368 if 'IsFloating' in self.flags: 1369 self.op_class = 'FloatMemWriteOp' 1370 else: 1371 self.op_class = 'MemWriteOp' 1372 elif 'IsLoad' in self.flags or 'IsPrefetch' in self.flags: 1373 # The order matters here: 'IsFloating' and 'IsInteger' are 1374 # usually set in FP instructions because of the base 1375 # register 1376 if 'IsFloating' in self.flags: 1377 self.op_class = 'FloatMemReadOp' 1378 else: 1379 self.op_class = 'MemReadOp' 1380 elif 'IsFloating' in self.flags: 1381 self.op_class = 'FloatAddOp' 1382 elif 'IsVector' in self.flags: 1383 self.op_class = 'SimdAddOp' 1384 else: 1385 self.op_class = 'IntAluOp' 1386 1387 # add flag initialization to contructor here to include 1388 # any flags added via opt_args 1389 self.constructor += makeFlagConstructor(self.flags) 1390 1391 # if 'IsFloating' is set, add call to the FP enable check 1392 # function (which should be provided by isa_desc via a declare) 1393 # if 'IsVector' is set, add call to the Vector enable check 1394 # function (which should be provided by isa_desc via a declare) 1395 if 'IsFloating' in self.flags: 1396 self.fp_enable_check = 'fault = checkFpEnableFault(xc);' 1397 elif 'IsVector' in self.flags: 1398 self.fp_enable_check = 'fault = checkVecEnableFault(xc);' 1399 else: 1400 self.fp_enable_check = '' 1401 1402############## 1403# Stack: a simple stack object. Used for both formats (formatStack) 1404# and default cases (defaultStack). Simply wraps a list to give more 1405# stack-like syntax and enable initialization with an argument list 1406# (as opposed to an argument that's a list). 1407 1408class Stack(list): 1409 def __init__(self, *items): 1410 list.__init__(self, items) 1411 1412 def push(self, item): 1413 self.append(item); 1414 1415 def top(self): 1416 return self[-1] 1417 1418# Format a file include stack backtrace as a string 1419def backtrace(filename_stack): 1420 fmt = "In file included from %s:" 1421 return "\n".join([fmt % f for f in filename_stack]) 1422 1423 1424####################### 1425# 1426# LineTracker: track filenames along with line numbers in PLY lineno fields 1427# PLY explicitly doesn't do anything with 'lineno' except propagate 1428# it. This class lets us tie filenames with the line numbers with a 1429# minimum of disruption to existing increment code. 1430# 1431 1432class LineTracker(object): 1433 def __init__(self, filename, lineno=1): 1434 self.filename = filename 1435 self.lineno = lineno 1436 1437 # Overload '+=' for increments. We need to create a new object on 1438 # each update else every token ends up referencing the same 1439 # constantly incrementing instance. 1440 def __iadd__(self, incr): 1441 return LineTracker(self.filename, self.lineno + incr) 1442 1443 def __str__(self): 1444 return "%s:%d" % (self.filename, self.lineno) 1445 1446 # In case there are places where someone really expects a number 1447 def __int__(self): 1448 return self.lineno 1449 1450 1451####################### 1452# 1453# ISA Parser 1454# parses ISA DSL and emits C++ headers and source 1455# 1456 1457class ISAParser(Grammar): 1458 def __init__(self, output_dir): 1459 super(ISAParser, self).__init__() 1460 self.output_dir = output_dir 1461 1462 self.filename = None # for output file watermarking/scaremongering 1463 1464 # variable to hold templates 1465 self.templateMap = {} 1466 1467 # This dictionary maps format name strings to Format objects. 1468 self.formatMap = {} 1469 1470 # Track open files and, if applicable, how many chunks it has been 1471 # split into so far. 1472 self.files = {} 1473 self.splits = {} 1474 1475 # isa_name / namespace identifier from namespace declaration. 1476 # before the namespace declaration, None. 1477 self.isa_name = None 1478 self.namespace = None 1479 1480 # The format stack. 1481 self.formatStack = Stack(NoFormat()) 1482 1483 # The default case stack. 1484 self.defaultStack = Stack(None) 1485 1486 # Stack that tracks current file and line number. Each 1487 # element is a tuple (filename, lineno) that records the 1488 # *current* filename and the line number in the *previous* 1489 # file where it was included. 1490 self.fileNameStack = Stack() 1491 1492 symbols = ('makeList', 're', 'string') 1493 self.exportContext = dict([(s, eval(s)) for s in symbols]) 1494 1495 self.maxInstSrcRegs = 0 1496 self.maxInstDestRegs = 0 1497 self.maxMiscDestRegs = 0 1498 1499 def __getitem__(self, i): # Allow object (self) to be 1500 return getattr(self, i) # passed to %-substitutions 1501 1502 # Change the file suffix of a base filename: 1503 # (e.g.) decoder.cc -> decoder-g.cc.inc for 'global' outputs 1504 def suffixize(self, s, sec): 1505 extn = re.compile('(\.[^\.]+)$') # isolate extension 1506 if self.namespace: 1507 return extn.sub(r'-ns\1.inc', s) # insert some text on either side 1508 else: 1509 return extn.sub(r'-g\1.inc', s) 1510 1511 # Get the file object for emitting code into the specified section 1512 # (header, decoder, exec, decode_block). 1513 def get_file(self, section): 1514 if section == 'decode_block': 1515 filename = 'decode-method.cc.inc' 1516 else: 1517 if section == 'header': 1518 file = 'decoder.hh' 1519 else: 1520 file = '%s.cc' % section 1521 filename = self.suffixize(file, section) 1522 try: 1523 return self.files[filename] 1524 except KeyError: pass 1525 1526 f = self.open(filename) 1527 self.files[filename] = f 1528 1529 # The splittable files are the ones with many independent 1530 # per-instruction functions - the decoder's instruction constructors 1531 # and the instruction execution (execute()) methods. These both have 1532 # the suffix -ns.cc.inc, meaning they are within the namespace part 1533 # of the ISA, contain object-emitting C++ source, and are included 1534 # into other top-level files. These are the files that need special 1535 # #define's to allow parts of them to be compiled separately. Rather 1536 # than splitting the emissions into separate files, the monolithic 1537 # output of the ISA parser is maintained, but the value (or lack 1538 # thereof) of the __SPLIT definition during C preprocessing will 1539 # select the different chunks. If no 'split' directives are used, 1540 # the cpp emissions have no effect. 1541 if re.search('-ns.cc.inc$', filename): 1542 print('#if !defined(__SPLIT) || (__SPLIT == 1)', file=f) 1543 self.splits[f] = 1 1544 # ensure requisite #include's 1545 elif filename == 'decoder-g.hh.inc': 1546 print('#include "base/bitfield.hh"', file=f) 1547 1548 return f 1549 1550 # Weave together the parts of the different output sections by 1551 # #include'ing them into some very short top-level .cc/.hh files. 1552 # These small files make it much clearer how this tool works, since 1553 # you directly see the chunks emitted as files that are #include'd. 1554 def write_top_level_files(self): 1555 # decoder header - everything depends on this 1556 file = 'decoder.hh' 1557 with self.open(file) as f: 1558 fn = 'decoder-g.hh.inc' 1559 assert(fn in self.files) 1560 f.write('#include "%s"\n' % fn) 1561 1562 fn = 'decoder-ns.hh.inc' 1563 assert(fn in self.files) 1564 f.write('namespace %s {\n#include "%s"\n}\n' 1565 % (self.namespace, fn)) 1566 1567 # decoder method - cannot be split 1568 file = 'decoder.cc' 1569 with self.open(file) as f: 1570 fn = 'base/compiler.hh' 1571 f.write('#include "%s"\n' % fn) 1572 1573 fn = 'decoder-g.cc.inc' 1574 assert(fn in self.files) 1575 f.write('#include "%s"\n' % fn) 1576 1577 fn = 'decoder.hh' 1578 f.write('#include "%s"\n' % fn) 1579 1580 fn = 'decode-method.cc.inc' 1581 # is guaranteed to have been written for parse to complete 1582 f.write('#include "%s"\n' % fn) 1583 1584 extn = re.compile('(\.[^\.]+)$') 1585 1586 # instruction constructors 1587 splits = self.splits[self.get_file('decoder')] 1588 file_ = 'inst-constrs.cc' 1589 for i in range(1, splits+1): 1590 if splits > 1: 1591 file = extn.sub(r'-%d\1' % i, file_) 1592 else: 1593 file = file_ 1594 with self.open(file) as f: 1595 fn = 'decoder-g.cc.inc' 1596 assert(fn in self.files) 1597 f.write('#include "%s"\n' % fn) 1598 1599 fn = 'decoder.hh' 1600 f.write('#include "%s"\n' % fn) 1601 1602 fn = 'decoder-ns.cc.inc' 1603 assert(fn in self.files) 1604 print('namespace %s {' % self.namespace, file=f) 1605 if splits > 1: 1606 print('#define __SPLIT %u' % i, file=f) 1607 print('#include "%s"' % fn, file=f) 1608 print('}', file=f) 1609 1610 # instruction execution 1611 splits = self.splits[self.get_file('exec')] 1612 for i in range(1, splits+1): 1613 file = 'generic_cpu_exec.cc' 1614 if splits > 1: 1615 file = extn.sub(r'_%d\1' % i, file) 1616 with self.open(file) as f: 1617 fn = 'exec-g.cc.inc' 1618 assert(fn in self.files) 1619 f.write('#include "%s"\n' % fn) 1620 f.write('#include "cpu/exec_context.hh"\n') 1621 f.write('#include "decoder.hh"\n') 1622 1623 fn = 'exec-ns.cc.inc' 1624 assert(fn in self.files) 1625 print('namespace %s {' % self.namespace, file=f) 1626 if splits > 1: 1627 print('#define __SPLIT %u' % i, file=f) 1628 print('#include "%s"' % fn, file=f) 1629 print('}', file=f) 1630 1631 # max_inst_regs.hh 1632 self.update('max_inst_regs.hh', 1633 '''namespace %(namespace)s { 1634 const int MaxInstSrcRegs = %(maxInstSrcRegs)d; 1635 const int MaxInstDestRegs = %(maxInstDestRegs)d; 1636 const int MaxMiscDestRegs = %(maxMiscDestRegs)d;\n}\n''' % self) 1637 1638 scaremonger_template ='''// DO NOT EDIT 1639// This file was automatically generated from an ISA description: 1640// %(filename)s 1641 1642'''; 1643 1644 ##################################################################### 1645 # 1646 # Lexer 1647 # 1648 # The PLY lexer module takes two things as input: 1649 # - A list of token names (the string list 'tokens') 1650 # - A regular expression describing a match for each token. The 1651 # regexp for token FOO can be provided in two ways: 1652 # - as a string variable named t_FOO 1653 # - as the doc string for a function named t_FOO. In this case, 1654 # the function is also executed, allowing an action to be 1655 # associated with each token match. 1656 # 1657 ##################################################################### 1658 1659 # Reserved words. These are listed separately as they are matched 1660 # using the same regexp as generic IDs, but distinguished in the 1661 # t_ID() function. The PLY documentation suggests this approach. 1662 reserved = ( 1663 'BITFIELD', 'DECODE', 'DECODER', 'DEFAULT', 'DEF', 'EXEC', 'FORMAT', 1664 'HEADER', 'LET', 'NAMESPACE', 'OPERAND_TYPES', 'OPERANDS', 1665 'OUTPUT', 'SIGNED', 'SPLIT', 'TEMPLATE' 1666 ) 1667 1668 # List of tokens. The lex module requires this. 1669 tokens = reserved + ( 1670 # identifier 1671 'ID', 1672 1673 # integer literal 1674 'INTLIT', 1675 1676 # string literal 1677 'STRLIT', 1678 1679 # code literal 1680 'CODELIT', 1681 1682 # ( ) [ ] { } < > , ; . : :: * 1683 'LPAREN', 'RPAREN', 1684 'LBRACKET', 'RBRACKET', 1685 'LBRACE', 'RBRACE', 1686 'LESS', 'GREATER', 'EQUALS', 1687 'COMMA', 'SEMI', 'DOT', 'COLON', 'DBLCOLON', 1688 'ASTERISK', 1689 1690 # C preprocessor directives 1691 'CPPDIRECTIVE' 1692 1693 # The following are matched but never returned. commented out to 1694 # suppress PLY warning 1695 # newfile directive 1696 # 'NEWFILE', 1697 1698 # endfile directive 1699 # 'ENDFILE' 1700 ) 1701 1702 # Regular expressions for token matching 1703 t_LPAREN = r'\(' 1704 t_RPAREN = r'\)' 1705 t_LBRACKET = r'\[' 1706 t_RBRACKET = r'\]' 1707 t_LBRACE = r'\{' 1708 t_RBRACE = r'\}' 1709 t_LESS = r'\<' 1710 t_GREATER = r'\>' 1711 t_EQUALS = r'=' 1712 t_COMMA = r',' 1713 t_SEMI = r';' 1714 t_DOT = r'\.' 1715 t_COLON = r':' 1716 t_DBLCOLON = r'::' 1717 t_ASTERISK = r'\*' 1718 1719 # Identifiers and reserved words 1720 reserved_map = { } 1721 for r in reserved: 1722 reserved_map[r.lower()] = r 1723 1724 def t_ID(self, t): 1725 r'[A-Za-z_]\w*' 1726 t.type = self.reserved_map.get(t.value, 'ID') 1727 return t 1728 1729 # Integer literal 1730 def t_INTLIT(self, t): 1731 r'-?(0x[\da-fA-F]+)|\d+' 1732 try: 1733 t.value = int(t.value,0) 1734 except ValueError: 1735 error(t.lexer.lineno, 'Integer value "%s" too large' % t.value) 1736 t.value = 0 1737 return t 1738 1739 # String literal. Note that these use only single quotes, and 1740 # can span multiple lines. 1741 def t_STRLIT(self, t): 1742 r"(?m)'([^'])+'" 1743 # strip off quotes 1744 t.value = t.value[1:-1] 1745 t.lexer.lineno += t.value.count('\n') 1746 return t 1747 1748 1749 # "Code literal"... like a string literal, but delimiters are 1750 # '{{' and '}}' so they get formatted nicely under emacs c-mode 1751 def t_CODELIT(self, t): 1752 r"(?m)\{\{([^\}]|}(?!\}))+\}\}" 1753 # strip off {{ & }} 1754 t.value = t.value[2:-2] 1755 t.lexer.lineno += t.value.count('\n') 1756 return t 1757 1758 def t_CPPDIRECTIVE(self, t): 1759 r'^\#[^\#].*\n' 1760 t.lexer.lineno += t.value.count('\n') 1761 return t 1762 1763 def t_NEWFILE(self, t): 1764 r'^\#\#newfile\s+"[^"]*"\n' 1765 self.fileNameStack.push(t.lexer.lineno) 1766 t.lexer.lineno = LineTracker(t.value[11:-2]) 1767 1768 def t_ENDFILE(self, t): 1769 r'^\#\#endfile\n' 1770 t.lexer.lineno = self.fileNameStack.pop() 1771 1772 # 1773 # The functions t_NEWLINE, t_ignore, and t_error are 1774 # special for the lex module. 1775 # 1776 1777 # Newlines 1778 def t_NEWLINE(self, t): 1779 r'\n+' 1780 t.lexer.lineno += t.value.count('\n') 1781 1782 # Comments 1783 def t_comment(self, t): 1784 r'//.*' 1785 1786 # Completely ignored characters 1787 t_ignore = ' \t\x0c' 1788 1789 # Error handler 1790 def t_error(self, t): 1791 error(t.lexer.lineno, "illegal character '%s'" % t.value[0]) 1792 t.skip(1) 1793 1794 ##################################################################### 1795 # 1796 # Parser 1797 # 1798 # Every function whose name starts with 'p_' defines a grammar 1799 # rule. The rule is encoded in the function's doc string, while 1800 # the function body provides the action taken when the rule is 1801 # matched. The argument to each function is a list of the values 1802 # of the rule's symbols: t[0] for the LHS, and t[1..n] for the 1803 # symbols on the RHS. For tokens, the value is copied from the 1804 # t.value attribute provided by the lexer. For non-terminals, the 1805 # value is assigned by the producing rule; i.e., the job of the 1806 # grammar rule function is to set the value for the non-terminal 1807 # on the LHS (by assigning to t[0]). 1808 ##################################################################### 1809 1810 # The LHS of the first grammar rule is used as the start symbol 1811 # (in this case, 'specification'). Note that this rule enforces 1812 # that there will be exactly one namespace declaration, with 0 or 1813 # more global defs/decls before and after it. The defs & decls 1814 # before the namespace decl will be outside the namespace; those 1815 # after will be inside. The decoder function is always inside the 1816 # namespace. 1817 def p_specification(self, t): 1818 'specification : opt_defs_and_outputs top_level_decode_block' 1819 1820 for f in self.splits.iterkeys(): 1821 f.write('\n#endif\n') 1822 1823 for f in self.files.itervalues(): # close ALL the files; 1824 f.close() # not doing so can cause compilation to fail 1825 1826 self.write_top_level_files() 1827 1828 t[0] = True 1829 1830 # 'opt_defs_and_outputs' is a possibly empty sequence of def and/or 1831 # output statements. Its productions do the hard work of eventually 1832 # instantiating a GenCode, which are generally emitted (written to disk) 1833 # as soon as possible, except for the decode_block, which has to be 1834 # accumulated into one large function of nested switch/case blocks. 1835 def p_opt_defs_and_outputs_0(self, t): 1836 'opt_defs_and_outputs : empty' 1837 1838 def p_opt_defs_and_outputs_1(self, t): 1839 'opt_defs_and_outputs : defs_and_outputs' 1840 1841 def p_defs_and_outputs_0(self, t): 1842 'defs_and_outputs : def_or_output' 1843 1844 def p_defs_and_outputs_1(self, t): 1845 'defs_and_outputs : defs_and_outputs def_or_output' 1846 1847 # The list of possible definition/output statements. 1848 # They are all processed as they are seen. 1849 def p_def_or_output(self, t): 1850 '''def_or_output : name_decl 1851 | def_format 1852 | def_bitfield 1853 | def_bitfield_struct 1854 | def_template 1855 | def_operand_types 1856 | def_operands 1857 | output 1858 | global_let 1859 | split''' 1860 1861 # Utility function used by both invocations of splitting - explicit 1862 # 'split' keyword and split() function inside "let {{ }};" blocks. 1863 def split(self, sec, write=False): 1864 assert(sec != 'header' and "header cannot be split") 1865 1866 f = self.get_file(sec) 1867 self.splits[f] += 1 1868 s = '\n#endif\n#if __SPLIT == %u\n' % self.splits[f] 1869 if write: 1870 f.write(s) 1871 else: 1872 return s 1873 1874 # split output file to reduce compilation time 1875 def p_split(self, t): 1876 'split : SPLIT output_type SEMI' 1877 assert(self.isa_name and "'split' not allowed before namespace decl") 1878 1879 self.split(t[2], True) 1880 1881 def p_output_type(self, t): 1882 '''output_type : DECODER 1883 | HEADER 1884 | EXEC''' 1885 t[0] = t[1] 1886 1887 # ISA name declaration looks like "namespace <foo>;" 1888 def p_name_decl(self, t): 1889 'name_decl : NAMESPACE ID SEMI' 1890 assert(self.isa_name == None and "Only 1 namespace decl permitted") 1891 self.isa_name = t[2] 1892 self.namespace = t[2] + 'Inst' 1893 1894 # Output blocks 'output <foo> {{...}}' (C++ code blocks) are copied 1895 # directly to the appropriate output section. 1896 1897 # Massage output block by substituting in template definitions and 1898 # bit operators. We handle '%'s embedded in the string that don't 1899 # indicate template substitutions by doubling them first so that the 1900 # format operation will reduce them back to single '%'s. 1901 def process_output(self, s): 1902 s = self.protectNonSubstPercents(s) 1903 return substBitOps(s % self.templateMap) 1904 1905 def p_output(self, t): 1906 'output : OUTPUT output_type CODELIT SEMI' 1907 kwargs = { t[2]+'_output' : self.process_output(t[3]) } 1908 GenCode(self, **kwargs).emit() 1909 1910 # global let blocks 'let {{...}}' (Python code blocks) are 1911 # executed directly when seen. Note that these execute in a 1912 # special variable context 'exportContext' to prevent the code 1913 # from polluting this script's namespace. 1914 def p_global_let(self, t): 1915 'global_let : LET CODELIT SEMI' 1916 def _split(sec): 1917 return self.split(sec) 1918 self.updateExportContext() 1919 self.exportContext["header_output"] = '' 1920 self.exportContext["decoder_output"] = '' 1921 self.exportContext["exec_output"] = '' 1922 self.exportContext["decode_block"] = '' 1923 self.exportContext["split"] = _split 1924 split_setup = ''' 1925def wrap(func): 1926 def split(sec): 1927 globals()[sec + '_output'] += func(sec) 1928 return split 1929split = wrap(split) 1930del wrap 1931''' 1932 # This tricky setup (immediately above) allows us to just write 1933 # (e.g.) "split('exec')" in the Python code and the split #ifdef's 1934 # will automatically be added to the exec_output variable. The inner 1935 # Python execution environment doesn't know about the split points, 1936 # so we carefully inject and wrap a closure that can retrieve the 1937 # next split's #define from the parser and add it to the current 1938 # emission-in-progress. 1939 try: 1940 exec split_setup+fixPythonIndentation(t[2]) in self.exportContext 1941 except Exception, exc: 1942 traceback.print_exc(file=sys.stdout) 1943 if debug: 1944 raise 1945 error(t.lineno(1), 'In global let block: %s' % exc) 1946 GenCode(self, 1947 header_output=self.exportContext["header_output"], 1948 decoder_output=self.exportContext["decoder_output"], 1949 exec_output=self.exportContext["exec_output"], 1950 decode_block=self.exportContext["decode_block"]).emit() 1951 1952 # Define the mapping from operand type extensions to C++ types and 1953 # bit widths (stored in operandTypeMap). 1954 def p_def_operand_types(self, t): 1955 'def_operand_types : DEF OPERAND_TYPES CODELIT SEMI' 1956 try: 1957 self.operandTypeMap = eval('{' + t[3] + '}') 1958 except Exception, exc: 1959 if debug: 1960 raise 1961 error(t.lineno(1), 1962 'In def operand_types: %s' % exc) 1963 1964 # Define the mapping from operand names to operand classes and 1965 # other traits. Stored in operandNameMap. 1966 def p_def_operands(self, t): 1967 'def_operands : DEF OPERANDS CODELIT SEMI' 1968 if not hasattr(self, 'operandTypeMap'): 1969 error(t.lineno(1), 1970 'error: operand types must be defined before operands') 1971 try: 1972 user_dict = eval('{' + t[3] + '}', self.exportContext) 1973 except Exception, exc: 1974 if debug: 1975 raise 1976 error(t.lineno(1), 'In def operands: %s' % exc) 1977 self.buildOperandNameMap(user_dict, t.lexer.lineno) 1978 1979 # A bitfield definition looks like: 1980 # 'def [signed] bitfield <ID> [<first>:<last>]' 1981 # This generates a preprocessor macro in the output file. 1982 def p_def_bitfield_0(self, t): 1983 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT COLON INTLIT GREATER SEMI' 1984 expr = 'bits(machInst, %2d, %2d)' % (t[6], t[8]) 1985 if (t[2] == 'signed'): 1986 expr = 'sext<%d>(%s)' % (t[6] - t[8] + 1, expr) 1987 hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr) 1988 GenCode(self, header_output=hash_define).emit() 1989 1990 # alternate form for single bit: 'def [signed] bitfield <ID> [<bit>]' 1991 def p_def_bitfield_1(self, t): 1992 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT GREATER SEMI' 1993 expr = 'bits(machInst, %2d, %2d)' % (t[6], t[6]) 1994 if (t[2] == 'signed'): 1995 expr = 'sext<%d>(%s)' % (1, expr) 1996 hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr) 1997 GenCode(self, header_output=hash_define).emit() 1998 1999 # alternate form for structure member: 'def bitfield <ID> <ID>' 2000 def p_def_bitfield_struct(self, t): 2001 'def_bitfield_struct : DEF opt_signed BITFIELD ID id_with_dot SEMI' 2002 if (t[2] != ''): 2003 error(t.lineno(1), 2004 'error: structure bitfields are always unsigned.') 2005 expr = 'machInst.%s' % t[5] 2006 hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr) 2007 GenCode(self, header_output=hash_define).emit() 2008 2009 def p_id_with_dot_0(self, t): 2010 'id_with_dot : ID' 2011 t[0] = t[1] 2012 2013 def p_id_with_dot_1(self, t): 2014 'id_with_dot : ID DOT id_with_dot' 2015 t[0] = t[1] + t[2] + t[3] 2016 2017 def p_opt_signed_0(self, t): 2018 'opt_signed : SIGNED' 2019 t[0] = t[1] 2020 2021 def p_opt_signed_1(self, t): 2022 'opt_signed : empty' 2023 t[0] = '' 2024 2025 def p_def_template(self, t): 2026 'def_template : DEF TEMPLATE ID CODELIT SEMI' 2027 if t[3] in self.templateMap: 2028 print("warning: template %s already defined" % t[3]) 2029 self.templateMap[t[3]] = Template(self, t[4]) 2030 2031 # An instruction format definition looks like 2032 # "def format <fmt>(<params>) {{...}};" 2033 def p_def_format(self, t): 2034 'def_format : DEF FORMAT ID LPAREN param_list RPAREN CODELIT SEMI' 2035 (id, params, code) = (t[3], t[5], t[7]) 2036 self.defFormat(id, params, code, t.lexer.lineno) 2037 2038 # The formal parameter list for an instruction format is a 2039 # possibly empty list of comma-separated parameters. Positional 2040 # (standard, non-keyword) parameters must come first, followed by 2041 # keyword parameters, followed by a '*foo' parameter that gets 2042 # excess positional arguments (as in Python). Each of these three 2043 # parameter categories is optional. 2044 # 2045 # Note that we do not support the '**foo' parameter for collecting 2046 # otherwise undefined keyword args. Otherwise the parameter list 2047 # is (I believe) identical to what is supported in Python. 2048 # 2049 # The param list generates a tuple, where the first element is a 2050 # list of the positional params and the second element is a dict 2051 # containing the keyword params. 2052 def p_param_list_0(self, t): 2053 'param_list : positional_param_list COMMA nonpositional_param_list' 2054 t[0] = t[1] + t[3] 2055 2056 def p_param_list_1(self, t): 2057 '''param_list : positional_param_list 2058 | nonpositional_param_list''' 2059 t[0] = t[1] 2060 2061 def p_positional_param_list_0(self, t): 2062 'positional_param_list : empty' 2063 t[0] = [] 2064 2065 def p_positional_param_list_1(self, t): 2066 'positional_param_list : ID' 2067 t[0] = [t[1]] 2068 2069 def p_positional_param_list_2(self, t): 2070 'positional_param_list : positional_param_list COMMA ID' 2071 t[0] = t[1] + [t[3]] 2072 2073 def p_nonpositional_param_list_0(self, t): 2074 'nonpositional_param_list : keyword_param_list COMMA excess_args_param' 2075 t[0] = t[1] + t[3] 2076 2077 def p_nonpositional_param_list_1(self, t): 2078 '''nonpositional_param_list : keyword_param_list 2079 | excess_args_param''' 2080 t[0] = t[1] 2081 2082 def p_keyword_param_list_0(self, t): 2083 'keyword_param_list : keyword_param' 2084 t[0] = [t[1]] 2085 2086 def p_keyword_param_list_1(self, t): 2087 'keyword_param_list : keyword_param_list COMMA keyword_param' 2088 t[0] = t[1] + [t[3]] 2089 2090 def p_keyword_param(self, t): 2091 'keyword_param : ID EQUALS expr' 2092 t[0] = t[1] + ' = ' + t[3].__repr__() 2093 2094 def p_excess_args_param(self, t): 2095 'excess_args_param : ASTERISK ID' 2096 # Just concatenate them: '*ID'. Wrap in list to be consistent 2097 # with positional_param_list and keyword_param_list. 2098 t[0] = [t[1] + t[2]] 2099 2100 # End of format definition-related rules. 2101 ############## 2102 2103 # 2104 # A decode block looks like: 2105 # decode <field1> [, <field2>]* [default <inst>] { ... } 2106 # 2107 def p_top_level_decode_block(self, t): 2108 'top_level_decode_block : decode_block' 2109 codeObj = t[1] 2110 codeObj.wrap_decode_block(''' 2111StaticInstPtr 2112%(isa_name)s::Decoder::decodeInst(%(isa_name)s::ExtMachInst machInst) 2113{ 2114 using namespace %(namespace)s; 2115''' % self, '}') 2116 2117 codeObj.emit() 2118 2119 def p_decode_block(self, t): 2120 'decode_block : DECODE ID opt_default LBRACE decode_stmt_list RBRACE' 2121 default_defaults = self.defaultStack.pop() 2122 codeObj = t[5] 2123 # use the "default defaults" only if there was no explicit 2124 # default statement in decode_stmt_list 2125 if not codeObj.has_decode_default: 2126 codeObj += default_defaults 2127 codeObj.wrap_decode_block('switch (%s) {\n' % t[2], '}\n') 2128 t[0] = codeObj 2129 2130 # The opt_default statement serves only to push the "default 2131 # defaults" onto defaultStack. This value will be used by nested 2132 # decode blocks, and used and popped off when the current 2133 # decode_block is processed (in p_decode_block() above). 2134 def p_opt_default_0(self, t): 2135 'opt_default : empty' 2136 # no default specified: reuse the one currently at the top of 2137 # the stack 2138 self.defaultStack.push(self.defaultStack.top()) 2139 # no meaningful value returned 2140 t[0] = None 2141 2142 def p_opt_default_1(self, t): 2143 'opt_default : DEFAULT inst' 2144 # push the new default 2145 codeObj = t[2] 2146 codeObj.wrap_decode_block('\ndefault:\n', 'break;\n') 2147 self.defaultStack.push(codeObj) 2148 # no meaningful value returned 2149 t[0] = None 2150 2151 def p_decode_stmt_list_0(self, t): 2152 'decode_stmt_list : decode_stmt' 2153 t[0] = t[1] 2154 2155 def p_decode_stmt_list_1(self, t): 2156 'decode_stmt_list : decode_stmt decode_stmt_list' 2157 if (t[1].has_decode_default and t[2].has_decode_default): 2158 error(t.lineno(1), 'Two default cases in decode block') 2159 t[0] = t[1] + t[2] 2160 2161 # 2162 # Decode statement rules 2163 # 2164 # There are four types of statements allowed in a decode block: 2165 # 1. Format blocks 'format <foo> { ... }' 2166 # 2. Nested decode blocks 2167 # 3. Instruction definitions. 2168 # 4. C preprocessor directives. 2169 2170 2171 # Preprocessor directives found in a decode statement list are 2172 # passed through to the output, replicated to all of the output 2173 # code streams. This works well for ifdefs, so we can ifdef out 2174 # both the declarations and the decode cases generated by an 2175 # instruction definition. Handling them as part of the grammar 2176 # makes it easy to keep them in the right place with respect to 2177 # the code generated by the other statements. 2178 def p_decode_stmt_cpp(self, t): 2179 'decode_stmt : CPPDIRECTIVE' 2180 t[0] = GenCode(self, t[1], t[1], t[1], t[1]) 2181 2182 # A format block 'format <foo> { ... }' sets the default 2183 # instruction format used to handle instruction definitions inside 2184 # the block. This format can be overridden by using an explicit 2185 # format on the instruction definition or with a nested format 2186 # block. 2187 def p_decode_stmt_format(self, t): 2188 'decode_stmt : FORMAT push_format_id LBRACE decode_stmt_list RBRACE' 2189 # The format will be pushed on the stack when 'push_format_id' 2190 # is processed (see below). Once the parser has recognized 2191 # the full production (though the right brace), we're done 2192 # with the format, so now we can pop it. 2193 self.formatStack.pop() 2194 t[0] = t[4] 2195 2196 # This rule exists so we can set the current format (& push the 2197 # stack) when we recognize the format name part of the format 2198 # block. 2199 def p_push_format_id(self, t): 2200 'push_format_id : ID' 2201 try: 2202 self.formatStack.push(self.formatMap[t[1]]) 2203 t[0] = ('', '// format %s' % t[1]) 2204 except KeyError: 2205 error(t.lineno(1), 'instruction format "%s" not defined.' % t[1]) 2206 2207 # Nested decode block: if the value of the current field matches 2208 # the specified constant(s), do a nested decode on some other field. 2209 def p_decode_stmt_decode(self, t): 2210 'decode_stmt : case_list COLON decode_block' 2211 case_list = t[1] 2212 codeObj = t[3] 2213 # just wrap the decoding code from the block as a case in the 2214 # outer switch statement. 2215 codeObj.wrap_decode_block('\n%s\n' % ''.join(case_list), 2216 'M5_UNREACHABLE;\n') 2217 codeObj.has_decode_default = (case_list == ['default:']) 2218 t[0] = codeObj 2219 2220 # Instruction definition (finally!). 2221 def p_decode_stmt_inst(self, t): 2222 'decode_stmt : case_list COLON inst SEMI' 2223 case_list = t[1] 2224 codeObj = t[3] 2225 codeObj.wrap_decode_block('\n%s' % ''.join(case_list), 'break;\n') 2226 codeObj.has_decode_default = (case_list == ['default:']) 2227 t[0] = codeObj 2228 2229 # The constant list for a decode case label must be non-empty, and must 2230 # either be the keyword 'default', or made up of one or more 2231 # comma-separated integer literals or strings which evaluate to 2232 # constants when compiled as C++. 2233 def p_case_list_0(self, t): 2234 'case_list : DEFAULT' 2235 t[0] = ['default:'] 2236 2237 def prep_int_lit_case_label(self, lit): 2238 if lit >= 2**32: 2239 return 'case ULL(%#x): ' % lit 2240 else: 2241 return 'case %#x: ' % lit 2242 2243 def prep_str_lit_case_label(self, lit): 2244 return 'case %s: ' % lit 2245 2246 def p_case_list_1(self, t): 2247 'case_list : INTLIT' 2248 t[0] = [self.prep_int_lit_case_label(t[1])] 2249 2250 def p_case_list_2(self, t): 2251 'case_list : STRLIT' 2252 t[0] = [self.prep_str_lit_case_label(t[1])] 2253 2254 def p_case_list_3(self, t): 2255 'case_list : case_list COMMA INTLIT' 2256 t[0] = t[1] 2257 t[0].append(self.prep_int_lit_case_label(t[3])) 2258 2259 def p_case_list_4(self, t): 2260 'case_list : case_list COMMA STRLIT' 2261 t[0] = t[1] 2262 t[0].append(self.prep_str_lit_case_label(t[3])) 2263 2264 # Define an instruction using the current instruction format 2265 # (specified by an enclosing format block). 2266 # "<mnemonic>(<args>)" 2267 def p_inst_0(self, t): 2268 'inst : ID LPAREN arg_list RPAREN' 2269 # Pass the ID and arg list to the current format class to deal with. 2270 currentFormat = self.formatStack.top() 2271 codeObj = currentFormat.defineInst(self, t[1], t[3], t.lexer.lineno) 2272 args = ','.join(map(str, t[3])) 2273 args = re.sub('(?m)^', '//', args) 2274 args = re.sub('^//', '', args) 2275 comment = '\n// %s::%s(%s)\n' % (currentFormat.id, t[1], args) 2276 codeObj.prepend_all(comment) 2277 t[0] = codeObj 2278 2279 # Define an instruction using an explicitly specified format: 2280 # "<fmt>::<mnemonic>(<args>)" 2281 def p_inst_1(self, t): 2282 'inst : ID DBLCOLON ID LPAREN arg_list RPAREN' 2283 try: 2284 format = self.formatMap[t[1]] 2285 except KeyError: 2286 error(t.lineno(1), 'instruction format "%s" not defined.' % t[1]) 2287 2288 codeObj = format.defineInst(self, t[3], t[5], t.lexer.lineno) 2289 comment = '\n// %s::%s(%s)\n' % (t[1], t[3], t[5]) 2290 codeObj.prepend_all(comment) 2291 t[0] = codeObj 2292 2293 # The arg list generates a tuple, where the first element is a 2294 # list of the positional args and the second element is a dict 2295 # containing the keyword args. 2296 def p_arg_list_0(self, t): 2297 'arg_list : positional_arg_list COMMA keyword_arg_list' 2298 t[0] = ( t[1], t[3] ) 2299 2300 def p_arg_list_1(self, t): 2301 'arg_list : positional_arg_list' 2302 t[0] = ( t[1], {} ) 2303 2304 def p_arg_list_2(self, t): 2305 'arg_list : keyword_arg_list' 2306 t[0] = ( [], t[1] ) 2307 2308 def p_positional_arg_list_0(self, t): 2309 'positional_arg_list : empty' 2310 t[0] = [] 2311 2312 def p_positional_arg_list_1(self, t): 2313 'positional_arg_list : expr' 2314 t[0] = [t[1]] 2315 2316 def p_positional_arg_list_2(self, t): 2317 'positional_arg_list : positional_arg_list COMMA expr' 2318 t[0] = t[1] + [t[3]] 2319 2320 def p_keyword_arg_list_0(self, t): 2321 'keyword_arg_list : keyword_arg' 2322 t[0] = t[1] 2323 2324 def p_keyword_arg_list_1(self, t): 2325 'keyword_arg_list : keyword_arg_list COMMA keyword_arg' 2326 t[0] = t[1] 2327 t[0].update(t[3]) 2328 2329 def p_keyword_arg(self, t): 2330 'keyword_arg : ID EQUALS expr' 2331 t[0] = { t[1] : t[3] } 2332 2333 # 2334 # Basic expressions. These constitute the argument values of 2335 # "function calls" (i.e. instruction definitions in the decode 2336 # block) and default values for formal parameters of format 2337 # functions. 2338 # 2339 # Right now, these are either strings, integers, or (recursively) 2340 # lists of exprs (using Python square-bracket list syntax). Note 2341 # that bare identifiers are trated as string constants here (since 2342 # there isn't really a variable namespace to refer to). 2343 # 2344 def p_expr_0(self, t): 2345 '''expr : ID 2346 | INTLIT 2347 | STRLIT 2348 | CODELIT''' 2349 t[0] = t[1] 2350 2351 def p_expr_1(self, t): 2352 '''expr : LBRACKET list_expr RBRACKET''' 2353 t[0] = t[2] 2354 2355 def p_list_expr_0(self, t): 2356 'list_expr : expr' 2357 t[0] = [t[1]] 2358 2359 def p_list_expr_1(self, t): 2360 'list_expr : list_expr COMMA expr' 2361 t[0] = t[1] + [t[3]] 2362 2363 def p_list_expr_2(self, t): 2364 'list_expr : empty' 2365 t[0] = [] 2366 2367 # 2368 # Empty production... use in other rules for readability. 2369 # 2370 def p_empty(self, t): 2371 'empty :' 2372 pass 2373 2374 # Parse error handler. Note that the argument here is the 2375 # offending *token*, not a grammar symbol (hence the need to use 2376 # t.value) 2377 def p_error(self, t): 2378 if t: 2379 error(t.lexer.lineno, "syntax error at '%s'" % t.value) 2380 else: 2381 error("unknown syntax error") 2382 2383 # END OF GRAMMAR RULES 2384 2385 def updateExportContext(self): 2386 2387 # create a continuation that allows us to grab the current parser 2388 def wrapInstObjParams(*args): 2389 return InstObjParams(self, *args) 2390 self.exportContext['InstObjParams'] = wrapInstObjParams 2391 self.exportContext.update(self.templateMap) 2392 2393 def defFormat(self, id, params, code, lineno): 2394 '''Define a new format''' 2395 2396 # make sure we haven't already defined this one 2397 if id in self.formatMap: 2398 error(lineno, 'format %s redefined.' % id) 2399 2400 # create new object and store in global map 2401 self.formatMap[id] = Format(id, params, code) 2402 2403 def protectNonSubstPercents(self, s): 2404 '''Protect any non-dict-substitution '%'s in a format string 2405 (i.e. those not followed by '(')''' 2406 2407 return re.sub(r'%(?!\()', '%%', s) 2408 2409 def buildOperandNameMap(self, user_dict, lineno): 2410 operand_name = {} 2411 for op_name, val in user_dict.iteritems(): 2412 2413 # Check if extra attributes have been specified. 2414 if len(val) > 9: 2415 error(lineno, 'error: too many attributes for operand "%s"' % 2416 base_cls_name) 2417 2418 # Pad val with None in case optional args are missing 2419 val += (None, None, None, None) 2420 base_cls_name, dflt_ext, reg_spec, flags, sort_pri, \ 2421 read_code, write_code, read_predicate, write_predicate = val[:9] 2422 2423 # Canonical flag structure is a triple of lists, where each list 2424 # indicates the set of flags implied by this operand always, when 2425 # used as a source, and when used as a dest, respectively. 2426 # For simplicity this can be initialized using a variety of fairly 2427 # obvious shortcuts; we convert these to canonical form here. 2428 if not flags: 2429 # no flags specified (e.g., 'None') 2430 flags = ( [], [], [] ) 2431 elif isinstance(flags, str): 2432 # a single flag: assumed to be unconditional 2433 flags = ( [ flags ], [], [] ) 2434 elif isinstance(flags, list): 2435 # a list of flags: also assumed to be unconditional 2436 flags = ( flags, [], [] ) 2437 elif isinstance(flags, tuple): 2438 # it's a tuple: it should be a triple, 2439 # but each item could be a single string or a list 2440 (uncond_flags, src_flags, dest_flags) = flags 2441 flags = (makeList(uncond_flags), 2442 makeList(src_flags), makeList(dest_flags)) 2443 2444 # Accumulate attributes of new operand class in tmp_dict 2445 tmp_dict = {} 2446 attrList = ['reg_spec', 'flags', 'sort_pri', 2447 'read_code', 'write_code', 2448 'read_predicate', 'write_predicate'] 2449 if dflt_ext: 2450 dflt_ctype = self.operandTypeMap[dflt_ext] 2451 attrList.extend(['dflt_ctype', 'dflt_ext']) 2452 # reg_spec is either just a string or a dictionary 2453 # (for elems of vector) 2454 if isinstance(reg_spec, tuple): 2455 (reg_spec, elem_spec) = reg_spec 2456 if isinstance(elem_spec, str): 2457 attrList.append('elem_spec') 2458 else: 2459 assert(isinstance(elem_spec, dict)) 2460 elems = elem_spec 2461 attrList.append('elems') 2462 for attr in attrList: 2463 tmp_dict[attr] = eval(attr) 2464 tmp_dict['base_name'] = op_name 2465 2466 # New class name will be e.g. "IntReg_Ra" 2467 cls_name = base_cls_name + '_' + op_name 2468 # Evaluate string arg to get class object. Note that the 2469 # actual base class for "IntReg" is "IntRegOperand", i.e. we 2470 # have to append "Operand". 2471 try: 2472 base_cls = eval(base_cls_name + 'Operand') 2473 except NameError: 2474 error(lineno, 2475 'error: unknown operand base class "%s"' % base_cls_name) 2476 # The following statement creates a new class called 2477 # <cls_name> as a subclass of <base_cls> with the attributes 2478 # in tmp_dict, just as if we evaluated a class declaration. 2479 operand_name[op_name] = type(cls_name, (base_cls,), tmp_dict) 2480 2481 self.operandNameMap = operand_name 2482 2483 # Define operand variables. 2484 operands = user_dict.keys() 2485 # Add the elems defined in the vector operands and 2486 # build a map elem -> vector (used in OperandList) 2487 elem_to_vec = {} 2488 for op in user_dict.keys(): 2489 if hasattr(self.operandNameMap[op], 'elems'): 2490 for elem in self.operandNameMap[op].elems.keys(): 2491 operands.append(elem) 2492 elem_to_vec[elem] = op 2493 self.elemToVector = elem_to_vec 2494 extensions = self.operandTypeMap.keys() 2495 2496 operandsREString = r''' 2497 (?<!\w) # neg. lookbehind assertion: prevent partial matches 2498 ((%s)(?:_(%s))?) # match: operand with optional '_' then suffix 2499 (?!\w) # neg. lookahead assertion: prevent partial matches 2500 ''' % (string.join(operands, '|'), string.join(extensions, '|')) 2501 2502 self.operandsRE = re.compile(operandsREString, re.MULTILINE|re.VERBOSE) 2503 2504 # Same as operandsREString, but extension is mandatory, and only two 2505 # groups are returned (base and ext, not full name as above). 2506 # Used for subtituting '_' for '.' to make C++ identifiers. 2507 operandsWithExtREString = r'(?<!\w)(%s)_(%s)(?!\w)' \ 2508 % (string.join(operands, '|'), string.join(extensions, '|')) 2509 2510 self.operandsWithExtRE = \ 2511 re.compile(operandsWithExtREString, re.MULTILINE) 2512 2513 def substMungedOpNames(self, code): 2514 '''Munge operand names in code string to make legal C++ 2515 variable names. This means getting rid of the type extension 2516 if any. Will match base_name attribute of Operand object.)''' 2517 return self.operandsWithExtRE.sub(r'\1', code) 2518 2519 def mungeSnippet(self, s): 2520 '''Fix up code snippets for final substitution in templates.''' 2521 if isinstance(s, str): 2522 return self.substMungedOpNames(substBitOps(s)) 2523 else: 2524 return s 2525 2526 def open(self, name, bare=False): 2527 '''Open the output file for writing and include scary warning.''' 2528 filename = os.path.join(self.output_dir, name) 2529 f = open(filename, 'w') 2530 if f: 2531 if not bare: 2532 f.write(ISAParser.scaremonger_template % self) 2533 return f 2534 2535 def update(self, file, contents): 2536 '''Update the output file only. Scons should handle the case when 2537 the new contents are unchanged using its built-in hash feature.''' 2538 f = self.open(file) 2539 f.write(contents) 2540 f.close() 2541 2542 # This regular expression matches '##include' directives 2543 includeRE = re.compile(r'^\s*##include\s+"(?P<filename>[^"]*)".*$', 2544 re.MULTILINE) 2545 2546 def replace_include(self, matchobj, dirname): 2547 """Function to replace a matched '##include' directive with the 2548 contents of the specified file (with nested ##includes 2549 replaced recursively). 'matchobj' is an re match object 2550 (from a match of includeRE) and 'dirname' is the directory 2551 relative to which the file path should be resolved.""" 2552 2553 fname = matchobj.group('filename') 2554 full_fname = os.path.normpath(os.path.join(dirname, fname)) 2555 contents = '##newfile "%s"\n%s\n##endfile\n' % \ 2556 (full_fname, self.read_and_flatten(full_fname)) 2557 return contents 2558 2559 def read_and_flatten(self, filename): 2560 """Read a file and recursively flatten nested '##include' files.""" 2561 2562 current_dir = os.path.dirname(filename) 2563 try: 2564 contents = open(filename).read() 2565 except IOError: 2566 error('Error including file "%s"' % filename) 2567 2568 self.fileNameStack.push(LineTracker(filename)) 2569 2570 # Find any includes and include them 2571 def replace(matchobj): 2572 return self.replace_include(matchobj, current_dir) 2573 contents = self.includeRE.sub(replace, contents) 2574 2575 self.fileNameStack.pop() 2576 return contents 2577 2578 AlreadyGenerated = {} 2579 2580 def _parse_isa_desc(self, isa_desc_file): 2581 '''Read in and parse the ISA description.''' 2582 2583 # The build system can end up running the ISA parser twice: once to 2584 # finalize the build dependencies, and then to actually generate 2585 # the files it expects (in src/arch/$ARCH/generated). This code 2586 # doesn't do anything different either time, however; the SCons 2587 # invocations just expect different things. Since this code runs 2588 # within SCons, we can just remember that we've already run and 2589 # not perform a completely unnecessary run, since the ISA parser's 2590 # effect is idempotent. 2591 if isa_desc_file in ISAParser.AlreadyGenerated: 2592 return 2593 2594 # grab the last three path components of isa_desc_file 2595 self.filename = '/'.join(isa_desc_file.split('/')[-3:]) 2596 2597 # Read file and (recursively) all included files into a string. 2598 # PLY requires that the input be in a single string so we have to 2599 # do this up front. 2600 isa_desc = self.read_and_flatten(isa_desc_file) 2601 2602 # Initialize lineno tracker 2603 self.lex.lineno = LineTracker(isa_desc_file) 2604 2605 # Parse. 2606 self.parse_string(isa_desc) 2607 2608 ISAParser.AlreadyGenerated[isa_desc_file] = None 2609 2610 def parse_isa_desc(self, *args, **kwargs): 2611 try: 2612 self._parse_isa_desc(*args, **kwargs) 2613 except ISAParserError, e: 2614 print(backtrace(self.fileNameStack)) 2615 print("At %s:" % e.lineno) 2616 print(e) 2617 sys.exit(1) 2618 2619# Called as script: get args from command line. 2620# Args are: <isa desc file> <output dir> 2621if __name__ == '__main__': 2622 ISAParser(sys.argv[2]).parse_isa_desc(sys.argv[1]) 2623