p4_hp4.py 74.8 KB
Newer Older
1 2 3
#!/usr/bin/python

from p4_hlir.main import HLIR
4
from p4_hlir.hlir.p4_parser import p4_parse_state
5
import p4_hlir
6
from p4_hlir.hlir.p4_tables import p4_table
7
from compiler import HP4Compiler, CodeRepresentation
8
import argparse
9
import itertools
10
import code
11
from inspect import currentframe, getframeinfo
12 13
import sys
import math
14
from math import ceil
15
import json
16
import pkg_resources
17

18
SEB = 320
David Hancock's avatar
David Hancock committed
19
METADATA_WIDTH = 256
20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
PS_RET_TYPE = 0
PS_RET_CRITERIA = 1
PS_RET_BRANCHES = 2
PS_RET_IMM_STATE = 1
PS_CALL_TYPE = 0
PS_CALL_H_INST = 1
OFFSET = 0
WIDTH = 1
BRANCH_VALUES = 0
BRANCH_STATE = 1
VAL_TYPE = 0
VAL_VALUE = 1
MAX_BYTE = 100
T_NAME = 0
L_BOUND = 1
U_BOUND = 2
HIGHEST_PRIORITY = '0'
LOWEST_PRIORITY = '2147483646'
VBITS_WIDTH = 80
MATCH_TYPE = 1
MATCH_FIELD = 0
PRIM_TYPE = 0
PRIM_SUBTYPE = 1
P4_CALL_PRIMITIVE = 0
P4_CALL_PARAMS = 1
PARAM = 0
PARAM_TYPE = 1
MATCH_OBJECT = 0
MATCH_TYPE = 1
EXT_FIRST_WIDTH = 40 # in bytes
EXT_START_INDEX = 2

parse_select_table_boundaries = [0, 20, 30, 40, 50, 60, 70, 80, 90, 100]
54 55 56 57 58 59

primitive_ID = {'modify_field': '[MODIFY_FIELD]',
                'add_header': '[ADD_HEADER]',
                'copy_header': '[COPY_HEADER]',
                'remove_header': '[REMOVE_HEADER]',
                'modify_field_with_hash_based_offset': '[MODIFY_FIELD_WITH_HBO]',
60
                'modify_field_rng_uniform': '[MODIFY_FIELD_RNG_U]',
61 62 63 64 65 66 67 68 69 70 71 72 73
                'truncate': '[TRUNCATE]',
                'drop': '[DROP]',
                'no_op': '[NO_OP]',
                'push': '[PUSH]',
                'pop': '[POP]',
                'count': '[COUNT]',
                'execute_meter': '[METER]',
                'generate_digest': '[GENERATE_DIGEST]',
                'recirculate': '[RECIRCULATE]',
                'resubmit': '[RESUBMIT]',
                'clone_ingress_pkt_to_egress': '[CLONE_INGRESS_EGRESS]',
                'clone_egress_pkt_to_egress': '[CLONE_EGRESS_EGRESS]',
                'multicast': '[MULTICAST]',
74 75
                'add_to_field': '[MATH_ON_FIELD]',
                'bit_xor': '[BIT_XOR]'}
76 77 78 79

primitive_tnames = {'modify_field': 'mod',
                    'add_header': 'addh',
                    'copy_header': '',
80
                    'remove_header': 'removeh',
81
                    'modify_field_with_hash_based_offset': '',
82
                    'modify_field_rng_uniform': 'mod_rng',
83 84 85 86 87 88 89 90 91 92 93 94 95
                    'truncate' : 'truncate',
                    'drop' : 'drop',
                    'no_op' : '',
                    'push' : '',
                    'pop' : '',
                    'count' : '',
                    'execute_meter': '',
                    'generate_digest': '',
                    'recirculate': '',
                    'resubmit': '',
                    'clone_ingress_pkt_to_egress': '',
                    'clone_egress_pkt_to_egress': '',
                    'multicast': 'multicast',
96 97
                    'add_to_field': 'math_on_field',
                    'bit_xor': 'bit_xor'}
98 99 100 101 102 103 104 105 106 107 108 109 110 111

mf_prim_subtype_ID = {('meta', 'ingress_port'): '1',
                      ('meta', 'packet_length'): '2',
                      ('meta', 'egress_spec'): '3',
                      ('meta', 'egress_port'): '4',
                      ('meta', 'egress_instance'): '5',
                      ('meta', 'instance_type'): '6',
                      ('egress_spec', 'meta'): '7',
                      ('meta', 'const'): '8',
                      ('egress_spec', 'const'): '9',
                      ('ext', 'const'): '10',
                      ('egress_spec', 'ingress_port'): '11',
                      ('ext', 'ext'): '12',
                      ('meta', 'ext'): '13',
112
                      ('ext', 'meta'): '14'}
113 114 115 116 117 118 119 120 121 122 123 124 125 126

mf_prim_subtype_action = {'1': 'mod_meta_stdmeta_ingressport',
                          '2': 'mod_meta_stdmeta_packetlength',
                          '3': 'mod_meta_stdmeta_egressspec',
                          '4': 'mod_meta_stdmeta_egressport',
                          '5': 'mod_meta_stdmeta_egressinst',
                          '6': 'mod_meta_stdmeta_insttype',
                          '7': 'mod_stdmeta_egressspec_meta',
                          '8': 'mod_meta_const',
                          '9': 'mod_stdmeta_egressspec_const',
                          '10': 'mod_extracted_const',
                          '11': 'mod_stdmeta_egressspec_stdmeta_ingressport',
                          '12': 'mod_extracted_extracted',
                          '13': 'mod_meta_extracted',
127
                          '14': 'mod_extracted_meta'}
128 129 130 131 132 133

a2f_prim_subtype_ID = {'add': '1', 'sub': '2'}

a2f_prim_subtype_action = {'1': 'a_add2f_extracted_const_u',
                           '2': 'a_subff_extracted_const_u'}

134 135 136 137 138 139 140 141
bx_prim_subtype_ID = {('meta', 'meta', 'const'): '1',
                      ('ext', 'ext', 'const'): '2',
                      ('meta', 'ext', 'const'): '3'}

bx_prim_subtype_action = {'1': 'bit_xor_meta_meta_const',
                          '2': 'bit_xor_extracted_extracted_const',
                          '3': 'bit_xor_meta_extracted_const'}

142 143
gen_prim_subtype_action = {'add_header': 'a_addh',
                           'copy_header': '',
144
                           'remove_header': 'a_removeh',
145
                           'modify_field_with_hash_based_offset': '',
146
                           'modify_field_rng_uniform': 'mod_extracted_rng',
147 148 149 150 151 152 153 154 155 156 157 158 159
                           'truncate': 'a_truncate',
                           'drop': 'a_drop',
                           'no_op': '',
                           'push': '',
                           'pop': '',
                           'count': '',
                           'execute_meter': '',
                           'recirculate': '',
                           'resubmit': '',
                           'clone_ingress_pkt_to_egress': '',
                           'clone_egress_pkt_to_egress': '',
                           'multicast': 'a_multicast'}

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
current_call = tuple

def debug():
  """ Break and enter interactive method after printing location info """
  # written before I knew about the pdb module
  caller = currentframe().f_back
  method_name = caller.f_code.co_name
  line_no = getframeinfo(caller).lineno
  print(method_name + ": line " + str(line_no))
  code.interact(local=dict(globals(), **caller.f_locals))

def unsupported(msg):
  print(msg)
  exit()

175 176 177 178 179
def convert_to_builtin_type(obj):
  d = { '__class__':obj.__class__.__name__, '__module__':obj.__module__, }
  d.update(obj.__dict__)
  return d

180 181 182 183 184 185
class HP4_Command(object):
  def __init__(self, command='table_add',
                     table='',
                     action='',
                     match_params=[],
                     action_params=[]):
186 187 188
    self.command = command
    self.table = table
    self.action = action
189 190
    self.match_params = match_params
    self.action_params = action_params
191 192 193
  def __str__(self):
    """ assumes command is \'table_add\' """
    if self.command != 'table_add':
194
      debug()
195
      raise Exception("Incorrect table command %s, table %s" % (self.command, self.table))
196 197 198 199 200 201 202
    ret = self.table + ' ' + self.action + ' :'
    ret += ' '.join(self.match_params)
    ret += ':'
    ret += ' '.join(self.action_params)
    return ret

class HP4_Match_Command(HP4_Command):
203 204 205 206
  def __init__(self, source_table='',
                     source_action='',
                     **kwargs):
    super(HP4_Match_Command, self).__init__(**kwargs)
207 208 209 210 211 212 213 214 215 216
    self.source_table = source_table
    self.source_action = source_action

class HP4_Primitive_Command(HP4_Command):
  def __init__(self, source_table, source_action, command, table, action, mparams, aparams, src_aparam_id):
    HP4_Command.__init__(self, command, table, action, mparams, aparams)
    self.source_table = source_table
    self.source_action = source_action
    self.src_aparam_id = src_aparam_id

217 218 219 220 221 222 223 224 225 226
class DAG_Topo_Sorter():
  def __init__(self, p4_tables):
    self.unmarked = []
    self.tempmarked = []
    self.permmarked = []
    self.L = []
    for key in p4_tables:
      self.unmarked.append(p4_tables[key])

  def visit(self, n):
David Hancock's avatar
David Hancock committed
227
    if n.control_flow_parent == 'egress':
228 229
      unsupported("ERROR: Not yet supported: tables in egress (" + n.name + ")")

230
    if n in self.tempmarked:
231 232
      unsupported("ERROR: not a DAG")

233 234 235 236
    if n in self.unmarked:
      self.unmarked.remove(n)
      self.tempmarked.append(n)
      for m in n.next_.values():
David Hancock's avatar
David Hancock committed
237 238
        if m != None:
          self.visit(m)
239 240 241 242 243 244 245 246 247 248 249 250
      self.permmarked.append(n)
      self.tempmarked.remove(n)
      self.L.insert(0, n)

  def sort(self):      
    while len(self.unmarked) > 0: # while there are unmarked nodes do
      n = self.unmarked[0]
      self.visit(n)
    return self.L

class Table_Rep():
  def __init__(self, stage, match_type, source_type, field_name):
251
    self.stage = stage # int
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    self.match_type = match_type
    self.source_type = source_type
    self.field_name = field_name
    self.name = 't' + str(self.stage) + '_'
    if source_type == 'standard_metadata':
      self.name += 'stdmeta_' + field_name + '_'
    elif source_type == 'metadata':
      self.name += 'metadata_'
    elif source_type == 'extracted':
      self.name += 'extracted_'
    if match_type == 'P4_MATCH_EXACT':
      self.name += 'exact'
    elif match_type == 'P4_MATCH_VALID':
      self.name += 'valid'
    elif match_type == 'P4_MATCH_TERNARY':
      self.name += 'ternary'
    elif match_type == 'MATCHLESS':
      self.name += 'matchless'
  def table_type(self):
    if self.source_type == 'standard_metadata':
      if self.match_type == 'P4_MATCH_EXACT':
        if self.field_name == 'ingress_port':
          return '[STDMETA_INGRESS_PORT_EXACT]'
        elif self.field_name == 'packet_length':
          return '[STDMETA_PACKET_LENGTH_EXACT]'
        elif self.field_name == 'instance_type':
          return '[STDMETA_INSTANCE_TYPE_EXACT]'
        elif self.field_name == 'egress_spec':
          return '[STDMETA_EGRESS_SPEC_EXACT]'
        else:
282 283
          unsupported("Not supported: standard_metadata field %s" \
                                                % self.field_name)
284
      else:
285 286 287
        unsupported("Not supported: standard_metadata with %s match type" \
                                                        % self.match_type)

288 289 290
    elif self.source_type == 'metadata':
      if self.match_type == 'P4_MATCH_EXACT':
        return '[METADATA_EXACT]'
291 292
      elif self.match_type == 'P4_MATCH_TERNARY':
        return '[METADATA_TERNARY]'
293
      else:
294 295
        unsupported("Not supported: metadata with %s match type" \
                                               % self.match_type)
296 297 298 299 300
    elif self.source_type == 'extracted':
      if self.match_type == 'P4_MATCH_EXACT':
        return '[EXTRACTED_EXACT]'
      elif self.match_type == 'P4_MATCH_VALID':
        return '[EXTRACTED_VALID]'
301 302
      elif self.match_type == 'P4_MATCH_TERNARY':
        return '[EXTRACTED_TERNARY]'
303
      else:
304 305
        unsupported("Not supported: extracted with %s match type" \
                                                % self.match_type)
306 307 308 309
    elif self.source_type == '':
      if self.match_type == 'MATCHLESS':
        return '[MATCHLESS]'
      else:
310 311
        unsupported("Not supported: [no source] with %s match type" \
                                                  % self.match_type)
312
    else:
313 314 315
      unsupported("Not supported: source type %s, match type %s" \
                           % (self.source_type, self.match_type))

316 317 318 319 320 321
  def __str__(self):
    return self.name

class Action_Rep():
  def __init__(self):
    self.stages = set()
322 323
    self.tables = {} # {stage (int) : table_name (str)}
    self.next = {} # {table_name (str) : (next_stage (int), next_table_code (int))}
324 325
    self.call_sequence = []

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
class PC_State(object):
  newid = itertools.count().next
  def __init__(self, hp4_bits_extracted=SEB,
                     p4_bits_extracted=0,
                     ps_path=[],
                     pcs_path=[],
                     parse_state=None,
                     entry_table='tset_parse_control',
                     **kwargs):
    self.hp4_bits_extracted = hp4_bits_extracted
    self.p4_bits_extracted = p4_bits_extracted
    self.ps_path = ps_path
    self.pcs_path = pcs_path
    self.pcs_id = PC_State.newid()
    self.parse_state = parse_state
    self.entry_table = entry_table # TODO: Delete if we don't need this
    self.children = []
    self.header_offsets = {} # header name (str) : hp4 bit offset (int)
    for pcs in self.pcs_path:
      self.header_offsets.update(pcs.header_offsets)
    self.select_criteria = [] # list of (offset, width) tuples, each
                              #  element corresponding to a criteria in the
                              #  select statement, representing the hp4 view
    self.select_values = [] # list of lists: each member a list of values,
                            #  each value corresponding to a criteria in
                            #  select_criteria
352

353 354 355 356 357 358 359 360 361 362 363 364 365
  def __str__(self):
    ret = 'ID: ' + str(self.pcs_id) + '; ' + self.parse_state.name + '\n'
    ret += 'hp4_bits_extracted: ' + str(self.hp4_bits_extracted) + '\n'
    ret += 'p4_bits_extracted: ' + str(self.p4_bits_extracted) + '\n'
    ret += 'ps_path: ' + str(self.ps_path) + '\n'
    ret += 'pcs_path: ' 
    for pcs in self.pcs_path:
      ret += str(pcs.pcs_id) + '(' + pcs.parse_state.name + ') '
    ret += '\n'
    ret += 'children: '
    for child in self.children:
      ret += child.parse_state.name + ' '
    return ret
366

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
def collect_meta(headers):
  """ Classify headers (metadata | parsed representation)
      - For metadata: assign each field an offset into meta.data
      - NOTE: the same cannot be done for parsed representation headers
        until we traverse the parse tree, because each path through the
        parse tree potentially yields a distinct set of field offsets
        into pr.data.
  """
  meta_offsets = {}
  metadata_offset = 0

  for header_key in headers.keys():
    header = headers[header_key]

    if header.name == 'standard_metadata':
      continue

384 385 386
    if header.name == 'intrinsic_metadata':
      continue

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
    if header.metadata == True:

      for field in header.fields:
        fullname = header.name + '.' + field.name
        meta_offsets[fullname] = metadata_offset
        metadata_offset += field.width
        if metadata_offset > METADATA_WIDTH:
          unsupported("Error: out of metadata memory with %s" % fullname)

  return meta_offsets

def collect_actions(actions):
  """ Uniquely number each action """
  action_ID = {}
  actionID = 1
  for action in actions:
    if action.lineno > 0: # is action from source (else built-in)?
      action_ID[action] = actionID
      actionID += 1
  return action_ID

def get_prim_subtype(p4_call):
  """ p4_call: (p4_action, [list of parameters])
  """
  primitive = p4_call[P4_CALL_PRIMITIVE]
  params = p4_call[P4_CALL_PARAMS]
413 414 415 416
  if (primitive.name == 'drop' or 
      primitive.name == 'add_header' or 
      primitive.name == 'remove_header' or
      primitive.name == 'modify_field_rng_uniform'):
417 418 419 420 421 422
    return '0'
  elif primitive.name == 'add_to_field':
    if type(params[0]) is p4_hlir.hlir.p4_headers.p4_field:
      if params[0].instance.metadata == True:
        unsupported("Not supported: metadata (%s) as dst field in \
                         add_to_field" %  params[0].instance.name)
David Hancock's avatar
David Hancock committed
423

424 425 426 427 428 429 430 431 432
      else:
        if type(params[1]) is int:
          if params[1] < 0:
            return(a2f_prim_subtype_ID['sub'])
          else:
            return(a2f_prim_subtype_ID['add'])
        else:
          unsupported("ERROR: Not supported: %s type for src field in \
                                      add_to_field" % type(params[1]))
David Hancock's avatar
David Hancock committed
433

434
    else:
435 436
      unsupported("ERROR: dst field type %s in add_to_field" % type(params[0]))

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
  elif primitive.name == 'bit_xor':
    first = 0
    second = 0
    third = 0
    if params[0].instance.metadata == True:
      first = 'meta' # user-defined metadata
    else: # parsed representation
      first = 'ext'
    if params[1].instance.metadata == True:
      second = 'meta' # user-defined metadata
    else: # parsed representation
      second = 'ext'
    if type(params[2]) in [int, long]:
      third = 'const'
    elif type(params[2]) is p4_hlir.hlir.p4_imperatives.p4_signature_ref:
      third = 'const'
    else:
      unsupported("ERROR: Unexpected type %s as third param in \
                    bit_xor call" % type(params[2]))

    return bx_prim_subtype_ID[(first, second, third)]

459 460 461 462 463 464 465
  elif primitive.name == 'modify_field':
    first = 0
    second = 0
    if params[0].instance.metadata == True:
      if params[0].instance.name == 'standard_metadata':
        if params[0].name == 'egress_spec':
          first = params[0].name
466
        else:
467 468
          unsupported("ERROR: Unexpected stdmeta field %s as dst in \
                           modify_field primitive" % params[0].name)
469

470 471 472 473 474 475
      elif params[0].instance.name == 'intrinsic_metadata':
        if params[0].name == 'mcast_grp':
          #first = params[0].name
          first = 'egress_spec'
        else:
          unsupported("ERROR: Unexpected intmeta field %s as dst in \
476
                        modify_field primitive" % params[0].name)
477 478 479 480 481

      else: # user-defined metadata
        first = 'meta'
    else: # parsed representation
      first = 'ext'
482
    if type(params[1]) in [int, long]:
483 484 485 486 487 488 489 490 491 492 493
      second = 'const'
    elif type(params[1]) is p4_hlir.hlir.p4_headers.p4_field:
      if params[1].instance.metadata == True:
        if params[1].instance.name == 'standard_metadata':
          second = params[1].name
        else:
          second = 'meta'
      else:
        second = 'ext'
    elif type(params[1]) is p4_hlir.hlir.p4_imperatives.p4_signature_ref:
      second = 'const'
David Hancock's avatar
David Hancock committed
494
    else:
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
      unsupported("ERROR: Unexpected type %s as src in \
                    modify_field call" % type(params[1]))

    return mf_prim_subtype_ID[first, second]

def gen_bitmask(fieldwidth, offset, maskwidth):
  """fieldwidth: bits; offset: bits; maskwidth: bytes"""
  mask = '0x'

  bytes_written = offset / 8
  bits_left = fieldwidth
  while bits_left > 0:
    byte = 0
    bit = 0b10000000 >> (offset % 8)
    if bits_left >= 8 - (offset % 8):
      for i in range(8 - (offset % 8)):
        byte = byte | bit
        bit = bit >> 1
      bits_left = bits_left - (8 - (offset % 8))
      offset = offset + 8 - (offset % 8)
    else:
      for i in range(bits_left):
        byte = byte | bit
        bit = bit >> 1
      bits_left = 0
    mask += hex(byte)[2:]
    bytes_written += 1
522

523
  mask += '[' + str(maskwidth - bytes_written) + 'x00s]'
David Hancock's avatar
David Hancock committed
524

525 526
  return mask

527 528 529 530 531 532
def gen_addremove_header_bitmask(offset, maskwidth):
  """offset: bits; maskwidth: bytes"""

  bytes_written = offset / 8
  return '0x[' + str(maskwidth - bytes_written) + 'xFFs]'

533 534 535
class P4_to_HP4(HP4Compiler):

  def walk_ingress_pipeline(self, tables):
536
    """ populate table_to_trep and action_to_arep data structures """
537 538 539
    table_to_trep = {}
    action_to_arep = {}
    stage = 1
540 541

    # 1) Do topological sort of tables
542
    tsorter = DAG_Topo_Sorter(tables)
543 544 545 546 547 548 549 550
    tsort = tsorter.sort()
    # 2) assign each one to a unique stage
    for i in range(len(tsort)):
      curr_table = tsort[i]
      source_type = ''
      match_type = 'MATCHLESS'
      field_name = ''
      if len(curr_table.match_fields) > 0:
551 552 553
        match = curr_table.match_fields[0]
        match_type = match[MATCH_TYPE].value
        field_name = match[MATCH_FIELD].name
554 555 556
        if (match_type == 'P4_MATCH_EXACT' or
            match_type == 'P4_MATCH_TERNARY'):
          # headers_hp4_type[<str>]: 'standard_metadata' | 'metadata' | 'extracted'
557
          source_type = get_hp4_type(match[MATCH_FIELD].instance)
558
        elif match_type == 'P4_MATCH_VALID':
559 560 561 562 563
          source_type = get_hp4_type(match[MATCH_FIELD])
      table_to_trep[curr_table] = Table_Rep(stage,
                                            match_type,
                                            source_type,
                                            field_name)
564 565

      for action in curr_table.actions:
566 567
        if action_to_arep.has_key(action) is False:
          action_to_arep[action] = Action_Rep()
568
          for call in action.call_sequence:
569 570 571 572 573
            prim_type = call[PRIM_TYPE].name
            prim_subtype = get_prim_subtype(call)
            action_to_arep[action].call_sequence.append((prim_type, prim_subtype))
        action_to_arep[action].stages.add(stage)
        action_to_arep[action].tables[stage] = curr_table.name
574

575 576 577 578 579 580
      stage += 1

    return table_to_trep, action_to_arep

  def gen_tX_templates(self, tables):
    command_templates = []
581 582 583 584

    for table in self.table_to_trep:
      tname = str(self.table_to_trep[table])
      aname = 'init_program_state'
585
      mparams = ['[vdev ID]']
586
      if len(table.match_fields) > 1:
587 588 589
        unsupported("Not yet supported: more than 1 match field (table: %s)" % table.name)

      # mparams_list = []
590 591 592 593 594 595
      if len(table.match_fields) == 1:      
        if table.match_fields[0][1].value == 'P4_MATCH_VALID':
          mp = '[valid]&&&'
          # self.vbits[(level, header_instance)]
          hinst = table.match_fields[0][0]
          for key in self.vbits.keys():
596
            if hinst.name == key[1]:
597
              mp += format(self.vbits[key], '#x')
598 599 600 601
              # temp_mparams = list(mparams)
              # temp_mparams.append(mp)
              # mparams_list.append(temp_mparams)
              mparams.append(mp)
602 603
        elif ((table.match_fields[0][1].value == 'P4_MATCH_EXACT') or
             (table.match_fields[0][1].value == 'P4_MATCH_TERNARY')):
604 605 606 607 608 609
          field = table.match_fields[0][0]
          mp = '[val]'
          if field.instance.name != 'standard_metadata':
            maskwidth = 100
            if field.instance.metadata:
              maskwidth = 32
610 611 612 613
            offset = self.field_offsets[str(field)]
            mp += '&&&' + gen_bitmask(field.width,
                                      offset,
                                      maskwidth)
614
          elif field.name != 'egress_spec' and field.name != 'ingress_port':
615 616 617
            mp += '&&&' + hex((1 << field.width) - 1)
          else: # egress_spec... rep'd by virt_egress_spec, which is 8 bits
            mp += '&&&0xFF'
618
          mparams.append(mp)
619 620

      # need a distinct template entry for every possible action
621 622 623 624 625
      for action in table.actions:
        # action_ID
        aparams = [str(self.action_ID[action])]
        # match_ID
        aparams.append('[match ID]')
626
        # next stage, next_table
627
        if 'hit' in table.next_:
628 629 630
          next_table_trep = self.table_to_trep[table.next_['hit']]
          aparams.append(str(next_table_trep.stage))
          aparams.append(next_table_trep.table_type())
631
        elif table.next_[action] == None:
632
          aparams.append('0')
633
          aparams.append('[DONE]')
634
        else:
635 636 637
          next_table_trep = self.table_to_trep[table.next_[action]]
          aparams.append(str(next_table_trep.stage))
          aparams.append(next_table_trep.table_type())
638 639 640
        # primitives
        idx = 0
        for call in action.call_sequence:
641 642
          prim_type = primitive_ID[call[P4_CALL_PRIMITIVE].name]
          prim_subtype = get_prim_subtype(call)
643 644
          if not prim_subtype:
            unsupported("Error: couldn't get the prim_subtype for " + prim_type)
645 646 647 648
          aparams.append(prim_type)
          aparams.append(prim_subtype)
          idx += 1

649 650
        if len(action.call_sequence) == 0:
          aparams.append(primitive_ID['no_op'])
651 652 653 654 655 656 657
          # subtype
          aparams.append('0')
          idx = 1

        # zeros for remaining type / subtype parameters of init_program_state
        for i in range(idx, self.numprimitives):
          aparams.append('0')
658 659
          aparams.append('0')

660
        # all matches are ternary, requiring priority
661
        # TODO: except matchless?
662
        aparams.append('[PRIORITY]')
663 664 665 666 667 668 669 670 671 672

        command_templates.append(HP4_Match_Command(source_table=table.name,
                                                   source_action=action.name,
                                                   command="table_add",
                                                   table=tname,
                                                   action=aname,
                                                   match_params=mparams,
                                                   action_params=aparams))
    return command_templates

673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
  def gen_action_aparams(self, p4_call, call, field_offsets):
    aparams = []
    primtype = call[PRIM_TYPE]
    subtype = call[PRIM_SUBTYPE]
    p4_call_params = p4_call[P4_CALL_PARAMS]

    if primtype == 'drop':
      return aparams
    if primtype == 'add_to_field':
      if (a2f_prim_subtype_action[subtype] == 'a_add2f_extracted_const_u' or
          a2f_prim_subtype_action[subtype] == 'a_subff_extracted_const_u'):
        # aparams: leftshift, val
        dst_offset = field_offsets[str(p4_call_params[0])]
        leftshift = 800 - (dst_offset + p4_call_params[0].width)
        if type(p4_call_params[1]) is int:
          val = str(p4_call_params[1])
          if a2f_prim_subtype_action[subtype] == 'a_subff_extracted_const_u':
            val = str(p4_call_params[1]*-1)
        else:
          val = '[val]'
        aparams.append(str(leftshift))
        aparams.append(val)

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
    if primtype == 'add_header' or primtype == 'remove_header':

      hdr = p4_call_params[0]
      offset = self.header_offsets[hdr.name]
      sz = hdr.header_type.length

      vb = 0
      for key in self.vbits:
        if hdr.name == key[1]:
          vb = self.vbits[key]
          break
      if vb == 0:
        print('Fail: didn\'t find vbits entry for ' + hdr.name)
        exit()

      mask = gen_addremove_header_bitmask(offset, MAX_BYTE)

      if primtype == 'add_header':
        # aparams: sz, offset, msk, vbits    
        aparams.append(str(sz))
        aparams.append(mask)
        aparams.append('0x%x' % vb)
      else: # 'remove_header'
        # aparams: sz, msk, vbits
        aparams.append(str(sz))
        aparams.append(mask)
        vbinv = ~vb & (2**VBITS_WIDTH - 1)
        aparams.append('0x%x' % vbinv)

    if primtype == 'modify_field_rng_uniform':
      # aparams: leftshift, emask, lowerbound, upperbound
727
      if type(p4_call_params[1]) in [int, long]:
728 729 730
        val1 = str(p4_call_params[1])
      else:
        val1 = '[val]'
731
      if type(p4_call_params[2]) in [int, long]:
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
        val2 = str(p4_call_params[2])
      else:
        val2 = '[val]'

      fo = field_offsets[str(p4_call_params[0])]
      fw = p4_call_params[0].width
      maskwidthbits = 800
      leftshift = str(maskwidthbits - (fo + fw))
      mask = gen_bitmask(p4_call_params[0].width,
                              field_offsets[str(p4_call_params[0])],
                              maskwidthbits / 8)
      aparams.append(leftshift)
      aparams.append(mask)
      aparams.append(val1)
      aparams.append(val2)
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792

    if primtype == 'bit_xor':
      # aparams: elshift, ershift, vlshift, dest_mask, src_mask, val
      fo_intermediate = field_offsets[str(p4_call_params[1])]
      fw_intermediate = p4_call_params[1].width
      fo_final = field_offsets[str(p4_call_params[0])]
      fw_final = p4_call_params[0].width
      if bx_prim_subtype_action[subtype] == 'bit_xor_meta_meta_const':
        unsupported("Not yet supported: bit_xor_meta_meta_const")
        dest_maskwidthbits = 256
        src_maskwidthbits = 256

      elif bx_prim_subtype_action[subtype] == 'bit_xor_extracted_extracted_const':
        dest_maskwidthbits = 800
        src_maskwidthbits = 800

      elif bx_prim_subtype_action[subtype] == 'bit_xor_meta_extracted_const':
        dest_maskwidthbits = 256
        src_maskwidthbits = 800

      elshift = 0
      ershift = 0
      dst_revo = dest_maskwidthbits - (fo_final + fw_final)
      src_revo = src_maskwidthbits - (fo_intermediate + fw_intermediate)
      if src_revo > dst_revo:
        ershift = src_revo - dst_revo
      else:
        elshift = dst_revo - src_revo

      vlshift = str(src_maskwidthbits - (fo_intermediate + fw_intermediate))

      dest_mask = gen_bitmask(fw_final, fo_final, dest_maskwidthbits / 8)
      src_mask = gen_bitmask(fw_intermediate, fo_intermediate, src_maskwidthbits / 8)
      src_mask = src_mask.split('[')[0]

      if type(p4_call_params[2]) in [int, long]:
        val = str(p4_call_params[2])
      else:
        val = '[val]'

      aparams.append(str(elshift))
      aparams.append(str(ershift))
      aparams.append(vlshift)
      aparams.append(dest_mask)
      aparams.append(src_mask)
      aparams.append(val)
793
      
794 795 796 797 798 799 800 801
    if primtype == 'modify_field':
      instance_name = p4_call_params[0].instance.name
      dst_field_name = p4_call_params[0].name
      if instance_name == 'intrinsic_metadata':
        if dst_field_name == 'mcast_grp':
          instance_name = 'standard_metadata'
          dst_field_name = 'egress_spec'
        else:
802
          unsupported("Not supported: modify_field(" + instance_name + '.' \
803
                + dst_field_name + ", *)")
804

805 806 807 808 809 810
      if type(p4_call_params[1]) is p4_hlir.hlir.p4_headers.p4_field:
        if p4_call_params[1].width > p4_call_params[0].width:
          dst = instance_name + '.' + dst_field_name
          src = p4_call_params[1].instance.name + '.' + p4_call_params[1].name
          print("WARNING: modify_field(%s, %s): %s width (%i) > %s width (%i)" \
              % (dst, src, src, p4_call_params[1].width, dst, p4_call_params[0].width))
811

812
      if mf_prim_subtype_action[subtype] == 'mod_meta_stdmeta_ingressport':
813 814
        unsupported("Not yet supported: %s" % mf_prim_subtype_action[subtype])

815
      elif mf_prim_subtype_action[subtype] == 'mod_meta_stdmeta_packetlength':
816 817
        unsupported("Not yet supported: %s" % mf_prim_subtype_action[subtype])

818
      elif mf_prim_subtype_action[subtype] == 'mod_meta_stdmeta_egressspec':
819 820
        unsupported("Not yet supported: %s" % mf_prim_subtype_action[subtype])

821
      elif mf_prim_subtype_action[subtype] == 'mod_meta_stdmeta_egressport':
822 823
        unsupported("Not yet supported: %s" % mf_prim_subtype_action[subtype])

824
      elif mf_prim_subtype_action[subtype] == 'mod_meta_stdmeta_egressinst':
825 826
        unsupported("Not yet supported: %s" % mf_prim_subtype_action[subtype])

827
      elif mf_prim_subtype_action[subtype] == 'mod_meta_stdmeta_insttype':
828 829
        unsupported("Not yet supported: %s" % mf_prim_subtype_action[subtype])

830 831 832 833 834 835 836 837 838 839
      elif mf_prim_subtype_action[subtype] == 'mod_stdmeta_egressspec_meta':
        # aparams: rightshift, tmask
        rshift = 256 - (field_offsets[str(p4_call_params[1])] + p4_call_params[1].width)
        mask = 0
        if p4_call_params[1].width < p4_call_params[0].width:
          mask = hex(int(math.pow(2, p4_call_params[1].width)) - 1)
        else:
          mask = hex(int(math.pow(2, p4_call_params[0].width)) - 1)
        aparams.append(str(rshift))
        aparams.append(mask)
840

841 842 843
      elif (mf_prim_subtype_action[subtype] == 'mod_meta_const' or
            mf_prim_subtype_action[subtype] == 'mod_extracted_const'):
        # aparams: leftshift, mask, val
844
        if type(p4_call_params[1]) in [int, long]:
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
          val = str(p4_call_params[1])
        else:
          val = '[val]'
        fo = field_offsets[str(p4_call_params[0])]
        fw = p4_call_params[0].width
        maskwidthbits = 800
        if mf_prim_subtype_action[subtype] == 'mod_meta_const':
          maskwidthbits = 256
        leftshift = str(maskwidthbits - (fo + fw))
        mask = gen_bitmask(p4_call_params[0].width,
                                field_offsets[str(p4_call_params[0])],
                                maskwidthbits / 8)
        aparams.append(leftshift)
        aparams.append(mask)
        aparams.append(val)
860

861 862 863 864 865
      elif (mf_prim_subtype_action[subtype] == 'mod_stdmeta_egressspec_const'):
        if type(p4_call_params[1]) is int:
          aparams.append(str(p4_call_params[1]))
        else:
          aparams.append('[val]')
866

867 868
      elif (mf_prim_subtype_action[subtype] == 'mod_intmeta_mcast_grp_const'):
        if type(p4_call_params[1]) is int:
869 870
          unsupported("Not yet supported: mod_intmeta_mcast_grp_const w/ explicit const")

871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
        else:
          aparams.append('[MCAST_GRP]')

      #elif mf_prim_subtype_action[subtype] == 'mod_stdmeta_egressspec_stdmeta_ingressport':
      #  return aparams
      elif mf_prim_subtype_action[subtype] == 'mod_extracted_extracted':
        # aparams:
        # - leftshift (how far should src field be shifted to align w/ dst)
        # - rightshift (how far should src field be shifted to align w/ dst)
        # - msk (bitmask for dest field)
        dst_offset = field_offsets[str(p4_call_params[0])]
        src_offset = field_offsets[str(p4_call_params[1])]
        lshift = 0
        rshift = 0
        # *_revo = revised offset; right-aligned instead of left-aligned
        dst_revo = 800 - (dst_offset + p4_call_params[0].width)
        src_revo = 800 - (src_offset + p4_call_params[1].width)
        if src_revo > dst_revo:
          rshift = src_revo - dst_revo
        else:
          lshift = dst_revo - src_revo
        aparams.append(str(lshift))
        aparams.append(str(rshift))
        aparams.append(gen_bitmask(p4_call_params[0].width, dst_offset, 100))
      elif mf_prim_subtype_action[subtype] == 'mod_meta_extracted':
        dst_offset = field_offsets[str(p4_call_params[0])]
        src_offset = field_offsets[str(p4_call_params[1])]
        lshift = 0
        rshift = 0
        dstmaskwidthbits = 256
        srcmaskwidthbits = 800
        # *_revo = revised offset; right-aligned instead of left-aligned
        dst_revo = dstmaskwidthbits - (dst_offset + p4_call_params[0].width)
        src_revo = srcmaskwidthbits - (src_offset + p4_call_params[1].width)
        if src_revo > dst_revo:
          rshift = src_revo - dst_revo
        else:
          lshift = dst_revo - src_revo
        dstmask = gen_bitmask(p4_call_params[0].width, dst_offset,
                                   dstmaskwidthbits / 8)
        srcmask = dstmask
        if p4_call_params[1].width < p4_call_params[0].width:
          srcmask = gen_bitmask(p4_call_params[1].width, dst_offset,
                                     dstmaskwidthbits / 8)
        aparams.append(str(lshift))
        aparams.append(str(rshift))
        aparams.append(dstmask)
        aparams.append(srcmask)
      elif mf_prim_subtype_action[subtype] == 'mod_extracted_meta':
        dst_offset = field_offsets[str(p4_call_params[0])]
        src_offset = field_offsets[str(p4_call_params[1])]
        lshift = 0
        rshift = 0
        dstmaskwidthbits = 800
        srcmaskwidthbits = 256
        # *_revo = revised offset; right-aligned instead of left-aligned
        dst_revo = dstmaskwidthbits - (dst_offset + p4_call_params[0].width)
        src_revo = srcmaskwidthbits - (src_offset + p4_call_params[1].width)
        if src_revo > dst_revo:
          rshift = src_revo - dst_revo
        else:
          lshift = dst_revo - src_revo
        dstmask = gen_bitmask(p4_call_params[0].width, dst_offset,
                                   dstmaskwidthbits / 8)
        srcmask = dstmask
        if p4_call_params[1].width < p4_call_params[0].width:
          srcmask = gen_bitmask(p4_call_params[1].width, dst_offset,
                                     dstmaskwidthbits / 8)
        aparams.append(str(lshift))
        aparams.append(str(rshift))
        aparams.append(dstmask)
        aparams.append(srcmask)

    return aparams

  def gen_action_entries(self, action_to_arep, action_ID, field_offsets):
    commands = []
    command_templates = []
    for action in action_to_arep:
      for stage in action_to_arep[action].stages:
        table_name = action_to_arep[action].tables[stage]
952

953 954 955 956 957 958 959 960 961 962 963 964 965 966
        for p4_call in action.call_sequence:
          p4_call_params = p4_call[P4_CALL_PARAMS]
          istemplate = False
          idx = action.call_sequence.index(p4_call)
          call = action_to_arep[action].call_sequence[idx]
          primtype = call[PRIM_TYPE]
          subtype = call[PRIM_SUBTYPE]
          rank = idx + 1
          tname = 't_' + primitive_tnames[primtype] + '_' + str(stage) + str(rank)

          if primtype == 'modify_field':
            aname = mf_prim_subtype_action[subtype]
          elif primtype == 'add_to_field':
            aname = a2f_prim_subtype_action[subtype]
967 968
          elif primtype == 'bit_xor':
            aname = bx_prim_subtype_action[subtype]
969 970 971 972
          else:
            aname = gen_prim_subtype_action[primtype]
          mparams = ['[vdev ID]']
          if primtype != 'drop':
973
            if primtype in ['modify_field', 'add_to_field', 'bit_xor']:
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
              mparams.append( subtype )
            mparams.append(str(action_ID[action]))
            # If the parameter passed to the primitive in the source code is an
            # action parameter reference, the match_ID parameter should be
            # [val]&&&0x7FFFFF because each distinct match could have a different
            # value for the action parameter.  Otherwise, we don't care what the
            # match_ID is so use 0&&&0.
            match_ID_param = '0&&&0'
            for param in p4_call_params:
              if type(param) is p4_hlir.hlir.p4_imperatives.p4_signature_ref:
                match_ID_param = '[match ID]&&&0x7FFFFF'
                istemplate = True
                break
            mparams.append(match_ID_param)

          aparams = self.gen_action_aparams(p4_call, call, field_offsets)

          if istemplate == True:
            aparams.append('0') # meta_primitive_state.match_ID mparam matters
            idx = -1
994 995 996

            if type(p4_call_params[-1]) is p4_hlir.hlir.p4_imperatives.p4_signature_ref:
              idx = p4_call_params[-1].idx
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
            command_templates.append(HP4_Primitive_Command(table_name,
                                            action.name,
                                            "table_add",
                                            tname,
                                            aname,
                                            mparams,
                                            aparams,
                                            str(idx)))
          else:
            # meta_primitive_state.match_ID mparam does not matter
            # only append priority if the table involves ternary matching
            #  e.g., drop tables do not
            if len(mparams) > 0:
              for param in mparams:
                if '&&&' in param:
                  aparams.append(str(LOWEST_PRIORITY))
                  break
            commands.append(HP4_Command("table_add",
                                        tname,
                                        aname,
                                        mparams,
                                        aparams))

    return commands, command_templates


1023 1024 1025 1026 1027
  def build(self, h):

    self.field_offsets = collect_meta(h.p4_header_instances)
    self.action_ID = collect_actions(h.p4_actions.values())

1028 1029 1030
    # reset id counter
    PC_State.newid = itertools.count().next

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
    pre_pcs = PC_State(parse_state=h.p4_parse_states['start'])
    launch_process_parse_tree_clr(pre_pcs, h)

    self.header_offsets = collect_header_offsets(pre_pcs)
    self.field_offsets.update(collect_field_offsets(self.header_offsets,
                                                    h.p4_header_instances))

    consolidate_parse_tree_clr(pre_pcs, h)

    ingress_pcs_list = collect_ingress_pcs(pre_pcs)
    self.vbits = get_vbits(ingress_pcs_list)

    first_table = h.p4_ingress_ptr.keys()[0]

    ps_entries = gen_parse_select_entries(pre_pcs)
    # post-process output of gen_parse_select_entries:
    #  parse_select_00_19, _20_29, and _30_39 use 320b field ext.first
    ps_entries = process_parse_select_entries(ps_entries)

    self.commands = gen_parse_control_entries(pre_pcs) \
                  + ps_entries \
                  + gen_pipeline_config_entries(pre_pcs, first_table,
                                                ingress_pcs_list, self.vbits)

    self.table_to_trep, self.action_to_arep = self.walk_ingress_pipeline(h.p4_tables)
    self.command_templates = self.gen_tX_templates(h.p4_tables)
1057

1058 1059 1060
    action_commands, action_templates = self.gen_action_entries(self.action_to_arep,
                                                               self.action_ID,
                                                               self.field_offsets)
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    self.commands += action_commands
    self.command_templates += action_templates

    self.commands += gen_tmiss_entries(h.p4_tables,
                                       self.table_to_trep,
                                       h.p4_control_flows['ingress'],
                                       self.numprimitives)

    self.commands += gen_t_checksum_entries(h.calculated_fields,
                                            h.p4_field_list_calculations,
                                            self.field_offsets,
                                            self.vbits)

    self.commands += gen_t_resize_pr_entries()

  def compile_to_hp4(self, program_path, out_path, mt_out_path, numprimitives):
    self.out_path = out_path
    self.mt_out_path = mt_out_path
    self.numprimitives = numprimitives
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090

    # reset state
    self.action_ID = {}
    self.action_to_arep = {}
    self.command_templates = []
    self.commands = []
    self.field_offsets = {}
    self.header_offsets = {}
    self.table_to_trep = {}
    self.vbits = {}

1091
    h = HLIR(program_path)
1092
    h.add_primitives(json.loads(pkg_resources.resource_string('p4c_bm', 'primitives.json')))
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
    h.build()
    do_support_checks(h)
    self.build(h)
    self.write_output()

    return CodeRepresentation(out_path, mt_out_path)

  def write_output(self):
    out = open(self.out_path, 'w')
    for command in self.commands:
      out.write(str(command) + '\n')
    out.close()
    out = open(self.mt_out_path, 'w')

    def getkey(command):
      return (command.table, command.source_action, command.action_params)
    sorted_ct = sorted(self.command_templates, key=getkey)

    json.dump(sorted_ct, out, default=convert_to_builtin_type, indent=2)
    out.close()

def do_support_checks(h):
  # Not sure how this would happen in P4 but HLIR suggests the possibility:
  if len(h.p4_ingress_ptr.keys()) > 1:
    unsupported("Not supported: multiple entry points into the ingress pipeline")

  # Tables with multiple match criteria:
  for table in h.p4_tables.values():
    if len(table.match_fields) > 1:
      unsupported("Not supported: multiple field matches (table: %s)" % table.name)

def get_parse_select_table_code(first_byte):
  for i in range(len(parse_select_table_boundaries) - 1):
    lowerbound = parse_select_table_boundaries[i]
    upperbound = parse_select_table_boundaries[i+1]
    if first_byte >= lowerbound and first_byte < upperbound:
      ret = '[PARSE_SELECT_'
      ret += '%02d_%02d]' % (lowerbound, upperbound - 1)
      return ret
1132
  debug()
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
  raise Exception("Did not find parse_select table; first_byte: %d" % first_byte)

def get_pc_action(pcs):
  select_first_byte = MAX_BYTE
  for criteria in pcs.select_criteria:
    select_first_byte = min(criteria[OFFSET] / 8, select_first_byte)
  return get_parse_select_table_code(select_first_byte)

def gen_pc_entry_start(pcs):
  """ Generate parse_control entries for pc 0/1:
       We need an entry for pc 1 only if SEB is insufficient
       to handle 'start', in which case the action for pc 0
       must be extract_more
  """
  start_pcs = pcs.children[0] # pc 0 always has one child: pc 1
  mparams = ['[vdev ID]', str(pcs.pcs_id)]
  aparams = []
  act = 'set_next_action'
  if start_pcs.p4_bits_extracted > pcs.hp4_bits_extracted:
    act = 'extract_more'
    aparams.append(str(int(ceil(start_pcs.p4_bits_extracted / 8.0))))
  else:
    if not start_pcs.children:
      aparams.append('[PROCEED]')
    else:
      aparams.append(get_pc_action(start_pcs))

  aparams.append(str(start_pcs.pcs_id))

  cmd = HP4_Command(command='table_add',
                    table='tset_parse_control',
                    action=act,
                    match_params=mparams,
                    action_params=aparams)
  return cmd

def get_p_ps_tables(pcs):
  # sort
  sorted_criteria, sorted_branches, default_branch = sort_return_select(pcs)

  # revise branch_values, select_criteria per parse_select table boundaries
  revised_criteria, revised_branches = revise_return_select(pcs,
                                                            sorted_criteria,
                                                            sorted_branches)
  return get_parse_select_tables(revised_criteria)

def did_rewind(pcs):
  if not pcs.children:
    return False
  first_criteria = sort_return_select(pcs)[0][0]
  j = 0
  while parse_select_table_boundaries[j+1] * 8 <= first_criteria[OFFSET]:
    j += 1
  p_ps_tables = get_p_ps_tables(pcs.pcs_path[-1])
  if parse_select_table_boundaries[j] <= p_ps_tables[-1][L_BOUND]:
    return True
  return False

1191 1192 1193
def gen_parse_control_entries(pcs, commands=None):
  if commands is None:
    commands = []
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
  if pcs.pcs_id == 0:
    cmd = gen_pc_entry_start(pcs)
    commands.append(cmd)
    if cmd.action == 'extract_more':
      commands = gen_parse_control_entries(pcs.children[0], commands)
    else:
      for child in pcs.children[0].children:
        commands = gen_parse_control_entries(child, commands)
  
  else:
1204 1205 1206 1207 1208
    try:
      test = pcs.pcs_path[-1].hp4_bits_extracted < pcs.hp4_bits_extracted
    except IndexError as e:
      print(e)
      debug()
1209 1210 1211 1212 1213 1214 1215
    if (pcs.pcs_path[-1].hp4_bits_extracted < pcs.hp4_bits_extracted or
        did_rewind(pcs)):
      mparams = ['[vdev ID]', str(pcs.pcs_id)]
      aparams = []
      act = 'set_next_action'
      if not pcs.children:
        aparams.append('[PROCEED]')
1216
      else:
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
        aparams.append(get_pc_action(pcs))
      aparams.append(str(pcs.pcs_id))

      cmd = HP4_Command(command='table_add',
                        table='tset_parse_control',
                        action=act,
                        match_params=mparams,
                        action_params=aparams)

      commands.append(cmd)

    for child in pcs.children:
      commands = gen_parse_control_entries(child, commands)

  return commands

def get_new_val(val, width, offset, new_width):
  mask = 0
  bitpos = offset
  while bitpos < (offset + new_width):
    mask += 2**(width - bitpos - 1)
    bitpos += 1
  newval = val & mask
  newval = newval >> (width - (offset + new_width))
  return newval

def sort_return_select(pcs):
  if pcs.parse_state.return_statement[PS_RET_TYPE] == 'immediate':
    return [], [], None

  sorted_indices = sorted(range(len(pcs.select_criteria)),
                          key=pcs.select_criteria.__getitem__)
  sorted_criteria = []
  for i in sorted_indices:
    sorted_criteria.append(pcs.select_criteria[i])
  sorted_branches = []
  default_branch = None

  for branch in pcs.parse_state.return_statement[PS_RET_BRANCHES]:
    if branch[BRANCH_VALUES][0][VAL_TYPE] == 'value':
      sorted_values = []
      for i in sorted_indices:
        sorted_values.append(branch[BRANCH_VALUES][i][VAL_VALUE])
      sorted_branches.append((sorted_values, branch[BRANCH_STATE]))
    elif branch[BRANCH_VALUES][0][VAL_TYPE] == 'default':
      default_branch = branch
  return sorted_criteria, sorted_branches, default_branch

def revise_value(val, crit, j):
  curr_offset = crit[OFFSET]
  ret = []
  while curr_offset < (crit[OFFSET] + crit[WIDTH]):
    # setup
    diff = parse_select_table_boundaries[j+1] * 8 - curr_offset
    if diff > crit[WIDTH]:
      diff = crit[OFFSET] + crit[WIDTH] - curr_offset
    # rev_branch_values
    ret.append(get_new_val(val,
                           crit[WIDTH],
                           curr_offset - crit[OFFSET],
                           diff))
    # cleanup
    curr_offset += diff
    j += 1
  return ret

def revise_criteria(crit, j):
  ret = []
  curr_offset = crit[OFFSET]
  while curr_offset < (crit[OFFSET] + crit[WIDTH]):
    # setup
    diff = parse_select_table_boundaries[j+1] * 8 - curr_offset
    if diff > crit[WIDTH]:
      diff = crit[OFFSET] + crit[WIDTH] - curr_offset
    # update
    ret.append((curr_offset, diff))
    # cleanup
    curr_offset += diff
    j += 1
  return ret

def revise_return_select(pcs, sorted_criteria, sorted_branches):
  revised_criteria = []
  revised_branches = [[] for count in xrange(len(sorted_branches))]

  i = 0
  for crit in sorted_criteria:
    j = 0
    while parse_select_table_boundaries[j+1] * 8 <= crit[OFFSET]:
      j += 1

    # detect and handle broken boundary
    if parse_select_table_boundaries[j+1] * 8 <= (crit[OFFSET] + crit[WIDTH]):    
      revised_criteria += revise_criteria(crit, j)
      k = 0
      for branch in sorted_branches:
        val = branch[BRANCH_VALUES][i]
        revised_branches[k] += revise_value(val, crit, j)
        k += 1

    else:
      revised_criteria.append(crit)
      k = 0
      for branch in sorted_branches:
        val = branch[BRANCH_VALUES][i]
        revised_branches[k].append(val)
        k += 1

    i += 1

  return revised_criteria, revised_branches

def do_split_criteria(crit):
  try:
    assert(crit[WIDTH] % 8 == 0)
  except AssertionError as e:
    print(e)
    unsupported("select criteria (" + str(crit[OFFSET]) + ", " + str(crit[WIDTH]) \
                              + ") not divisible by 8")

  curr_offset = crit[OFFSET]
  split_crit = []
  while curr_offset < crit[OFFSET] + crit[WIDTH]:
    split_crit.append((curr_offset, 8))
    curr_offset += 8
  return split_crit

def do_split_val(val, width):
  ret = []
  mask = 0
  bitpos = 0
  offset = 0

  while offset < width:
    mask = 0
    while bitpos < offset + 8:
      mask += 2**(width - bitpos - 1)
      bitpos += 1
    ret.append((val & mask) >> (width - bitpos))
    offset += 8
  return ret  

def split_return_select(revised_criteria, revised_branches):
  split_criteria = []
  split_branches = [[] for count in xrange(len(revised_branches))]

  i = 0
  for crit in revised_criteria:
    split_crits = do_split_criteria(crit)
    for split_crit in split_crits:
      split_criteria.append(split_crit)
    j = 0
    for branch in revised_branches:
      val = branch[i]
      split_vals = do_split_val(val, crit[WIDTH])
      for split_val in split_vals:
        split_branches[j].append(split_val)
      j += 1
    i += 1

  return split_criteria, split_branches

def get_parse_select_table(crit):
  j = 0
  while parse_select_table_boundaries[j+1] * 8 <= crit[OFFSET]:
    j += 1
  lowerbound = parse_select_table_boundaries[j]
  upperbound = parse_select_table_boundaries[j+1]
  table_name = 'tset_parse_select_%02d_%02d' % (lowerbound, upperbound - 1)
  return table_name, lowerbound * 8, upperbound * 8

def get_parse_select_tables(revised_criteria):
  parse_select_tables = []
  for crit in revised_criteria:
    parse_select_table = get_parse_select_table(crit)
    if parse_select_table not in parse_select_tables:
      parse_select_tables.append(parse_select_table)
  return parse_select_tables

def get_mparam_indices(table, crits):
  mparam_indices = []
  for crit in crits:
    curr_offset = crit[OFFSET]
    while curr_offset < crit[OFFSET] + crit[WIDTH]:
      mparam_indices.append((curr_offset - table[L_BOUND]) / 8)
      curr_offset += 8
  return mparam_indices

def get_branch_mparams(branch_mparams, branch, mparam_indices):
  for index in mparam_indices:
    branch_mparams[index] = hex(branch.pop(0)) + '&&&0xFF'
  return branch_mparams

def get_ps_action(tablename):
  return '[' + tablename.split('tset_')[1].upper() + ']'

def get_branch_action(pcs, pst_count, parse_select_tables, branch):
  action = ''
  aparams = []

  if branch[BRANCH_STATE] == 'ingress':
    action = 'set_next_action'
    aparams.append('[PROCEED]')
    aparams.append(str(pcs.pcs_id))
    return action, aparams

  # set_next_action or extract_more
  if pst_count != len(parse_select_tables) - 1:
    action = 'set_next_action'
    aparams.append(get_ps_action(parse_select_tables[pst_count + 1][T_NAME]))
    aparams.append(str(pcs.pcs_id))
  else:
    next_pcs = [child for child in pcs.children \
                       if child.parse_state.name == branch[BRANCH_STATE]][0]

    if next_pcs.hp4_bits_extracted > pcs.hp4_bits_extracted:
      action = 'extract_more'
      numbytes = int(ceil(next_pcs.hp4_bits_extracted / 8.0))
      aparams.append(str(numbytes))

    else:
      if not next_pcs.children:
        action = 'set_next_action'
        aparams.append('[PROCEED]')
        aparams.append(str(next_pcs.pcs_id))
        return action, aparams
      # another select statement in next pcs - need to rewind?
      n_first_criteria = sort_return_select(next_pcs)[0][0]
      j = 0
      while parse_select_table_boundaries[j+1] * 8 <= n_first_criteria[OFFSET]:
        j += 1
      if parse_select_table_boundaries[j] <= parse_select_tables[pst_count][L_BOUND]:
        # rewind
        action = 'extract_more'
        numbytes = int(ceil(next_pcs.hp4_bits_extracted / 8.0))
        aparams.append(str(numbytes))
1453
      else:
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
        action = 'set_next_action'
        next_ps_table = get_parse_select_table(n_first_criteria)
        aparams.append(get_ps_action(next_ps_table[T_NAME]))

    aparams.append(str(next_pcs.pcs_id))

  return action, aparams

def get_parse_select_entries(pcs,
                             parse_select_tables,
                             split_criteria,
                             split_branches_with_dests,
                             default_branch):
  commands = []
  # for each parse_select table:
  # - pop all queue items that belong to the table
  # - generate table entry
  for pst_count, table in enumerate(parse_select_tables):
    crits = []
    while (split_criteria[0][OFFSET] >= table[L_BOUND] and
           split_criteria[0][OFFSET] < table[U_BOUND]):
      crits.append(split_criteria.pop(0))
      if not split_criteria:
        break
    mparam_indices = get_mparam_indices(table, crits)
    mparams = ['0&&&0' for count in xrange((table[U_BOUND] - table[L_BOUND]) / 8)]
    for branch in split_branches_with_dests:
      branch_mparams = ['[vdev ID]', str(pcs.pcs_id)]
      branch_mparams += get_branch_mparams(list(mparams), branch[BRANCH_VALUES], mparam_indices)
      # determine action and action_params
      branch_action, branch_aparams = get_branch_action(pcs,
                                                        pst_count,
                                                        parse_select_tables,
                                                        branch)
      # priority
      branch_aparams.append(HIGHEST_PRIORITY)
      commands.append(HP4_Command(command='table_add',
                                  table=table[T_NAME],
                                  action=branch_action,
                                  match_params=branch_mparams,
                                  action_params=branch_aparams))
    # default branch
    default_mparams = ['[vdev ID]', str(pcs.pcs_id)]
    default_mparams += list(mparams)
    default_action, default_aparams = get_branch_action(pcs,
                                                        pst_count,
                                                        parse_select_tables,
                                                        default_branch)
    default_aparams.append(LOWEST_PRIORITY)
    commands.append(HP4_Command(command='table_add',
                                table=table[T_NAME],
                                action=default_action,
                                match_params=default_mparams,
                                action_params=default_aparams))

  return commands

1511 1512 1513
def gen_parse_select_entries(pcs, commands=None):
  if commands is None:
    commands = []
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
  # base cases
  if pcs.pcs_id == 0:
    return gen_parse_select_entries(pcs.children[0])
  if pcs.parse_state.return_statement[PS_RET_TYPE] == 'immediate':
    return commands

  # sort
  sorted_criteria, sorted_branches, default_branch = sort_return_select(pcs)

  # revise branch_values, select_criteria per parse_select table boundaries
  revised_criteria, revised_branches = revise_return_select(pcs,
                                                            sorted_criteria,
                                                            sorted_branches)

  split_criteria, split_branches = split_return_select(revised_criteria,
                                                       revised_branches)

  parse_select_tables = get_parse_select_tables(revised_criteria)

  dests = [branch[BRANCH_STATE] for branch in sorted_branches]

  commands += get_parse_select_entries(pcs,
                                       parse_select_tables,
                                       split_criteria,
                                       zip(split_branches, dests),
                                       default_branch)

  for child in pcs.children:
    commands = gen_parse_select_entries(child, commands)

  return commands

def process_parse_select_entries(ps_entries):
  ret = []
  for command in ps_entries:
    strbounds = command.table.split('tset_parse_select_')[1].split('_')
    lower, upper = [int(x) for x in strbounds]
    if lower > EXT_FIRST_WIDTH:
      ret.append(command)

    new_mp_val = ''
    new_mp_mask = ''
    started = False
    for mp in command.match_params[EXT_START_INDEX:]:
      val, mask = [int(x, 0) for x in mp.split('&&&')]
      if started or mask != 0:
        started = True
        valstr, maskstr = ["0x{:02x}".format(x).split('0x')[1] for x in [val, mask]]
        new_mp_val += valstr
        new_mp_mask += maskstr

    # fill out remaining bytes until we have all 40
    for j in range(upper + 1, EXT_FIRST_WIDTH):
      new_mp_val += '00'
      new_mp_mask += '00'

    new_mp = command.match_params[0:EXT_START_INDEX]
1571 1572 1573 1574 1575 1576
    if new_mp_val == '':
      assert(new_mp_mask == '')
      new_mp.append('0&&&0')
    else:
      new_mp.append('0x' + new_mp_val + '&&&0x' + new_mp_mask)

1577 1578 1579 1580 1581 1582 1583 1584
    ret.append(HP4_Command(command='table_add',
                           table=command.table,
                           action=command.action,
                           match_params=new_mp,
                           action_params=command.action_params))
    
  return ret

1585 1586 1587
def collect_ingress_pcs(pcs, ingress_pcs_list=None):
  if ingress_pcs_list is None:
    ingress_pcs_list = []
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
  if pcs.pcs_id == 0:
    return collect_ingress_pcs(pcs.children[0])

  ps = pcs.parse_state

  if ps.return_statement[PS_RET_TYPE] == 'select':
    for branch in ps.return_statement[PS_RET_BRANCHES]:
      if branch[BRANCH_STATE] == 'ingress':
        ingress_pcs_list.append(pcs)
        break
  elif ps.return_statement[PS_RET_TYPE] == 'immediate':
    if ps.return_statement[PS_RET_IMM_STATE] == 'ingress':
      ingress_pcs_list.append(pcs)
  else:
    unsupported("Unhandled ps return_statement: " + ps.return_statement[PS_RET_TYPE])

  for child in pcs.children:
    ingress_pcs_list = collect_ingress_pcs(child, ingress_pcs_list)

  return ingress_pcs_list

def get_headerset_and_maxdepth(ingress_pcs_list):
  pcs_headers = {}
  longest = 0
  for pcs in ingress_pcs_list:
    if len(pcs.header_offsets) > longest:
      longest = len(pcs.header_offsets)
  headerset = [set() for count in xrange(longest)]
  for j in range(longest):
    for pcs in ingress_pcs_list:
      if len(pcs.header_offsets) > j:
        pcs_headers = sorted(pcs.header_offsets, key=pcs.header_offsets.get)
        headerset[j].add(pcs_headers[j])

  return headerset, longest

def get_vbits(ingress_pcs_list):
  headerset, maxdepth = get_headerset_and_maxdepth(ingress_pcs_list)
  vbits = {}
  lshift = VBITS_WIDTH
  for j in range(maxdepth):
    numbits = len(headerset[j])
    lshift = lshift - numbits
    i = 1
    for header in headerset[j]:
      vbits[(j, header)] = i << lshift
      i = i << 1
  return vbits

def get_hp4_type(header):
  if header.name == 'standard_metadata':
    return 'standard_metadata'
  if header.metadata == True:
    return 'metadata'
  return 'extracted'

def get_aparam_table_ID(table):
  if len(table.match_fields) == 0:
    return '[MATCHLESS]'

  match = table.match_fields[0] # supporting only one match field
  match_type = match[MATCH_TYPE]

  if match_type.value == 'P4_MATCH_EXACT':
    field = match[MATCH_OBJECT]
    header = field.instance
    header_hp4_type = get_hp4_type(header)
    if header_hp4_type == 'standard_metadata':
      if field.name == 'ingress_port':
        return '[STDMETA_INGRESS_PORT_EXACT]'
      elif field.name == 'packet_length':
        return '[STDMETA_PACKET_LENGTH_EXACT]'
      elif field.name == 'instance_type':
        return '[STDMETA_INSTANCE_TYPE_EXACT]'
      elif field.name == 'egress_spec':
        return '[STDMETA_EGRESS_SPEC_EXACT]'
      else:
        unsupported("ERROR: Unsupported: match on stdmetadata field %s" % field.name)

    elif header_hp4_type == 'metadata':
      return '[METADATA_EXACT]'
    elif header_hp4_type == 'extracted':
      return '[EXTRACTED_EXACT]'
  elif match_type.value == 'P4_MATCH_VALID':
    return '[EXTRACTED_VALID]'
  else:
    unsupported("Not yet supported: " + match_type.value)
  
def gen_pipeline_config_entries(pcs, first_table, ingress_pcs_list, vbits):
  if pcs.pcs_id == 0:
    return gen_pipeline_config_entries(pcs.children[0],
                                       first_table,
                                       ingress_pcs_list,
                                       vbits)

  commands = []

  aparam_table_ID = get_aparam_table_ID(first_table)  

  for pcs in ingress_pcs_list:
    val = 0
    for i, header in enumerate( sorted(pcs.header_offsets,
                                       key=pcs.header_offsets.get) ):
      val = val | vbits[(i, header)]

    valstr = '0x' + '%x' % val
    commands.append(HP4_Command('table_add',
                                'tset_pipeline_config',
                                'a_set_pipeline',
                                ['[vdev ID]', str(pcs.pcs_id)],
                                [aparam_table_ID, valstr, HIGHEST_PRIORITY]))

  return commands

def process_extract_statements(pcs):
  for call in pcs.parse_state.call_sequence:
    if call[PS_CALL_TYPE] == p4_hlir.hlir.p4_parser.parse_call.extract:
      pcs.header_offsets[call[PS_CALL_H_INST].name] = pcs.p4_bits_extracted
      pcs.p4_bits_extracted += call[PS_CALL_H_INST].header_type.length * 8
      if pcs.hp4_bits_extracted < pcs.p4_bits_extracted:
        pcs.hp4_bits_extracted = pcs.p4_bits_extracted
    else:
1710
      debug()
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
      raise Exception('Unsupported parse call: %s' % call[PS_CALL_TYPE])

def process_parse_tree_clr(pcs, h):
  #print(str(pcs.pcs_id) + ' [' + pcs.parse_state.name + ']')
  process_extract_statements(pcs)

  def add_next(next_parse_state):
    next_pcs_pcs_path = list(pcs.pcs_path)
    next_pcs_pcs_path.append(pcs)
    next_pcs_ps_path = list(pcs.ps_path)
    next_pcs_ps_path.append(pcs.parse_state)
    next_pcs = PC_State(hp4_bits_extracted = pcs.hp4_bits_extracted,
                        p4_bits_extracted = pcs.p4_bits_extracted,
                        ps_path = next_pcs_ps_path,
                        pcs_path = next_pcs_pcs_path,
                        parse_state = next_parse_state)
    pcs.children.append(next_pcs)
    return next_pcs

  if pcs.parse_state.return_statement[PS_RET_TYPE] == 'select':
    for criteria in pcs.parse_state.return_statement[PS_RET_CRITERIA]:
      if isinstance(criteria, current_call):
        curr_reqmt = criteria[OFFSET] + criteria[WIDTH]
        if pcs.p4_bits_extracted + curr_reqmt > pcs.hp4_bits_extracted:
          pcs.hp4_bits_extracted += curr_reqmt
        hp4_criteria_offset = criteria[OFFSET] + pcs.p4_bits_extracted
        pcs.select_criteria.append((hp4_criteria_offset, criteria[WIDTH]))
      else:
        hdr_name, fld_name = criteria.split('.')
        hp4_criteria_offset = h.p4_fields[criteria].offset + pcs.header_offsets[hdr_name]
        pcs.select_criteria.append((hp4_criteria_offset, h.p4_fields[criteria].width))

    next_parse_states = []
    for branch in pcs.parse_state.return_statement[PS_RET_BRANCHES]:
      # e.g., ([('value', 1108152157446)], 'parse_A')
      values = []
      for value in branch[BRANCH_VALUES]:
        if value[VAL_TYPE] != 'value' and value[VAL_TYPE] != 'default':
1749
          debug()
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
          raise Exception('Unsupported branch value type: %s' % value[VAL_TYPE])
        if value[VAL_TYPE] == 'default':
          values.append('default')
        else:
          values.append(value[VAL_VALUE])
      pcs.select_values.append( values )
      if branch[BRANCH_STATE] != 'ingress':
        next_parse_state = h.p4_parse_states[branch[BRANCH_STATE]]
        if next_parse_state not in next_parse_states:
          next_parse_states.append(next_parse_state)
          next_pcs = add_next(next_parse_state)
          process_parse_tree_clr(next_pcs, h)
  elif pcs.parse_state.return_statement[PS_RET_TYPE] == 'immediate':
      next_parse_state_name = pcs.parse_state.return_statement[PS_RET_IMM_STATE]
      if next_parse_state_name != 'ingress':
        next_parse_state = h.p4_parse_states[next_parse_state_name]
        next_pcs = add_next(next_parse_state)
        process_parse_tree_clr(next_pcs, h)
  else:
1769
    debug()
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
    raise Exception('Unsupported return type: %s' % \
                    pcs.parse_state.return_statement[PS_RET_TYPE])

def consolidate_parse_tree_clr(pcs, h):
  if pcs.parse_state.return_statement[PS_RET_TYPE] == 'immediate':
    next_parse_state_name = pcs.parse_state.return_statement[PS_RET_IMM_STATE]
    if next_parse_state_name != 'ingress':
      next_pc_state = pcs.children[0]
      next_parse_state = next_pc_state.parse_state
      old_ps_name = pcs.parse_state.name
      new_ps_name = pcs.parse_state.name + '-' + next_parse_state.name
      new_ps_call_sequence = list(pcs.parse_state.call_sequence)
      new_ps_call_sequence += next_parse_state.call_sequence
      new_ps = p4_parse_state(h,
                              new_ps_name,
                              call_sequence=new_ps_call_sequence,
                              return_statement=next_parse_state.return_statement)
      hp4_bits_diff = next_pc_state.hp4_bits_extracted - pcs.hp4_bits_extracted
      pcs.hp4_bits_extracted += hp4_bits_diff
      p4_bits_diff = next_pc_state.p4_bits_extracted - pcs.p4_bits_extracted
      pcs.p4_bits_extracted += p4_bits_diff
      pcs.parse_state = new_ps
      pcs.children = list(next_pc_state.children)
      prev_ps = pcs.ps_path[-1]
      for i, branch in enumerate(prev_ps.return_statement[PS_RET_BRANCHES]):
        if branch[BRANCH_STATE] == old_ps_name:
          prev_ps.return_statement[PS_RET_BRANCHES][i] = (branch[BRANCH_VALUES], new_ps_name)
  for child in pcs.children:
    consolidate_parse_tree_clr(child, h)

1800 1801 1802
def collect_header_offsets(pcs, header_offsets=None):
  if header_offsets is None:
    header_offsets = {}
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
  for header in pcs.header_offsets:
    if header in header_offsets:
      if pcs.header_offsets[header] != header_offsets[header]:
        unsupported("Unsupported: %s has multiple potential offsets; %db and %db" \
                    % (header, pcs.header_offsets[header], header_offsets[header]))
  header_offsets.update(pcs.header_offsets)
  for child in pcs.children:
    header_offsets = collect_header_offsets(child, header_offsets)

  return header_offsets

def collect_field_offsets(header_offsets, header_instances):
  field_offsets = {}
  for header in header_offsets:
1817 1818 1819 1820 1821
    try:
      hinst = header_instances[header]
    except KeyError as e:
      print(e)
      debug()
1822 1823 1824 1825 1826 1827 1828
    for field in hinst.fields:
      field_offsets[header + '.' + field.name] = field.offset + header_offsets[header]

  return field_offsets

def get_table_from_cs(control_statement):
    if type(control_statement) is p4_table:
1829
      return control_statement
1830
    elif type(control_statement) is tuple:
1831 1832
      return control_statement[0]
    else:
1833
      unsupported("Error (get_table_from_cs): unsupported control statement type: " \
1834
            + str(type(control_statement)))
1835

1836
def walk_control_block(control_block, table):
1837 1838
    for control_statement in control_block:
      cs_idx = control_block.index(control_statement)
1839
      if type(control_statement) is p4_table:
1840 1841
        # apply_table_call
        if control_statement == table:
1842 1843
          if cs_idx == len(control_block) - 1:
            return True, None
1844 1845
          return True, get_table_from_cs(control_block[cs_idx + 1])
      elif type(control_statement) is tuple:
1846 1847
        # apply_and_select_block
        if control_statement[0] == table:
1848 1849
          if cs_idx == len(control_block) - 1:
            return True, None
1850
          return True, get_table_from_cs(control_block[cs_idx + 1])
1851 1852
        else:
          for case in control_statement[1]:
1853
            found, next_table = walk_control_block(case[1], table)
1854 1855 1856 1857
            if found:
              if next_table != None:
                return True, next_table
              elif cs_idx < len(control_block) - 1:
1858
                return True, get_table_from_cs(control_block[cs_idx + 1])
1859 1860
              else:
                return True, None
1861
      else:
1862 1863
        unsupported("Error: unsupported call_sequence entry type: " + str(type(entry)))

1864
    return False, None
1865

1866 1867
def gen_tmiss_entries(tables, table_to_trep, ingress, numprimitives):
  commands = []
1868

1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
  for table_name in tables:

    table = tables[table_name]
    trep = table_to_trep[table]
    tname = trep.name
    stage = trep.stage # int
    aname = 'init_program_state'
    mparams = ['[vdev ID]']
    if 'matchless' not in tname:
      mparams.append('0&&&0')
1879
                 
1880 1881 1882 1883 1884 1885
    # identify next_table so we can look up stage for aparams[0]
    #   aparams[0]: 'next_stage' parameter in finish_action (stages.p4/p4t)
    if 'miss' in table.next_:
      next_table = table.next_['miss']
    else:
      found, next_table = walk_control_block(ingress.call_sequence, table)
1886

1887 1888 1889 1890 1891 1892
    if next_table == None:
      next_stage = '0'
      next_table_type = '0'
    else:
      next_stage = str(table_to_trep[next_table].stage)
      next_table_type = table_to_trep[next_table].table_type()
1893

1894 1895 1896 1897
    aparams = ['0', # action_ID
               '0', # match_ID
               next_stage,
               next_table_type]
1898
      
1899 1900 1901 1902
    # zeros for remaining type / subtype parameters of init_program_state
    for i in range(numprimitives):
      aparams.append('0')
      aparams.append('0')
1903

1904 1905
    if 'matchless' not in tname:
      aparams.append(str(LOWEST_PRIORITY))
1906

1907 1908 1909 1910 1911
    commands.append(HP4_Command(command="table_add",
                                table=tname,
                                action=aname,
                                match_params=mparams,
                                action_params=aparams))
1912

1913 1914 1915 1916 1917
  return commands

# gen_t_checksum_entries(h.calculated_fields)
def gen_t_checksum_entries(calculated_fields, p4_field_list_calculations,
                           field_offsets, vbits):
1918
    """ detect and handle ipv4 checksum """
1919 1920
    commands = []