code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
# dump header info
# file_timestamp = time.strftime("%a, %d %b %Y %H:%M:%S (UTC/GMT)", time.gmtime())
# print >>file, " ".join(["$date", file_timestamp, "$end"])
self.internal_names = _VerilogSanitizer('_vcd_tmp_')
for wire in self.wires_to_track:
self.internal_names.make_valid_string(wire.name)
def _varname(wireName):
return self.internal_names[wireName]
print(' '.join(['$timescale', '1ns', '$end']), file=file)
print(' '.join(['$scope', 'module logic', '$end']), file=file)
def print_trace_strs(time):
for wn in sorted(self.trace, key=_trace_sort_key):
print(' '.join([str(bin(self.trace[wn][time]))[1:], _varname(wn)]), file=file)
# dump variables
if include_clock:
print(' '.join(['$var', 'wire', '1', 'clk', 'clk', '$end']), file=file)
for wn in sorted(self.trace, key=_trace_sort_key):
print(' '.join(['$var', 'wire', str(self._wires[wn].bitwidth),
_varname(wn), _varname(wn), '$end']), file=file)
print(' '.join(['$upscope', '$end']), file=file)
print(' '.join(['$enddefinitions', '$end']), file=file)
print(' '.join(['$dumpvars']), file=file)
print_trace_strs(0)
print(' '.join(['$end']), file=file)
# dump values
endtime = max([len(self.trace[w]) for w in self.trace])
for timestamp in range(endtime):
print(''.join(['#', str(timestamp*10)]), file=file)
print_trace_strs(timestamp)
if include_clock:
print('b1 clk', file=file)
print('', file=file)
print(''.join(['#', str(timestamp*10+5)]), file=file)
print('b0 clk', file=file)
print('', file=file)
print(''.join(['#', str(endtime*10)]), file=file)
file.flush()
|
def print_vcd(self, file=sys.stdout, include_clock=False)
|
Print the trace out as a VCD File for use in other tools.
:param file: file to open and output vcd dump to.
:param include_clock: boolean specifying if the implicit clk should be included.
Dumps the current trace to file as a "value change dump" file. The file parameter
defaults to _stdout_ and the include_clock defaults to True.
Examples ::
sim_trace.print_vcd()
sim_trace.print_vcd("my_waveform.vcd", include_clock=False)
| 3.22526 | 3.300533 | 0.977194 |
if _currently_in_ipython():
from IPython.display import display, HTML, Javascript # pylint: disable=import-error
from .inputoutput import trace_to_html
htmlstring = trace_to_html(self, trace_list=trace_list, sortkey=_trace_sort_key)
html_elem = HTML(htmlstring)
display(html_elem)
# print(htmlstring)
js_stuff =
display(Javascript(js_stuff))
else:
self.render_trace_to_text(
trace_list=trace_list, file=file, render_cls=render_cls,
symbol_len=symbol_len, segment_size=segment_size,
segment_delim=segment_delim, extra_line=extra_line)
|
def render_trace(
self, trace_list=None, file=sys.stdout, render_cls=default_renderer(),
symbol_len=5, segment_size=5, segment_delim=' ', extra_line=True)
|
Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output in the specified order.
:param file: The place to write output, default to stdout.
:param render_cls: A class that translates traces into output bytes.
:param symbol_len: The "length" of each rendered cycle in characters.
:param segment_size: Traces are broken in the segments of this number of cycles.
:param segment_delim: The character to be output between segments.
:param extra_line: A Boolean to determin if we should print a blank line between signals.
The resulting output can be viewed directly on the terminal or looked
at with "more" or "less -R" which both should handle the ASCII escape
sequences used in rendering. render_trace takes the following optional
arguments.
| 2.912709 | 3.111971 | 0.935969 |
if len(selects) != len(vals):
raise pyrtl.PyrtlError("Number of select and val signals must match")
if len(vals) == 0:
raise pyrtl.PyrtlError("Must have a signal to mux")
if len(vals) == 1:
return vals[0]
else:
half = len(vals) // 2
return pyrtl.select(pyrtl.rtl_any(*selects[:half]),
truecase=prioritized_mux(selects[:half], vals[:half]),
falsecase=prioritized_mux(selects[half:], vals[half:]))
|
def prioritized_mux(selects, vals)
|
Returns the value in the first wire for which its select bit is 1
:param [WireVector] selects: a list of WireVectors signaling whether
a wire should be chosen
:param [WireVector] vals: values to return when the corresponding select
value is 1
:return: WireVector
If none of the items are high, the last val is returned
| 2.789579 | 2.962214 | 0.941721 |
import numbers
max_val = 2**len(sel) - 1
if SparseDefault in vals:
default_val = vals[SparseDefault]
del vals[SparseDefault]
for i in range(max_val + 1):
if i not in vals:
vals[i] = default_val
for key in vals.keys():
if not isinstance(key, numbers.Integral):
raise pyrtl.PyrtlError("value %s nust be either an integer or 'default'" % str(key))
if key < 0 or key > max_val:
raise pyrtl.PyrtlError("value %s is out of range of the sel wire" % str(key))
return _sparse_mux(sel, vals)
|
def sparse_mux(sel, vals)
|
Mux that avoids instantiating unnecessary mux_2s when possible.
:param WireVector sel: Select wire, determines what is selected on a given cycle
:param dictionary vals: dictionary of values at mux inputs (of type `{int:WireVector}`)
:return: WireVector that signifies the change
This mux supports not having a full specification. Indices that are not
specified are treated as don't-cares
It also supports a specified default value, SparseDefault
| 3.11877 | 2.878913 | 1.083315 |
items = list(vals.values())
if len(vals) <= 1:
if len(vals) == 0:
raise pyrtl.PyrtlError("Needs at least one parameter for val")
return items[0]
if len(sel) == 1:
try:
false_result = vals[0]
true_result = vals[1]
except KeyError:
raise pyrtl.PyrtlError("Failed to retrieve values for smartmux. "
"The length of sel might be wrong")
else:
half = 2**(len(sel) - 1)
first_dict = {indx: wire for indx, wire in vals.items() if indx < half}
second_dict = {indx-half: wire for indx, wire in vals.items() if indx >= half}
if not len(first_dict):
return sparse_mux(sel[:-1], second_dict)
if not len(second_dict):
return sparse_mux(sel[:-1], first_dict)
false_result = sparse_mux(sel[:-1], first_dict)
true_result = sparse_mux(sel[:-1], second_dict)
if _is_equivelent(false_result, true_result):
return true_result
return pyrtl.select(sel[-1], falsecase=false_result, truecase=true_result)
|
def _sparse_mux(sel, vals)
|
Mux that avoids instantiating unnecessary mux_2s when possible.
:param WireVector sel: Select wire, determines what is selected on a given cycle
:param {int: WireVector} vals: dictionary to store the values that are
:return: Wirevector that signifies the change
This mux supports not having a full specification. indices that are not
specified are treated as Don't Cares
| 3.10014 | 3.125975 | 0.991735 |
if len(select) == 1:
return _demux_2(select)
wires = demux(select[:-1])
sel = select[-1]
not_select = ~sel
zero_wires = tuple(not_select & w for w in wires)
one_wires = tuple(sel & w for w in wires)
return zero_wires + one_wires
|
def demux(select)
|
Demultiplexes a wire of arbitrary bitwidth
:param WireVector select: indicates which wire to set on
:return (WireVector, ...): a tuple of wires corresponding to each demultiplexed wire
| 3.426206 | 3.693017 | 0.927752 |
self._check_finalized()
self._final = True
for dest_w, values in self.dest_instrs_info.items():
mux_vals = dict(zip(self.instructions, values))
dest_w <<= sparse_mux(self.signal_wire, mux_vals)
|
def finalize(self)
|
Connects the wires.
| 12.01466 | 10.288876 | 1.167733 |
if "_bitmask" not in self.__dict__:
self._bitmask = (1 << len(self)) - 1
return self._bitmask
|
def bitmask(self)
|
A property holding a bitmask of the same length as this WireVector.
Specifically it is an integer with a number of bits set to 1 equal to the
bitwidth of the WireVector.
It is often times useful to "mask" an integer such that it fits in the
the number of bits of a WireVector. As a convenience for this, the
`bitmask` property is provided. As an example, if there was a 3-bit
WireVector `a`, a call to `a.bitmask()` should return 0b111 or 0x7.
| 3.403576 | 4.250448 | 0.800757 |
def wrapper(next_):
def log_dispatch(action):
print('Dispatch Action:', action)
return next_(action)
return log_dispatch
return wrapper
|
def log_middleware(store)
|
log all actions to console as they are dispatched
| 4.422017 | 3.560821 | 1.241853 |
if isinstance(w, WireVector):
w = w.name
try:
vals = self.tracer.trace[w]
except KeyError:
pass
else:
if not vals:
raise PyrtlError('No context available. Please run a simulation step')
return vals[-1]
raise PyrtlError('CompiledSimulation does not support inspecting internal WireVectors')
|
def inspect(self, w)
|
Get the latest value of the wire given, if possible.
| 8.051484 | 6.750544 | 1.192716 |
steps = len(inputs)
# create i/o arrays of the appropriate length
ibuf_type = ctypes.c_uint64*(steps*self._ibufsz)
obuf_type = ctypes.c_uint64*(steps*self._obufsz)
ibuf = ibuf_type()
obuf = obuf_type()
# these array will be passed to _crun
self._crun.argtypes = [ctypes.c_uint64, ibuf_type, obuf_type]
# build the input array
for n, inmap in enumerate(inputs):
for w in inmap:
if isinstance(w, WireVector):
name = w.name
else:
name = w
start, count = self._inputpos[name]
start += n*self._ibufsz
val = inmap[w]
if val >= 1 << self._inputbw[name]:
raise PyrtlError(
'Wire {} has value {} which cannot be represented '
'using its bitwidth'.format(name, val))
# pack input
for pos in range(start, start+count):
ibuf[pos] = val & ((1 << 64)-1)
val >>= 64
# run the simulation
self._crun(steps, ibuf, obuf)
# save traced wires
for name in self.tracer.trace:
rname = self._probe_mapping.get(name, name)
if rname in self._outputpos:
start, count = self._outputpos[rname]
buf, sz = obuf, self._obufsz
elif rname in self._inputpos:
start, count = self._inputpos[rname]
buf, sz = ibuf, self._ibufsz
else:
raise PyrtlInternalError('Untraceable wire in tracer')
res = []
for n in range(steps):
val = 0
# unpack output
for pos in reversed(range(start, start+count)):
val <<= 64
val |= buf[pos]
res.append(val)
start += sz
self.tracer.trace[name].extend(res)
|
def run(self, inputs)
|
Run many steps of the simulation.
The argument is a list of input mappings for each step,
and its length is the number of steps to be executed.
| 3.180192 | 3.088973 | 1.029531 |
if isinstance(wv, (Input, Output)):
return True
for net in self.block.logic:
if net.op == 'w' and net.args[0].name == wv.name and isinstance(net.dests[0], Output):
self._probe_mapping[wv.name] = net.dests[0].name
return True
return False
|
def _traceable(self, wv)
|
Check if wv is able to be traced
If it is traceable due to a probe, record that probe in _probe_mapping.
| 5.057606 | 3.914904 | 1.291885 |
self._probe_mapping = {}
wvs = {wv for wv in self.tracer.wires_to_track if self._traceable(wv)}
self.tracer.wires_to_track = wvs
self.tracer._wires = {wv.name: wv for wv in wvs}
self.tracer.trace.__init__(wvs)
|
def _remove_untraceable(self)
|
Remove from the tracer those wires that CompiledSimulation cannot track.
Create _probe_mapping for wires only traceable via probes.
| 5.966943 | 3.784624 | 1.576628 |
self._dir = tempfile.mkdtemp()
with open(path.join(self._dir, 'pyrtlsim.c'), 'w') as f:
self._create_code(lambda s: f.write(s+'\n'))
if platform.system() == 'Darwin':
shared = '-dynamiclib'
else:
shared = '-shared'
subprocess.check_call([
'gcc', '-O0', '-march=native', '-std=c99', '-m64',
shared, '-fPIC',
path.join(self._dir, 'pyrtlsim.c'), '-o', path.join(self._dir, 'pyrtlsim.so'),
], shell=(platform.system() == 'Windows'))
self._dll = ctypes.CDLL(path.join(self._dir, 'pyrtlsim.so'))
self._crun = self._dll.sim_run_all
self._crun.restype = None
|
def _create_dll(self)
|
Create a dynamically-linked library implementing the simulation logic.
| 2.645724 | 2.522395 | 1.048893 |
pieces = []
for n in range(self._limbs(w)):
pieces.append(hex(v & ((1 << 64)-1)))
v >>= 64
return ','.join(pieces).join('{}')
|
def _makeini(self, w, v)
|
C initializer string for a wire with a given value.
| 8.549685 | 7.182443 | 1.190359 |
if (res is None or dest.bitwidth < res) and 0 < (dest.bitwidth - 64*pos) < 64:
return '&0x{:X}'.format((1 << (dest.bitwidth % 64))-1)
return ''
|
def _makemask(self, dest, res, pos)
|
Create a bitmask.
The value being masked is of width `res`.
Limb number `pos` of `dest` is being assigned to.
| 6.911488 | 6.887125 | 1.003537 |
return '{vn}[{n}]'.format(vn=self.varname[arg], n=n) if arg.bitwidth > 64*n else '0'
|
def _getarglimb(self, arg, n)
|
Get the nth limb of the given wire.
Returns '0' when the wire does not have sufficient limbs.
| 12.462976 | 12.479133 | 0.998705 |
return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum()))
|
def _clean_name(self, prefix, obj)
|
Create a C variable name with the given prefix based on the name of obj.
| 5.698232 | 4.735394 | 1.203328 |
triv_result = _trivial_mult(A, B)
if triv_result is not None:
return triv_result, pyrtl.Const(1, 1)
alen = len(A)
blen = len(B)
areg = pyrtl.Register(alen)
breg = pyrtl.Register(blen + alen)
accum = pyrtl.Register(blen + alen)
done = (areg == 0) # Multiplication is finished when a becomes 0
# During multiplication, shift a right every cycle, b left every cycle
with pyrtl.conditional_assignment:
with start: # initialization
areg.next |= A
breg.next |= B
accum.next |= 0
with ~done: # don't run when there's no work to do
areg.next |= areg[1:] # right shift
breg.next |= pyrtl.concat(breg, pyrtl.Const(0, 1)) # left shift
a_0_val = areg[0].sign_extended(len(accum))
# adds to accum only when LSB of areg is 1
accum.next |= accum + (a_0_val & breg)
return accum, done
|
def simple_mult(A, B, start)
|
Builds a slow, small multiplier using the simple shift-and-add algorithm.
Requires very small area (it uses only a single adder), but has long delay
(worst case is len(A) cycles). start is a one-bit input to indicate inputs are ready.
done is a one-bit output signal raised when the multiplication is finished.
:param WireVector A, B: two input wires for the multiplication
:returns: Register containing the product; the "done" signal
| 4.633608 | 4.901144 | 0.945414 |
if len(B) == 1:
A, B = B, A # so that we can reuse the code below :)
if len(A) == 1:
a_vals = A.sign_extended(len(B))
# keep the wirevector len consistent
return pyrtl.concat_list([a_vals & B, pyrtl.Const(0)])
|
def _trivial_mult(A, B)
|
turns a multiplication into an And gate if one of the
wires is a bitwidth of 1
:param A:
:param B:
:return:
| 10.520498 | 10.552095 | 0.997006 |
alen = len(A)
blen = len(B)
areg = pyrtl.Register(alen)
breg = pyrtl.Register(alen + blen)
accum = pyrtl.Register(alen + blen)
done = (areg == 0) # Multiplication is finished when a becomes 0
if (shifts > alen) or (shifts > blen):
raise pyrtl.PyrtlError("shift is larger than one or both of the parameters A or B,"
"please choose smaller shift")
# During multiplication, shift a right every cycle 'shift' times,
# shift b left every cycle 'shift' times
with pyrtl.conditional_assignment:
with start: # initialization
areg.next |= A
breg.next |= B
accum.next |= 0
with ~done: # don't run when there's no work to do
# "Multiply" shifted breg by LSB of areg by cond. adding
areg.next |= libutils._shifted_reg_next(areg, 'r', shifts) # right shift
breg.next |= libutils._shifted_reg_next(breg, 'l', shifts) # left shift
accum.next |= accum + _one_cycle_mult(areg, breg, shifts)
return accum, done
|
def complex_mult(A, B, shifts, start)
|
Generate shift-and-add multiplier that can shift and add multiple bits per clock cycle.
Uses substantially more space than `simple_mult()` but is much faster.
:param WireVector A, B: two input wires for the multiplication
:param int shifts: number of spaces Register is to be shifted per clk cycle
(cannot be greater than the length of `A` or `B`)
:param bool start: start signal
:returns: Register containing the product; the "done" signal
| 5.530407 | 5.221838 | 1.059092 |
if rem_bits == 0:
return sum_sf
else:
a_curr_val = areg[curr_bit].sign_extended(len(breg))
if curr_bit == 0: # if no shift
return(_one_cycle_mult(areg, breg, rem_bits-1, # areg, breg, rem_bits
sum_sf + (a_curr_val & breg), # sum_sf
curr_bit+1)) # curr_bit
else:
return _one_cycle_mult(
areg, breg, rem_bits-1, # areg, breg, rem_bits
sum_sf + (a_curr_val &
pyrtl.concat(breg, pyrtl.Const(0, curr_bit))), # sum_sf
curr_bit+1 # curr_bit
)
|
def _one_cycle_mult(areg, breg, rem_bits, sum_sf=0, curr_bit=0)
|
returns a WireVector sum of rem_bits multiplies (in one clock cycle)
note: this method requires a lot of area because of the indexing in the else statement
| 2.79941 | 2.717617 | 1.030098 |
triv_res = _trivial_mult(A, B)
if triv_res is not None:
return triv_res
bits_length = (len(A) + len(B))
# create a list of lists, with slots for all the weights (bit-positions)
bits = [[] for weight in range(bits_length)]
# AND every bit of A with every bit of B (N^2 results) and store by "weight" (bit-position)
for i, a in enumerate(A):
for j, b in enumerate(B):
bits[i + j].append(a & b)
return reducer(bits, bits_length, adder_func)
|
def tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone)
|
Build an fast unclocked multiplier for inputs A and B using a Wallace or Dada Tree.
:param WireVector A, B: two input wires for the multiplication
:param function reducer: Reduce the tree using either a Dada recuder or a Wallace reducer
determines whether it is a Wallace tree multiplier or a Dada tree multiplier
:param function adder_func: an adder function that will be used to do the last addition
:return WireVector: The multiplied result
Delay is order logN, while area is order N^2.
| 5.123104 | 5.185442 | 0.987978 |
if len(A) == 1 or len(B) == 1:
raise pyrtl.PyrtlError("sign bit required, one or both wires too small")
aneg, bneg = A[-1], B[-1]
a = _twos_comp_conditional(A, aneg)
b = _twos_comp_conditional(B, bneg)
res = tree_multiplier(a[:-1], b[:-1]).zero_extended(len(A) + len(B))
return _twos_comp_conditional(res, aneg ^ bneg)
|
def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone)
|
Same as tree_multiplier, but uses two's-complement signed integers
| 4.945651 | 4.542684 | 1.088707 |
if bw is None:
bw = len(orig_wire)
new_wire = pyrtl.WireVector(bw)
with pyrtl.conditional_assignment:
with sign_bit:
new_wire |= ~orig_wire + 1
with pyrtl.otherwise:
new_wire |= orig_wire
return new_wire
|
def _twos_comp_conditional(orig_wire, sign_bit, bw=None)
|
Returns two's complement of wire (using bitwidth bw) if sign_bit == 1
| 2.5705 | 2.525033 | 1.018007 |
# TODO: Specify the length of the result wirevector
return generalized_fma(((mult_A, mult_B),), (add,), signed, reducer, adder_func)
|
def fused_multiply_adder(mult_A, mult_B, add, signed=False, reducer=adders.wallace_reducer,
adder_func=adders.kogge_stone)
|
Generate efficient hardware for a*b+c.
Multiplies two wirevectors together and adds a third wirevector to the
multiplication result, all in
one step. By doing it this way (instead of separately), one reduces both
the area and the timing delay of the circuit.
:param Bool signed: Currently not supported (will be added in the future)
The default will likely be changed to True, so if you want the smallest
set of wires in the future, specify this as False
:param reducer: (advanced) The tree reducer to use
:param adder_func: (advanced) The adder to use to add the two results at the end
:return WireVector: The result WireVector
| 14.020748 | 11.813161 | 1.186875 |
# first need to figure out the max length
if mult_pairs: # Need to deal with the case when it is empty
mult_max = max(len(m[0]) + len(m[1]) - 1 for m in mult_pairs)
else:
mult_max = 0
if add_wires:
add_max = max(len(x) for x in add_wires)
else:
add_max = 0
longest_wire_len = max(add_max, mult_max)
bits = [[] for i in range(longest_wire_len)]
for mult_a, mult_b in mult_pairs:
for i, a in enumerate(mult_a):
for j, b in enumerate(mult_b):
bits[i + j].append(a & b)
for wire in add_wires:
for bit_loc, bit in enumerate(wire):
bits[bit_loc].append(bit)
import math
result_bitwidth = (longest_wire_len +
int(math.ceil(math.log(len(add_wires) + len(mult_pairs), 2))))
return reducer(bits, result_bitwidth, adder_func)
|
def generalized_fma(mult_pairs, add_wires, signed=False, reducer=adders.wallace_reducer,
adder_func=adders.kogge_stone)
|
Generated an opimitized fused multiply adder.
A generalized FMA unit that multiplies each pair of numbers in mult_pairs,
then adds the resulting numbers and and the values of the add wires all
together to form an answer. This is faster than separate adders and
multipliers because you avoid unnecessary adder structures for intermediate
representations.
:param mult_pairs: Either None (if there are no pairs to multiply) or
a list of pairs of wires to multiply:
[(mult1_1, mult1_2), ...]
:param add_wires: Either None (if there are no individual
items to add other than the mult_pairs), or a list of wires for adding on
top of the result of the pair multiplication.
:param Bool signed: Currently not supported (will be added in the future)
The default will likely be changed to True, so if you want the smallest
set of wires in the future, specify this as False
:param reducer: (advanced) The tree reducer to use
:param adder_func: (advanced) The adder to use to add the two results at the end
:return WireVector: The result WireVector
| 2.609901 | 2.639169 | 0.98891 |
block = working_block(block)
with set_working_block(block, True):
for net in block.logic.copy():
keep_orig_net = transform_func(net, **kwargs)
if not keep_orig_net:
block.logic.remove(net)
|
def net_transform(transform_func, block=None, **kwargs)
|
Maps nets to new sets of nets according to a custom function
:param transform_func:
Function signature: func(orig_net (logicnet)) -> keep_orig_net (bool)
:return:
| 5.862608 | 4.157319 | 1.41019 |
@functools.wraps(transform_func)
def t_res(**kwargs):
net_transform(transform_func, **kwargs)
return t_res
|
def all_nets(transform_func)
|
Decorator that wraps a net transform function
| 4.472909 | 4.028107 | 1.110425 |
block = working_block(block)
for orig_wire in block.wirevector_subset(select_types, exclude_types):
new_src, new_dst = transform_func(orig_wire)
replace_wire(orig_wire, new_src, new_dst, block)
|
def wire_transform(transform_func, select_types=WireVector,
exclude_types=(Input, Output, Register, Const), block=None)
|
Maps Wires to new sets of nets and wires according to a custom function
:param transform_func: The function you want to run on all wires
Function signature: func(orig_wire (WireVector)) -> src_wire, dst_wire
src_wire is the src for the stuff you made in the transform func
and dst_wire is the sink
to indicate that the wire has not been changed, make src_wire and dst_wire both
the original wire
:param select_types: Type or Tuple of types of WireVectors to replace
:param exclude_types: Type or Tuple of types of WireVectors to exclude from replacement
:param block: The Block to replace wires on
| 3.320051 | 3.268027 | 1.015919 |
@functools.wraps(transform_func)
def t_res(**kwargs):
wire_transform(transform_func, **kwargs)
return t_res
|
def all_wires(transform_func)
|
Decorator that wraps a wire transform function
| 4.437083 | 3.89251 | 1.139903 |
block = working_block(block)
src_nets, dst_nets = block.net_connections(include_virtual_nodes=False)
for old_w, new_w in wire_map.items():
replace_wire_fast(old_w, new_w, new_w, src_nets, dst_nets, block)
|
def replace_wires(wire_map, block=None)
|
Quickly replace all wires in a block
:param {old_wire: new_wire} wire_map: mapping of old wires to
new wires
| 5.229966 | 5.288306 | 0.988968 |
if isinstance(old_wire, Const):
return Const(old_wire.val, old_wire.bitwidth)
else:
if name is None:
return old_wire.__class__(old_wire.bitwidth, name=old_wire.name)
return old_wire.__class__(old_wire.bitwidth, name=name)
|
def clone_wire(old_wire, name=None)
|
Makes a copy of any existing wire
:param old_wire: The wire to clone
:param name: a name fo rhte new wire
Note that this function is mainly intended to be used when the
two wires are from different blocks. Making two wires with the
same name in the same block is not allowed
| 2.558842 | 2.741599 | 0.933339 |
block_in = working_block(block)
block_out, temp_wv_map = _clone_block_and_wires(block_in)
mems = {}
for net in block_in.logic:
_copy_net(block_out, net, temp_wv_map, mems)
block_out.mem_map = mems
if update_working_block:
set_working_block(block_out)
return block_out
|
def copy_block(block=None, update_working_block=True)
|
Makes a copy of an existing block
:param block: The block to clone. (defaults to the working block)
:return: The resulting block
| 4.717793 | 5.474567 | 0.861765 |
block_in.sanity_check() # make sure that everything is valid
block_out = block_in.__class__()
temp_wv_map = {}
with set_working_block(block_out, no_sanity_check=True):
for wirevector in block_in.wirevector_subset():
new_wv = clone_wire(wirevector)
temp_wv_map[wirevector] = new_wv
return block_out, temp_wv_map
|
def _clone_block_and_wires(block_in)
|
This is a generic function to copy the WireVectors for another round of
synthesis This does not split a WireVector with multiple wires.
:param block_in: The block to change
:param synth_name: a name to prepend to all new copies of a wire
:return: the resulting block and a WireVector map
| 4.592272 | 4.154227 | 1.105446 |
new_args = tuple(temp_wv_net[a_arg] for a_arg in net.args)
new_dests = tuple(temp_wv_net[a_dest] for a_dest in net.dests)
if net.op in "m@": # special stuff for copying memories
new_param = _get_new_block_mem_instance(net.op_param, mem_map, block_out)
else:
new_param = net.op_param
new_net = LogicNet(net.op, new_param, args=new_args, dests=new_dests)
block_out.add_net(new_net)
|
def _copy_net(block_out, net, temp_wv_net, mem_map)
|
This function makes a copy of all nets passed to it for synth uses
| 3.899499 | 3.827812 | 1.018728 |
memid, old_mem = op_param
if old_mem not in mem_map:
new_mem = old_mem._make_copy(block_out)
new_mem.id = old_mem.id
mem_map[old_mem] = new_mem
return memid, mem_map[old_mem]
|
def _get_new_block_mem_instance(op_param, mem_map, block_out)
|
gets the instance of the memory in the new block that is
associated with a memory in a old block
| 3.106203 | 2.984218 | 1.040877 |
if not isinstance(w, WireVector):
raise PyrtlError('Only WireVectors can be probed')
if name is None:
name = '(%s: %s)' % (probeIndexer.make_valid_string(), w.name)
print("Probe: " + name + ' ' + get_stack(w))
p = Output(name=name)
p <<= w # late assigns len from w automatically
return w
|
def probe(w, name=None)
|
Print useful information about a WireVector when in debug mode.
:param w: WireVector from which to get info
:param name: optional name for probe (defaults to an autogenerated name)
:return: original WireVector w
Probe can be inserted into a existing design easily as it returns the
original wire unmodified. For example ``y <<= x[0:3] + 4`` could be turned
into ``y <<= probe(x)[0:3] + 4`` to give visibility into both the origin of
``x`` (including the line that WireVector was originally created) and
the run-time values of ``x`` (which will be named and thus show up by
default in a trace. Likewise ``y <<= probe(x[0:3]) + 4``,
``y <<= probe(x[0:3] + 4)``, and ``probe(y) <<= x[0:3] + 4`` are all
valid uses of `probe`.
Note: `probe` does actually add a wire to the working block of w (which can
confuse various post-processing transforms such as output to verilog).
| 11.487617 | 11.148163 | 1.030449 |
block = working_block(block)
if not isinstance(w, WireVector):
raise PyrtlError('Only WireVectors can be asserted with rtl_assert')
if len(w) != 1:
raise PyrtlError('rtl_assert checks only a WireVector of bitwidth 1')
if not isinstance(exp, Exception):
raise PyrtlError('the second argument to rtl_assert must be an instance of Exception')
if isinstance(exp, KeyError):
raise PyrtlError('the second argument to rtl_assert cannot be a KeyError')
if w not in block.wirevector_set:
raise PyrtlError('assertion wire not part of the block to which it is being added')
if w not in block.wirevector_set:
raise PyrtlError('assertion not a known wirevector in the target block')
if w in block.rtl_assert_dict:
raise PyrtlInternalError('assertion conflicts with existing registered assertion')
assert_wire = Output(bitwidth=1, name=assertIndexer.make_valid_string(), block=block)
assert_wire <<= w
block.rtl_assert_dict[assert_wire] = exp
return assert_wire
|
def rtl_assert(w, exp, block=None)
|
Add hardware assertions to be checked on the RTL design.
:param w: should be a WireVector
:param Exception exp: Exception to throw when assertion fails
:param Block block: block to which the assertion should be added (default to working block)
:return: the Output wire for the assertion (can be ignored in most cases)
If at any time during execution the wire w is not `true` (i.e. asserted low)
then simulation will raise exp.
| 4.206583 | 3.922898 | 1.072315 |
for (w, exp) in sim.block.rtl_assert_dict.items():
try:
value = sim.inspect(w)
if not value:
raise exp
except KeyError:
pass
|
def check_rtl_assertions(sim)
|
Checks the values in sim to see if any registers assertions fail.
:param sim: Simulation in which to check the assertions
:return: None
| 9.681424 | 9.424674 | 1.027242 |
if isinstance(names, str):
names = names.replace(',', ' ').split()
if any('/' in name for name in names) and bitwidth is not None:
raise PyrtlError('only one of optional "/" or bitwidth parameter allowed')
if bitwidth is None:
bitwidth = 1
if isinstance(bitwidth, numbers.Integral):
bitwidth = [bitwidth]*len(names)
if len(bitwidth) != len(names):
raise ValueError('number of names ' + str(len(names))
+ ' should match number of bitwidths ' + str(len(bitwidth)))
wirelist = []
for fullname, bw in zip(names, bitwidth):
try:
name, bw = fullname.split('/')
except ValueError:
name, bw = fullname, bw
wirelist.append(wvtype(bitwidth=int(bw), name=name))
return wirelist
|
def wirevector_list(names, bitwidth=None, wvtype=WireVector)
|
Allocate and return a list of WireVectors.
:param names: Names for the WireVectors. Can be a list or single comma/space-separated string
:param bitwidth: The desired bitwidth for the resulting WireVectors.
:param WireVector wvtype: Which WireVector type to create.
:return: List of WireVectors.
Additionally, the ``names`` string can also contain an additional bitwidth specification
separated by a ``/`` in the name. This cannot be used in combination with a ``bitwidth``
value other than ``1``.
Examples: ::
wirevector_list(['name1', 'name2', 'name3'])
wirevector_list('name1, name2, name3')
wirevector_list('input1 input2 input3', bitwidth=8, wvtype=pyrtl.wire.Input)
wirevector_list('output1, output2 output3', bitwidth=3, wvtype=pyrtl.wire.Output)
wirevector_list('two_bits/2, four_bits/4, eight_bits/8')
wirevector_list(['name1', 'name2', 'name3'], bitwidth=[2, 4, 8])
| 2.756299 | 2.775508 | 0.993079 |
if isinstance(value, WireVector) or isinstance(bitwidth, WireVector):
raise PyrtlError('inputs must not be wirevectors')
if bitwidth < 1:
raise PyrtlError('bitwidth must be a positive integer')
neg_mask = 1 << (bitwidth - 1)
neg_part = value & neg_mask
pos_mask = neg_mask - 1
pos_part = value & pos_mask
return pos_part - neg_part
|
def val_to_signed_integer(value, bitwidth)
|
Return value as intrepreted as a signed integer under twos complement.
:param value: a python integer holding the value to convert
:param bitwidth: the length of the integer in bits to assume for conversion
Given an unsigned integer (not a wirevector!) covert that to a signed
integer. This is useful for printing and interpreting values which are
negative numbers in twos complement. ::
val_to_signed_integer(0xff, 8) == -1
| 2.944022 | 3.201633 | 0.919537 |
type = format[0]
bitwidth = int(format[1:].split('/')[0])
bitmask = (1 << bitwidth)-1
if type == 's':
rval = int(data) & bitmask
elif type == 'x':
rval = int(data, 16)
elif type == 'b':
rval = int(data, 2)
elif type == 'u':
rval = int(data)
if rval < 0:
raise PyrtlError('unsigned format requested, but negative value provided')
elif type == 'e':
enumname = format.split('/')[1]
enum_inst_list = [e for e in enum_set if e.__name__ == enumname]
if len(enum_inst_list) == 0:
raise PyrtlError('enum "{}" not found in passed enum_set "{}"'
.format(enumname, enum_set))
rval = getattr(enum_inst_list[0], data).value
else:
raise PyrtlError('unknown format type {}'.format(format))
return rval
|
def formatted_str_to_val(data, format, enum_set=None)
|
Return an unsigned integer representation of the data given format specified.
:param data: a string holding the value to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable of enums which are used as part of the converstion process
Given a string (not a wirevector!) covert that to an unsigned integer ready for input
to the simulation enviornment. This helps deal with signed/unsigned numbers (simulation
assumes the values have been converted via two's complement already), but it also takes
hex, binary, and enum types as inputs. It is easiest to see how it works with some
examples. ::
formatted_str_to_val('2', 's3') == 2 # 0b010
formatted_str_to_val('-1', 's3') == 7 # 0b111
formatted_str_to_val('101', 'b3') == 5
formatted_str_to_val('5', 'u3') == 5
formatted_str_to_val('-3', 's3') == 5
formatted_str_to_val('a', 'x3') == 10
class Ctl(Enum):
ADD = 5
SUB = 12
formatted_str_to_val('ADD', 'e3/Ctl', [Ctl]) == 5
formatted_str_to_val('SUB', 'e3/Ctl', [Ctl]) == 12
| 2.619535 | 2.459052 | 1.065262 |
type = format[0]
bitwidth = int(format[1:].split('/')[0])
bitmask = (1 << bitwidth)-1
if type == 's':
rval = str(val_to_signed_integer(val, bitwidth))
elif type == 'x':
rval = hex(val)[2:] # cuts off '0x' at the start
elif type == 'b':
rval = bin(val)[2:] # cuts off '0b' at the start
elif type == 'u':
rval = str(int(val)) # nothing fancy
elif type == 'e':
enumname = format.split('/')[1]
enum_inst_list = [e for e in enum_set if e.__name__ == enumname]
if len(enum_inst_list) == 0:
raise PyrtlError('enum "{}" not found in passed enum_set "{}"'
.format(enumname, enum_set))
rval = enum_inst_list[0](val).name
else:
raise PyrtlError('unknown format type {}'.format(format))
return rval
|
def val_to_formatted_str(val, format, enum_set=None)
|
Return a string representation of the value given format specified.
:param val: a string holding an unsigned integer to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable of enums which are used as part of the converstion process
Given an unsigned integer (not a wirevector!) covert that to a strong ready for output
to a human to interpret. This helps deal with signed/unsigned numbers (simulation
operates on values that have been converted via two's complement), but it also generates
hex, binary, and enum types as outputs. It is easiest to see how it works with some
examples. ::
formatted_str_to_val(2, 's3') == '2'
formatted_str_to_val(7, 's3') == '-1'
formatted_str_to_val(5, 'b3') == '101'
formatted_str_to_val(5, 'u3') == '5'
formatted_str_to_val(5, 's3') == '-3'
formatted_str_to_val(10, 'x3') == 'a'
class Ctl(Enum):
ADD = 5
SUB = 12
formatted_str_to_val('ADD', 'e3/Ctl', [Ctl]) == 5
formatted_str_to_val('SUB', 'e3/Ctl', [Ctl]) == 12
| 2.718275 | 2.52032 | 1.078543 |
if block is None:
block = self.block
cur_nets = len(block.logic)
net_goal = self.prev_nets * (1 - percent_diff) - abs_diff
less_nets = (cur_nets <= net_goal)
self.prev_nets = cur_nets
return less_nets
|
def shrank(self, block=None, percent_diff=0, abs_diff=1)
|
Returns whether a block has less nets than before
:param Block block: block to check (if changed)
:param Number percent_diff: percentage difference threshold
:param int abs_diff: absolute difference threshold
:return: boolean
This function checks whether the change in the number of
nets is greater than the percentage and absolute difference
thresholds.
| 4.841061 | 4.046083 | 1.196481 |
a, b = libutils.match_bitwidth(a, b)
prop_orig = a ^ b
prop_bits = [i for i in prop_orig]
gen_bits = [i for i in a & b]
prop_dist = 1
# creation of the carry calculation
while prop_dist < len(a):
for i in reversed(range(prop_dist, len(a))):
prop_old = prop_bits[i]
gen_bits[i] = gen_bits[i] | (prop_old & gen_bits[i - prop_dist])
if i >= prop_dist * 2: # to prevent creating unnecessary nets and wires
prop_bits[i] = prop_old & prop_bits[i - prop_dist]
prop_dist *= 2
# assembling the result of the addition
# preparing the cin (and conveniently shifting the gen bits)
gen_bits.insert(0, pyrtl.as_wires(cin))
return pyrtl.concat_list(gen_bits) ^ prop_orig
|
def kogge_stone(a, b, cin=0)
|
Creates a Kogge-Stone adder given two inputs
:param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match)
:param cin: An optimal carry in WireVector or value
:return: a Wirevector representing the output of the adder
The Kogge-Stone adder is a fast tree-based adder with O(log(n))
propagation delay, useful for performance critical designs. However,
it has O(n log(n)) area usage, and large fan out.
| 5.69757 | 5.642007 | 1.009848 |
a, b, c = libutils.match_bitwidth(a, b, c)
partial_sum = a ^ b ^ c
shift_carry = (a | b) & (a | c) & (b | c)
return pyrtl.concat(final_adder(partial_sum[1:], shift_carry), partial_sum[0])
|
def carrysave_adder(a, b, c, final_adder=ripple_add)
|
Adds three wirevectors up in an efficient manner
:param WireVector a, b, c : the three wires to add up
:param function final_adder : The adder to use to do the final addition
:return: a wirevector with length 2 longer than the largest input
| 4.5233 | 5.009196 | 0.902999 |
a, b = pyrtl.match_bitwidth(a, b)
if len(a) <= la_unit_len:
sum, cout = _cla_adder_unit(a, b, cin)
return pyrtl.concat(cout, sum)
else:
sum, cout = _cla_adder_unit(a[0:la_unit_len], b[0:la_unit_len], cin)
msbits = cla_adder(a[la_unit_len:], b[la_unit_len:], cout, la_unit_len)
return pyrtl.concat(msbits, sum)
|
def cla_adder(a, b, cin=0, la_unit_len=4)
|
Carry Lookahead Adder
:param int la_unit_len: the length of input that every unit processes
A Carry LookAhead Adder is an adder that is faster than
a ripple carry adder, as it calculates the carry bits faster.
It is not as fast as a Kogge-Stone adder, but uses less area.
| 2.487465 | 2.671075 | 0.93126 |
gen = a & b
prop = a ^ b
assert(len(prop) == len(gen))
carry = [gen[0] | prop[0] & cin]
sum_bit = prop[0] ^ cin
cur_gen = gen[0]
cur_prop = prop[0]
for i in range(1, len(prop)):
cur_gen = gen[i] | (prop[i] & cur_gen)
cur_prop = cur_prop & prop[i]
sum_bit = pyrtl.concat(prop[i] ^ carry[i - 1], sum_bit)
carry.append(gen[i] | (prop[i] & carry[i-1]))
cout = cur_gen | (cur_prop & cin)
return sum_bit, cout
|
def _cla_adder_unit(a, b, cin)
|
Carry generation and propogation signals will be calculated only using
the inputs; their values don't rely on the sum. Every unit generates
a cout signal which is used as cin for the next unit.
| 3.265842 | 3.138087 | 1.040711 |
# verification that the wires are actually wirevectors of length 1
for wire_set in wire_array_2:
for a_wire in wire_set:
if not isinstance(a_wire, pyrtl.WireVector) or len(a_wire) != 1:
raise pyrtl.PyrtlError(
"The item {} is not a valid element for the wire_array_2. "
"It must be a WireVector of bitwidth 1".format(a_wire))
while not all(len(i) <= 2 for i in wire_array_2):
deferred = [[] for weight in range(result_bitwidth + 1)]
for i, w_array in enumerate(wire_array_2): # Start with low weights and start reducing
while len(w_array) >= 3:
cout, sum = _one_bit_add_no_concat(*(w_array.pop(0) for j in range(3)))
deferred[i].append(sum)
deferred[i + 1].append(cout)
if len(w_array) == 2:
cout, sum = half_adder(*w_array)
deferred[i].append(sum)
deferred[i + 1].append(cout)
else:
deferred[i].extend(w_array)
wire_array_2 = deferred[:result_bitwidth]
# At this stage in the multiplication we have only 2 wire vectors left.
# now we need to add them up
result = _sparse_adder(wire_array_2, final_adder)
if len(result) > result_bitwidth:
return result[:result_bitwidth]
else:
return result
|
def wallace_reducer(wire_array_2, result_bitwidth, final_adder=kogge_stone)
|
The reduction and final adding part of a dada tree. Useful for adding many numbers together
The use of single bitwidth wires is to allow for additional flexibility
:param [[Wirevector]] wire_array_2: An array of arrays of single bitwidth
wirevectors
:param int result_bitwidth: The bitwidth you want for the resulting wire.
Used to eliminate unnessary wires.
:param final_adder: The adder used for the final addition
:return: wirevector of length result_wirevector
| 3.760127 | 3.676273 | 1.02281 |
import math
# verification that the wires are actually wirevectors of length 1
for wire_set in wire_array_2:
for a_wire in wire_set:
if not isinstance(a_wire, pyrtl.WireVector) or len(a_wire) != 1:
raise pyrtl.PyrtlError(
"The item {} is not a valid element for the wire_array_2. "
"It must be a WireVector of bitwidth 1".format(a_wire))
max_width = max(len(i) for i in wire_array_2)
reduction_schedule = [2]
while reduction_schedule[-1] <= max_width:
reduction_schedule.append(int(reduction_schedule[-1]*3/2))
for reduction_target in reversed(reduction_schedule[:-1]):
deferred = [[] for weight in range(result_bitwidth + 1)]
last_round = (max(len(i) for i in wire_array_2) == 3)
for i, w_array in enumerate(wire_array_2): # Start with low weights and start reducing
while len(w_array) + len(deferred[i]) > reduction_target:
if len(w_array) + len(deferred[i]) - reduction_target >= 2:
cout, sum = _one_bit_add_no_concat(*(w_array.pop(0) for j in range(3)))
deferred[i].append(sum)
deferred[i + 1].append(cout)
else:
# if (last_round and len(deferred[i]) % 3 == 1) or (len(deferred[i]) % 3 == 2):
# if not(last_round and len(wire_array_2[i + 1]) < 3):
cout, sum = half_adder(*(w_array.pop(0) for j in range(2)))
deferred[i].append(sum)
deferred[i + 1].append(cout)
deferred[i].extend(w_array)
if len(deferred[i]) > reduction_target:
raise pyrtl.PyrtlError("Expected that the code would be able to reduce more wires")
wire_array_2 = deferred[:result_bitwidth]
# At this stage in the multiplication we have only 2 wire vectors left.
# now we need to add them up
result = _sparse_adder(wire_array_2, final_adder)
if len(result) > result_bitwidth:
return result[:result_bitwidth]
else:
return result
|
def dada_reducer(wire_array_2, result_bitwidth, final_adder=kogge_stone)
|
The reduction and final adding part of a dada tree. Useful for adding many numbers together
The use of single bitwidth wires is to allow for additional flexibility
:param [[Wirevector]] wire_array_2: An array of arrays of single bitwidth
wirevectors
:param int result_bitwidth: The bitwidth you want for the resulting wire.
Used to eliminate unnessary wires.
:param final_adder: The adder used for the final addition
:return: wirevector of length result_wirevector
| 3.593156 | 3.527281 | 1.018676 |
import math
longest_wire_len = max(len(w) for w in wires_to_add)
result_bitwidth = longest_wire_len + int(math.ceil(math.log(len(wires_to_add), 2)))
bits = [[] for i in range(longest_wire_len)]
for wire in wires_to_add:
for bit_loc, bit in enumerate(wire):
bits[bit_loc].append(bit)
return reducer(bits, result_bitwidth, final_adder)
|
def fast_group_adder(wires_to_add, reducer=wallace_reducer, final_adder=kogge_stone)
|
A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_add: an array of wirevectors to add
:param reducer: the tree reducer to use
:param final_adder: The two value adder to use at the end
:return: a wirevector with the result of the addition
The length of the result is:
max(len(w) for w in wires_to_add) + ceil(len(wires_to_add))
| 2.641247 | 2.505669 | 1.054108 |
if self.max_write_ports is not None:
self.write_ports += 1
if self.write_ports > self.max_write_ports:
raise PyrtlError('maximum number of write ports (%d) exceeded' %
self.max_write_ports)
writeport_net = LogicNet(
op='@',
op_param=(self.id, self),
args=(addr, data, enable),
dests=tuple())
working_block().add_net(writeport_net)
self.writeport_nets.append(writeport_net)
|
def _build(self, addr, data, enable)
|
Builds a write port.
| 4.593704 | 4.184493 | 1.097792 |
if len(plaintext) != self._key_len:
raise pyrtl.PyrtlError("Ciphertext length is invalid")
if len(key) != self._key_len:
raise pyrtl.PyrtlError("key length is invalid")
key_list = self._key_gen(key)
t = self._add_round_key(plaintext, key_list[0])
for round in range(1, 11):
t = self._sub_bytes(t)
t = self._shift_rows(t)
if round != 10:
t = self._mix_columns(t)
t = self._add_round_key(t, key_list[round])
return t
|
def encryption(self, plaintext, key)
|
Builds a single cycle AES Encryption circuit
:param WireVector plaintext: text to encrypt
:param WireVector key: AES key to use to encrypt
:return: a WireVector containing the ciphertext
| 2.468445 | 2.491585 | 0.990712 |
if len(key_in) != len(plaintext_in):
raise pyrtl.PyrtlError("AES key and plaintext should be the same length")
plain_text, key = (pyrtl.Register(len(plaintext_in)) for i in range(2))
key_exp_in, add_round_in = (pyrtl.WireVector(len(plaintext_in)) for i in range(2))
counter = pyrtl.Register(4, 'counter')
round = pyrtl.WireVector(4, 'round')
counter.next <<= round
sub_out = self._sub_bytes(plain_text)
shift_out = self._shift_rows(sub_out)
mix_out = self._mix_columns(shift_out)
key_out = self._key_expansion(key, counter)
add_round_out = self._add_round_key(add_round_in, key_exp_in)
with pyrtl.conditional_assignment:
with reset == 1:
round |= 0
key_exp_in |= key_in # to lower the number of cycles
plain_text.next |= add_round_out
key.next |= key_in
add_round_in |= plaintext_in
with counter == 10: # keep everything the same
round |= counter
plain_text.next |= plain_text
with pyrtl.otherwise: # running through AES
round |= counter + 1
key_exp_in |= key_out
plain_text.next |= add_round_out
key.next |= key_out
with counter == 9:
add_round_in |= shift_out
with pyrtl.otherwise:
add_round_in |= mix_out
ready = (counter == 10)
return ready, plain_text
|
def encrypt_state_m(self, plaintext_in, key_in, reset)
|
Builds a multiple cycle AES Encryption state machine circuit
:param reset: a one bit signal telling the state machine
to reset and accept the current plaintext and key
:return ready, cipher_text: ready is a one bit signal showing
that the encryption result (cipher_text) has been calculated.
| 3.161956 | 3.113726 | 1.01549 |
if len(ciphertext) != self._key_len:
raise pyrtl.PyrtlError("Ciphertext length is invalid")
if len(key) != self._key_len:
raise pyrtl.PyrtlError("key length is invalid")
key_list = self._key_gen(key)
t = self._add_round_key(ciphertext, key_list[10])
for round in range(1, 11):
t = self._inv_shift_rows(t)
t = self._sub_bytes(t, True)
t = self._add_round_key(t, key_list[10 - round])
if round != 10:
t = self._mix_columns(t, True)
return t
|
def decryption(self, ciphertext, key)
|
Builds a single cycle AES Decryption circuit
:param WireVector ciphertext: data to decrypt
:param WireVector key: AES key to use to encrypt (AES is symmetric)
:return: a WireVector containing the plaintext
| 2.728863 | 2.790158 | 0.978032 |
if len(key_in) != len(ciphertext_in):
raise pyrtl.PyrtlError("AES key and ciphertext should be the same length")
cipher_text, key = (pyrtl.Register(len(ciphertext_in)) for i in range(2))
key_exp_in, add_round_in = (pyrtl.WireVector(len(ciphertext_in)) for i in range(2))
# this is not part of the state machine as we need the keys in
# reverse order...
reversed_key_list = reversed(self._key_gen(key_exp_in))
counter = pyrtl.Register(4, 'counter')
round = pyrtl.WireVector(4)
counter.next <<= round
inv_shift = self._inv_shift_rows(cipher_text)
inv_sub = self._sub_bytes(inv_shift, True)
key_out = pyrtl.mux(round, *reversed_key_list, default=0)
add_round_out = self._add_round_key(add_round_in, key_out)
inv_mix_out = self._mix_columns(add_round_out, True)
with pyrtl.conditional_assignment:
with reset == 1:
round |= 0
key.next |= key_in
key_exp_in |= key_in # to lower the number of cycles needed
cipher_text.next |= add_round_out
add_round_in |= ciphertext_in
with counter == 10: # keep everything the same
round |= counter
cipher_text.next |= cipher_text
with pyrtl.otherwise: # running through AES
round |= counter + 1
key.next |= key
key_exp_in |= key
add_round_in |= inv_sub
with counter == 9:
cipher_text.next |= add_round_out
with pyrtl.otherwise:
cipher_text.next |= inv_mix_out
ready = (counter == 10)
return ready, cipher_text
|
def decryption_statem(self, ciphertext_in, key_in, reset)
|
Builds a multiple cycle AES Decryption state machine circuit
:param reset: a one bit signal telling the state machine
to reset and accept the current plaintext and key
:return ready, plain_text: ready is a one bit signal showing
that the decryption result (plain_text) has been calculated.
| 3.812723 | 3.717423 | 1.025636 |
import numbers
self._build_memories_if_not_exists()
a = libutils.partition_wire(word, 8)
sub = [self.sbox[a[index]] for index in (3, 0, 1, 2)]
if isinstance(key_expand_round, numbers.Number):
rcon_data = self._rcon_data[key_expand_round + 1] # int value
else:
rcon_data = self.rcon[key_expand_round + 1]
sub[3] = sub[3] ^ rcon_data
return pyrtl.concat_list(sub)
|
def _g(self, word, key_expand_round)
|
One-byte left circular rotation, substitution of each byte
| 5.461426 | 5.119675 | 1.066753 |
if not args:
return {}
first = args[0]
rest = args[1:]
out = type(first)(first)
for each in rest:
out.update(each)
return out
|
def extend(*args)
|
shallow dictionary merge
Args:
a: dict to extend
b: dict to apply to a
Returns:
new instance of the same type as _a_, with _a_ and _b_ merged.
| 3.426784 | 4.417394 | 0.775748 |
if is_edge:
if thing.name is None or thing.name.startswith('tmp'):
return ''
else:
return '/'.join([thing.name, str(len(thing))])
elif isinstance(thing, Const):
return str(thing.val)
elif isinstance(thing, WireVector):
return thing.name or '??'
else:
try:
return thing.op + str(thing.op_param or '')
except AttributeError:
raise PyrtlError('no naming rule for "%s"' % str(thing))
|
def _trivialgraph_default_namer(thing, is_edge=True)
|
Returns a "good" string for thing in printed graphs.
| 4.196565 | 4.081509 | 1.02819 |
# FIXME: make it not try to add unused wires (issue #204)
block = working_block(block)
from .wire import Register
# self.sanity_check()
graph = {}
# add all of the nodes
for net in block.logic:
graph[net] = {}
wire_src_dict, wire_dst_dict = block.net_connections()
dest_set = set(wire_src_dict.keys())
arg_set = set(wire_dst_dict.keys())
dangle_set = dest_set.symmetric_difference(arg_set)
for w in dangle_set:
graph[w] = {}
if split_state:
for w in block.wirevector_subset(Register):
graph[w] = {}
# add all of the edges
for w in (dest_set & arg_set):
try:
_from = wire_src_dict[w]
except Exception:
_from = w
if split_state and isinstance(w, Register):
_from = w
try:
_to_list = wire_dst_dict[w]
except Exception:
_to_list = [w]
for _to in _to_list:
graph[_from][_to] = w
return graph
|
def net_graph(block=None, split_state=False)
|
Return a graph representation of the current block.
Graph has the following form:
{ node1: { nodeA: edge1A, nodeB: edge1B},
node2: { nodeB: edge2B, nodeC: edge2C},
...
}
aka: edge = graph[source][dest]
Each node can be either a logic net or a WireVector (e.g. an Input, and Output, a
Const or even an undriven WireVector (which acts as a source or sink in the network)
Each edge is a WireVector or derived type (Input, Output, Register, etc.)
Note that inputs, consts, and outputs will be both "node" and "edge".
WireVectors that are not connected to any nets are not returned as part
of the graph.
| 3.876793 | 3.549998 | 1.092055 |
graph = net_graph(block)
node_index_map = {} # map node -> index
# print the list of nodes
for index, node in enumerate(graph):
print('%d %s' % (index, namer(node, is_edge=False)), file=file)
node_index_map[node] = index
print('#', file=file)
# print the list of edges
for _from in graph:
for _to in graph[_from]:
from_index = node_index_map[_from]
to_index = node_index_map[_to]
edge = graph[_from][_to]
print('%d %d %s' % (from_index, to_index, namer(edge)), file=file)
|
def output_to_trivialgraph(file, namer=_trivialgraph_default_namer, block=None)
|
Walk the block and output it in trivial graph format to the open file.
| 2.643745 | 2.583829 | 1.023189 |
if is_edge:
if (thing.name is None or
thing.name.startswith('tmp') or
isinstance(thing, (Input, Output, Const, Register))):
name = ''
else:
name = '/'.join([thing.name, str(len(thing))])
penwidth = 2 if len(thing) == 1 else 6
arrowhead = 'none' if is_to_splitmerge else 'normal'
return '[label="%s", penwidth="%d", arrowhead="%s"]' % (name, penwidth, arrowhead)
elif isinstance(thing, Const):
return '[label="%d", shape=circle, fillcolor=lightgrey]' % thing.val
elif isinstance(thing, (Input, Output)):
return '[label="%s", shape=circle, fillcolor=none]' % thing.name
elif isinstance(thing, Register):
return '[label="%s", shape=square, fillcolor=gold]' % thing.name
elif isinstance(thing, WireVector):
return '[label="", shape=circle, fillcolor=none]'
else:
try:
if thing.op == '&':
return '[label="and"]'
elif thing.op == '|':
return '[label="or"]'
elif thing.op == '^':
return '[label="xor"]'
elif thing.op == '~':
return '[label="not"]'
elif thing.op == 'x':
return '[label="mux"]'
elif thing.op in 'sc':
return '[label="", height=.1, width=.1]'
elif thing.op == 'r':
name = thing.dests[0].name or ''
return '[label="%s.next", shape=square, fillcolor=gold]' % name
elif thing.op == 'w':
return '[label="buf"]'
else:
return '[label="%s"]' % (thing.op + str(thing.op_param or ''))
except AttributeError:
raise PyrtlError('no naming rule for "%s"' % str(thing))
|
def _graphviz_default_namer(thing, is_edge=True, is_to_splitmerge=False)
|
Returns a "good" graphviz label for thing.
| 2.62659 | 2.602139 | 1.009397 |
print(block_to_graphviz_string(block, namer), file=file)
|
def output_to_graphviz(file, namer=_graphviz_default_namer, block=None)
|
Walk the block and output it in graphviz format to the open file.
| 5.536313 | 4.456493 | 1.242303 |
graph = net_graph(block, split_state=True)
node_index_map = {} # map node -> index
rstring =
# print the list of nodes
for index, node in enumerate(graph):
label = namer(node, is_edge=False)
rstring += ' n%s %s;\n' % (index, label)
node_index_map[node] = index
# print the list of edges
for _from in graph:
for _to in graph[_from]:
from_index = node_index_map[_from]
to_index = node_index_map[_to]
edge = graph[_from][_to]
is_to_splitmerge = True if hasattr(_to, 'op') and _to.op in 'cs' else False
label = namer(edge, is_to_splitmerge=is_to_splitmerge)
rstring += ' n%d -> n%d %s;\n' % (from_index, to_index, label)
rstring += '}\n'
return rstring
|
def block_to_graphviz_string(block=None, namer=_graphviz_default_namer)
|
Return a graphviz string for the block.
| 3.160082 | 3.122151 | 1.012149 |
block = working_block(block)
try:
from graphviz import Source
return Source(block_to_graphviz_string())._repr_svg_()
except ImportError:
raise PyrtlError('need graphviz installed (try "pip install graphviz")')
|
def block_to_svg(block=None)
|
Return an SVG for the block.
| 6.258172 | 5.897263 | 1.061199 |
from .simulation import SimulationTrace, _trace_sort_key
if not isinstance(simtrace, SimulationTrace):
raise PyrtlError('first arguement must be of type SimulationTrace')
trace = simtrace.trace
if sortkey is None:
sortkey = _trace_sort_key
if trace_list is None:
trace_list = sorted(trace, key=sortkey)
wave_template = (
)
def extract(w):
wavelist = []
datalist = []
last = None
for i, value in enumerate(trace[w]):
if last == value:
wavelist.append('.')
else:
if len(w) == 1:
wavelist.append(str(value))
else:
wavelist.append('=')
datalist.append(value)
last = value
wavestring = ''.join(wavelist)
datastring = ', '.join(['"%d"' % data for data in datalist])
if len(w) == 1:
return bool_signal_template % (w, wavestring)
else:
return int_signal_template % (w, wavestring, datastring)
bool_signal_template = '{ name: "%s", wave: "%s" },'
int_signal_template = '{ name: "%s", wave: "%s", data: [%s] },'
signals = [extract(w) for w in trace_list]
all_signals = '\n'.join(signals)
wave = wave_template % all_signals
# print(wave)
return wave
|
def trace_to_html(simtrace, trace_list=None, sortkey=None)
|
Return a HTML block showing the trace.
| 2.935159 | 2.878047 | 1.019844 |
if enhancer is not None:
if not hasattr(enhancer, '__call__'):
raise TypeError('Expected the enhancer to be a function.')
return enhancer(create_store)(reducer, initial_state)
if not hasattr(reducer, '__call__'):
raise TypeError('Expected the reducer to be a function.')
# single-element arrays for r/w closure
current_reducer = [reducer]
current_state = [initial_state]
current_listeners = [[]]
next_listeners = [current_listeners[0]]
is_dispatching = [False]
def ensure_can_mutate_next_listeners():
if next_listeners[0] == current_listeners[0]:
next_listeners[0] = current_listeners[0][:]
def get_state():
return current_state[0]
def subscribe(listener):
if not hasattr(listener, '__call__'):
raise TypeError('Expected listener to be a function.')
is_subscribed = [True] # r/w closure
ensure_can_mutate_next_listeners()
next_listeners[0].append(listener)
def unsubcribe():
if not is_subscribed[0]:
return
is_subscribed[0] = False
ensure_can_mutate_next_listeners()
index = next_listeners[0].index(listener)
next_listeners[0].pop(index)
return unsubcribe
def dispatch(action):
if not isinstance(action, dict):
raise TypeError('Actions must be a dict. '
'Use custom middleware for async actions.')
if action.get('type') is None:
raise ValueError('Actions must have a non-None "type" property. '
'Have you misspelled a constant?')
if is_dispatching[0]:
raise Exception('Reducers may not dispatch actions.')
try:
is_dispatching[0] = True
current_state[0] = current_reducer[0](current_state[0], action)
finally:
is_dispatching[0] = False
listeners = current_listeners[0] = next_listeners[0]
for listener in listeners:
listener()
return action
def replace_reducer(next_reducer):
if not hasattr(next_reducer, '__call__'):
raise TypeError('Expected next_reducer to be a function')
current_reducer[0] = next_reducer
dispatch({'type': ActionTypes.INIT})
dispatch({'type': ActionTypes.INIT})
return StoreDict(
dispatch=dispatch,
subscribe=subscribe,
get_state=get_state,
replace_reducer=replace_reducer,
)
|
def create_store(reducer, initial_state=None, enhancer=None)
|
redux in a nutshell.
observable has been omitted.
Args:
reducer: root reducer function for the state tree
initial_state: optional initial state data
enhancer: optional enhancer function for middleware etc.
Returns:
a Pydux store
| 1.879633 | 1.915445 | 0.981304 |
if not _setting_slower_but_more_descriptive_tmps:
return None
import inspect
loc = None
frame_stack = inspect.stack()
try:
for frame in frame_stack:
modname = inspect.getmodule(frame[0]).__name__
if not modname.startswith('pyrtl.'):
full_filename = frame[0].f_code.co_filename
filename = full_filename.split('/')[-1].rstrip('.py')
lineno = frame[0].f_lineno
loc = (filename, lineno)
break
except:
loc = None
finally:
del frame_stack
return loc
|
def _get_useful_callpoint_name()
|
Attempts to find the lowest user-level call into the pyrtl module
:return (string, int) or None: the file name and line number respectively
This function walks back the current frame stack attempting to find the
first frame that is not part of the pyrtl module. The filename (stripped
of path and .py extention) and line number of that call are returned.
This point should be the point where the user-level code is making the
call to some pyrtl intrisic (for example, calling "mux"). If the
attempt to find the callpoint fails for any reason, None is returned.
| 3.981219 | 3.459149 | 1.150924 |
global debug_mode
global _setting_keep_wirevector_call_stack
global _setting_slower_but_more_descriptive_tmps
debug_mode = debug
_setting_keep_wirevector_call_stack = debug
_setting_slower_but_more_descriptive_tmps = debug
|
def set_debug_mode(debug=True)
|
Set the global debug mode.
| 6.245206 | 6.300215 | 0.991269 |
self.sanity_check_wirevector(wirevector)
self.wirevector_set.add(wirevector)
self.wirevector_by_name[wirevector.name] = wirevector
|
def add_wirevector(self, wirevector)
|
Add a wirevector object to the block.
| 2.975527 | 2.911572 | 1.021966 |
self.wirevector_set.remove(wirevector)
del self.wirevector_by_name[wirevector.name]
|
def remove_wirevector(self, wirevector)
|
Remove a wirevector object to the block.
| 3.453367 | 2.965237 | 1.164618 |
self.sanity_check_net(net)
self.logic.add(net)
|
def add_net(self, net)
|
Add a net to the logic of the block.
The passed net, which must be of type LogicNet, is checked and then
added to the block. No wires are added by this member, they must be
added seperately with add_wirevector.
| 10.062938 | 7.989951 | 1.259449 |
if cls is None:
initial_set = self.wirevector_set
else:
initial_set = (x for x in self.wirevector_set if isinstance(x, cls))
if exclude == tuple():
return set(initial_set)
else:
return set(x for x in initial_set if not isinstance(x, exclude))
|
def wirevector_subset(self, cls=None, exclude=tuple())
|
Return set of wirevectors, filtered by the type or tuple of types provided as cls.
If no cls is specified, the full set of wirevectors associated with the Block are
returned. If cls is a single type, or a tuple of types, only those wirevectors of
the matching types will be returned. This is helpful for getting all inputs, outputs,
or registers of a block for example.
| 2.387279 | 2.23137 | 1.069871 |
if op is None:
return self.logic
else:
return set(x for x in self.logic if x.op in op)
|
def logic_subset(self, op=None)
|
Return set of logicnets, filtered by the type(s) of logic op provided as op.
If no op is specified, the full set of logicnets associated with the Block are
returned. This is helpful for getting all memories of a block for example.
| 4.011712 | 3.265389 | 1.228556 |
if name in self.wirevector_by_name:
return self.wirevector_by_name[name]
elif strict:
raise PyrtlError('error, block does not have a wirevector named %s' % name)
else:
return None
|
def get_wirevector_by_name(self, name, strict=False)
|
Return the wirevector matching name.
By fallthrough, if a matching wirevector cannot be found the value None is
returned. However, if the argument strict is set to True, then this will
instead throw a PyrtlError when no match is found.
| 2.945637 | 2.808138 | 1.048965 |
src_list = {}
dst_list = {}
def add_wire_src(edge, node):
if edge in src_list:
raise PyrtlError('Wire "{}" has multiple drivers (check for multiple assignments '
'with "<<=" or accidental mixing of "|=" and "<<=")'.format(edge))
src_list[edge] = node
def add_wire_dst(edge, node):
if edge in dst_list:
# if node in dst_list[edge]:
# raise PyrtlError("The net already exists in the graph")
dst_list[edge].append(node)
else:
dst_list[edge] = [node]
if include_virtual_nodes:
from .wire import Input, Output, Const
for wire in self.wirevector_subset((Input, Const)):
add_wire_src(wire, wire)
for wire in self.wirevector_subset(Output):
add_wire_dst(wire, wire)
for net in self.logic:
for arg in set(net.args): # prevents unexpected duplicates when doing b <<= a & a
add_wire_dst(arg, net)
for dest in net.dests:
add_wire_src(dest, net)
return src_list, dst_list
|
def net_connections(self, include_virtual_nodes=False)
|
Returns a representation of the current block useful for creating a graph.
:param include_virtual_nodes: if enabled, the wire itself will be used to
signal an external source or sink (such as the source for an Input net).
If disabled, these nodes will be excluded from the adjacency dictionaries
:return wire_src_dict, wire_sink_dict
Returns two dictionaries: one that map WireVectors to the logic
nets that creates their signal and one that maps WireVectors to
a list of logic nets that use the signal
These dictionaries make the creation of a graph much easier, as
well as facilitate other places in which one would need wire source
and wire sink information
Look at input_output.net_graph for one such graph that uses the information
from this function
| 4.119741 | 4.066145 | 1.013181 |
# TODO: check that the wirevector_by_name is sane
from .wire import Input, Const, Output
from .helperfuncs import get_stack, get_stacks
# check for valid LogicNets (and wires)
for net in self.logic:
self.sanity_check_net(net)
for w in self.wirevector_subset():
if w.bitwidth is None:
raise PyrtlError(
'error, missing bitwidth for WireVector "%s" \n\n %s' % (w.name, get_stack(w)))
# check for unique names
wirevector_names_set = set(x.name for x in self.wirevector_set)
if len(self.wirevector_set) != len(wirevector_names_set):
wirevector_names_list = [x.name for x in self.wirevector_set]
for w in wirevector_names_set:
wirevector_names_list.remove(w)
raise PyrtlError('Duplicate wire names found for the following '
'different signals: %s' % repr(wirevector_names_list))
# check for dead input wires (not connected to anything)
all_input_and_consts = self.wirevector_subset((Input, Const))
# The following line also checks for duplicate wire drivers
wire_src_dict, wire_dst_dict = self.net_connections()
dest_set = set(wire_src_dict.keys())
arg_set = set(wire_dst_dict.keys())
full_set = dest_set | arg_set
connected_minus_allwires = full_set.difference(self.wirevector_set)
if len(connected_minus_allwires) > 0:
bad_wire_names = '\n '.join(str(x) for x in connected_minus_allwires)
raise PyrtlError('Unknown wires found in net:\n %s \n\n %s' % (bad_wire_names,
get_stacks(*connected_minus_allwires)))
allwires_minus_connected = self.wirevector_set.difference(full_set)
allwires_minus_connected = allwires_minus_connected.difference(all_input_and_consts)
# ^ allow inputs and consts to be unconnected
if len(allwires_minus_connected) > 0:
bad_wire_names = '\n '.join(str(x) for x in allwires_minus_connected)
raise PyrtlError('Wires declared but not connected:\n %s \n\n %s' % (bad_wire_names,
get_stacks(*allwires_minus_connected)))
# Check for wires that are inputs to a logicNet, but are not block inputs and are never
# driven.
ins = arg_set.difference(dest_set)
undriven = ins.difference(all_input_and_consts)
if len(undriven) > 0:
raise PyrtlError('Wires used but never driven: %s \n\n %s' %
([w.name for w in undriven], get_stacks(*undriven)))
# Check for async memories not specified as such
self.sanity_check_memory_sync(wire_src_dict)
if debug_mode:
# Check for wires that are destinations of a logicNet, but are not outputs and are never
# used as args.
outs = dest_set.difference(arg_set)
unused = outs.difference(self.wirevector_subset(Output))
if len(unused) > 0:
names = [w.name for w in unused]
print('Warning: Wires driven but never used { %s } ' % names)
print(get_stacks(*unused))
|
def sanity_check(self)
|
Check block and throw PyrtlError or PyrtlInternalError if there is an issue.
Should not modify anything, only check data structures to make sure they have been
built according to the assumptions stated in the Block comments.
| 3.446711 | 3.318657 | 1.038586 |
sync_mems = set(m for m in self.logic_subset('m') if not m.op_param[1].asynchronous)
if not len(sync_mems):
return # nothing to check here
if wire_src_dict is None:
wire_src_dict, wdd = self.net_connections()
from .wire import Input, Const
sync_src = 'r'
sync_prop = 'wcs'
for net in sync_mems:
wires_to_check = list(net.args)
while len(wires_to_check):
wire = wires_to_check.pop()
if isinstance(wire, (Input, Const)):
continue
src_net = wire_src_dict[wire]
if src_net.op == sync_src:
continue
elif src_net.op in sync_prop:
wires_to_check.extend(src_net.args)
else:
raise PyrtlError(
'memory "%s" is not specified as asynchronous but has an index '
'"%s" that is not ready at the start of the cycle due to net "%s"'
% (net.op_param[1].name, net.args[0].name, str(src_net)))
|
def sanity_check_memory_sync(self, wire_src_dict=None)
|
Check that all memories are synchronous unless explicitly specified as async.
While the semantics of 'm' memories reads is asynchronous, if you want your design
to use a block ram (on an FPGA or otherwise) you want to make sure the index is
available at the beginning of the clock edge. This check will walk the logic structure
and throw an error on any memory if finds that has an index that is not ready at the
beginning of the cycle.
| 4.890698 | 3.998587 | 1.223107 |
from .wire import WireVector
if not isinstance(w, WireVector):
raise PyrtlError(
'error attempting to pass an input of type "%s" '
'instead of WireVector' % type(w))
|
def sanity_check_wirevector(self, w)
|
Check that w is a valid wirevector type.
| 6.21274 | 5.512874 | 1.126951 |
if not self.is_valid_str(string):
if string in self.val_map and not self.allow_dups:
raise IndexError("Value {} has already been given to the sanitizer".format(string))
internal_name = super(_NameSanitizer, self).make_valid_string()
self.val_map[string] = internal_name
return internal_name
else:
if self.map_valid:
self.val_map[string] = string
return string
|
def make_valid_string(self, string='')
|
Inputting a value for the first time
| 4.708629 | 4.532711 | 1.038811 |
int_strings = string.split()
return [int(int_str, base) for int_str in int_strings]
|
def str_to_int_array(string, base=16)
|
Converts a string to an array of integer values according to the
base specified (int numbers must be whitespace delimited).\n
Example: "13 a3 3c" => [0x13, 0xa3, 0x3c]
:return: [int]
| 3.955978 | 4.35049 | 0.909318 |
correctbw = abs(val).bit_length() + 1
if bitwidth < correctbw:
raise pyrtl.PyrtlError("please choose a larger target bitwidth")
if val >= 0:
return val
else:
return (~abs(val) & (2**bitwidth-1)) + 1
|
def twos_comp_repr(val, bitwidth)
|
Converts a value to it's two's-complement (positive) integer representation using a
given bitwidth (only converts the value if it is negative).
For use with Simulation.step() etc. in passing negative numbers, which it does not accept
| 5.186996 | 5.681471 | 0.912967 |
valbl = val.bit_length()
if bitwidth < val.bit_length() or val == 2**(bitwidth-1):
raise pyrtl.PyrtlError("please choose a larger target bitwidth")
if bitwidth == valbl: # MSB is a 1, value is negative
return -((~val & (2**bitwidth-1)) + 1) # flip the bits, add one, and make negative
else:
return val
|
def rev_twos_comp_repr(val, bitwidth)
|
Takes a two's-complement represented value and
converts it to a signed integer based on the provided bitwidth.
For use with Simulation.inspect() etc. when expecting negative numbers,
which it does not recognize
| 6.022006 | 6.11699 | 0.984472 |
if direct == 'l':
if num >= len(reg):
return 0
else:
return pyrtl.concat(reg, pyrtl.Const(0, num))
elif direct == 'r':
if num >= len(reg):
return 0
else:
return reg[num:]
else:
raise pyrtl.PyrtlError("direction must be specified with 'direct'"
"parameter as either 'l' or 'r'")
|
def _shifted_reg_next(reg, direct, num=1)
|
Creates a shifted 'next' property for shifted (left or right) register.\n
Use: `myReg.next = shifted_reg_next(myReg, 'l', 4)`
:param string direct: direction of shift, either 'l' or 'r'
:param int num: number of shifts
:return: Register containing reg's (shifted) next state
| 3.319246 | 3.420681 | 0.970346 |
block = working_block(block)
if not update_working_block:
block = copy_block(block)
with set_working_block(block, no_sanity_check=True):
if (not skip_sanity_check) or debug_mode:
block.sanity_check()
_remove_wire_nets(block)
constant_propagation(block, True)
_remove_unlistened_nets(block)
common_subexp_elimination(block)
if (not skip_sanity_check) or debug_mode:
block.sanity_check()
return block
|
def optimize(update_working_block=True, block=None, skip_sanity_check=False)
|
Return an optimized version of a synthesized hardware block.
:param Boolean update_working_block: Don't copy the block and optimize the
new block
:param Block block: the block to optimize (defaults to working block)
Note:
optimize works on all hardware designs, both synthesized and non synthesized
| 4.357504 | 4.599804 | 0.947324 |
wire_src_dict = _ProducerList()
wire_removal_set = set() # set of all wirevectors to be removed
# one pass to build the map of value producers and
# all of the nets and wires to be removed
for net in block.logic:
if net.op == 'w':
wire_src_dict[net.dests[0]] = net.args[0]
if not isinstance(net.dests[0], Output):
wire_removal_set.add(net.dests[0])
# second full pass to create the new logic without the wire nets
new_logic = set()
for net in block.logic:
if net.op != 'w' or isinstance(net.dests[0], Output):
new_args = tuple(wire_src_dict.find_producer(x) for x in net.args)
new_net = LogicNet(net.op, net.op_param, new_args, net.dests)
new_logic.add(new_net)
# now update the block with the new logic and remove wirevectors
block.logic = new_logic
for dead_wirevector in wire_removal_set:
del block.wirevector_by_name[dead_wirevector.name]
block.wirevector_set.remove(dead_wirevector)
block.sanity_check()
|
def _remove_wire_nets(block)
|
Remove all wire nodes from the block.
| 3.937585 | 3.86806 | 1.017974 |
net_count = _NetCount(block)
while net_count.shrinking():
_constant_prop_pass(block, silence_unexpected_net_warnings)
|
def constant_propagation(block, silence_unexpected_net_warnings=False)
|
Removes excess constants in the block.
Note on resulting block:
The output of the block can have wirevectors that are driven but not
listened to. This is to be expected. These are to be removed by the
_remove_unlistened_nets function
| 7.612416 | 9.141253 | 0.832754 |
block = working_block(block)
net_count = _NetCount(block)
while net_count.shrinking(block, percent_thresh, abs_thresh):
net_table = _find_common_subexps(block)
_replace_subexps(block, net_table)
|
def common_subexp_elimination(block=None, abs_thresh=1, percent_thresh=0)
|
Common Subexpression Elimination for PyRTL blocks
:param block: the block to run the subexpression elimination on
:param abs_thresh: absolute threshold for stopping optimization
:param percent_thresh: percent threshold for stopping optimization
| 6.632265 | 8.037271 | 0.825189 |
listened_nets = set()
listened_wires = set()
prev_listened_net_count = 0
def add_to_listened(net):
listened_nets.add(net)
listened_wires.update(net.args)
for a_net in block.logic:
if a_net.op == '@':
add_to_listened(a_net)
elif any(isinstance(destW, Output) for destW in a_net.dests):
add_to_listened(a_net)
while len(listened_nets) > prev_listened_net_count:
prev_listened_net_count = len(listened_nets)
for net in block.logic - listened_nets:
if any((destWire in listened_wires) for destWire in net.dests):
add_to_listened(net)
block.logic = listened_nets
_remove_unused_wires(block)
|
def _remove_unlistened_nets(block)
|
Removes all nets that are not connected to an output wirevector
| 2.680357 | 2.505236 | 1.069902 |
valid_wires = set()
for logic_net in block.logic:
valid_wires.update(logic_net.args, logic_net.dests)
wire_removal_set = block.wirevector_set.difference(valid_wires)
for removed_wire in wire_removal_set:
if isinstance(removed_wire, Input):
term = " optimized away"
if keep_inputs:
valid_wires.add(removed_wire)
term = " deemed useless by optimization"
print("Input Wire, " + removed_wire.name + " has been" + term)
if isinstance(removed_wire, Output):
PyrtlInternalError("Output wire, " + removed_wire.name + " not driven")
block.wirevector_set = valid_wires
|
def _remove_unused_wires(block, keep_inputs=True)
|
Removes all unconnected wires from a block
| 5.008683 | 4.801474 | 1.043155 |
def arg(x, i):
# return the mapped wire vector for argument x, wire number i
return wv_map[(net.args[x], i)]
def destlen():
# return iterator over length of the destination in bits
return range(len(net.dests[0]))
def assign_dest(i, v):
# assign v to the wiremap for dest[0], wire i
wv_map[(net.dests[0], i)] <<= v
one_var_ops = {
'w': lambda w: w,
'~': lambda w: ~w,
}
c_two_var_ops = {
'&': lambda l, r: l & r,
'|': lambda l, r: l | r,
'^': lambda l, r: l ^ r,
'n': lambda l, r: l.nand(r),
}
if net.op in one_var_ops:
for i in destlen():
assign_dest(i, one_var_ops[net.op](arg(0, i)))
elif net.op in c_two_var_ops:
for i in destlen():
assign_dest(i, c_two_var_ops[net.op](arg(0, i), arg(1, i)))
elif net.op == 's':
for i in destlen():
selected_bit = arg(0, net.op_param[i])
assign_dest(i, selected_bit)
elif net.op == 'c':
arg_wirelist = []
# generate list of wires for vectors being concatenated
for arg_vector in net.args:
arg_vector_as_list = [wv_map[(arg_vector, i)] for i in range(len(arg_vector))]
arg_wirelist = arg_vector_as_list + arg_wirelist
for i in destlen():
assign_dest(i, arg_wirelist[i])
elif net.op == 'r':
for i in destlen():
args = (arg(0, i),)
dests = (wv_map[(net.dests[0], i)],)
new_net = LogicNet('r', None, args=args, dests=dests)
block_out.add_net(new_net)
elif net.op == 'm':
arg0list = [arg(0, i) for i in range(len(net.args[0]))]
addr = concat_list(arg0list)
new_mem = _get_new_block_mem_instance(net.op_param, mems, block_out)[1]
data = as_wires(new_mem[addr])
for i in destlen():
assign_dest(i, data[i])
elif net.op == '@':
addrlist = [arg(0, i) for i in range(len(net.args[0]))]
addr = concat_list(addrlist)
datalist = [arg(1, i) for i in range(len(net.args[1]))]
data = concat_list(datalist)
enable = arg(2, 0)
new_mem = _get_new_block_mem_instance(net.op_param, mems, block_out)[1]
new_mem[addr] <<= MemBlock.EnabledWrite(data=data, enable=enable)
else:
raise PyrtlInternalError('Unable to synthesize the following net '
'due to unimplemented op :\n%s' % str(net))
return
|
def _decompose(net, wv_map, mems, block_out)
|
Add the wires and logicnets to block_out and wv_map to decompose net
| 2.939983 | 2.884532 | 1.019224 |
if net.op in '~nrwcsm@':
return True
def arg(num):
return net.args[num]
dest = net.dests[0]
if net.op == '&':
dest <<= ~(arg(0).nand(arg(1)))
elif net.op == '|':
dest <<= (~arg(0)).nand(~arg(1))
elif net.op == '^':
temp_0 = arg(0).nand(arg(1))
dest <<= temp_0.nand(arg(0)).nand(temp_0.nand(arg(1)))
else:
raise PyrtlError("Op, '{}' is not supported in nand_synth".format(net.op))
|
def nand_synth(net)
|
Synthesizes an Post-Synthesis block into one consisting of nands and inverters in place
:param block: The block to synthesize.
| 4.879415 | 5.343795 | 0.913099 |
if net.op in '~&rwcsm@':
return True
def arg(num):
return net.args[num]
dest = net.dests[0]
if net.op == '|':
dest <<= ~(~arg(0) & ~arg(1))
elif net.op == '^':
all_1 = arg(0) & arg(1)
all_0 = ~arg(0) & ~arg(1)
dest <<= all_0 & ~all_1
elif net.op == 'n':
dest <<= ~(arg(0) & arg(1))
else:
raise PyrtlError("Op, '{}' is not supported in and_inv_synth".format(net.op))
|
def and_inverter_synth(net)
|
Transforms a decomposed block into one consisting of ands and inverters in place
:param block: The block to synthesize
| 4.567121 | 4.96383 | 0.92008 |
from pyrtl import concat, select # just for readability
if wrap_around != 0:
raise NotImplementedError
# Implement with logN stages pyrtl.muxing between shifted and un-shifted values
final_width = len(bits_to_shift)
val = bits_to_shift
append_val = bit_in
for i in range(len(shift_dist)):
shift_amt = pow(2, i) # stages shift 1,2,4,8,...
if shift_amt < final_width:
newval = select(direction,
concat(val[:-shift_amt], append_val), # shift up
concat(append_val, val[shift_amt:])) # shift down
val = select(shift_dist[i],
truecase=newval, # if bit of shift is 1, do the shift
falsecase=val) # otherwise, don't
# the value to append grows exponentially, but is capped at full width
append_val = concat(append_val, append_val)[:final_width]
else:
# if we are shifting this much, all the data is gone
val = select(shift_dist[i],
truecase=append_val, # if bit of shift is 1, do the shift
falsecase=val) # otherwise, don't
return val
|
def barrel_shifter(bits_to_shift, bit_in, direction, shift_dist, wrap_around=0)
|
Create a barrel shifter that operates on data based on the wire width.
:param bits_to_shift: the input wire
:param bit_in: the 1-bit wire giving the value to shift in
:param direction: a one bit WireVector representing shift direction
(0 = shift down, 1 = shift up)
:param shift_dist: WireVector representing offset to shift
:param wrap_around: ****currently not implemented****
:return: shifted WireVector
| 5.050446 | 5.056743 | 0.998755 |
if not funcs:
return lambda *args: args[0] if args else None
if len(funcs) == 1:
return funcs[0]
last = funcs[-1]
rest = funcs[0:-1]
return lambda *args: reduce(lambda ax, func: func(ax),
reversed(rest), last(*args))
|
def compose(*funcs)
|
chained function composition wrapper
creates function f, where f(x) = arg0(arg1(arg2(...argN(x))))
if *funcs is empty, an identity function is returned.
Args:
*funcs: list of functions to chain
Returns:
a new function composed of chained calls to *args
| 2.923029 | 3.441983 | 0.849228 |
final_reducers = {key: reducer
for key, reducer in reducers.items()
if hasattr(reducer, '__call__')}
sanity_error = None
try:
assert_reducer_sanity(final_reducers)
except Exception as e:
sanity_error = e
def combination(state=None, action=None):
if state is None:
state = {}
if sanity_error:
raise sanity_error
has_changed = False
next_state = {}
for key, reducer in final_reducers.items():
previous_state_for_key = state.get(key)
next_state_for_key = reducer(previous_state_for_key, action)
if next_state_for_key is None:
msg = get_undefined_state_error_message(key, action)
raise Exception(msg)
next_state[key] = next_state_for_key
has_changed = (has_changed or
next_state_for_key != previous_state_for_key)
return next_state if has_changed else state
return combination
|
def combine_reducers(reducers)
|
composition tool for creating reducer trees.
Args:
reducers: dict with state keys and reducer functions
that are responsible for each key
Returns:
a new, combined reducer function
| 2.212672 | 2.34156 | 0.944956 |
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
|
def software_fibonacci(n)
|
a normal old python function to return the Nth fibonacci number.
| 1.952579 | 1.98866 | 0.981857 |
def inner(create_store_):
def create_wrapper(reducer, enhancer=None):
store = create_store_(reducer, enhancer)
dispatch = store['dispatch']
middleware_api = {
'get_state': store['get_state'],
'dispatch': lambda action: dispatch(action),
}
chain = [mw(middleware_api) for mw in middlewares]
dispatch = compose(*chain)(store['dispatch'])
return extend(store, {'dispatch': dispatch})
return create_wrapper
return inner
|
def apply_middleware(*middlewares)
|
creates an enhancer function composed of middleware
Args:
*middlewares: list of middleware functions to apply
Returns:
an enhancer for subsequent calls to create_store()
| 3.131883 | 2.990595 | 1.047244 |
if kwargs: # only "default" is allowed as kwarg.
if len(kwargs) != 1 or 'default' not in kwargs:
try:
result = select(index, **kwargs)
import warnings
warnings.warn("Predicates are being deprecated in Mux. "
"Use the select operator instead.", stacklevel=2)
return result
except Exception:
bad_args = [k for k in kwargs.keys() if k != 'default']
raise PyrtlError('unknown keywords %s applied to mux' % str(bad_args))
default = kwargs['default']
else:
default = None
# find the diff between the addressable range and number of inputs given
short_by = 2**len(index) - len(mux_ins)
if short_by > 0:
if default is not None: # extend the list to appropriate size
mux_ins = list(mux_ins)
extention = [default] * short_by
mux_ins.extend(extention)
if 2 ** len(index) != len(mux_ins):
raise PyrtlError(
'Mux select line is %d bits, but selecting from %d inputs. '
% (len(index), len(mux_ins)))
if len(index) == 1:
return select(index, falsecase=mux_ins[0], truecase=mux_ins[1])
half = len(mux_ins) // 2
return select(index[-1],
falsecase=mux(index[0:-1], *mux_ins[:half]),
truecase=mux(index[0:-1], *mux_ins[half:]))
|
def mux(index, *mux_ins, **kwargs)
|
Multiplexer returning the value of the wire in .
:param WireVector index: used as the select input to the multiplexer
:param WireVector mux_ins: additional WireVector arguments selected when select>1
:param WireVector kwargs: additional WireVectors, keyword arg "default"
If you are selecting between less items than your index can address, you can
use the "default" keyword argument to auto-expand those terms. For example,
if you have a 3-bit index but are selecting between 6 options, you need to specify
a value for those other 2 possible values of index (0b110 and 0b111).
:return: WireVector of length of the longest input (not including select)
To avoid confusion, if you are using the mux where the select is a "predicate"
(meaning something that you are checking the truth value of rather than using it
as a number) it is recommended that you use the select function instead
as named arguments because the ordering is different from the classic ternary
operator of some languages.
Example of mux as "selector" to pick between a0 and a1: ::
index = WireVector(1)
mux( index, a0, a1 )
Example of mux as "selector" to pick between a0 ... a3: ::
index = WireVector(2)
mux( index, a0, a1, a2, a3 )
Example of "default" to specify additional arguments: ::
index = WireVector(3)
mux( index, a0, a1, a2, a3, a4, a5, default=0 )
| 4.067592 | 3.98922 | 1.019646 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.