Exemplo n.º 1
0
def p_assign(p):
    ''' assign : simple_expr1  asgn or_expression
    '''
    if 'islit' in p[1].keys():
        sys.exit("Type Error: Assignment to constant not defined.")
    temp = ST.getTemp()
    p[0] = {'place': temp, 'isarray': False, 'type': 'Not defined'}
    if p[2] == '=':
        c1 = p[1]['type']
        c2 = p[3]['type']
        if p[1]['type'] == 'Array':
            c1 = 'INT'
        if p[3]['type'] == 'Array':
            c2 = 'INT'
        if c1 != c2:
            sys.exit("Type error bla")
        p[3] = evalArray(p[3])
        if p[1]['type'] == 'Array':
            emit('star', p[1]['place'], p[1]['index'], p[3]['place'])
        else:
            emit(op='=', out=p[1]['place'], in1=p[3]['place'])
    else:
        #print "ds is awesome"
        p[3] = evalArray(p[3])
        t1 = ST.getTemp()
        t2 = evalArray(p[1])
        #print p[2][0]
        emit(p[2][0], t1, t2['place'], p[3]['place'])
        if p[1]['type'] == 'Array':
            emit('star', p[1]['place'], p[1]['index'], t1)
        else:
            emit('=', p[1]['place'], t1)
    ##Check
    printp(p)
Exemplo n.º 2
0
def p_prefix_expr(p):
    '''prefix_expr  :   simple_expr
                    |   OP_SUB infix_expr
                    |   OP_ADD infix_expr
                    |   OP_NOT infix_expr'''
    if len(p) == 2:
        p[0] = p[1]
    else:
        if p.slice[1].type == 'OP_ADD':
            p[0] = p[2]
        elif p.slice[1].type == 'OP_SUB':
            temp = ST.getTemp()
            emit("-", temp, 0, p[2]['place'])
            p[0] = {}
            p[0]['type'] = p[2]['type']
            p[0]['place'] = temp
            p[0]['idVal'] = temp
        else:
            temp = ST.getTemp()
            emit("!", temp, p[2]['place'])
            p[0] = {}
            p[0]['type'] = p[2]['type']
            p[0]['place'] = temp
            p[0]['idVal'] = temp

    printp(p)
Exemplo n.º 3
0
def p_WhMark3(p):
    '''WhMark3 : '''
    emit(op='goto', out=p[-6][0])  #goto l1
    emit(op='label', out=p[-6][2])  #exit label
    ST.endScope()
    ST.stackbegin.pop()
    ST.stackend.pop()
    printp(p)
Exemplo n.º 4
0
def p_FunMark2(p):
    ''' FunMark2 : epsilon
    '''
    ST.endFunc()
    #if(p[-5]==False):
    #    ST.function[p[-6][1]]["return"]=False
    #if(p[-6][1]!="main@0"):
    #    emit("freturn")
    printp(p)
Exemplo n.º 5
0
def p_f_mark3(p):
    ''' f_mark3 : epsilon
    '''
    emit(op='goto', out=p[-3][1])  #goto l2
    emit(op='label', out=p[-3][3])  #exit label
    ST.endScope()
    ST.stackbegin.pop()
    ST.stackend.pop()
    printp(p)
Exemplo n.º 6
0
def p_var_dcl(p):
    '''var_dcl  :   id COLON type
    '''
    ST.addVar(p[1], p[1], p[3]['type'])
    #print p[1]
    p[0] = {}
    p[0]['place'] = p[1]
    p[0]['type'] = p[3]['type']
    printp(p)
Exemplo n.º 7
0
def p_WhMark1(p):
    '''WhMark1 : '''
    l1 = newLabel()
    l2 = newLabel()
    l3 = newLabel()
    ST.stackbegin.append(l1)
    ST.stackend.append(l3)
    ST.newScope()
    emit(op='label', out=l1)  #emit label 1
    p[0] = [l1, l2, l3]
    printp(p)
Exemplo n.º 8
0
def p_s_mark1(p):
    '''s_mark1 : epsilon
    '''
    ST.newScope()
    test = newLabel()
    exit = newLabel()
    emit('goto', test)
    ST.stackbegin.append(test)
    ST.stackend.append(exit)
    p[0] = {'label': [test, exit], 'idVal': p[-3]}
    printp(p)
Exemplo n.º 9
0
def p_switch_block(p):
    ''' switch_block : BLOCKBEGIN s_mark1 switch_block_statements_0 BLOCKEND
    '''
    emit('goto', p[2]['label'][1])
    emit('label', p[2]['label'][0])
    for d in p[3]:
        temp = ST.getTemp()
        emit(op='==', out=temp, in1=d['place'], in2=p[2]['idVal']['place'])
        emit('if', d['label'], temp)
    emit('label', p[2]['label'][1])
    ST.endScope()
    printp(p)
Exemplo n.º 10
0
def p_if_mark1(p):
    '''if_mark1 : epsilon
    '''
    p[0] = {}
    l1 = newLabel()
    l2 = newLabel()
    emit('if', l1, p[-3]['place'])
    emit('goto', l2)
    emit('label', l1)
    ST.newScope()
    p[0]['label'] = [l1, l2]
    printp(p)
Exemplo n.º 11
0
def address(var):
    #scope = ST.currScope
    #print ST.SymbolTable[scope]["identifiers"][var]['offset']
    ## print var
    if var.startswith("this."):
        parent = ST.SymbolTable[ST.currScope]['classname']
        #print parent
        off = []
        #if var.split('.')[1] in ST.SymbolTable[parent]['identifiers']:
        #print ST.currScope
        off = ST.SymbolTable[parent]["identifiers"][var.split('.')
                                                    [1]]['offset'] - 4
        #else:
        #    sys.exit("Variable not found address line 45 in registeralloc")
        #else:
        #    extend = ST.SymbolTable[parent]['extends']
        #    if extend is None:
        #        sys.exit("variable not found")
        #    else:
        #        if var.split('.')[1] in ST.SymbolTable[extend]['identifiers']:
        #            off = ST.SymbolTable[extend]['extend'+var.split('.')[1]]
        #        else:
        #            sys.exit("Variable not found")
        print('\tmovl 8(%ebp), %edi')
        print('\taddl $' + str(off) + ", %edi")
        #print('\tmovl (%edi), %edi')
        return "(%edi)"
    if var.startswith("_t"):
        var = "-" + str(int(var[2:]) * 4) + "(%ebp)"
        #print("I am awesome")
        return var
    #print "-------------"
    if '@ARRAY' in var:
        z = ST.getId(var.split('@')[0])
        if 'isparam' in z.keys():
            print('\tmovl -' + str(ST.getOffset(var.split('@')[0])) +
                  "(%ebp), %edi")
            return "%edi"
        else:
            print('\tleal -' + str(ST.getOffset(var.split('@')[0])) +
                  "(%ebp), %edi")
            return "%edi"
    #ST.printSymbolTable()
    a = ST.getOffset(var)
    if a < 0:
        var = str(a * -1) + "(%ebp)"
    else:
        var = "-" + str(a) + "(%ebp)"
    return var
Exemplo n.º 12
0
def evalArray(temp):
    if type(temp) == type({}) and 'type' in temp and temp['type'] == 'Array':
        t1 = ST.getTemp()
        #print "I am here"
        emit(op='ldar', out=t1, in1=temp['place'], in2=temp['index'])
        r = {'place': t1, 'type': 'Array'}
        return r
    return temp
Exemplo n.º 13
0
def p_fun_dcl(p):
    '''fun_dcl  :   id param_clause BLOCKBEGIN COLON type BLOCKEND'''
    #         |   id param_clause'''

    p[0] = ["func"] + [p[1]] + p[2]
    arg = len(p[2])
    if p[1] == 'main':
        name = p[1] + "@" + str(arg)
    else:
        name = "_ZXY" + ST.currScope + p[1] + "@" + str(arg)
    p[0][1] = name
    ST.function.append("_ZXY" + ST.currScope + p[1])
    #print p[0]
    if len(p[0]) > 2:
        ST.addDef(p[0][1], p[0][2:])
    else:
        ST.addDef(p[0][1])
    printp(p)
Exemplo n.º 14
0
def check(var, op):
    if is_number(var) and op != "=":
        t = ST.getTemp()
        l = ['=', t, var]
        myList = ','.join(map(str, l))
        print myList
        return t
    else:
        return var
Exemplo n.º 15
0
def makeIndex(size, place):
    t = ST.getTemp()
    t1 = ST.getTemp()
    old = 0
    old1 = 0
    for i in range(0, len(place) - 1):
        for j in range(i + 1, len(size)):
            if (j == i + 1 and len(size) > 1):
                t = ST.getTemp()
                emit("*", t, place[i]['place'], size[j])
                old = t
            elif (len(size) > 1):
                t = ST.getTemp()
                emit("*", t, old, size[j])
                old = t
        t1 = ST.getTemp()
        emit("+", t1, old1, t)
        old1 = t1
    emit("+", t1, old1, place[len(place) - 1]["place"])
    return t1
Exemplo n.º 16
0
def p_var_def(p):
    ''' var_def : id COLON type EQUALASGN val_var_init

    '''
    #if('isArray' in p[5].keys() and p[5]['isArray']):
    if type(p[5]) == type({}) and 'isArray' in p[5] and p[5]['isArray']:
        ST.addVar(p[1], p[1], 'Array', p[3]['size'], p[3]['type'])
        ST.addAttribute(p[1], 'typeArray', p[3]['type'])
        size = 1
        for x in p[3]["size"]:
            size *= x
        emit('array', p[1], size)
        i = 0
        for d in p[5]['values']:
            emit('star', p[1], i, d['place'])
            i += 1
    # emit('array',p[],'n')
    elif type(p[5]) == type({}) and 'isObject' in p[5] and p[5]['isObject']:
        l = {}
        emit("Object", p[1], p[3]['type'])
        off = ST.SymbolTable[p[3]['type']]['totalOffset']
        ST.addVar(p[1], p[1], p[3]['type'], sizeObj=off)
        offset = 0
        for i in ST.SymbolTable[p[3]['type']]['identifiers'].keys():
            l[ST.SymbolTable[p[3]['type']]['identifiers'][i]['place']] = {
                'place':
                p[1] + '.' +
                ST.SymbolTable[p[3]['type']]['identifiers'][i]['place'],
                'type':
                ST.SymbolTable[p[3]['type']]['identifiers'][i]['type'],
                'offset':
                ST.SymbolTable[p[3]['type']]["identifiers"][i]['offset']
            }
        ST.addAttribute(p[1], 'list', l)
        #ST.printSymbolTable()
    else:
        #print(p[5])
        p[5] = evalArray(p[5])
        ST.addVar(p[1], p[1], p[3]['type'])
        emit('=', in1=p[5]['place'], out=p[1])
    printp(p)
Exemplo n.º 17
0
def p_xor_expression(p):
    ''' xor_expression : bit_and_expression
                       | xor_expression XOR bit_and_expression
    '''
    if len(p) == 2:
        p[0] = p[1]
    else:
        c1 = p[1]['type']
        c2 = p[3]['type']
        if p[1]['type'] == 'Array':
            c1 = 'INT'
        if p[3]['type'] == 'Array':
            c2 = 'INT'
        if c1 != c2:
            sys.exit("Type error bla")
        temp = ST.getTemp()
        p[0] = {'place': temp, 'type': 'INT'}
        p[3] = evalArray(p[3])
        p[1] = evalArray(p[1])
        emit(op='^', out=temp, in1=p[1]['place'], in2=p[3]['place'])
    printp(p)
Exemplo n.º 18
0
def p_add_expression(p):
    '''add_expression : mul_expression
                      | add_expression OP_ADD mul_expression
                      | add_expression OP_SUB  mul_expression
    '''
    if len(p) == 2:
        p[0] = p[1]
    else:
        c1 = p[1]['type']
        c2 = p[3]['type']
        if p[1]['type'] == 'Array':
            c1 = 'INT'
        if p[3]['type'] == 'Array':
            c2 = 'INT'
        if c1 != c2:
            sys.exit("Type error bla")
        temp = ST.getTemp()
        p[0] = {'place': temp, 'type': 'INT'}
        p[3] = evalArray(p[3])
        p[1] = evalArray(p[1])
        emit(op=p[2], out=temp, in1=p[1]['place'], in2=p[3]['place'])
    printp(p)
Exemplo n.º 19
0
def p_eq_expression(p):
    '''eq_expression : comp_expression
                      | eq_expression EQ comp_expression
                      | eq_expression NEQ comp_expression
    '''
    if len(p) == 2:
        p[0] = p[1]
    else:
        c1 = p[1]['type']
        c2 = p[3]['type']
        if p[1]['type'] == 'Array':
            c1 = 'INT'
        if p[3]['type'] == 'Array':
            c2 = 'INT'
        if c1 != c2:
            sys.exit("Type error bla")
        temp = ST.getTemp()
        p[0] = {'place': temp, 'type': 'bool'}
        p[3] = evalArray(p[3])
        p[1] = evalArray(p[1])
        emit(op=p[2], out=temp, in1=p[1]['place'], in2=p[3]['place'])
    #printp(p)
    printp(p)
Exemplo n.º 20
0
def p_simple_expr1(p):
    '''simple_expr1 :   literal
                    |   ID LSQRB access RSQRB
                    |   path
                    |   LPARAN exprs_1 RPARAN
                    |   simple_expr1 argument_exprs'''
    #|   simple_expr DOT id
    p[0] = dict()
    if p.slice[1].type == 'literal':
        p[0] = p[1]
    elif p.slice[1].type == 'path':
        p[0] = p[1]
    elif len(p) == 5:
        p[0]['idVal'] = p[1]
        p[0]['arrAccess'] = True
        p[0]['type'] = ST.getAttribute(p[0]['idVal'], 'type')
        p[0]['place'] = p[1]
        size = ST.getId(p[1])['size']  #a,b,c size
        place = p[3]  # i,j,k access index
        temp = makeIndex(size, place)
        p[0]['index'] = temp
        #p[0]['index'] = p[3]['place']
    elif p.slice[1].type == 'LPARAN':
        p[0] = p[2]
    elif p.slice[2].type == 'argument_exprs':
        #       x = p[1]['idVal'].split('.')
        if (p[1]['name'] == 'println'):
            if (is_number(p[2][0]['place'])):
                temp = ST.getTemp()
                emit("=", temp, p[2][0]['place'])
                emit('printInt', temp)
            else:
                p[2][0] = evalArray(p[2][0])
                emit('printInt', p[2][0]['place'])
        elif (p[1]['name'] == 'readInt'):
            emit('scanInt', p[2][0]['place'])
        else:
            #temp=ST.getTemp()
            #print("=,"+temp+","+str(len(p[2])))
            #print "HUl"
            l = []
            for i in p[2]:
                if (is_number(i['place'])):
                    temp = ST.getTemp()
                    print("=," + temp + "," + str(i['place']))
                    l.append(temp)
                else:
                    if i['type'] == 'Array':
                        l.append(i['place'] + "@" + "ARRAY")
                    else:
                        l.append(i['place'])
            for i in reversed(l):
                emit("param", i)
            name = p[1]["place"] + "@" + str(len(p[2]))
            rtype = ST.getRType(name)
            if (rtype != "void"):
                temp1 = ST.getTemp()
                p[0]["place"] = temp1
                p[0]['type'] = p[1]['rType']['type']
                #print p[1]
                emit("fcall", temp1, p[1]["place"] + "__" + p[1]['objname'],
                     len(p[2]))
            else:
                emit('call', None, p[1]['place'] + "__" + p[1]['objname'],
                     temp)
    printp(p)
Exemplo n.º 21
0
def p_path(p):
    '''path :   id
            |   R_THIS
            |   path DOT id
            |   R_SUPER DOT path
            '''
    # ST.printSymbolTable(ST,1)
    if (p.slice[1].type == 'id'):
        if p[1] not in ST.function:
            p[0] = ST.getId(p[1])
        else:
            p[0] = ST.getFunc(p[1])
    elif (p.slice[1].type == 'R_THIS'):
        p[0] = {
            'isthis': True,
        }
    elif (p.slice[1].type == 'path'):
        #print ST.function
        #ST.printSymbolTable()
        #print p[1]['type'],p[3]
        #print p[1]
        if 'isthis' in p[1].keys():
            parent = ST.SymbolTable[ST.currScope]['classname']
            extends = ST.SymbolTable[parent]['extends']
            flagfunc = 1
            while parent is not None:
                if "_ZXY" + parent + p[3] in ST.function:
                    flagfunc = 0
                    break
                if extends is None:
                    break
                parent = extends
                extends = ST.SymbolTable[parent]['extends']
            #if "_ZXY"+parent+ p[3] not in ST.function:
            if flagfunc:
                parent = ST.SymbolTable[ST.currScope]['classname']
                extends = ST.SymbolTable[parent]['extends']
                if p[3] in ST.SymbolTable[parent]['identifiers']:
                    p[0] = dict(ST.SymbolTable[parent]['identifiers'][p[3]])
                    p[0]['isthis'] = True
                    p[0]['place'] = 'this.' + p[3]
                elif extends is not None:
                    flag = 1
                    p[3] = extends + p[3]
                    me = parent
                    while extends is not None:
                        #p[3] = extends + p[3]
                        if p[3] in ST.SymbolTable[me]['identifiers']:
                            p[0] = dict(
                                ST.SymbolTable[me]['identifiers'][p[3]])
                            p[0]['isthis'] = True
                            p[0]['place'] = 'this.' + p[3]
                            flag = 0
                            break
                        print me
                        parent = extends
                        print p[3]
                        # ST.printSymbolTable()
                        extends = ST.SymbolTable[parent]['extends']
                        if extends is not None:
                            p[3] = p[3].replace(parent, parent + extends)

                    #if p[3] in ST.SymbolTable[extends]['identifiers']:
                    #    p[0] = dict(ST.SymbolTable[parent]['identifiers'][extends+p[3]])
                    #    p[0]['isthis']=True
                    #    p[0]['place']='this.'+extends+p[3]
                    if flag:
                        sys.exit("Variable not found")
                else:
                    sys.exit("Variable not found")
            else:
                p[0] = dict(ST.getClassFunc("_ZXY" + parent + p[3]))
                p[0]['objname'] = "this"
        else:
            parent = p[1]['type']
            flagfunc = 1
            if parent in ST.SymbolTable:
                extends = ST.SymbolTable[parent]['extends']
                while parent is not None:
                    if "_ZXY" + parent + p[3] in ST.function:
                        flagfunc = 0
                        break
                    if extends is None:
                        break
                    parent = extends
                    extends = ST.SymbolTable[parent]['extends']

            if flagfunc:
                l = ST.getAttribute(p[1]['place'], 'list')
                p[0] = l[p[3]]
            else:
                p[0] = dict(ST.getClassFunc("_ZXY" + parent + p[3]))
                p[0]['objname'] = p[1]['place']
        #print p[0]
    printp(p)
Exemplo n.º 22
0
def p_f_scope_mark(p):
    '''f_scope_mark : epsilon
    '''
    ST.newScope()
    printp(p)
Exemplo n.º 23
0
def p_if_mark2(p):
    '''if_mark2 : epsilon
    '''
    ST.endScope()
    emit('label', p[-3]['label'][1])
    printp(p)
Exemplo n.º 24
0
def p_FunMark1(p):
    ''' FunMark1 : epsilon
    '''
    #if p[-2][1] in ST.SymbolTable[ST.currScope]["function"].keys():
    #     error("Error: function with same name and same number of arguments already defined.")
    #  else:
    if (len(p[-2]) > 2):
        ST.addFunc(p[-2][1], p[-2][2:])
    else:
        ST.addFunc(p[-2][1])
    ST.setRType(p[-1])
    for l in range(2, len(p[-2])):
        ST.addParamVar(p[-2][l][0], p[-2][l][0], p[-2][l][1])
        if p[-2][l][1] is 'Array':
            ST.addAttribute(p[-2][l][0], 'typeArray', 'Int')
            ST.addAttribute(p[-2][l][0], 'isparam', True)

    printp(p)
Exemplo n.º 25
0
def p_if_mark4(p):
    '''if_mark4 : epsilon
    '''
    ST.endScope()
    emit('label', p[-4]['label'][0])
    printp(p)
Exemplo n.º 26
0
def generateCode(i):
    global lab
    if tacTable[i].oper in ['+', '-', '*', '&', '|', '^']:
        ry = getRegIn(i, tacTable[i].in1)
        if registerDescr[ry] != tacTable[i].in1:
            printInstr('movl', regName(ry), 'Register',
                       address(tacTable[i].in1), 'Memory')
            #print('\tmov ' + regName(ry) + ', DWORD PTR ' + tacTable[i].in1)
            addressDescr[tacTable[i].in1]['Register'] = ry
            registerDescr[ry] = tacTable[i].in1

        rz = getRegIn(i, tacTable[i].in2)
        if registerDescr[rz] != tacTable[i].in2:
            printInstr('movl', regName(rz), 'Register',
                       address(tacTable[i].in2), 'Memory')
            #print('\tmov ' + regName(rz) + ', DWORD PTR ' + tacTable[i].in2)
            addressDescr[tacTable[i].in2]['Register'] = rz
            registerDescr[rz] = tacTable[i].in2

        rx = getRegOut(i, tacTable[i].out)
        registerDescr[rx] = tacTable[i].out
        printInstr('movl', regName(rx), 'Register', regName(ry), 'Register')
        #print('\tmov ' + regName(rx) + ', ' + regName(ry))

        if tacTable[i].oper == '+':
            printInstr('addl', regName(rx), 'Register', regName(rz),
                       'Register')
            #print('\tadd ' + regName(rx) + ', ' + regName(rz))
            addressDescr[tacTable[i].out]['Register'] = rx
            addressDescr[tacTable[i].out]['Memory'] = None
        elif tacTable[i].oper == '-':
            printInstr('subl', regName(rx), 'Register', regName(rz),
                       'Register')
            #print('\tsub ' + regName(rx) + ', ' + regName(rz))
            addressDescr[tacTable[i].out]['Register'] = rx
            addressDescr[tacTable[i].out]['Memory'] = None
        elif tacTable[i].oper == '*':
            printInstr('imull', regName(rx), 'Register', regName(rz),
                       'Register')
            #print('\timul ' + regName(rx) + ', ' + regName(rz))
            addressDescr[tacTable[i].out]['Register'] = rx
            addressDescr[tacTable[i].out]['Memory'] = None
        elif tacTable[i].oper == '&':
            print('\tandl %' + regName(rz) + ', %' + regName(rx))
            addressDescr[tacTable[i].out]['Register'] = rx
            addressDescr[tacTable[i].out]['Memory'] = None
        elif tacTable[i].oper == '|':
            print('\torl %' + regName(rz) + ', %' + regName(rx))
            addressDescr[tacTable[i].out]['Register'] = rx
            addressDescr[tacTable[i].out]['Memory'] = None
        elif tacTable[i].oper == '^':
            print('\txorl %' + regName(rz) + ', %' + regName(rx))
            addressDescr[tacTable[i].out]['Register'] = rx
            addressDescr[tacTable[i].out]['Memory'] = None
    elif tacTable[i].oper == '||':
        #printInstr('movl',regName(rx),'Register',regName(ry),'Register')
        ry = getRegIn(i, tacTable[i].in1)
        if registerDescr[ry] != tacTable[i].in1:
            printInstr('movl', regName(ry), 'Register',
                       address(tacTable[i].in1), 'Memory')
            #print('\tmov ' + regName(ry) + ', DWORD PTR ' + tacTable[i].in1)
            addressDescr[tacTable[i].in1]['Register'] = ry
            registerDescr[ry] = tacTable[i].in1

        rz = getRegIn(i, tacTable[i].in2)
        if registerDescr[rz] != tacTable[i].in2:
            printInstr('movl', regName(rz), 'Register',
                       address(tacTable[i].in2), 'Memory')
            #print('\tmov ' + regName(rz) + ', DWORD PTR ' + tacTable[i].in2)
            addressDescr[tacTable[i].in2]['Register'] = rz
            registerDescr[rz] = tacTable[i].in2

        rx = getRegOut(i, tacTable[i].out)
        registerDescr[rx] = tacTable[i].out

        printInstr('movl', address(registerDescr[0]), 'Memory', regName(rx),
                   'Register')
        #print('\tmov DWORD PTR ' + variable + ', ' + regName(addressDescr[variable]['Register']))
        #registerDescr[0] = None
        #addressDescr[var]['Register'] = None
        #addressDescr[var]['Memory'] = var
        print("\tcmpl $0, %" + regName(rz))
        lab2 = lab
        lab += 1
        lab3 = lab
        lab += 1
        lab4 = lab
        lab += 1
        print("\tjne .L" + str(lab2))
        print("\tcmpl $0, %" + regName(ry))
        print("\tje .L" + str(lab3))
        print(".L" + str(lab2) + ":")
        print("\tmovl $1, %" + regName(rx))
        print("\tjmp .L" + str(lab4))
        print(".L" + str(lab3) + ":")
        print("\tmovl $0, %" + regName(rx))
        print(".L" + str(lab4) + ":")
        print("\tmovl %" + regName(rx) + ", %" + regName(rz))
    elif tacTable[i].oper == '&&':
        ry = getRegIn(i, tacTable[i].in1)
        if registerDescr[ry] != tacTable[i].in1:
            printInstr('movl', regName(ry), 'Register',
                       address(tacTable[i].in1), 'Memory')
            #print('\tmov ' + regName(ry) + ', DWORD PTR ' + tacTable[i].in1)
            addressDescr[tacTable[i].in1]['Register'] = ry
            registerDescr[ry] = tacTable[i].in1

        rz = getRegIn(i, tacTable[i].in2)
        if registerDescr[rz] != tacTable[i].in2:
            printInstr('movl', regName(rz), 'Register',
                       address(tacTable[i].in2), 'Memory')
            #print('\tmov ' + regName(rz) + ', DWORD PTR ' + tacTable[i].in2)
            addressDescr[tacTable[i].in2]['Register'] = rz
            registerDescr[rz] = tacTable[i].in2

        rx = getRegOut(i, tacTable[i].out)
        registerDescr[rx] = tacTable[i].out

        printInstr('movl', address(registerDescr[0]), 'Memory', regName(rx),
                   'Register')
        #print('\tmov DWORD PTR ' + variable + ', ' + regName(addressDescr[variable]['Register']))
        #registerDescr[0] = None
        #addressDescr[var]['Register'] = None
        #addressDescr[var]['Memory'] = var
        print("\tcmpl $0, %" + regName(rz))
        global lab
        lab1 = lab
        lab += 1
        lab2 = lab
        lab += 1
        print("\tje .L" + str(lab1))
        print("\tcmpl $0, %" + regName(ry))
        print("\tje .L" + str(lab1))
        print("\tmovl $1, %" + regName(rx))
        print("\tjmp .L" + str(lab2))
        print(".L" + str(lab1) + ":")
        print("\tmovl $0, %" + regName(rx))
        print(".L" + str(lab2) + ":")
        print("\tmovl %" + regName(rx) + ", %" + regName(rz))
    elif tacTable[i].oper == '=':
        if not is_number(tacTable[i].in1):
            ry = getRegIn(i, tacTable[i].in1)
            if registerDescr[ry] != tacTable[i].in1:
                printInstr('movl', regName(ry), 'Register',
                           address(tacTable[i].in1), 'Memory')
                addressDescr[tacTable[i].in1]['Register'] = ry
                registerDescr[ry] = tacTable[i].in1
            rx = getRegOut(i, tacTable[i].out)
            printInstr('movl', regName(rx), 'Register', regName(ry),
                       'Register')
        else:
            rx = getRegOut(i, tacTable[i].out)
            const = tacTable[i].in1
            printInstr('movl', regName(rx), 'Register', const, 'Constant')

    #print('\tmov ' + regName(rx) + ', ' + regName(ry))
        registerDescr[rx] = tacTable[i].out
        addressDescr[tacTable[i].out]['Register'] = rx
        addressDescr[tacTable[i].out]['Memory'] = None
    elif tacTable[i].oper == '/' or tacTable[i].oper == '%':
        if registerDescr[0] != None:
            printInstr('movl', address(registerDescr[0]), 'Memory', regName(0),
                       'Register')
            #print('\tmov  DWORD PTR ' + registerDescr[0] + ', ' + regName(0))
            addressDescr[registerDescr[0]]['Register'] = None
            addressDescr[registerDescr[0]]['Memory'] = registerDescr[0]

        if registerDescr[3] != None:
            printInstr('movl', address(registerDescr[3]), 'Memory', regName(3),
                       'Register')
            #print('\tmov  DWORD PTR ' + registerDescr[3] + ', ' + regName(3))
            addressDescr[registerDescr[3]]['Register'] = None
            addressDescr[registerDescr[3]]['Memory'] = registerDescr[3]

        printInstr('movl', regName(0), 'Register', address(tacTable[i].in1),
                   'Memory')
        registerDescr[0] = tacTable[i].in1
        addressDescr[tacTable[i].in1]['Register'] = 0

        print('\tcltd')
        registerDescr[3] = tacTable[i].in1

        rz = getRegIn(i, tacTable[i].in2)
        if registerDescr[rz] != tacTable[i].in2:
            printInstr('movl', regName(rz), 'Register',
                       address(tacTable[i].in2), 'Memory')
            addressDescr[tacTable[i].in2]['Register'] = rz
            registerDescr[rz] = tacTable[i].in2

        #print('\tidivl %' + regName(rz))
        printInstr('idivl', regName(rz), 'Register')
        rx = getRegOut(i, tacTable[i].out)
        if tacTable[i].oper == '/':
            # move eax to rx
            printInstr('movl', regName(rx), 'Register', 'eax', 'Register')
            registerDescr[rx] = registerDescr[0]
        elif tacTable[i].oper == '%':
            # move edx to rx
            printInstr('movl', regName(rx), 'Register', 'edx', 'Register')
            registerDescr[rx] = registerDescr[3]
        registerDescr[0], registerDescr[3] = None, None
        addressDescr[tacTable[i].out]['Register'] = rx
        addressDescr[tacTable[i].out]['Memory'] = None
        registerDescr[rx] = tacTable[i].out

    elif tacTable[i].oper in ['<', '<=', '==', '>=', '>', '!=']:
        ry = getRegIn(i, tacTable[i].in1)
        if registerDescr[ry] != tacTable[i].in1:
            printInstr('movl', regName(ry), 'Register',
                       address(tacTable[i].in1), 'Memory')
            addressDescr[tacTable[i].in1]['Register'] = ry
            registerDescr[ry] = tacTable[i].in1

        rz = getRegIn(i, tacTable[i].in2)
        if registerDescr[rz] != tacTable[i].in2:
            printInstr('movl', regName(rz), 'Register',
                       address(tacTable[i].in2), 'Memory')
            addressDescr[tacTable[i].in2]['Register'] = rz
            registerDescr[rz] = tacTable[i].in2

        printInstr('cmpl', regName(rz), 'Register', regName(ry), 'Register')

        rx = getRegOut(i, tacTable[i].out)
        #if b = a<b is an independent statement and not followed by if?
        printInstr('movl', address(registerDescr[0]), 'Memory', regName(0),
                   'Register')
        addressDescr[registerDescr[0]]['Register'] = None
        addressDescr[registerDescr[0]]['Memory'] = registerDescr[0]
        registerDescr[0] = None

        printInstr('cmp', regName(rx), 'Register', i=i)
        print('\tmovzbl %al, %' + regName(rx))
        registerDescr[rx] = tacTable[i].out
        addressDescr[tacTable[i].out]['Register'] = rx
        addressDescr[tacTable[i].out]['Memory'] = None

    elif tacTable[i].oper == 'if':
        ry = getRegIn(i, tacTable[i].in1)
        if registerDescr[ry] != tacTable[i].in1:
            printInstr('movl', regName(ry), 'Register',
                       address(tacTable[i].in1), 'Memory')
            addressDescr[tacTable[i].in1]['Register'] = ry
            registerDescr[ry] = tacTable[i].in1
        endBlock()
        print('\ttestl %' + regName(ry) + ', %' + regName(ry))
        print('\tjne .' + tacTable[i].out)

    elif tacTable[i].oper == 'goto':
        endBlock()
        print('\tjmp .' + tacTable[i].out)

    elif tacTable[i].oper == 'label':
        endBlock()
        #print('\t.globl ' + tacTable[i].out)
        print('.' + tacTable[i].out + ':')

    elif tacTable[i].oper == 'flabel':
        endBlock()
        print('\t.globl ' + tacTable[i].out)
        print(tacTable[i].out + ':')

    elif tacTable[i].oper == 'ldar':
        endBlock()
        rx = getRegOut(i, tacTable[i].out)
        if registerDescr[rx] != tacTable[i].out:
            printInstr('movl', regName(rx), 'Register',
                       address(tacTable[i].out), 'Memory')
            addressDescr[tacTable[i].out]['Register'] = rx
            registerDescr[rx] = tacTable[i].out
        addressDescr[tacTable[i].out]['Memory'] = None

        ri = getRegOut(i, tacTable[i].in2)
        if registerDescr[ri] != tacTable[i].in2:
            printInstr('movl', regName(ri), 'Register',
                       address(tacTable[i].in2), 'Memory')
            addressDescr[tacTable[i].in2]['Register'] = ri
            registerDescr[ri] = tacTable[i].in2

        z = ST.getId(tacTable[i].in1)
        if 'isparam' in z.keys():
            print('\tmovl ' + str(-1 * ST.getOffset(tacTable[i].in1)) +
                  "(%ebp), %edi")
            print('\timull $4, %' + regName(ri))
            print('\taddl %' + regName(ri) + ', %edi')
            print('\tmovl (%edi), %' + regName(rx))
            #print"boom"
        else:
            print('\tmovl -' + str(ST.getOffset(tacTable[i].in1)) + "(%ebp,%" +
                  regName(ri) + ",4), %" + regName(rx))

    elif tacTable[i].oper == 'star':
        endBlock()
        ry = getRegIn(i, tacTable[i].in2)
        if registerDescr[ry] != tacTable[i].in2:
            printInstr('movl', regName(ry), 'Register',
                       address(tacTable[i].in2), 'Memory')
            addressDescr[tacTable[i].in2]['Register'] = ry
            registerDescr[ry] = tacTable[i].in2
        ri = getRegIn(i, tacTable[i].in1)
        if registerDescr[ri] != tacTable[i].in1:
            printInstr('movl', regName(ri), 'Register',
                       address(tacTable[i].in1), 'Memory')
            addressDescr[tacTable[i].in1]['Register'] = ri
            registerDescr[ri] = tacTable[i].in1

        z = ST.getId(tacTable[i].out)
        if 'isparam' in z.keys():
            #print "BAAAM"
            print('\tmovl ' + str(-1 * ST.getOffset(tacTable[i].out)) +
                  "(%ebp), %edi")
            print('\timull $4, %' + regName(ri))
            print('\taddl %' + regName(ri) + ', %edi')
            print('\tmovl %' + regName(ry) + ', (%edi)')
            #print('\tmovl (%edi), %'+regName(rx))
            #print"boom"
        else:
            print('\tmovl %' + regName(ry) + ', -' +
                  str(ST.getOffset(tacTable[i].out)) + "(%ebp,%" +
                  regName(ri) + ",4)")
    elif tacTable[i].oper == 'printInt':
        endBlock()
        if is_number(tacTable[i].out):
            printInstr('movl', regName(0), 'Register', tacTable[i].out,
                       'Constant')
        else:
            printInstr('movl', regName(0), 'Register',
                       address(tacTable[i].out), 'Memory')
        print('\tsubl $8, %esp')
        print('\tpushl %' + regName(0))
        print('\tpushl $.format')
        #printInstr('movl',regName(5),'Register','$.format','Memory')
        print('\tcall printf')
        print('\taddl $16, %esp')
    elif tacTable[i].oper == 'scanInt':
        #spillAllReg()
        endBlock()
        print('\tsubl $8, %esp')
        print('\tleal ' + address(tacTable[i].out) + ', %edi')
        print('\tpushl %edi')
        print('\tpushl $.format2')
        #printInstr('xorl',regName(0),'Register',regName(0),'Register')
        #if is_number(tacTable[i].in1):
        #printInstr('movl',regName(4),'Register',tacTable[i].out,'Constant')
        #else:
        #    printInstr('movl',regName(4),'Register',tacTable[i].in1,'Memory')
        #printInstr('movl',regName(5),'Register','$.format2','Memory')
        print('\tcall scanf')
        print('\taddl $16, %esp')

    elif tacTable[i].oper in ['call', 'fcall']:
        endBlock()
        funname = tacTable[i].in1.split('__')[0]
        objname = tacTable[i].in1.split('__')[1]
        #print objname
        if objname != 'this':
            print('\tleal ' + str(-1 * ST.getOffset(objname)) + '(%ebp), %eax')
            print('\tpushl %eax')
        else:
            print('\tpushl 8(%ebp)')

        print('\tcall ' + funname)
        print('\taddl $' +
              str(-1 * (ST.SymbolTable[funname + "@" +
                                       tacTable[i].in2]['paramoffset']) - 4) +
              ', %esp')
        if tacTable[i].oper == 'fcall':
            #print tacTable[i]
            printInstr('movl', address(tacTable[i].out), 'Memory', regName(0),
                       'Register')
            registerDescr[0] = None
            addressDescr[tacTable[i].out]['Memory'] = tacTable[i].out
            addressDescr[tacTable[i].out]['Register'] = None

    elif tacTable[i].oper in ['return', 'freturn']:
        endBlock()
        if tacTable[i].oper == 'freturn':
            printInstr('movl', regName(0), 'Register',
                       address(tacTable[i].in1), 'Memory')
            addressDescr[tacTable[i].in1]['Register'] = 0
            addressDescr[tacTable[i].in1]['Memory'] = tacTable[i].in1
        print('\tleave')
        print('\tret')

    elif tacTable[i].oper == '!':
        ry = getRegIn(i, tacTable[i].in1)
        if registerDescr[ry] != tacTable[i].in1:
            printInstr('movl', regName(ry), 'Register',
                       address(tacTable[i].in1), 'Memory')
            #print('\tmov ' + regName(ry) + ', DWORD PTR ' + tacTable[i].in1)
            addressDescr[tacTable[i].in1]['Register'] = ry
            registerDescr[ry] = tacTable[i].in1

        rx = getRegOut(i, tacTable[i].out)
        registerDescr[rx] = tacTable[i].out
        printInstr('movl', regName(rx), 'Register', regName(ry), 'Register')

        printInstr('movl', tacTable[i].in1, 'Memory', regName(ry), 'Register')
        print('\tnotl %' + regName(ry))
        printInstr('movl', regName(rx), 'Register', regName(ry), 'Register')
        addressDescr[tacTable[i].in1]['Register'] = None
        addressDescr[tacTable[i].in1]['Memory'] = tacTable[i].in1
        addressDescr[tacTable[i].out]['Register'] = ry
        addressDescr[tacTable[i].out]['Memory'] = None
        registerDescr[ry] = tacTable[i].out
    elif tacTable[i].oper == 'scope':
        endBlock()
        #print tacTable[i].out
        #ST.printSymbolTable(1,1)
        ST.currScope = tacTable[i].out

    elif tacTable[i].oper == 'startscope':
        endBlock()
        #print tacTable[i].out
        #ST.printSymbolTable(1,1)
        ST.currScope = tacTable[i].out
        #tempmax = ST.SymbolTable[ST.currScope]['tempmax']
        ST.SymbolTable[ST.currScope]['tempmax'] = ST.SymbolTable[
            ST.SymbolTable[ST.currScope]['parent']]['tempmax']
        print('\tsubl $' + str(ST.numVarScope()) + ', %esp')
    elif tacTable[i].oper == 'fstartscope':
        #print tacTable[i].out
        #ST.printSymbolTable(1,1)
        ST.currScope = tacTable[i].out
        tempmax = ST.SymbolTable[ST.currScope]['tempmax']
        print('\tpushl %ebp')
        print('\tmovl %esp, %ebp')
        print('\tsubl $' + str(ST.printScopeOffset() + tempmax * 4) + ', %esp')
    elif tacTable[i].oper == 'param':
        endBlock()
        print('\tpushl ' + address(tacTable[i].in1))
Exemplo n.º 27
0
def p_cmark1(p):
    '''cmark1 : epsilon
    '''
    ST.addCls(p[-1])
    printp(p)
Exemplo n.º 28
0
import sys
import ply.yacc as yacc
import lexer
#from globalvar import *
import pickle
from globalOther import ST
#ST=SymbolTable()
#global ST
#ST.newScope()
ST.addFunc('println')
ST.endFunc()
ST.addFunc('readInt')
ST.endFunc()
#ST.endScope()
x = 1


def newLabel():
    global x
    x = x + 1
    return "label" + str(x)


def is_number(var):
    try:
        int(var)
        return True
    except Exception:
        return False