Example #1
0
    def buildRuleActionResponse(self):
        TMP1 = "let v <- toGet(bbRspFifo[readyChannel]).get;"
        TMP2 = "let meta <- toGet(metadata_ff).get;"
        TMP3 = "tagged %(name)sRspT {%(field)s}"
        TMP4 = "MetadataResponse rsp = tagged %(name)s%(action)sRspT {pkt: pkt, meta: meta};"
        TMP5 = "tx_info_%(name)s.enq(rsp);"
        TMP6 = "meta.%(name)s = tagged Valid %(name)s;"

        stmt = []
        case_stmt = ast.Case("v")

        for idx, action in enumerate(self.actions):
            basic_block = self.basic_block_map[action]
            fields = basic_block.response.build_match_expr()
            action_stmt = []
            for field in basic_block.response.get_members():
                action_stmt.append(ast.Template(TMP6 % {"name": field}))
            action_stmt.append(
                ast.Template(TMP4 % {
                    "name": CamelCase(self.name),
                    "action": CamelCase(action)
                }))
            action_stmt.append(ast.Template(TMP5 % {"name": "metadata"}))

            action = TMP3 % {"name": CamelCase(action), "field": fields}
            case_stmt.casePatStmt[action] = action_stmt

        stmt.append(ast.Template(TMP1))
        stmt.append(ast.Template(TMP2))
        stmt.append(case_stmt)

        rname = "rl_handle_action_response"
        cond = "interruptStatus"
        rule = ast.Rule(rname, cond, stmt)
        return rule
Example #2
0
    def buildRuleMatchResponseStmt(self):
        TMP1 = "let v <- toGet(bbRspFifo[readyChannel]).get;"
        TMP2 = "let meta <- toGet(metadata_ff[1]).get;"
        TMP3 = "tagged %(name)sRspT {%(field)s}"
        TMP4 = "%(ty_metadata)s rsp = tagged %(name)s {pkt: pkt, meta: meta};"
        TMP5 = "tx_info_%(name)s.enq(rsp);"
        TMP6 = "meta.%(mname)s = tagged Valid %(mname)s;"

        stmt = []
        case_stmt = ast.Case("v")

        for idx, action in enumerate(self.actions):
            basic_block = self.basic_block_map[action]
            fields = basic_block.response.build_match_expr()
            action_stmt = []
            for field in basic_block.response.members:
                mname = p4name(field)
                action_stmt.append(ast.Template(TMP6 % {"mname": mname}))

            tagname = "%s%sRspT" % (CamelCase(self.name), CamelCase(action))
            action_stmt.append(
                ast.Template(
                    TMP4 % {
                        "name": tagname,
                        "ty_metadata": CamelCase(self.name) + "Response"
                    }))
            action_stmt.append(ast.Template(TMP5 % {"name": "metadata"}))
            action = TMP3 % {"name": CamelCase(action), "field": fields}
            case_stmt.casePatStmt[action] = action_stmt

        stmt.append(ast.Template(TMP1))
        stmt.append(ast.Template(TMP2))
        stmt.append(case_stmt)
        return stmt
 def emit_include(builder):
     for n in ir.basic_blocks.keys():
         builder.appendLine("import %s::*;" % CamelCase(n))
     for ctrl in ir.controls.values():
         for n in ctrl.tables.keys():
             builder.appendLine("import %s::*;" % CamelCase(n))
     builder.appendLine("import UnionGenerated::*;")
 def __init__(self, name, actions, action_info):
     def findActionInfo(action_info, action):
         for at in action_info:
             if at['name'] == action[1]:
                 return at
     self.name = name
     elements = []
     atype = "%sActionT" %(CamelCase(name))
     elements.append(ast.EnumElement("DEFAULT_%s"%(name.upper()), "", 0))
     for idx, at in enumerate(actions):
         elements.append(ast.EnumElement(at.lstrip('_').upper(), "", idx))
     self.enum = ast.Enum(atype, elements)
     fields = []
     field_set = set()
     fields.append(ast.StructMember(atype, "_action"))
     dwidth = 0
     for at in enumerate(actions):
         info = findActionInfo(action_info, at)
         runtime_data = info['runtime_data']
         for data in runtime_data:
             data_width = data['bitwidth']
             data_name = "runtime_%s"%(data['name'])
             if data_name not in field_set:
                 fields.append(ast.StructMember("Bit#(%s)" %(data_width), data_name))
                 field_set.add(data_name)
                 dwidth += data_width
     self.struct = ast.Struct("%sRspT"%(CamelCase(self.name)), fields)
     self.width = int(math.ceil(math.log(len(actions) + 1, 2))) + dwidth
Example #5
0
 def buildLoopback(self):
     TMP1 = "tagged %(type)s {%(field)s}"
     TMP2 = "let v = rx_info_prev_control_state.first;"
     TMP3 = "rx_info_prev_control_state.deq;"
     TMP4 = "BBResponse rsp = tagged %(type)s {pkt: pkt};"
     TMP5 = "tx_info_prev_control_state.enq(rsp);"
     rules = []
     stmt = []
     cname = CamelCase(self.name)
     ctype = "%sReqT"%(cname)
     pdict = {"type": ctype, "field": self.request.build_match_expr()}
     casePatStmts = []
     stmt.append(ast.Template(TMP2))
     stmt.append(ast.Template(TMP3))
     ctype = ast.Template(TMP1, pdict)
     case_stmt = ast.Case("v")
     case_stmt.casePatStmt[ctype] = casePatStmts
     rsp_prefix = CamelCase(self.name)
     casePatStmts.append(ast.Template(TMP4, {"type": "%sRspT"%(rsp_prefix)} ))
     casePatStmts.append(ast.Template(TMP5, {"name": self.name}))
     stmt.append(case_stmt)
     rname = self.name + "_loopback"
     rule = ast.Rule(rname, [], stmt)
     rules.append(rule)
     return rules
 def _add_defaults(self, fields):
     self.stmt.append(ast.Template(STRUCT_DEFAULT, {"name": CamelCase(self.name)}))
     self.stmt.append(ast.Template(STRUCT_MASK, {"name": CamelCase(self.name)}))
     _sum = 0
     for _, l in fields:
         _sum += l
     self.stmt.append(ast.Template(EXTRACT_TEMP, {"name": CamelCase(self.name), "lname": self.name, "width": _sum}))
Example #7
0
 def emitModule(self, builder):
     logger.info("emitModule: {}".format(self.name))
     mname = "mk{}".format(CamelCase(self.name))
     iname = CamelCase(self.name)
     params = []
     provisos = []
     decls = []
     stmt = self.buildModuleStmt()
     module = ast.Module(mname, params, iname, provisos, decls, stmt)
     module.emit(builder)
    def buildConditionalStmt(self, tblName, stmt, metadata=set()):
        TMP1 = "MetadataRequest req = MetadataRequest {pkt: pkt, meta: meta};"
        TMP2 = "%(name)s_req_ff.enq(req);"
        toCurrPacketFifo = False

        def search_conditional(name):
            for key, cond in self.conditionals.items():
                print key, cond
                if key == name:
                    return cond
            return None

        if tblName is None:
            stmt.append(
                ast.Template(
                    "MetadataRequest req = MetadataRequest {pkt: pkt, meta: meta};"
                ))
            stmt.append(ast.Template("next_req_ff.enq(req);"))

        if tblName in self.tables:
            stmt.append(ast.Template(TMP1))
            stmt.append(ast.Template(TMP2, {"name": tblName}))

        if tblName in self.conditionals:
            cond = search_conditional(tblName)
            expr = cond['expression'].replace("0x", "'h")
            true_next = cond['true_next']
            false_next = cond['false_next']
            _meta = cond['metadata']
            for m in _meta:
                if type(m) is list:
                    metadata.add(tuple(m))
                else:
                    metadata.add(m)
            if true_next in self.tables:
                _stmt = []
                _stmt.append(ast.Template(TMP1,
                                          {"name": CamelCase(true_next)}))
                _stmt.append(ast.Template(TMP2, {"name": true_next}))
                stmt.append(ast.If(expr, _stmt))
            if true_next in self.conditionals:
                _stmt = []
                self.buildConditionalStmt(true_next, _stmt, metadata)
                stmt.append(ast.If(expr, _stmt))

            if false_next in self.tables:
                _stmt = []
                _stmt.append(
                    ast.Template(TMP1, {"name": CamelCase(false_next)}))
                _stmt.append(ast.Template(TMP2, {"name": false_next}))
                stmt.append(ast.Else(_stmt))
            if false_next in self.conditionals:
                _stmt = []
                self.buildConditionalStmt(false_next, _stmt, metadata)
                stmt.append(ast.Else(_stmt))
 def emitModule(self, builder):
     mname = "mk{}".format(CamelCase(self.name))
     iname = CamelCase(self.name)
     params = []
     decls = [
         "Vector#(numClients, Client#(MetadataRequest, MetadataResponse)) mdc"
     ]
     provisos = []
     stmt = self.buildModuleStmt()
     module = ast.Module(mname, params, iname, provisos, decls, stmt)
     module.emit(builder)
Example #10
0
    def buildModuleStmt(self):
        TMP1 = "Vector#(%(num)s, FIFOF#(BBRequest)) bbReqFifo <- replicateM(mkFIFOF);"
        TMP2 = "Vector#(%(num)s, FIFOF#(BBResponse)) bbRspFifo <- replicateM(mkFIFOF);"
        TMP3 = "MatchTable#(%(tid)s, %(sz)s, SizeOf#(%(reqT)s), SizeOf#(%(rspT)s)) matchTable <- mkMatchTable(\"%(name)s\");"
        TMP4 = "interface next_control_state_%(id)s = toClient(bbReqFifo[%(id)s], bbRspFifo[%(id)s]);"
        TMP5 = "interface prev_control_state_%(id)s = toServer(rx_%(name)s.e, tx_%(name)s.e);"
        TMP6 = "Vector#(2, FIFOF#(MetadataT)) metadata_ff <- replicateM(mkFIFOF);"
        TMP8 = "FIFOF#(MetadataT) metadata_ff <- mkFIFOF;"
        TMP7 = "FIFOF#(PacketInstance) packet_ff <- mkFIFOF;"

        stmt = []
        stmt += build_funct_verbosity()
        stmt += self.buildTXRX("metadata")

        num = len(self.actions)
        stmt.append(ast.Template(TMP1, {"num": num}))
        stmt.append(ast.Template(TMP2, {"num": num}))
        stmt.append(ast.Template(TMP7))

        if len(self.key) != 0:
            reqT = "%sReqT" % (CamelCase(self.name))
            rspT = "%sRspT" % (CamelCase(self.name))
            # size must be 256 or multiple of 256
            size = int(256 * math.ceil(float(self.depth) / 256))
            tid = self.tid
            pdict = {
                "sz": size,
                "reqT": reqT,
                "rspT": rspT,
                "tid": tid,
                "name": self.name + '.dat'
            }
            stmt.append(ast.Template(TMP3, pdict))

        pdict = {"sz": num, "szminus1": num - 1, "fifo": "bbRspFifo"}
        stmt.append(ast.Template(IRQ_TEMPLATE, pdict))

        if len(self.key) != 0:
            stmt.append(ast.Template(TMP6))
            stmt.append(self.buildRuleMatchRequest())
            stmt.append(self.buildRuleExecuteAction())
            stmt.append(self.buildRuleMatchResponse())
        else:
            stmt.append(ast.Template(TMP8))
            stmt.append(self.buildRuleActionRequest())
            stmt.append(self.buildRuleActionResponse())

        stmt.append(ast.Template(TMP5 % {"name": "metadata", "id": 0}))
        for idx, _ in enumerate(self.actions):
            stmt.append(ast.Template(TMP4 % {"id": idx}))
        stmt += self.build_intf_decl_verbosity()
        return stmt
Example #11
0
    def __init__(self, basicblock_attrs, json_dict):
        def addRuntimeData(action, json_dict):
            fields = set()
            actions = json_dict['actions']
            for at in actions:
                if at['name'] == action:
                    rdata = at['runtime_data']
                    for d in rdata:
                        fields.add((d['bitwidth'], d['name']))
            return fields


        def addRawRuntimeData(action, json_dict):
            actions = json_dict['actions']
            for at in actions:
                if at['name'] == action:
                    rdata = at['runtime_data']
                    return rdata

        self.name = basicblock_attrs['name']
        self.primitives = []
        self.meta_read = set()
        self.meta_write = set()
        for p in basicblock_attrs['primitives']:
            obj, meta_read, meta_write = self.buildPrimitives(p)
            assert obj is not None
            self.primitives.append(obj)
            self.meta_read |= meta_read
            self.meta_write |= meta_write
        # perform RAW optimization
        # build mapping between dst_field and src_field
        self.bypass_map = None
        self.optimize()
        #print self.bypass_map

        # add runtime data to basic block request
        runtime_data = addRuntimeData(self.name, json_dict)
        self.runtime_data = runtime_data
        self.raw_runtime_data = addRawRuntimeData(self.name, json_dict)

        req_name = "%sReqT" % (CamelCase(self.name))
        self.request = StructM(req_name, self.meta_read, runtime_data=runtime_data)

        rsp_name = "%sRspT" % (CamelCase(self.name))
        self.response = StructM(rsp_name, self.meta_write, bypass_map=self.bypass_map)

        self.clientInterfaces = self.buildClientInterfaces(json_dict)
        self.serverInterfaces = self.buildServerInterfaces(json_dict)

        self.json_dict = json_dict
Example #12
0
 def __init__(self, table_attrs, basic_block_map, json_dict):
     self.name = table_attrs["name"]
     self.tid = table_attrs["id"]
     self.match_type = table_attrs['match_type']
     self.depth = 256 if table_attrs['max_size'] == 16384 else table_attrs[
         'max_size']
     self.key = table_attrs.get('key', None)
     self.actions = table_attrs.get('actions', None)
     self.next_tables = table_attrs.get('next_tables', None)
     self.req_name = "%sReqT" % (CamelCase(self.name))
     self.request = StructT(self.req_name)
     self.rsp_name = "%sRspT" % (CamelCase(self.name))
     self.response = StructT(self.rsp_name)
     self.basic_block_map = basic_block_map
     self.json_dict = json_dict
Example #13
0
 def buildTXRX(self, pname):
     TMP1 = "RX #(%(type)sRequest) rx_%(name)s <- mkRX;"
     TMP3 = "TX #(%(tblname)sResponse) tx_%(name)s <- mkTX;"
     TMP2 = "let rx_info_%(name)s = rx_%(name)s.u;"
     TMP4 = "let tx_info_%(name)s = tx_%(name)s.u;"
     stmt = []
     pdict = {
         'type': CamelCase(pname),
         'name': pname,
         'tblname': CamelCase(self.name)
     }
     stmt.append(ast.Template(TMP1, pdict))
     stmt.append(ast.Template(TMP2, pdict))
     stmt.append(ast.Template(TMP3, pdict))
     stmt.append(ast.Template(TMP4, pdict))
     return stmt
 def emitInterface(self, builder):
     iname = CamelCase(self.name)
     table_intf = ast.Interface(typedef=iname)
     intf0 = ast.Interface("next",
                           "Client#(MetadataRequest, MetadataResponse)")
     intf1 = ast.Method("set_verbosity", "Action", "int verbosity")
     table_intf.subinterfaces.append(intf0)
     table_intf.subinterfaces.append(intf1)
     table_intf.emitInterfaceDecl(builder)
Example #15
0
 def rule_state_next(self, state, width):
     tmpl = []
     tmpl.append("deparse_state_ff.enq(StateDeparse%s);" % CamelCase(state))
     tmpl.append("fetch_next_header(%d);" % width)
     rname = "rl_deparse_%s_next" % (state.translate(None, "[]"))
     rcond = "w_deparse_%s" % (state.translate(None, "[]"))
     stmt = apply_pdict(tmpl, {})
     rule = ast.Rule(rname, rcond, stmt)
     return rule
Example #16
0
 def rule_state_send(self, state, width):
     tmpl = []
     tmpl.append("succeed_and_next(%d);" % width)
     tmpl.append("deparse_state_ff.deq;")
     rname = "rl_deparse_%s_send" % (state.translate(None, "[]"))
     rcond = "(deparse_state_ff.first == StateDeparse%s) && (rg_buffered[0] >= %d)" % (
         CamelCase(state), width)
     stmt = apply_pdict(tmpl, {})
     rule = ast.Rule(rname, rcond, stmt)
     return rule
 def __init__(self, struct_attrs):
     self.name = struct_attrs['name']
     self.stmt = []
     fields = struct_attrs['fields']
     e = []
     for f, l in fields:
         if f[0].isupper():
             f = f[0].lower() + f
         e.append(ast.StructMember("Bit#(%s)"%(l), avoid_bsv_keyword(f)))
     self.struct = ast.Struct(CamelCase(self.name), e)
     self._add_defaults(fields)
Example #18
0
 def emitInterface(self, builder):
     logger.info("emitBasicBlockIntf: {}".format(self.name))
     iname = CamelCase(self.name)
     stmt = []
     stmt += self.clientInterfaces
     stmt += self.serverInterfaces
     intf = ast.Interface(typedef=iname)
     intf.subinterfaces = stmt
     intf1 = ast.Method("set_verbosity", "Action", "int verbosity")
     intf.subinterfaces.append(intf1)
     intf.emitInterfaceDecl(builder)
    def build_rule_state_extract(self, state):
        tmpl = []
        tmpl.append("let data = rg_tmp[0];")
        tmpl.append("if (isValid(data_ff.first)) begin")
        tmpl.append("  data_ff.deq;")
        tmpl.append("  data = zeroExtend(data_this_cycle) << rg_shift_amt[0] | rg_tmp[0];")
        tmpl.append("end")
        tmpl.append("report_parse_action(parse_state_ff.first, rg_buffered[0], data_this_cycle, data);")
        TMP = "let %(header)s = extract_%(ktype)s(truncate(data));"
        tmpl2 = []
        tmpl2.append("compute_next_state_%(name)s(%(field)s);")
        tmpl2.append("rg_tmp[0] <= zeroExtend(data >> %(len)s);")
        tmpl2.append("succeed_and_next(%(len)s);")
        tmpl2.append("dbprint(3, $format(\"extract %%s\", \"%(name)s\"));")
        tmpl2.append("parse_state_ff.deq;")

        TMP3 = "%(header)s_out_ff.enq(tagged Valid %(header)s);"

        pdict = {}
        pdict['name'] = state.name
        pdict['CurrState'] = 'State%s' % (CamelCase(state.name))
        pdict['len'] = state.len
        keys = []
        pdict['ktype'] = set()
        for k in state.transition_keys:
            if k['type'] == 'lookahead':
                print "WARNING: lookahead type not handled"
                continue
            header_type = GetHeaderType(k['value'][0])
            header = k['value'][0]
            keys.append("%s.%s" % (header, k['value'][1]))
            pdict['ktype'].add((header, header_type))
        pdict['field'] = ",".join(keys)

        stmt = apply_pdict(tmpl, pdict)
        for hdr, ktype in pdict['ktype']:
            stmt += [ast.Template(TMP, {'header': hdr, 'ktype': ktype})]
        stmt += apply_pdict(tmpl2, pdict)
        for hdr, ktype in pdict['ktype']:
            stmt += [ast.Template(TMP3, {'header': hdr, 'ktype': ktype})]

        # build expression
        setexpr = GetExpressionInState(state.name)
        if setexpr[2] != None and setexpr[1] != None:
            dst = "".join(setexpr[1])+"[0]"
            src = "".join(setexpr[2])
            stmt += [ast.Template(dst + " <= " + src.replace("0x", "'h") + ";")]

        rcond = '(parse_state_ff.first == %(CurrState)s) && (rg_buffered[0] >= %(len)s)' % pdict
        rname = 'rl_%(name)s_extract' % pdict
        attr = ['fire_when_enabled']
        rule = ast.Rule(rname, rcond, stmt, attr)
        return [rule]
Example #20
0
 def build_struct(self):
     stmt = []
     stmt.append(ast.Template('`ifdef DEPARSER_STRUCT\n'))
     elem = []
     elem.append(ast.EnumElement("StateDeparseStart", None, None))
     for state in self.deparse_states:
         elem.append(
             ast.EnumElement("StateDeparse%s" % (CamelCase(state)), None,
                             None))
     state = ast.Enum("DeparserState", elem)
     stmt.append(state)
     stmt.append(ast.Template('`endif // DEPARSER_STRUCT\n'))
     return stmt
 def buildTableInstance(self):
     TMP1 = "%(tblType)s %(tblName)s <- mk%(tblType)s();"
     TMP2 = "mkConnection(toClient(%(tblName)s_req_ff, %(tblName)s_rsp_ff), %(tblName)s.prev_control_state_%(id)s);"
     stmt = []
     for t in self.tables.values():
         stmt.append(
             ast.Template(TMP1, {
                 "tblType": CamelCase(t.name),
                 "tblName": t.name
             }))
     for t in self.tables.values():
         stmt.append(ast.Template(TMP2, {"tblName": t.name, "id": 0}))
     return stmt
 def build_types(self):
     stmt = []
     stmt.append(ast.Template("\n"))
     stmt.append(ast.Template("`ifdef PARSER_STRUCT\n"))
     elem = []
     if self.initial_state == 'default':
         elem.append(ast.EnumElement("StateDefault", None, None))
     for s in self.states.values():
         elem.append(ast.EnumElement("State%s" % (CamelCase(s.name)), None, None))
     state = ast.Enum("ParserState", elem)
     stmt.append(state)
     stmt.append(ast.Template("`endif //PARSER_STRUCT\n"))
     return stmt
Example #23
0
def render_runtime_types(ir, json_dict):
    # metadata req/rsp
    ir.structs['metadata_request'] = StructT("MetadataRequest")
    ir.structs['metadata_response'] = StructT("MetadataResponse")

    #responses = []
    for pipeline in json_dict['pipelines']:
        name = pipeline['name']
        for t in sorted(pipeline['tables'], key=lambda k: k['name']):
            responses = []
            tname = t['name']
            tnext = t['actions']
            for n in tnext:
                sname = "%s%sRspT" % (CamelCase(tname), CamelCase(n))
                stmt = []
                stmt.append(ast.StructMember("PacketInstance", "pkt"))
                stmt.append(ast.StructMember("MetadataT", "meta"))
                responses.append(ast.Struct(sname, stmt))
            union_name = "%sResponse" % CamelCase(tname)
            ir.structs[union_name] = ast.TypeDef("union tagged", union_name,
                                                 responses)
    ir.structs['metadata'] = StructMetadata("MetadataT", ir)
 def buildTableRuleStmt(self, tblName):
     TMP1 = "%(tblName)s_rsp_ff.deq;"
     TMP2 = "let _rsp = %(tblName)s_rsp_ff.first;"
     TMP3 = "let meta = _req.meta;"
     TMP4 = "let pkt = _req.pkt;"
     TMP5 = "let %(name)s = fromMaybe(?, meta.%(name)s);"
     TMP6 = "tagged %(type)s {%(field)s}"
     stmt = []
     stmt.append(ast.Template(TMP1, {"tblName": tblName}))
     stmt.append(ast.Template(TMP2, {"tblName": tblName}))
     case_stmt = ast.Case("_rsp")
     for action, next_table in self.tables[tblName].next_tables.items():
         ctype = "%s%sRspT" % (CamelCase(tblName), CamelCase(action))
         pdict = {"type": ctype, "field": "meta: .meta, pkt: .pkt"}
         _ctype = ast.Template(TMP6, pdict)
         #case_stmt.casePatItem[ctype] = ast.Template(TMP6, pdict)
         _stmt, _meta, metadata = [], [], set()
         self.buildConditionalStmt(next_table, _stmt, metadata)
         for m in metadata:
             if type(m) is tuple:
                 _meta.append(ast.Template(TMP5, {"name": p4name(m)}))
         case_stmt.casePatStmt[_ctype] = _meta + _stmt
     stmt.append(case_stmt)
     return stmt
Example #25
0
 def rule_state_load(self, state, width):
     tmpl = []
     tmpl.append(
         "rg_tmp[0] <= zeroExtend(data_this_cycle) << rg_shift_amt[0] | rg_tmp[0];"
     )
     tmpl.append(
         "UInt#(NumBytes) n_bytes_used = countOnes(mask_this_cycle);")
     tmpl.append("UInt#(NumBits) n_bits_used = cExtend(n_bytes_used) << 3;")
     tmpl.append("move_buffered_amt(cExtend(n_bits_used));")
     rname = "rl_deparse_%s_load" % (state.translate(None, "[]"))
     rcond = "(deparse_state_ff.first == StateDeparse%s) && (rg_buffered[0] < %d)" % (
         CamelCase(state), width)
     stmt = apply_pdict(tmpl, {})
     rule = ast.Rule(rname, rcond, stmt)
     return rule
 def buildBasicBlocks(self):
     TMP1 = "%(type)s %(name)s <- mk%(type)s();"
     stmt = []
     stmt.append(ast.Template("// Basic Blocks"))
     basic_block_set = dict()  # to ensure unique name
     for b in self.basic_blocks:
         btype = CamelCase(b.name)
         bname = b.name
         if bname in basic_block_set:
             basic_block_set[bname] += 1
             name = b.name + "_%s" % (basic_block_set[b.name])
         else:
             basic_block_set[bname] = 0
             name = b.name + "_0"
         stmt.append(ast.Template(TMP1, {"type": btype, "name": name}))
     return stmt
 def buildRules(self):
     TMP1 = "%(name)s_req_ff.notEmpty"
     TMP2 = "%(name)s_rsp_ff.notEmpty"
     rules = []
     rname = "default_next_state"
     cond = TMP1 % ({"name": "default", "type": "Default"})
     stmt = self.buildDefaultRuleStmt(self.init_table)
     rule = ast.Rule(rname, cond, stmt)
     rules.append(rule)
     for t in self.tables.values():
         rname = t.name + "_next_state"
         cond = TMP2 % ({"name": t.name, "type": CamelCase(t.name)})
         stmt = self.buildTableRuleStmt(t.name)
         rule = ast.Rule(rname, cond, stmt)
         rules.append(rule)
     return rules
Example #28
0
 def emitInterface(self, builder):
     logger.info("emitTable: {}".format(self.name))
     TMP1 = "prev_control_state_%(id)s"
     TMP2 = "Server #(MetadataRequest, %(ty_metadata)s)"
     TMP3 = "next_control_state_%(id)s"
     TMP4 = "Client #(BBRequest, BBResponse)"
     iname = CamelCase(self.name)
     intf = ast.Interface(typedef=iname)
     s_intf = ast.Interface(TMP1 % {"id": 0},
                            TMP2 % {"ty_metadata": iname + "Response"})
     intf.subinterfaces.append(s_intf)
     for idx, _ in enumerate(self.actions):
         c_intf = ast.Interface(TMP3 % {"id": idx}, TMP4)
         intf.subinterfaces.append(c_intf)
     intf1 = ast.Method("set_verbosity", "Action", "int verbosity")
     intf.subinterfaces.append(intf1)
     intf.emitInterfaceDecl(builder)
Example #29
0
def generate_pipeline(ir):
    def emit_include(builder):
        for n in ir.basic_blocks.keys():
            builder.appendLine("import %s::*;" % CamelCase(n))
        for ctrl in ir.controls.values():
            for n in ctrl.tables.keys():
                builder.appendLine("import %s::*;" % CamelCase(n))
        builder.appendLine("import UnionGenerated::*;")

    for c in ir.controls.values():
        builder = SourceCodeBuilder()
        emit_import(builder)
        emit_include(builder)
        c.emit(builder)
        emit_license(builder)
        with open(os.path.join('generatedbsv', '%s.bsv' % (CamelCase(c.name))),
                  'w') as bsv:
            bsv.write(builder.toString())
 def build_rule_state_load(self, state):
     tmpl = []
     tmpl.append("data_ff.deq;")
     tmpl.append("let data = zeroExtend(data_this_cycle) << rg_shift_amt[0] | rg_tmp[0];")
     tmpl.append("rg_tmp[0] <= zeroExtend(data);")
     tmpl.append("move_shift_amt(%d);" % (config.DP_WIDTH))
     pdict = {}
     pdict['name'] = state.name
     pdict['CurrState'] = 'State%s' % (CamelCase(state.name))
     pdict['len'] = state.len
     stmt = apply_pdict(tmpl, pdict)
     expr = "isValid(data_ff.first)"
     ifstmt = []
     ifstmt.append(ast.Template("report_parse_action(parse_state_ff.first, rg_buffered[0], data_this_cycle, rg_tmp[0]);"))
     ifstmt.append(ast.If(expr, stmt))
     rcond = '(parse_state_ff.first == %(CurrState)s) && (rg_buffered[0] < %(len)s)' % pdict
     attr = ['fire_when_enabled']
     rule = ast.Rule('rl_%(name)s_load' % pdict, rcond, ifstmt, attr)
     return [rule]