@yowasp/yosys 0.39.92-dev.686 → 0.39.693
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/gen/resources-yosys.js
CHANGED
|
@@ -132,7 +132,7 @@ export const filesystem = {
|
|
|
132
132
|
"cxxrtl_capi_vcd.h": "/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2020 whitequark <whitequark@whitequark.org>\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n */\n\n#ifndef CXXRTL_CAPI_VCD_H\n#define CXXRTL_CAPI_VCD_H\n\n// This file is a part of the CXXRTL C API. It should be used together with `cxxrtl_vcd_capi.cc`.\n//\n// The CXXRTL C API for VCD writing makes it possible to insert virtual probes into designs and\n// dump waveforms to Value Change Dump files.\n\n#include <stddef.h>\n#include <stdint.h>\n\n#include <cxxrtl/capi/cxxrtl_capi.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// Opaque reference to a VCD writer.\ntypedef struct _cxxrtl_vcd *cxxrtl_vcd;\n\n// Create a VCD writer.\ncxxrtl_vcd cxxrtl_vcd_create();\n\n// Release all resources used by a VCD writer.\nvoid cxxrtl_vcd_destroy(cxxrtl_vcd vcd);\n\n// Set VCD timescale.\n//\n// The `number` must be 1, 10, or 100, and the `unit` must be one of `\"s\"`, `\"ms\"`, `\"us\"`, `\"ns\"`,\n// `\"ps\"`, or `\"fs\"`.\n//\n// Timescale can only be set before the first call to `cxxrtl_vcd_sample`.\nvoid cxxrtl_vcd_timescale(cxxrtl_vcd vcd, int number, const char *unit);\n\n// Schedule a specific CXXRTL object to be sampled.\n//\n// The `name` is a full hierarchical name as described for `cxxrtl_get`; it does not need to match\n// the original name of `object`, if any. The `object` must outlive the VCD writer, but there are\n// no other requirements; if desired, it can be provided by user code, rather than come from\n// a design.\n//\n// Objects can only be scheduled before the first call to `cxxrtl_vcd_sample`.\nvoid cxxrtl_vcd_add(cxxrtl_vcd vcd, const char *name, struct cxxrtl_object *object);\n\n// Schedule all CXXRTL objects in a simulation.\n//\n// The design `handle` must outlive the VCD writer.\n//\n// Objects can only be scheduled before the first call to `cxxrtl_vcd_sample`.\nvoid cxxrtl_vcd_add_from(cxxrtl_vcd vcd, cxxrtl_handle handle);\n\n// Schedule CXXRTL objects in a simulation that match a given predicate.\n//\n// For every object in the simulation, `filter` is called with the provided `data`, the full\n// hierarchical name of the object (see `cxxrtl_get` for details), and the object description.\n// The object will be sampled if the predicate returns a non-zero value.\n//\n// Objects can only be scheduled before the first call to `cxxrtl_vcd_sample`.\nvoid cxxrtl_vcd_add_from_if(cxxrtl_vcd vcd, cxxrtl_handle handle, void *data,\n int (*filter)(void *data, const char *name,\n const struct cxxrtl_object *object));\n\n// Schedule all CXXRTL objects in a simulation except for memories.\n//\n// The design `handle` must outlive the VCD writer.\n//\n// Objects can only be scheduled before the first call to `cxxrtl_vcd_sample`.\nvoid cxxrtl_vcd_add_from_without_memories(cxxrtl_vcd vcd, cxxrtl_handle handle);\n\n// Sample all scheduled objects.\n//\n// First, `time` is written to the internal buffer. Second, the values of every signal changed since\n// the previous call to `cxxrtl_vcd_sample` (all values if this is the first call) are written to\n// the internal buffer. The contents of the buffer can be retrieved with `cxxrtl_vcd_read`.\nvoid cxxrtl_vcd_sample(cxxrtl_vcd vcd, uint64_t time);\n\n// Retrieve buffered VCD data.\n//\n// The pointer to the start of the next chunk of VCD data is assigned to `*data`, and the length\n// of that chunk is assigned to `*size`. The pointer to the data is valid until the next call to\n// `cxxrtl_vcd_sample` or `cxxrtl_vcd_read`. Once all of the buffered data has been retrieved,\n// this function will always return zero sized chunks.\nvoid cxxrtl_vcd_read(cxxrtl_vcd vcd, const char **data, size_t *size);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n",
|
|
133
133
|
},
|
|
134
134
|
"cxxrtl.h": "/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2019-2020 whitequark <whitequark@whitequark.org>\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n */\n\n// This file is included by the designs generated with `write_cxxrtl`. It is not used in Yosys itself.\n//\n// The CXXRTL support library implements compile time specialized arbitrary width arithmetics, as well as provides\n// composite lvalues made out of bit slices and concatenations of lvalues. This allows the `write_cxxrtl` pass\n// to perform a straightforward translation of RTLIL structures to readable C++, relying on the C++ compiler\n// to unwrap the abstraction and generate efficient code.\n\n#ifndef CXXRTL_H\n#define CXXRTL_H\n\n#include <cstddef>\n#include <cstdint>\n#include <cstring>\n#include <cassert>\n#include <limits>\n#include <type_traits>\n#include <tuple>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <memory>\n#include <functional>\n#include <sstream>\n#include <iostream>\n\n// `cxxrtl::debug_item` has to inherit from `cxxrtl_object` to satisfy strict aliasing requirements.\n#include <cxxrtl/capi/cxxrtl_capi.h>\n\n#ifndef __has_attribute\n#\tdefine __has_attribute(x) 0\n#endif\n\n// CXXRTL essentially uses the C++ compiler as a hygienic macro engine that feeds an instruction selector.\n// It generates a lot of specialized template functions with relatively large bodies that, when inlined\n// into the caller and (for those with loops) unrolled, often expose many new optimization opportunities.\n// Because of this, most of the CXXRTL runtime must be always inlined for best performance.\n#if __has_attribute(always_inline)\n#define CXXRTL_ALWAYS_INLINE inline __attribute__((__always_inline__))\n#else\n#define CXXRTL_ALWAYS_INLINE inline\n#endif\n// Conversely, some functions in the generated code are extremely large yet very cold, with both of these\n// properties being extreme enough to confuse C++ compilers into spending pathological amounts of time\n// on a futile (the code becomes worse) attempt to optimize the least important parts of code.\n#if __has_attribute(optnone)\n#define CXXRTL_EXTREMELY_COLD __attribute__((__optnone__))\n#elif __has_attribute(optimize)\n#define CXXRTL_EXTREMELY_COLD __attribute__((__optimize__(0)))\n#else\n#define CXXRTL_EXTREMELY_COLD\n#endif\n\n// CXXRTL uses assert() to check for C++ contract violations (which may result in e.g. undefined behavior\n// of the simulation code itself), and CXXRTL_ASSERT to check for RTL contract violations (which may at\n// most result in undefined simulation results).\n//\n// Though by default, CXXRTL_ASSERT() expands to assert(), it may be overridden e.g. when integrating\n// the simulation into another process that should survive violating RTL contracts.\n#ifndef CXXRTL_ASSERT\n#ifndef CXXRTL_NDEBUG\n#define CXXRTL_ASSERT(x) assert(x)\n#else\n#define CXXRTL_ASSERT(x)\n#endif\n#endif\n\nnamespace cxxrtl {\n\n// All arbitrary-width values in CXXRTL are backed by arrays of unsigned integers called chunks. The chunk size\n// is the same regardless of the value width to simplify manipulating values via FFI interfaces, e.g. driving\n// and introspecting the simulation in Python.\n//\n// It is practical to use chunk sizes between 32 bits and platform register size because when arithmetics on\n// narrower integer types is legalized by the C++ compiler, it inserts code to clear the high bits of the register.\n// However, (a) most of our operations do not change those bits in the first place because of invariants that are\n// invisible to the compiler, (b) we often operate on non-power-of-2 values and have to clear the high bits anyway.\n// Therefore, using relatively wide chunks and clearing the high bits explicitly and only when we know they may be\n// clobbered results in simpler generated code.\ntypedef uint32_t chunk_t;\ntypedef uint64_t wide_chunk_t;\n\ntemplate<typename T>\nstruct chunk_traits {\n\tstatic_assert(std::is_integral<T>::value && std::is_unsigned<T>::value,\n\t \"chunk type must be an unsigned integral type\");\n\tusing type = T;\n\tstatic constexpr size_t bits = std::numeric_limits<T>::digits;\n\tstatic constexpr T mask = std::numeric_limits<T>::max();\n};\n\ntemplate<class T>\nstruct expr_base;\n\ntemplate<size_t Bits>\nstruct value : public expr_base<value<Bits>> {\n\tstatic constexpr size_t bits = Bits;\n\n\tusing chunk = chunk_traits<chunk_t>;\n\tstatic constexpr chunk::type msb_mask = (Bits % chunk::bits == 0) ? chunk::mask\n\t\t: chunk::mask >> (chunk::bits - (Bits % chunk::bits));\n\n\tstatic constexpr size_t chunks = (Bits + chunk::bits - 1) / chunk::bits;\n\tchunk::type data[chunks] = {};\n\n\tvalue() = default;\n\ttemplate<typename... Init>\n\texplicit constexpr value(Init ...init) : data{init...} {}\n\n\tvalue(const value<Bits> &) = default;\n\tvalue<Bits> &operator=(const value<Bits> &) = default;\n\n\tvalue(value<Bits> &&) = default;\n\tvalue<Bits> &operator=(value<Bits> &&) = default;\n\n\t// A (no-op) helper that forces the cast to value<>.\n\tCXXRTL_ALWAYS_INLINE\n\tconst value<Bits> &val() const {\n\t\treturn *this;\n\t}\n\n\tstd::string str() const {\n\t\tstd::stringstream ss;\n\t\tss << *this;\n\t\treturn ss.str();\n\t}\n\n\t// Conversion operations.\n\t//\n\t// These functions ensure that a conversion is never out of range, and should be always used, if at all\n\t// possible, instead of direct manipulation of the `data` member. For very large types, .slice() and\n\t// .concat() can be used to split them into more manageable parts.\n\ttemplate<class IntegerT, typename std::enable_if<!std::is_signed<IntegerT>::value, int>::type = 0>\n\tCXXRTL_ALWAYS_INLINE\n\tIntegerT get() const {\n\t\tstatic_assert(std::numeric_limits<IntegerT>::is_integer && !std::numeric_limits<IntegerT>::is_signed,\n\t\t \"get<T>() requires T to be an unsigned integral type\");\n\t\tstatic_assert(std::numeric_limits<IntegerT>::digits >= Bits,\n\t\t \"get<T>() requires T to be at least as wide as the value is\");\n\t\tIntegerT result = 0;\n\t\tfor (size_t n = 0; n < chunks; n++)\n\t\t\tresult |= IntegerT(data[n]) << (n * chunk::bits);\n\t\treturn result;\n\t}\n\n\ttemplate<class IntegerT, typename std::enable_if<std::is_signed<IntegerT>::value, int>::type = 0>\n\tCXXRTL_ALWAYS_INLINE\n\tIntegerT get() const {\n\t\tauto unsigned_result = get<typename std::make_unsigned<IntegerT>::type>();\n\t\tIntegerT result;\n\t\tmemcpy(&result, &unsigned_result, sizeof(IntegerT));\n\t\treturn result;\n\t}\n\n\ttemplate<class IntegerT, typename std::enable_if<!std::is_signed<IntegerT>::value, int>::type = 0>\n\tCXXRTL_ALWAYS_INLINE\n\tvoid set(IntegerT value) {\n\t\tstatic_assert(std::numeric_limits<IntegerT>::is_integer && !std::numeric_limits<IntegerT>::is_signed,\n\t\t \"set<T>() requires T to be an unsigned integral type\");\n\t\tstatic_assert(std::numeric_limits<IntegerT>::digits >= Bits,\n\t\t \"set<T>() requires the value to be at least as wide as T is\");\n\t\tfor (size_t n = 0; n < chunks; n++)\n\t\t\tdata[n] = (value >> (n * chunk::bits)) & chunk::mask;\n\t}\n\n\ttemplate<class IntegerT, typename std::enable_if<std::is_signed<IntegerT>::value, int>::type = 0>\n\tCXXRTL_ALWAYS_INLINE\n\tvoid set(IntegerT value) {\n\t\ttypename std::make_unsigned<IntegerT>::type unsigned_value;\n\t\tmemcpy(&unsigned_value, &value, sizeof(IntegerT));\n\t\tset(unsigned_value);\n\t}\n\n\t// Operations with compile-time parameters.\n\t//\n\t// These operations are used to implement slicing, concatenation, and blitting.\n\t// The trunc, zext and sext operations add or remove most significant bits (i.e. on the left);\n\t// the rtrunc and rzext operations add or remove least significant bits (i.e. on the right).\n\ttemplate<size_t NewBits>\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<NewBits> trunc() const {\n\t\tstatic_assert(NewBits <= Bits, \"trunc() may not increase width\");\n\t\tvalue<NewBits> result;\n\t\tfor (size_t n = 0; n < result.chunks; n++)\n\t\t\tresult.data[n] = data[n];\n\t\tresult.data[result.chunks - 1] &= result.msb_mask;\n\t\treturn result;\n\t}\n\n\ttemplate<size_t NewBits>\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<NewBits> zext() const {\n\t\tstatic_assert(NewBits >= Bits, \"zext() may not decrease width\");\n\t\tvalue<NewBits> result;\n\t\tfor (size_t n = 0; n < chunks; n++)\n\t\t\tresult.data[n] = data[n];\n\t\treturn result;\n\t}\n\n\ttemplate<size_t NewBits>\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<NewBits> sext() const {\n\t\tstatic_assert(NewBits >= Bits, \"sext() may not decrease width\");\n\t\tvalue<NewBits> result;\n\t\tfor (size_t n = 0; n < chunks; n++)\n\t\t\tresult.data[n] = data[n];\n\t\tif (is_neg()) {\n\t\t\tresult.data[chunks - 1] |= ~msb_mask;\n\t\t\tfor (size_t n = chunks; n < result.chunks; n++)\n\t\t\t\tresult.data[n] = chunk::mask;\n\t\t\tresult.data[result.chunks - 1] &= result.msb_mask;\n\t\t}\n\t\treturn result;\n\t}\n\n\ttemplate<size_t NewBits>\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<NewBits> rtrunc() const {\n\t\tstatic_assert(NewBits <= Bits, \"rtrunc() may not increase width\");\n\t\tvalue<NewBits> result;\n\t\tconstexpr size_t shift_chunks = (Bits - NewBits) / chunk::bits;\n\t\tconstexpr size_t shift_bits = (Bits - NewBits) % chunk::bits;\n\t\tchunk::type carry = 0;\n\t\tif (shift_chunks + result.chunks < chunks) {\n\t\t\tcarry = (shift_bits == 0) ? 0\n\t\t\t\t: data[shift_chunks + result.chunks] << (chunk::bits - shift_bits);\n\t\t}\n\t\tfor (size_t n = result.chunks; n > 0; n--) {\n\t\t\tresult.data[n - 1] = carry | (data[shift_chunks + n - 1] >> shift_bits);\n\t\t\tcarry = (shift_bits == 0) ? 0\n\t\t\t\t: data[shift_chunks + n - 1] << (chunk::bits - shift_bits);\n\t\t}\n\t\treturn result;\n\t}\n\n\ttemplate<size_t NewBits>\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<NewBits> rzext() const {\n\t\tstatic_assert(NewBits >= Bits, \"rzext() may not decrease width\");\n\t\tvalue<NewBits> result;\n\t\tconstexpr size_t shift_chunks = (NewBits - Bits) / chunk::bits;\n\t\tconstexpr size_t shift_bits = (NewBits - Bits) % chunk::bits;\n\t\tchunk::type carry = 0;\n\t\tfor (size_t n = 0; n < chunks; n++) {\n\t\t\tresult.data[shift_chunks + n] = (data[n] << shift_bits) | carry;\n\t\t\tcarry = (shift_bits == 0) ? 0\n\t\t\t\t: data[n] >> (chunk::bits - shift_bits);\n\t\t}\n\t\tif (shift_chunks + chunks < result.chunks)\n\t\t\tresult.data[shift_chunks + chunks] = carry;\n\t\treturn result;\n\t}\n\n\t// Bit blit operation, i.e. a partial read-modify-write.\n\ttemplate<size_t Stop, size_t Start>\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<Bits> blit(const value<Stop - Start + 1> &source) const {\n\t\tstatic_assert(Stop >= Start, \"blit() may not reverse bit order\");\n\t\tconstexpr chunk::type start_mask = ~(chunk::mask << (Start % chunk::bits));\n\t\tconstexpr chunk::type stop_mask = (Stop % chunk::bits + 1 == chunk::bits) ? 0\n\t\t\t: (chunk::mask << (Stop % chunk::bits + 1));\n\t\tvalue<Bits> masked = *this;\n\t\tif (Start / chunk::bits == Stop / chunk::bits) {\n\t\t\tmasked.data[Start / chunk::bits] &= stop_mask | start_mask;\n\t\t} else {\n\t\t\tmasked.data[Start / chunk::bits] &= start_mask;\n\t\t\tfor (size_t n = Start / chunk::bits + 1; n < Stop / chunk::bits; n++)\n\t\t\t\tmasked.data[n] = 0;\n\t\t\tmasked.data[Stop / chunk::bits] &= stop_mask;\n\t\t}\n\t\tvalue<Bits> shifted = source\n\t\t\t.template rzext<Stop + 1>()\n\t\t\t.template zext<Bits>();\n\t\treturn masked.bit_or(shifted);\n\t}\n\n\t// Helpers for selecting extending or truncating operation depending on whether the result is wider or narrower\n\t// than the operand. In C++17 these can be replaced with `if constexpr`.\n\ttemplate<size_t NewBits, typename = void>\n\tstruct zext_cast {\n\t\tCXXRTL_ALWAYS_INLINE\n\t\tvalue<NewBits> operator()(const value<Bits> &val) {\n\t\t\treturn val.template zext<NewBits>();\n\t\t}\n\t};\n\n\ttemplate<size_t NewBits>\n\tstruct zext_cast<NewBits, typename std::enable_if<(NewBits < Bits)>::type> {\n\t\tCXXRTL_ALWAYS_INLINE\n\t\tvalue<NewBits> operator()(const value<Bits> &val) {\n\t\t\treturn val.template trunc<NewBits>();\n\t\t}\n\t};\n\n\ttemplate<size_t NewBits, typename = void>\n\tstruct sext_cast {\n\t\tCXXRTL_ALWAYS_INLINE\n\t\tvalue<NewBits> operator()(const value<Bits> &val) {\n\t\t\treturn val.template sext<NewBits>();\n\t\t}\n\t};\n\n\ttemplate<size_t NewBits>\n\tstruct sext_cast<NewBits, typename std::enable_if<(NewBits < Bits)>::type> {\n\t\tCXXRTL_ALWAYS_INLINE\n\t\tvalue<NewBits> operator()(const value<Bits> &val) {\n\t\t\treturn val.template trunc<NewBits>();\n\t\t}\n\t};\n\n\ttemplate<size_t NewBits>\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<NewBits> zcast() const {\n\t\treturn zext_cast<NewBits>()(*this);\n\t}\n\n\ttemplate<size_t NewBits>\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<NewBits> scast() const {\n\t\treturn sext_cast<NewBits>()(*this);\n\t}\n\n\t// Bit replication is far more efficient than the equivalent concatenation.\n\ttemplate<size_t Count>\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<Bits * Count> repeat() const {\n\t\tstatic_assert(Bits == 1, \"repeat() is implemented only for 1-bit values\");\n\t\treturn *this ? value<Bits * Count>().bit_not() : value<Bits * Count>();\n\t}\n\n\t// Operations with run-time parameters (offsets, amounts, etc).\n\t//\n\t// These operations are used for computations.\n\tbool bit(size_t offset) const {\n\t\treturn data[offset / chunk::bits] & (1 << (offset % chunk::bits));\n\t}\n\n\tvoid set_bit(size_t offset, bool value = true) {\n\t\tsize_t offset_chunks = offset / chunk::bits;\n\t\tsize_t offset_bits = offset % chunk::bits;\n\t\tdata[offset_chunks] &= ~(1 << offset_bits);\n\t\tdata[offset_chunks] |= value ? 1 << offset_bits : 0;\n\t}\n\n\texplicit operator bool() const {\n\t\treturn !is_zero();\n\t}\n\n\tbool is_zero() const {\n\t\tfor (size_t n = 0; n < chunks; n++)\n\t\t\tif (data[n] != 0)\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tbool is_neg() const {\n\t\treturn data[chunks - 1] & (1 << ((Bits - 1) % chunk::bits));\n\t}\n\n\tbool operator ==(const value<Bits> &other) const {\n\t\tfor (size_t n = 0; n < chunks; n++)\n\t\t\tif (data[n] != other.data[n])\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tbool operator !=(const value<Bits> &other) const {\n\t\treturn !(*this == other);\n\t}\n\n\tvalue<Bits> bit_not() const {\n\t\tvalue<Bits> result;\n\t\tfor (size_t n = 0; n < chunks; n++)\n\t\t\tresult.data[n] = ~data[n];\n\t\tresult.data[chunks - 1] &= msb_mask;\n\t\treturn result;\n\t}\n\n\tvalue<Bits> bit_and(const value<Bits> &other) const {\n\t\tvalue<Bits> result;\n\t\tfor (size_t n = 0; n < chunks; n++)\n\t\t\tresult.data[n] = data[n] & other.data[n];\n\t\treturn result;\n\t}\n\n\tvalue<Bits> bit_or(const value<Bits> &other) const {\n\t\tvalue<Bits> result;\n\t\tfor (size_t n = 0; n < chunks; n++)\n\t\t\tresult.data[n] = data[n] | other.data[n];\n\t\treturn result;\n\t}\n\n\tvalue<Bits> bit_xor(const value<Bits> &other) const {\n\t\tvalue<Bits> result;\n\t\tfor (size_t n = 0; n < chunks; n++)\n\t\t\tresult.data[n] = data[n] ^ other.data[n];\n\t\treturn result;\n\t}\n\n\tvalue<Bits> update(const value<Bits> &val, const value<Bits> &mask) const {\n\t\treturn bit_and(mask.bit_not()).bit_or(val.bit_and(mask));\n\t}\n\n\ttemplate<size_t AmountBits>\n\tvalue<Bits> shl(const value<AmountBits> &amount) const {\n\t\t// Ensure our early return is correct by prohibiting values larger than 4 Gbit.\n\t\tstatic_assert(Bits <= chunk::mask, \"shl() of unreasonably large values is not supported\");\n\t\t// Detect shifts definitely large than Bits early.\n\t\tfor (size_t n = 1; n < amount.chunks; n++)\n\t\t\tif (amount.data[n] != 0)\n\t\t\t\treturn {};\n\t\t// Past this point we can use the least significant chunk as the shift size.\n\t\tsize_t shift_chunks = amount.data[0] / chunk::bits;\n\t\tsize_t shift_bits = amount.data[0] % chunk::bits;\n\t\tif (shift_chunks >= chunks)\n\t\t\treturn {};\n\t\tvalue<Bits> result;\n\t\tchunk::type carry = 0;\n\t\tfor (size_t n = 0; n < chunks - shift_chunks; n++) {\n\t\t\tresult.data[shift_chunks + n] = (data[n] << shift_bits) | carry;\n\t\t\tcarry = (shift_bits == 0) ? 0\n\t\t\t\t: data[n] >> (chunk::bits - shift_bits);\n\t\t}\n\t\tresult.data[result.chunks - 1] &= result.msb_mask;\n\t\treturn result;\n\t}\n\n\ttemplate<size_t AmountBits, bool Signed = false>\n\tvalue<Bits> shr(const value<AmountBits> &amount) const {\n\t\t// Ensure our early return is correct by prohibiting values larger than 4 Gbit.\n\t\tstatic_assert(Bits <= chunk::mask, \"shr() of unreasonably large values is not supported\");\n\t\t// Detect shifts definitely large than Bits early.\n\t\tfor (size_t n = 1; n < amount.chunks; n++)\n\t\t\tif (amount.data[n] != 0)\n\t\t\t\treturn (Signed && is_neg()) ? value<Bits>().bit_not() : value<Bits>();\n\t\t// Past this point we can use the least significant chunk as the shift size.\n\t\tsize_t shift_chunks = amount.data[0] / chunk::bits;\n\t\tsize_t shift_bits = amount.data[0] % chunk::bits;\n\t\tif (shift_chunks >= chunks)\n\t\t\treturn (Signed && is_neg()) ? value<Bits>().bit_not() : value<Bits>();\n\t\tvalue<Bits> result;\n\t\tchunk::type carry = 0;\n\t\tfor (size_t n = 0; n < chunks - shift_chunks; n++) {\n\t\t\tresult.data[chunks - shift_chunks - 1 - n] = carry | (data[chunks - 1 - n] >> shift_bits);\n\t\t\tcarry = (shift_bits == 0) ? 0\n\t\t\t\t: data[chunks - 1 - n] << (chunk::bits - shift_bits);\n\t\t}\n\t\tif (Signed && is_neg()) {\n\t\t\tsize_t top_chunk_idx = amount.data[0] > Bits ? 0 : (Bits - amount.data[0]) / chunk::bits;\n\t\t\tsize_t top_chunk_bits = amount.data[0] > Bits ? 0 : (Bits - amount.data[0]) % chunk::bits;\n\t\t\tfor (size_t n = top_chunk_idx + 1; n < chunks; n++)\n\t\t\t\tresult.data[n] = chunk::mask;\n\t\t\tif (amount.data[0] != 0)\n\t\t\t\tresult.data[top_chunk_idx] |= chunk::mask << top_chunk_bits;\n\t\t\tresult.data[result.chunks - 1] &= result.msb_mask;\n\t\t}\n\t\treturn result;\n\t}\n\n\ttemplate<size_t AmountBits>\n\tvalue<Bits> sshr(const value<AmountBits> &amount) const {\n\t\treturn shr<AmountBits, /*Signed=*/true>(amount);\n\t}\n\n\ttemplate<size_t ResultBits, size_t SelBits>\n\tvalue<ResultBits> bmux(const value<SelBits> &sel) const {\n\t\tstatic_assert(ResultBits << SelBits == Bits, \"invalid sizes used in bmux()\");\n\t\tsize_t amount = sel.data[0] * ResultBits;\n\t\tsize_t shift_chunks = amount / chunk::bits;\n\t\tsize_t shift_bits = amount % chunk::bits;\n\t\tvalue<ResultBits> result;\n\t\tchunk::type carry = 0;\n\t\tif (ResultBits % chunk::bits + shift_bits > chunk::bits)\n\t\t\tcarry = data[result.chunks + shift_chunks] << (chunk::bits - shift_bits);\n\t\tfor (size_t n = 0; n < result.chunks; n++) {\n\t\t\tresult.data[result.chunks - 1 - n] = carry | (data[result.chunks + shift_chunks - 1 - n] >> shift_bits);\n\t\t\tcarry = (shift_bits == 0) ? 0\n\t\t\t\t: data[result.chunks + shift_chunks - 1 - n] << (chunk::bits - shift_bits);\n\t\t}\n\t\tresult.data[result.chunks - 1] &= result.msb_mask;\n\t\treturn result;\n\t}\n\n\ttemplate<size_t ResultBits, size_t SelBits>\n\tvalue<ResultBits> demux(const value<SelBits> &sel) const {\n\t\tstatic_assert(Bits << SelBits == ResultBits, \"invalid sizes used in demux()\");\n\t\tsize_t amount = sel.data[0] * Bits;\n\t\tsize_t shift_chunks = amount / chunk::bits;\n\t\tsize_t shift_bits = amount % chunk::bits;\n\t\tvalue<ResultBits> result;\n\t\tchunk::type carry = 0;\n\t\tfor (size_t n = 0; n < chunks; n++) {\n\t\t\tresult.data[shift_chunks + n] = (data[n] << shift_bits) | carry;\n\t\t\tcarry = (shift_bits == 0) ? 0\n\t\t\t\t: data[n] >> (chunk::bits - shift_bits);\n\t\t}\n\t\tif (Bits % chunk::bits + shift_bits > chunk::bits)\n\t\t\tresult.data[shift_chunks + chunks] = carry;\n\t\treturn result;\n\t}\n\n\tsize_t ctpop() const {\n\t\tsize_t count = 0;\n\t\tfor (size_t n = 0; n < chunks; n++) {\n\t\t\t// This loop implements the population count idiom as recognized by LLVM and GCC.\n\t\t\tfor (chunk::type x = data[n]; x != 0; count++)\n\t\t\t\tx = x & (x - 1);\n\t\t}\n\t\treturn count;\n\t}\n\n\tsize_t ctlz() const {\n\t\tsize_t count = 0;\n\t\tfor (size_t n = 0; n < chunks; n++) {\n\t\t\tchunk::type x = data[chunks - 1 - n];\n\t\t\t// First add to `count` as if the chunk is zero\n\t\t\tconstexpr size_t msb_chunk_bits = Bits % chunk::bits != 0 ? Bits % chunk::bits : chunk::bits;\n\t\t\tcount += (n == 0 ? msb_chunk_bits : chunk::bits);\n\t\t\t// If the chunk isn't zero, correct the `count` value and return\n\t\t\tif (x != 0) {\n\t\t\t\tfor (; x != 0; count--)\n\t\t\t\t\tx >>= 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn count;\n\t}\n\n\ttemplate<bool Invert, bool CarryIn>\n\tstd::pair<value<Bits>, bool /*CarryOut*/> alu(const value<Bits> &other) const {\n\t\tvalue<Bits> result;\n\t\tbool carry = CarryIn;\n\t\tfor (size_t n = 0; n < result.chunks; n++) {\n\t\t\tresult.data[n] = data[n] + (Invert ? ~other.data[n] : other.data[n]) + carry;\n\t\t\tif (result.chunks - 1 == n)\n\t\t\t\tresult.data[result.chunks - 1] &= result.msb_mask;\n\t\t\tcarry = (result.data[n] < data[n]) ||\n\t\t\t (result.data[n] == data[n] && carry);\n\t\t}\n\t\treturn {result, carry};\n\t}\n\n\tvalue<Bits> add(const value<Bits> &other) const {\n\t\treturn alu</*Invert=*/false, /*CarryIn=*/false>(other).first;\n\t}\n\n\tvalue<Bits> sub(const value<Bits> &other) const {\n\t\treturn alu</*Invert=*/true, /*CarryIn=*/true>(other).first;\n\t}\n\n\tvalue<Bits> neg() const {\n\t\treturn value<Bits>().sub(*this);\n\t}\n\n\tbool ucmp(const value<Bits> &other) const {\n\t\tbool carry;\n\t\tstd::tie(std::ignore, carry) = alu</*Invert=*/true, /*CarryIn=*/true>(other);\n\t\treturn !carry; // a.ucmp(b) ≡ a u< b\n\t}\n\n\tbool scmp(const value<Bits> &other) const {\n\t\tvalue<Bits> result;\n\t\tbool carry;\n\t\tstd::tie(result, carry) = alu</*Invert=*/true, /*CarryIn=*/true>(other);\n\t\tbool overflow = (is_neg() == !other.is_neg()) && (is_neg() != result.is_neg());\n\t\treturn result.is_neg() ^ overflow; // a.scmp(b) ≡ a s< b\n\t}\n\n\ttemplate<size_t ResultBits>\n\tvalue<ResultBits> mul(const value<Bits> &other) const {\n\t\tvalue<ResultBits> result;\n\t\twide_chunk_t wide_result[result.chunks + 1] = {};\n\t\tfor (size_t n = 0; n < chunks; n++) {\n\t\t\tfor (size_t m = 0; m < chunks && n + m < result.chunks; m++) {\n\t\t\t\twide_result[n + m] += wide_chunk_t(data[n]) * wide_chunk_t(other.data[m]);\n\t\t\t\twide_result[n + m + 1] += wide_result[n + m] >> chunk::bits;\n\t\t\t\twide_result[n + m] &= chunk::mask;\n\t\t\t}\n\t\t}\n\t\tfor (size_t n = 0; n < result.chunks; n++) {\n\t\t\tresult.data[n] = wide_result[n];\n\t\t}\n\t\tresult.data[result.chunks - 1] &= result.msb_mask;\n\t\treturn result;\n\t}\n\n\tstd::pair<value<Bits>, value<Bits>> udivmod(value<Bits> divisor) const {\n\t\tvalue<Bits> quotient;\n\t\tvalue<Bits> dividend = *this;\n\t\tif (dividend.ucmp(divisor))\n\t\t\treturn {/*quotient=*/value<Bits>{0u}, /*remainder=*/dividend};\n\t\tint64_t divisor_shift = divisor.ctlz() - dividend.ctlz();\n\t\tassert(divisor_shift >= 0);\n\t\tdivisor = divisor.shl(value<Bits>{(chunk::type) divisor_shift});\n\t\tfor (size_t step = 0; step <= divisor_shift; step++) {\n\t\t\tquotient = quotient.shl(value<Bits>{1u});\n\t\t\tif (!dividend.ucmp(divisor)) {\n\t\t\t\tdividend = dividend.sub(divisor);\n\t\t\t\tquotient.set_bit(0, true);\n\t\t\t}\n\t\t\tdivisor = divisor.shr(value<Bits>{1u});\n\t\t}\n\t\treturn {quotient, /*remainder=*/dividend};\n\t}\n\n\tstd::pair<value<Bits>, value<Bits>> sdivmod(const value<Bits> &other) const {\n\t\tvalue<Bits + 1> quotient;\n\t\tvalue<Bits + 1> remainder;\n\t\tvalue<Bits + 1> dividend = sext<Bits + 1>();\n\t\tvalue<Bits + 1> divisor = other.template sext<Bits + 1>();\n\t\tif (dividend.is_neg()) dividend = dividend.neg();\n\t\tif (divisor.is_neg()) divisor = divisor.neg();\n\t\tstd::tie(quotient, remainder) = dividend.udivmod(divisor);\n\t\tif (dividend.is_neg() != divisor.is_neg()) quotient = quotient.neg();\n\t\tif (dividend.is_neg()) remainder = remainder.neg();\n\t\treturn {quotient.template trunc<Bits>(), remainder.template trunc<Bits>()};\n\t}\n};\n\n// Expression template for a slice, usable as lvalue or rvalue, and composable with other expression templates here.\ntemplate<class T, size_t Stop, size_t Start>\nstruct slice_expr : public expr_base<slice_expr<T, Stop, Start>> {\n\tstatic_assert(Stop >= Start, \"slice_expr() may not reverse bit order\");\n\tstatic_assert(Start < T::bits && Stop < T::bits, \"slice_expr() must be within bounds\");\n\tstatic constexpr size_t bits = Stop - Start + 1;\n\n\tT &expr;\n\n\tslice_expr(T &expr) : expr(expr) {}\n\tslice_expr(const slice_expr<T, Stop, Start> &) = delete;\n\n\tCXXRTL_ALWAYS_INLINE\n\toperator value<bits>() const {\n\t\treturn static_cast<const value<T::bits> &>(expr)\n\t\t\t.template rtrunc<T::bits - Start>()\n\t\t\t.template trunc<bits>();\n\t}\n\n\tCXXRTL_ALWAYS_INLINE\n\tslice_expr<T, Stop, Start> &operator=(const value<bits> &rhs) {\n\t\t// Generic partial assignment implemented using a read-modify-write operation on the sliced expression.\n\t\texpr = static_cast<const value<T::bits> &>(expr)\n\t\t\t.template blit<Stop, Start>(rhs);\n\t\treturn *this;\n\t}\n\n\t// A helper that forces the cast to value<>, which allows deduction to work.\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<bits> val() const {\n\t\treturn static_cast<const value<bits> &>(*this);\n\t}\n};\n\n// Expression template for a concatenation, usable as lvalue or rvalue, and composable with other expression templates here.\ntemplate<class T, class U>\nstruct concat_expr : public expr_base<concat_expr<T, U>> {\n\tstatic constexpr size_t bits = T::bits + U::bits;\n\n\tT &ms_expr;\n\tU &ls_expr;\n\n\tconcat_expr(T &ms_expr, U &ls_expr) : ms_expr(ms_expr), ls_expr(ls_expr) {}\n\tconcat_expr(const concat_expr<T, U> &) = delete;\n\n\tCXXRTL_ALWAYS_INLINE\n\toperator value<bits>() const {\n\t\tvalue<bits> ms_shifted = static_cast<const value<T::bits> &>(ms_expr)\n\t\t\t.template rzext<bits>();\n\t\tvalue<bits> ls_extended = static_cast<const value<U::bits> &>(ls_expr)\n\t\t\t.template zext<bits>();\n\t\treturn ms_shifted.bit_or(ls_extended);\n\t}\n\n\tCXXRTL_ALWAYS_INLINE\n\tconcat_expr<T, U> &operator=(const value<bits> &rhs) {\n\t\tms_expr = rhs.template rtrunc<T::bits>();\n\t\tls_expr = rhs.template trunc<U::bits>();\n\t\treturn *this;\n\t}\n\n\t// A helper that forces the cast to value<>, which allows deduction to work.\n\tCXXRTL_ALWAYS_INLINE\n\tvalue<bits> val() const {\n\t\treturn static_cast<const value<bits> &>(*this);\n\t}\n};\n\n// Base class for expression templates, providing helper methods for operations that are valid on both rvalues and lvalues.\n//\n// Note that expression objects (slices and concatenations) constructed in this way should NEVER be captured because\n// they refer to temporaries that will, in general, only live until the end of the statement. For example, both of\n// these snippets perform use-after-free:\n//\n// const auto &a = val.slice<7,0>().slice<1>();\n// value<1> b = a;\n//\n// auto &&c = val.slice<7,0>().slice<1>();\n// c = value<1>{1u};\n//\n// An easy way to write code using slices and concatenations safely is to follow two simple rules:\n// * Never explicitly name any type except `value<W>` or `const value<W> &`.\n// * Never use a `const auto &` or `auto &&` in any such expression.\n// Then, any code that compiles will be well-defined.\ntemplate<class T>\nstruct expr_base {\n\ttemplate<size_t Stop, size_t Start = Stop>\n\tCXXRTL_ALWAYS_INLINE\n\tslice_expr<const T, Stop, Start> slice() const {\n\t\treturn {*static_cast<const T *>(this)};\n\t}\n\n\ttemplate<size_t Stop, size_t Start = Stop>\n\tCXXRTL_ALWAYS_INLINE\n\tslice_expr<T, Stop, Start> slice() {\n\t\treturn {*static_cast<T *>(this)};\n\t}\n\n\ttemplate<class U>\n\tCXXRTL_ALWAYS_INLINE\n\tconcat_expr<const T, typename std::remove_reference<const U>::type> concat(const U &other) const {\n\t\treturn {*static_cast<const T *>(this), other};\n\t}\n\n\ttemplate<class U>\n\tCXXRTL_ALWAYS_INLINE\n\tconcat_expr<T, typename std::remove_reference<U>::type> concat(U &&other) {\n\t\treturn {*static_cast<T *>(this), other};\n\t}\n};\n\ntemplate<size_t Bits>\nstd::ostream &operator<<(std::ostream &os, const value<Bits> &val) {\n\tauto old_flags = os.flags(std::ios::right);\n\tauto old_width = os.width(0);\n\tauto old_fill = os.fill('0');\n\tos << val.bits << '\\'' << std::hex;\n\tfor (size_t n = val.chunks - 1; n != (size_t)-1; n--) {\n\t\tif (n == val.chunks - 1 && Bits % value<Bits>::chunk::bits != 0)\n\t\t\tos.width((Bits % value<Bits>::chunk::bits + 3) / 4);\n\t\telse\n\t\t\tos.width((value<Bits>::chunk::bits + 3) / 4);\n\t\tos << val.data[n];\n\t}\n\tos.fill(old_fill);\n\tos.width(old_width);\n\tos.flags(old_flags);\n\treturn os;\n}\n\ntemplate<size_t Bits>\nstruct wire {\n\tstatic constexpr size_t bits = Bits;\n\n\tvalue<Bits> curr;\n\tvalue<Bits> next;\n\n\twire() = default;\n\texplicit constexpr wire(const value<Bits> &init) : curr(init), next(init) {}\n\ttemplate<typename... Init>\n\texplicit constexpr wire(Init ...init) : curr{init...}, next{init...} {}\n\n\t// Copying and copy-assigning values is natural. If, however, a value is replaced with a wire,\n\t// e.g. because a module is built with a different optimization level, then existing code could\n\t// unintentionally copy a wire instead, which would create a subtle but serious bug. To make sure\n\t// this doesn't happen, prohibit copying and copy-assigning wires.\n\twire(const wire<Bits> &) = delete;\n\twire<Bits> &operator=(const wire<Bits> &) = delete;\n\n\twire(wire<Bits> &&) = default;\n\twire<Bits> &operator=(wire<Bits> &&) = default;\n\n\ttemplate<class IntegerT>\n\tCXXRTL_ALWAYS_INLINE\n\tIntegerT get() const {\n\t\treturn curr.template get<IntegerT>();\n\t}\n\n\ttemplate<class IntegerT>\n\tCXXRTL_ALWAYS_INLINE\n\tvoid set(IntegerT other) {\n\t\tnext.template set<IntegerT>(other);\n\t}\n\n\t// This method intentionally takes a mandatory argument (to make it more difficult to misuse in\n\t// black box implementations, leading to missed observer events). It is generic over its argument\n\t// to allow the `on_update` method to be non-virtual.\n\ttemplate<class ObserverT>\n\tbool commit(ObserverT &observer) {\n\t\tif (curr != next) {\n\t\t\tobserver.on_update(curr.chunks, curr.data, next.data);\n\t\t\tcurr = next;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n};\n\ntemplate<size_t Bits>\nstd::ostream &operator<<(std::ostream &os, const wire<Bits> &val) {\n\tos << val.curr;\n\treturn os;\n}\n\ntemplate<size_t Width>\nstruct memory {\n\tconst size_t depth;\n\tstd::unique_ptr<value<Width>[]> data;\n\n\texplicit memory(size_t depth) : depth(depth), data(new value<Width>[depth]) {}\n\n\tmemory(const memory<Width> &) = delete;\n\tmemory<Width> &operator=(const memory<Width> &) = delete;\n\n\tmemory(memory<Width> &&) = default;\n\tmemory<Width> &operator=(memory<Width> &&other) {\n\t\tassert(depth == other.depth);\n\t\tdata = std::move(other.data);\n\t\twrite_queue = std::move(other.write_queue);\n\t\treturn *this;\n\t}\n\n\t// An operator for direct memory reads. May be used at any time during the simulation.\n\tconst value<Width> &operator [](size_t index) const {\n\t\tassert(index < depth);\n\t\treturn data[index];\n\t}\n\n\t// An operator for direct memory writes. May only be used before the simulation is started. If used\n\t// after the simulation is started, the design may malfunction.\n\tvalue<Width> &operator [](size_t index) {\n\t\tassert(index < depth);\n\t\treturn data[index];\n\t}\n\n\t// A simple way to make a writable memory would be to use an array of wires instead of an array of values.\n\t// However, there are two significant downsides to this approach: first, it has large overhead (2× space\n\t// overhead, and O(depth) time overhead during commit); second, it does not simplify handling write port\n\t// priorities. Although in principle write ports could be ordered or conditionally enabled in generated\n\t// code based on their priorities and selected addresses, the feedback arc set problem is computationally\n\t// expensive, and the heuristic based algorithms are not easily modified to guarantee (rather than prefer)\n\t// a particular write port evaluation order.\n\t//\n\t// The approach used here instead is to queue writes into a buffer during the eval phase, then perform\n\t// the writes during the commit phase in the priority order. This approach has low overhead, with both space\n\t// and time proportional to the amount of write ports. Because virtually every memory in a practical design\n\t// has at most two write ports, linear search is used on every write, being the fastest and simplest approach.\n\tstruct write {\n\t\tsize_t index;\n\t\tvalue<Width> val;\n\t\tvalue<Width> mask;\n\t\tint priority;\n\t};\n\tstd::vector<write> write_queue;\n\n\tvoid update(size_t index, const value<Width> &val, const value<Width> &mask, int priority = 0) {\n\t\tassert(index < depth);\n\t\t// Queue up the write while keeping the queue sorted by priority.\n\t\twrite_queue.insert(\n\t\t\tstd::upper_bound(write_queue.begin(), write_queue.end(), priority,\n\t\t\t\t[](const int a, const write& b) { return a < b.priority; }),\n\t\t\twrite { index, val, mask, priority });\n\t}\n\n\t// See the note for `wire::commit()`.\n\ttemplate<class ObserverT>\n\tbool commit(ObserverT &observer) {\n\t\tbool changed = false;\n\t\tfor (const write &entry : write_queue) {\n\t\t\tvalue<Width> elem = data[entry.index];\n\t\t\telem = elem.update(entry.val, entry.mask);\n\t\t\tif (data[entry.index] != elem) {\n\t\t\t\tobserver.on_update(value<Width>::chunks, data[0].data, elem.data, entry.index);\n\t\t\t\tchanged |= true;\n\t\t\t}\n\t\t\tdata[entry.index] = elem;\n\t\t}\n\t\twrite_queue.clear();\n\t\treturn changed;\n\t}\n};\n\nstruct metadata {\n\tconst enum {\n\t\tMISSING = 0,\n\t\tUINT \t= 1,\n\t\tSINT \t= 2,\n\t\tSTRING \t= 3,\n\t\tDOUBLE \t= 4,\n\t} value_type;\n\n\t// In debug mode, using the wrong .as_*() function will assert.\n\t// In release mode, using the wrong .as_*() function will safely return a default value.\n\tconst uint64_t uint_value = 0;\n\tconst int64_t sint_value = 0;\n\tconst std::string string_value = \"\";\n\tconst double double_value = 0.0;\n\n\tmetadata() : value_type(MISSING) {}\n\tmetadata(uint64_t value) : value_type(UINT), uint_value(value) {}\n\tmetadata(int64_t value) : value_type(SINT), sint_value(value) {}\n\tmetadata(const std::string &value) : value_type(STRING), string_value(value) {}\n\tmetadata(const char *value) : value_type(STRING), string_value(value) {}\n\tmetadata(double value) : value_type(DOUBLE), double_value(value) {}\n\n\tmetadata(const metadata &) = default;\n\tmetadata &operator=(const metadata &) = delete;\n\n\tuint64_t as_uint() const {\n\t\tassert(value_type == UINT);\n\t\treturn uint_value;\n\t}\n\n\tint64_t as_sint() const {\n\t\tassert(value_type == SINT);\n\t\treturn sint_value;\n\t}\n\n\tconst std::string &as_string() const {\n\t\tassert(value_type == STRING);\n\t\treturn string_value;\n\t}\n\n\tdouble as_double() const {\n\t\tassert(value_type == DOUBLE);\n\t\treturn double_value;\n\t}\n};\n\ntypedef std::map<std::string, metadata> metadata_map;\n\nstruct performer;\n\n// An object that allows formatting a string lazily.\nstruct lazy_fmt {\n\tvirtual std::string operator() () const = 0;\n};\n\n// Flavor of a `$check` cell.\nenum class flavor {\n\t// Corresponds to a `$assert` cell in other flows, and a Verilog `assert ()` statement.\n\tASSERT,\n\t// Corresponds to a `$assume` cell in other flows, and a Verilog `assume ()` statement.\n\tASSUME,\n\t// Corresponds to a `$live` cell in other flows, and a Verilog `assert (eventually)` statement.\n\tASSERT_EVENTUALLY,\n\t// Corresponds to a `$fair` cell in other flows, and a Verilog `assume (eventually)` statement.\n\tASSUME_EVENTUALLY,\n\t// Corresponds to a `$cover` cell in other flows, and a Verilog `cover ()` statement.\n\tCOVER,\n};\n\n// An object that can be passed to a `eval()` method in order to act on side effects. The default behavior implemented\n// below is the same as the behavior of `eval(nullptr)`, except that `-print-output` option of `write_cxxrtl` is not\n// taken into account.\nstruct performer {\n\t// Called by generated formatting code to evaluate a Verilog `$time` expression.\n\tvirtual int64_t vlog_time() const { return 0; }\n\n\t// Called by generated formatting code to evaluate a Verilog `$realtime` expression.\n\tvirtual double vlog_realtime() const { return vlog_time(); }\n\n\t// Called when a `$print` cell is triggered.\n\tvirtual void on_print(const lazy_fmt &formatter, const metadata_map &attributes) {\n\t\tstd::cout << formatter();\n\t}\n\n\t// Called when a `$check` cell is triggered.\n\tvirtual void on_check(flavor type, bool condition, const lazy_fmt &formatter, const metadata_map &attributes) {\n\t\tif (type == flavor::ASSERT || type == flavor::ASSUME) {\n\t\t\tif (!condition)\n\t\t\t\tstd::cerr << formatter();\n\t\t\tCXXRTL_ASSERT(condition && \"Check failed\");\n\t\t}\n\t}\n};\n\n// An object that can be passed to a `commit()` method in order to produce a replay log of every state change in\n// the simulation. Unlike `performer`, `observer` does not use virtual calls as their overhead is unacceptable, and\n// a comparatively heavyweight template-based solution is justified.\nstruct observer {\n\t// Called when the `commit()` method for a wire is about to update the `chunks` chunks at `base` with `chunks` chunks\n\t// at `value` that have a different bit pattern. It is guaranteed that `chunks` is equal to the wire chunk count and\n\t// `base` points to the first chunk.\n\tvoid on_update(size_t chunks, const chunk_t *base, const chunk_t *value) {}\n\n\t// Called when the `commit()` method for a memory is about to update the `chunks` chunks at `&base[chunks * index]`\n\t// with `chunks` chunks at `value` that have a different bit pattern. It is guaranteed that `chunks` is equal to\n\t// the memory element chunk count and `base` points to the first chunk of the first element of the memory.\n\tvoid on_update(size_t chunks, const chunk_t *base, const chunk_t *value, size_t index) {}\n};\n\n// Must be kept in sync with `struct FmtPart` in kernel/fmt.h!\n// Default member initializers would make this a non-aggregate-type in C++11, so they are commented out.\nstruct fmt_part {\n\tenum {\n\t\tSTRING = 0,\n\t\tINTEGER = 1,\n\t\tCHARACTER = 2,\n\t\tVLOG_TIME = 3,\n\t} type;\n\n\t// STRING type\n\tstd::string str;\n\n\t// INTEGER/CHARACTER types\n\t// + value<Bits> val;\n\n\t// INTEGER/CHARACTER/VLOG_TIME types\n\tenum {\n\t\tRIGHT\t= 0,\n\t\tLEFT\t= 1,\n\t} justify; // = RIGHT;\n\tchar padding; // = '\\0';\n\tsize_t width; // = 0;\n\n\t// INTEGER type\n\tunsigned base; // = 10;\n\tbool signed_; // = false;\n\tbool plus; // = false;\n\n\t// VLOG_TIME type\n\tbool realtime; // = false;\n\t// + int64_t itime;\n\t// + double ftime;\n\n\t// Format the part as a string.\n\t//\n\t// The values of `vlog_time` and `vlog_realtime` are used for Verilog `$time` and `$realtime`, correspondingly.\n\ttemplate<size_t Bits>\n\tstd::string render(value<Bits> val, performer *performer = nullptr)\n\t{\n\t\t// We might want to replace some of these bit() calls with direct\n\t\t// chunk access if it turns out to be slow enough to matter.\n\t\tstd::string buf;\n\t\tswitch (type) {\n\t\t\tcase STRING:\n\t\t\t\treturn str;\n\n\t\t\tcase CHARACTER: {\n\t\t\t\tbuf.reserve(Bits/8);\n\t\t\t\tfor (int i = 0; i < Bits; i += 8) {\n\t\t\t\t\tchar ch = 0;\n\t\t\t\t\tfor (int j = 0; j < 8 && i + j < int(Bits); j++)\n\t\t\t\t\t\tif (val.bit(i + j))\n\t\t\t\t\t\t\tch |= 1 << j;\n\t\t\t\t\tif (ch != 0)\n\t\t\t\t\t\tbuf.append({ch});\n\t\t\t\t}\n\t\t\t\tstd::reverse(buf.begin(), buf.end());\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase INTEGER: {\n\t\t\t\tsize_t width = Bits;\n\t\t\t\tif (base != 10) {\n\t\t\t\t\twidth = 0;\n\t\t\t\t\tfor (size_t index = 0; index < Bits; index++)\n\t\t\t\t\t\tif (val.bit(index))\n\t\t\t\t\t\t\twidth = index + 1;\n\t\t\t\t}\n\n\t\t\t\tif (base == 2) {\n\t\t\t\t\tfor (size_t i = width; i > 0; i--)\n\t\t\t\t\t\tbuf += (val.bit(i - 1) ? '1' : '0');\n\t\t\t\t} else if (base == 8 || base == 16) {\n\t\t\t\t\tsize_t step = (base == 16) ? 4 : 3;\n\t\t\t\t\tfor (size_t index = 0; index < width; index += step) {\n\t\t\t\t\t\tuint8_t value = val.bit(index) | (val.bit(index + 1) << 1) | (val.bit(index + 2) << 2);\n\t\t\t\t\t\tif (step == 4)\n\t\t\t\t\t\t\tvalue |= val.bit(index + 3) << 3;\n\t\t\t\t\t\tbuf += \"0123456789abcdef\"[value];\n\t\t\t\t\t}\n\t\t\t\t\tstd::reverse(buf.begin(), buf.end());\n\t\t\t\t} else if (base == 10) {\n\t\t\t\t\tbool negative = signed_ && val.is_neg();\n\t\t\t\t\tif (negative)\n\t\t\t\t\t\tval = val.neg();\n\t\t\t\t\tif (val.is_zero())\n\t\t\t\t\t\tbuf += '0';\n\t\t\t\t\tvalue<(Bits > 4 ? Bits : 4)> xval = val.template zext<(Bits > 4 ? Bits : 4)>();\n\t\t\t\t\twhile (!xval.is_zero()) {\n\t\t\t\t\t\tvalue<(Bits > 4 ? Bits : 4)> quotient, remainder;\n\t\t\t\t\t\tif (Bits >= 4)\n\t\t\t\t\t\t\tstd::tie(quotient, remainder) = xval.udivmod(value<(Bits > 4 ? Bits : 4)>{10u});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tstd::tie(quotient, remainder) = std::make_pair(value<(Bits > 4 ? Bits : 4)>{0u}, xval);\n\t\t\t\t\t\tbuf += '0' + remainder.template trunc<4>().template get<uint8_t>();\n\t\t\t\t\t\txval = quotient;\n\t\t\t\t\t}\n\t\t\t\t\tif (negative || plus)\n\t\t\t\t\t\tbuf += negative ? '-' : '+';\n\t\t\t\t\tstd::reverse(buf.begin(), buf.end());\n\t\t\t\t} else assert(false && \"Unsupported base for fmt_part\");\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase VLOG_TIME: {\n\t\t\t\tif (performer) {\n\t\t\t\t\tbuf = realtime ? std::to_string(performer->vlog_realtime()) : std::to_string(performer->vlog_time());\n\t\t\t\t} else {\n\t\t\t\t\tbuf = realtime ? std::to_string(0.0) : std::to_string(0);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tstd::string str;\n\t\tassert(width == 0 || padding != '\\0');\n\t\tif (justify == RIGHT && buf.size() < width) {\n\t\t\tsize_t pad_width = width - buf.size();\n\t\t\tif (padding == '0' && (buf.front() == '+' || buf.front() == '-')) {\n\t\t\t\tstr += buf.front();\n\t\t\t\tbuf.erase(0, 1);\n\t\t\t}\n\t\t\tstr += std::string(pad_width, padding);\n\t\t}\n\t\tstr += buf;\n\t\tif (justify == LEFT && buf.size() < width)\n\t\t\tstr += std::string(width - buf.size(), padding);\n\t\treturn str;\n\t}\n};\n\n// Tag class to disambiguate values/wires and their aliases.\nstruct debug_alias {};\n\n// Tag declaration to disambiguate values and debug outlines.\nusing debug_outline = ::_cxxrtl_outline;\n\n// This structure is intended for consumption via foreign function interfaces, like Python's ctypes.\n// Because of this it uses a C-style layout that is easy to parse rather than more idiomatic C++.\n//\n// To avoid violating strict aliasing rules, this structure has to be a subclass of the one used\n// in the C API, or it would not be possible to cast between the pointers to these.\n//\n// The `attrs` member cannot be owned by this structure because a `cxxrtl_object` can be created\n// from external C code.\nstruct debug_item : ::cxxrtl_object {\n\t// Object types.\n\tenum : uint32_t {\n\t\tVALUE = CXXRTL_VALUE,\n\t\tWIRE = CXXRTL_WIRE,\n\t\tMEMORY = CXXRTL_MEMORY,\n\t\tALIAS = CXXRTL_ALIAS,\n\t\tOUTLINE = CXXRTL_OUTLINE,\n\t};\n\n\t// Object flags.\n\tenum : uint32_t {\n\t\tINPUT = CXXRTL_INPUT,\n\t\tOUTPUT = CXXRTL_OUTPUT,\n\t\tINOUT = CXXRTL_INOUT,\n\t\tDRIVEN_SYNC = CXXRTL_DRIVEN_SYNC,\n\t\tDRIVEN_COMB = CXXRTL_DRIVEN_COMB,\n\t\tUNDRIVEN = CXXRTL_UNDRIVEN,\n\t};\n\n\tdebug_item(const ::cxxrtl_object &object) : cxxrtl_object(object) {}\n\n\ttemplate<size_t Bits>\n\tdebug_item(value<Bits> &item, size_t lsb_offset = 0, uint32_t flags_ = 0) {\n\t\tstatic_assert(Bits == 0 || sizeof(item) == value<Bits>::chunks * sizeof(chunk_t),\n\t\t \"value<Bits> is not compatible with C layout\");\n\t\ttype = VALUE;\n\t\tflags = flags_;\n\t\twidth = Bits;\n\t\tlsb_at = lsb_offset;\n\t\tdepth = 1;\n\t\tzero_at = 0;\n\t\tcurr = item.data;\n\t\tnext = item.data;\n\t\toutline = nullptr;\n\t\tattrs = nullptr;\n\t}\n\n\ttemplate<size_t Bits>\n\tdebug_item(const value<Bits> &item, size_t lsb_offset = 0) {\n\t\tstatic_assert(Bits == 0 || sizeof(item) == value<Bits>::chunks * sizeof(chunk_t),\n\t\t \"value<Bits> is not compatible with C layout\");\n\t\ttype = VALUE;\n\t\tflags = DRIVEN_COMB;\n\t\twidth = Bits;\n\t\tlsb_at = lsb_offset;\n\t\tdepth = 1;\n\t\tzero_at = 0;\n\t\tcurr = const_cast<chunk_t*>(item.data);\n\t\tnext = nullptr;\n\t\toutline = nullptr;\n\t\tattrs = nullptr;\n\t}\n\n\ttemplate<size_t Bits>\n\tdebug_item(wire<Bits> &item, size_t lsb_offset = 0, uint32_t flags_ = 0) {\n\t\tstatic_assert(Bits == 0 ||\n\t\t (sizeof(item.curr) == value<Bits>::chunks * sizeof(chunk_t) &&\n\t\t sizeof(item.next) == value<Bits>::chunks * sizeof(chunk_t)),\n\t\t \"wire<Bits> is not compatible with C layout\");\n\t\ttype = WIRE;\n\t\tflags = flags_;\n\t\twidth = Bits;\n\t\tlsb_at = lsb_offset;\n\t\tdepth = 1;\n\t\tzero_at = 0;\n\t\tcurr = item.curr.data;\n\t\tnext = item.next.data;\n\t\toutline = nullptr;\n\t\tattrs = nullptr;\n\t}\n\n\ttemplate<size_t Width>\n\tdebug_item(memory<Width> &item, size_t zero_offset = 0) {\n\t\tstatic_assert(Width == 0 || sizeof(item.data[0]) == value<Width>::chunks * sizeof(chunk_t),\n\t\t \"memory<Width> is not compatible with C layout\");\n\t\ttype = MEMORY;\n\t\tflags = 0;\n\t\twidth = Width;\n\t\tlsb_at = 0;\n\t\tdepth = item.depth;\n\t\tzero_at = zero_offset;\n\t\tcurr = item.data ? item.data[0].data : nullptr;\n\t\tnext = nullptr;\n\t\toutline = nullptr;\n\t\tattrs = nullptr;\n\t}\n\n\ttemplate<size_t Bits>\n\tdebug_item(debug_alias, const value<Bits> &item, size_t lsb_offset = 0) {\n\t\tstatic_assert(Bits == 0 || sizeof(item) == value<Bits>::chunks * sizeof(chunk_t),\n\t\t \"value<Bits> is not compatible with C layout\");\n\t\ttype = ALIAS;\n\t\tflags = DRIVEN_COMB;\n\t\twidth = Bits;\n\t\tlsb_at = lsb_offset;\n\t\tdepth = 1;\n\t\tzero_at = 0;\n\t\tcurr = const_cast<chunk_t*>(item.data);\n\t\tnext = nullptr;\n\t\toutline = nullptr;\n\t\tattrs = nullptr;\n\t}\n\n\ttemplate<size_t Bits>\n\tdebug_item(debug_alias, const wire<Bits> &item, size_t lsb_offset = 0) {\n\t\tstatic_assert(Bits == 0 ||\n\t\t (sizeof(item.curr) == value<Bits>::chunks * sizeof(chunk_t) &&\n\t\t sizeof(item.next) == value<Bits>::chunks * sizeof(chunk_t)),\n\t\t \"wire<Bits> is not compatible with C layout\");\n\t\ttype = ALIAS;\n\t\tflags = DRIVEN_COMB;\n\t\twidth = Bits;\n\t\tlsb_at = lsb_offset;\n\t\tdepth = 1;\n\t\tzero_at = 0;\n\t\tcurr = const_cast<chunk_t*>(item.curr.data);\n\t\tnext = nullptr;\n\t\toutline = nullptr;\n\t\tattrs = nullptr;\n\t}\n\n\ttemplate<size_t Bits>\n\tdebug_item(debug_outline &group, const value<Bits> &item, size_t lsb_offset = 0) {\n\t\tstatic_assert(Bits == 0 || sizeof(item) == value<Bits>::chunks * sizeof(chunk_t),\n\t\t \"value<Bits> is not compatible with C layout\");\n\t\ttype = OUTLINE;\n\t\tflags = DRIVEN_COMB;\n\t\twidth = Bits;\n\t\tlsb_at = lsb_offset;\n\t\tdepth = 1;\n\t\tzero_at = 0;\n\t\tcurr = const_cast<chunk_t*>(item.data);\n\t\tnext = nullptr;\n\t\toutline = &group;\n\t\tattrs = nullptr;\n\t}\n\n\ttemplate<size_t Bits, class IntegerT>\n\tIntegerT get() const {\n\t\tassert(width == Bits && depth == 1);\n\t\tvalue<Bits> item;\n\t\tstd::copy(curr, curr + value<Bits>::chunks, item.data);\n\t\treturn item.template get<IntegerT>();\n\t}\n\n\ttemplate<size_t Bits, class IntegerT>\n\tvoid set(IntegerT other) const {\n\t\tassert(width == Bits && depth == 1);\n\t\tvalue<Bits> item;\n\t\titem.template set<IntegerT>(other);\n\t\tstd::copy(item.data, item.data + value<Bits>::chunks, next);\n\t}\n};\nstatic_assert(std::is_standard_layout<debug_item>::value, \"debug_item is not compatible with C layout\");\n\n} // namespace cxxrtl\n\ntypedef struct _cxxrtl_attr_set {\n\tcxxrtl::metadata_map map;\n} *cxxrtl_attr_set;\n\nnamespace cxxrtl {\n\n// Representation of an attribute set in the C++ interface.\nusing debug_attrs = ::_cxxrtl_attr_set;\n\nstruct debug_items {\n\t// Debug items may be composed of multiple parts, but the attributes are shared between all of them.\n\t// There are additional invariants, not all of which are not checked by this code:\n\t// - Memories and non-memories cannot be mixed together.\n\t// - Bit indices (considering `lsb_at` and `width`) must not overlap.\n\t// - Row indices (considering `depth` and `zero_at`) must be the same.\n\t// - The `INPUT` and `OUTPUT` flags must be the same for all parts.\n\t// Other than that, the parts can be quite different, e.g. it is OK to mix a value, a wire, an alias,\n\t// and an outline, in the debug information for a single name in four parts.\n\tstd::map<std::string, std::vector<debug_item>> table;\n\tstd::map<std::string, std::unique_ptr<debug_attrs>> attrs_table;\n\n\tvoid add(const std::string &path, debug_item &&item, metadata_map &&item_attrs = {}) {\n\t\tassert((path.empty() || path[path.size() - 1] != ' ') && path.find(\" \") == std::string::npos);\n\t\tstd::unique_ptr<debug_attrs> &attrs = attrs_table[path];\n\t\tif (attrs.get() == nullptr)\n\t\t\tattrs = std::unique_ptr<debug_attrs>(new debug_attrs);\n\t\tfor (auto attr : item_attrs)\n\t\t\tattrs->map.insert(attr);\n\t\titem.attrs = attrs.get();\n\t\tstd::vector<debug_item> &parts = table[path];\n\t\tparts.emplace_back(item);\n\t\tstd::sort(parts.begin(), parts.end(),\n\t\t\t[](const debug_item &a, const debug_item &b) {\n\t\t\t\treturn a.lsb_at < b.lsb_at;\n\t\t\t});\n\t}\n\n\tsize_t count(const std::string &path) const {\n\t\tif (table.count(path) == 0)\n\t\t\treturn 0;\n\t\treturn table.at(path).size();\n\t}\n\n\tconst std::vector<debug_item> &at(const std::string &path) const {\n\t\treturn table.at(path);\n\t}\n\n\t// Like `at()`, but operates only on single-part debug items.\n\tconst debug_item &operator [](const std::string &path) const {\n\t\tconst std::vector<debug_item> &parts = table.at(path);\n\t\tassert(parts.size() == 1);\n\t\treturn parts.at(0);\n\t}\n\n\tbool is_memory(const std::string &path) const {\n\t\treturn at(path).at(0).type == debug_item::MEMORY;\n\t}\n\n\tconst metadata_map &attrs(const std::string &path) const {\n\t\treturn attrs_table.at(path)->map;\n\t}\n};\n\n// Only `module` scopes are defined. The type is implicit, since Yosys does not currently support\n// any other scope types.\nstruct debug_scope {\n\tstd::string module_name;\n\tstd::unique_ptr<debug_attrs> module_attrs;\n\tstd::unique_ptr<debug_attrs> cell_attrs;\n};\n\nstruct debug_scopes {\n\tstd::map<std::string, debug_scope> table;\n\n\tvoid add(const std::string &path, const std::string &module_name, metadata_map &&module_attrs, metadata_map &&cell_attrs) {\n\t\tassert((path.empty() || path[path.size() - 1] != ' ') && path.find(\" \") == std::string::npos);\n\t\tassert(table.count(path) == 0);\n\t\tdebug_scope &scope = table[path];\n\t\tscope.module_name = module_name;\n\t\tscope.module_attrs = std::unique_ptr<debug_attrs>(new debug_attrs { module_attrs });\n\t\tscope.cell_attrs = std::unique_ptr<debug_attrs>(new debug_attrs { cell_attrs });\n\t}\n\n\tsize_t contains(const std::string &path) const {\n\t\treturn table.count(path);\n\t}\n\n\tconst debug_scope &operator [](const std::string &path) const {\n\t\treturn table.at(path);\n\t}\n};\n\n// Tag class to disambiguate the default constructor used by the toplevel module that calls `reset()`,\n// and the constructor of interior modules that should not call it.\nstruct interior {};\n\n// The core API of the `module` class consists of only four virtual methods: `reset()`, `eval()`,\n// `commit`, and `debug_info()`. (The virtual destructor is made necessary by C++.) Every other method\n// is a convenience method, and exists solely to simplify some common pattern for C++ API consumers.\n// No behavior may be added to such convenience methods that other parts of CXXRTL can rely on, since\n// there is no guarantee they will be called (and, for example, other CXXRTL libraries will often call\n// the `eval()` and `commit()` directly instead, as well as being exposed in the C API).\nstruct module {\n\tmodule() {}\n\tvirtual ~module() {}\n\n\t// Modules with black boxes cannot be copied. Although not all designs include black boxes,\n\t// delete the copy constructor and copy assignment operator to make sure that any downstream\n\t// code that manipulates modules doesn't accidentally depend on their availability.\n\tmodule(const module &) = delete;\n\tmodule &operator=(const module &) = delete;\n\n\tmodule(module &&) = default;\n\tmodule &operator=(module &&) = default;\n\n\tvirtual void reset() = 0;\n\n\t// The `eval()` callback object, `performer`, is included in the virtual call signature since\n\t// the generated code has broadly identical performance properties.\n\tvirtual bool eval(performer *performer = nullptr) = 0;\n\n\t// The `commit()` callback object, `observer`, is not included in the virtual call signature since\n\t// the generated code is severely pessimized by it. To observe commit events, the non-virtual\n\t// `commit(observer *)` overload must be called directly on a `module` subclass.\n\tvirtual bool commit() = 0;\n\n\tsize_t step(performer *performer = nullptr) {\n\t\tsize_t deltas = 0;\n\t\tbool converged = false;\n\t\tdo {\n\t\t\tconverged = eval(performer);\n\t\t\tdeltas++;\n\t\t} while (commit() && !converged);\n\t\treturn deltas;\n\t}\n\n\tvirtual void debug_info(debug_items *items, debug_scopes *scopes, std::string path, metadata_map &&cell_attrs = {}) {\n\t\t(void)items, (void)scopes, (void)path, (void)cell_attrs;\n\t}\n\n\t// Compatibility method.\n#if __has_attribute(deprecated)\n\t__attribute__((deprecated(\"Use `debug_info(path, &items, /*scopes=*/nullptr);` instead. (`path` could be \\\"top \\\".)\")))\n#endif\n\tvoid debug_info(debug_items &items, std::string path) {\n\t\tdebug_info(&items, /*scopes=*/nullptr, path);\n\t}\n};\n\n} // namespace cxxrtl\n\n// Internal structures used to communicate with the implementation of the C interface.\n\ntypedef struct _cxxrtl_toplevel {\n\tstd::unique_ptr<cxxrtl::module> module;\n} *cxxrtl_toplevel;\n\ntypedef struct _cxxrtl_outline {\n\tstd::function<void()> eval;\n} *cxxrtl_outline;\n\n// Definitions of internal Yosys cells. Other than the functions in this namespace, CXXRTL is fully generic\n// and indepenent of Yosys implementation details.\n//\n// The `write_cxxrtl` pass translates internal cells (cells with names that start with `$`) to calls of these\n// functions. All of Yosys arithmetic and logical cells perform sign or zero extension on their operands,\n// whereas basic operations on arbitrary width values require operands to be of the same width. These functions\n// bridge the gap by performing the necessary casts. They are named similar to `cell_A[B]`, where A and B are `u`\n// if the corresponding operand is unsigned, and `s` if it is signed.\nnamespace cxxrtl_yosys {\n\nusing namespace cxxrtl;\n\n// std::max isn't constexpr until C++14 for no particular reason (it's an oversight), so we define our own.\ntemplate<class T>\nCXXRTL_ALWAYS_INLINE\nconstexpr T max(const T &a, const T &b) {\n\treturn a > b ? a : b;\n}\n\n// Logic operations\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> logic_not(const value<BitsA> &a) {\n\treturn value<BitsY> { a ? 0u : 1u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> logic_and(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn value<BitsY> { (bool(a) && bool(b)) ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> logic_or(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn value<BitsY> { (bool(a) || bool(b)) ? 1u : 0u };\n}\n\n// Reduction operations\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> reduce_and(const value<BitsA> &a) {\n\treturn value<BitsY> { a.bit_not().is_zero() ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> reduce_or(const value<BitsA> &a) {\n\treturn value<BitsY> { a ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> reduce_xor(const value<BitsA> &a) {\n\treturn value<BitsY> { (a.ctpop() % 2) ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> reduce_xnor(const value<BitsA> &a) {\n\treturn value<BitsY> { (a.ctpop() % 2) ? 0u : 1u };\n}\n\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> reduce_bool(const value<BitsA> &a) {\n\treturn value<BitsY> { a ? 1u : 0u };\n}\n\n// Bitwise operations\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> not_u(const value<BitsA> &a) {\n\treturn a.template zcast<BitsY>().bit_not();\n}\n\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> not_s(const value<BitsA> &a) {\n\treturn a.template scast<BitsY>().bit_not();\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> and_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template zcast<BitsY>().bit_and(b.template zcast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> and_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template scast<BitsY>().bit_and(b.template scast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> or_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template zcast<BitsY>().bit_or(b.template zcast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> or_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template scast<BitsY>().bit_or(b.template scast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> xor_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template zcast<BitsY>().bit_xor(b.template zcast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> xor_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template scast<BitsY>().bit_xor(b.template scast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> xnor_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template zcast<BitsY>().bit_xor(b.template zcast<BitsY>()).bit_not();\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> xnor_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template scast<BitsY>().bit_xor(b.template scast<BitsY>()).bit_not();\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shl_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template zcast<BitsY>().shl(b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shl_su(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template scast<BitsY>().shl(b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> sshl_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template zcast<BitsY>().shl(b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> sshl_su(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template scast<BitsY>().shl(b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shr_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.shr(b).template zcast<BitsY>();\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shr_su(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.shr(b).template scast<BitsY>();\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> sshr_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.shr(b).template zcast<BitsY>();\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> sshr_su(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.sshr(b).template scast<BitsY>();\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shift_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn shr_uu<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shift_su(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn shr_su<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shift_us(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn b.is_neg() ? shl_uu<BitsY>(a, b.template sext<BitsB + 1>().neg()) : shr_uu<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shift_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn b.is_neg() ? shl_su<BitsY>(a, b.template sext<BitsB + 1>().neg()) : shr_su<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shiftx_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn shift_uu<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shiftx_su(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn shift_su<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shiftx_us(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn shift_us<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> shiftx_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn shift_ss<BitsY>(a, b);\n}\n\n// Comparison operations\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> eq_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY>{ a.template zext<BitsExt>() == b.template zext<BitsExt>() ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> eq_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY>{ a.template sext<BitsExt>() == b.template sext<BitsExt>() ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> ne_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY>{ a.template zext<BitsExt>() != b.template zext<BitsExt>() ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> ne_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY>{ a.template sext<BitsExt>() != b.template sext<BitsExt>() ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> eqx_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn eq_uu<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> eqx_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn eq_ss<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> nex_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn ne_uu<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> nex_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn ne_ss<BitsY>(a, b);\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> gt_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY> { b.template zext<BitsExt>().ucmp(a.template zext<BitsExt>()) ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> gt_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY> { b.template sext<BitsExt>().scmp(a.template sext<BitsExt>()) ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> ge_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY> { !a.template zext<BitsExt>().ucmp(b.template zext<BitsExt>()) ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> ge_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY> { !a.template sext<BitsExt>().scmp(b.template sext<BitsExt>()) ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> lt_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY> { a.template zext<BitsExt>().ucmp(b.template zext<BitsExt>()) ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> lt_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY> { a.template sext<BitsExt>().scmp(b.template sext<BitsExt>()) ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> le_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY> { !b.template zext<BitsExt>().ucmp(a.template zext<BitsExt>()) ? 1u : 0u };\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> le_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsExt = max(BitsA, BitsB);\n\treturn value<BitsY> { !b.template sext<BitsExt>().scmp(a.template sext<BitsExt>()) ? 1u : 0u };\n}\n\n// Arithmetic operations\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> pos_u(const value<BitsA> &a) {\n\treturn a.template zcast<BitsY>();\n}\n\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> pos_s(const value<BitsA> &a) {\n\treturn a.template scast<BitsY>();\n}\n\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> neg_u(const value<BitsA> &a) {\n\treturn a.template zcast<BitsY>().neg();\n}\n\ntemplate<size_t BitsY, size_t BitsA>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> neg_s(const value<BitsA> &a) {\n\treturn a.template scast<BitsY>().neg();\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> add_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template zcast<BitsY>().add(b.template zcast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> add_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template scast<BitsY>().add(b.template scast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> sub_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template zcast<BitsY>().sub(b.template zcast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> sub_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template scast<BitsY>().sub(b.template scast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> mul_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t BitsM = BitsA >= BitsB ? BitsA : BitsB;\n\treturn a.template zcast<BitsM>().template mul<BitsY>(b.template zcast<BitsM>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> mul_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn a.template scast<BitsY>().template mul<BitsY>(b.template scast<BitsY>());\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nstd::pair<value<BitsY>, value<BitsY>> divmod_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t Bits = max(BitsY, max(BitsA, BitsB));\n\tvalue<Bits> quotient;\n\tvalue<Bits> remainder;\n\tvalue<Bits> dividend = a.template zext<Bits>();\n\tvalue<Bits> divisor = b.template zext<Bits>();\n\tstd::tie(quotient, remainder) = dividend.udivmod(divisor);\n\treturn {quotient.template trunc<BitsY>(), remainder.template trunc<BitsY>()};\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nstd::pair<value<BitsY>, value<BitsY>> divmod_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\tconstexpr size_t Bits = max(BitsY, max(BitsA, BitsB));\n\tvalue<Bits> quotient;\n\tvalue<Bits> remainder;\n\tvalue<Bits> dividend = a.template sext<Bits>();\n\tvalue<Bits> divisor = b.template sext<Bits>();\n\tstd::tie(quotient, remainder) = dividend.sdivmod(divisor);\n\treturn {quotient.template trunc<BitsY>(), remainder.template trunc<BitsY>()};\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> div_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn divmod_uu<BitsY>(a, b).first;\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> div_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn divmod_ss<BitsY>(a, b).first;\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> mod_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn divmod_uu<BitsY>(a, b).second;\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> mod_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn divmod_ss<BitsY>(a, b).second;\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> modfloor_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn divmod_uu<BitsY>(a, b).second;\n}\n\n// GHDL Modfloor operator. Returns r=a mod b, such that r has the same sign as b and\n// a=b*N+r where N is some integer\n// In practical terms, when a and b have different signs and the remainder returned by divmod_ss is not 0\n// then return the remainder + b\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> modfloor_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\tvalue<BitsY> r;\n\tr = divmod_ss<BitsY>(a, b).second;\n\tif((b.is_neg() != a.is_neg()) && !r.is_zero())\n\t\treturn add_ss<BitsY>(b, r);\n\treturn r;\n}\n\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> divfloor_uu(const value<BitsA> &a, const value<BitsB> &b) {\n\treturn divmod_uu<BitsY>(a, b).first;\n}\n\n// Divfloor. Similar to above: returns q=a//b, where q has the sign of a*b and a=b*q+N.\n// In other words, returns (truncating) a/b, except if a and b have different signs\n// and there's non-zero remainder, subtract one more towards floor.\ntemplate<size_t BitsY, size_t BitsA, size_t BitsB>\nCXXRTL_ALWAYS_INLINE\nvalue<BitsY> divfloor_ss(const value<BitsA> &a, const value<BitsB> &b) {\n\tvalue<BitsY> q, r;\n\tstd::tie(q, r) = divmod_ss<BitsY>(a, b);\n\tif ((b.is_neg() != a.is_neg()) && !r.is_zero())\n\t\treturn sub_uu<BitsY>(q, value<1> { 1u });\n\treturn q;\n\n}\n\n// Memory helper\nstruct memory_index {\n\tbool valid;\n\tsize_t index;\n\n\ttemplate<size_t BitsAddr>\n\tmemory_index(const value<BitsAddr> &addr, size_t offset, size_t depth) {\n\t\tstatic_assert(value<BitsAddr>::chunks <= 1, \"memory address is too wide\");\n\t\tsize_t offset_index = addr.data[0];\n\n\t\tvalid = (offset_index >= offset && offset_index < offset + depth);\n\t\tindex = offset_index - offset;\n\t}\n};\n\n} // namespace cxxrtl_yosys\n\n#endif\n",
|
|
135
|
-
"cxxrtl_replay.h": "/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2023 Catherine <whitequark@whitequark.org>\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n */\n\n#ifndef CXXRTL_REPLAY_H\n#define CXXRTL_REPLAY_H\n\n#if !defined(WIN32)\n#include <unistd.h>\n#define O_BINARY 0\n#else\n#include <io.h>\n#endif\n\n#include <fcntl.h>\n#include <cstring>\n#include <cstdio>\n#include <atomic>\n#include <unordered_map>\n\n#include <cxxrtl/cxxrtl.h>\n#include <cxxrtl/cxxrtl_time.h>\n\n// Theory of operation\n// ===================\n//\n// Log format\n// ----------\n//\n// The replay log is a simple data format based on a sequence of 32-bit words. The following BNF-like grammar describes\n// enough detail to understand the overall structure of the log data and be able to read hex dumps. For a greater\n// degree of detail see the source code. The format is considered fully internal to CXXRTL and is subject to change\n// without notice.\n//\n// <file> ::= <file-header> <definitions> <sample>+\n// <file-header> ::= 0x52585843 0x00004c54\n// <definitions> ::= <packet-define>* <packet-end>\n// <sample> ::= <packet-sample> <packet-change>* <packet-end>\n// <packet-define> ::= 0xc0000000 ...\n// <packet-sample> ::= 0xc0000001 ...\n// <packet-change> ::= 0x0??????? <chunk>+ | 0x1??????? <index> <chunk>+ | 0x2??????? | 0x3???????\n// <chunk>, <index> ::= 0x????????\n// <packet-end> ::= 0xFFFFFFFF\n//\n// The replay log contains sample data, however, it does not cover the entire design. Rather, it only contains sample\n// data for the subset of debug items containing _design state_: inputs and registers/latches. This keeps its size to\n// a minimum, and recording speed to a maximum. The player samples any missing data by setting the design state items\n// to the same values they had during recording, and re-evaluating the design.\n//\n// Limits\n// ------\n//\n// The log may contain:\n//\n// * Up to 2**28-1 debug items containing design state.\n// * Up to 2**32 chunks per debug item.\n// * Up to 2**32 rows per memory.\n// * Up to 2**32 samples.\n//\n// Of these limits, the last two are most likely to be eventually exceeded by practical recordings. However, other\n// performance considerations will likely limit the size of such practical recordings first, so the log data format\n// will undergo a breaking change at that point.\n//\n// Operations\n// ----------\n//\n// As suggested by the name \"replay log\", this format is designed for recording (writing) once and playing (reading)\n// many times afterwards, such that reading the format can be done linearly and quickly. The log format is designed to\n// support three primary read operations:\n//\n// 1. Initialization\n// 2. Rewinding (to time T)\n// 3. Replaying (for N samples)\n//\n// During initialization, the player establishes the mapping between debug item names and their 28-bit identifiers in\n// the log. It is done once.\n//\n// During rewinding, the player begins reading at the latest non-incremental sample that still lies before the requested\n// sample time. It continues reading incremental samples after that point until it reaches the requested sample time.\n// This process is very cheap as the design is not evaluated; it is essentially a (convoluted) memory copy operation.\n//\n// During replaying, the player evaluates the design at the current time, which causes all debug items to assume\n// the values they had before recording. This process is expensive. Once done, the player advances to the next state\n// by reading the next (complete or incremental) sample, as above. Since a range of samples is replayed, this process\n// is repeated several times in a row.\n//\n// In principle, when replaying, the player could only read the state of the inputs and the time delta and use a normal\n// eval/commit loop to progress the simulation, which is fully deterministic so its calculated design state should be\n// exactly the same as the recorded design state. In practice, it is both faster and more reliable (in presence of e.g.\n// user-defined black boxes) to read the recorded values instead of calculating them.\n//\n// Note: The operations described above are conceptual and do not correspond exactly to methods on `cxxrtl::player`.\n// The `cxxrtl::player::replay()` method does not evaluate the design. This is so that delta cycles could be ignored\n// if they are not of interest while replaying.\n\nnamespace cxxrtl {\n\n// A spool stores CXXRTL design state changes in a file.\nclass spool {\npublic:\n\t// Unique pointer to a specific sample within a replay log. (Timestamps are not unique.)\n\ttypedef uint32_t pointer_t;\n\n\t// Numeric identifier assigned to a debug item within a replay log. Range limited to [1, MAXIMUM_IDENT].\n\ttypedef uint32_t ident_t;\n\n\tstatic constexpr uint16_t VERSION = 0x0400;\n\n\tstatic constexpr uint64_t HEADER_MAGIC = 0x00004c5452585843;\n\tstatic constexpr uint64_t VERSION_MASK = 0xffff000000000000;\n\n\tstatic constexpr uint32_t PACKET_DEFINE = 0xc0000000;\n\n\tstatic constexpr uint32_t PACKET_SAMPLE = 0xc0000001;\n\tenum sample_flag : uint32_t {\n\t\tEMPTY = 0,\n\t\tINCREMENTAL = 1,\n\t};\n\n\tstatic constexpr uint32_t MAXIMUM_IDENT = 0x0fffffff;\n\tstatic constexpr uint32_t CHANGE_MASK = 0x30000000;\n\n\tstatic constexpr uint32_t PACKET_CHANGE = 0x00000000/* | ident */;\n\tstatic constexpr uint32_t PACKET_CHANGEI = 0x10000000/* | ident */;\n\tstatic constexpr uint32_t PACKET_CHANGEL = 0x20000000/* | ident */;\n\tstatic constexpr uint32_t PACKET_CHANGEH = 0x30000000/* | ident */;\n\n\tstatic constexpr uint32_t PACKET_END = 0xffffffff;\n\n\t// Writing spools.\n\n\tclass writer {\n\t\tint fd;\n\t\tsize_t position;\n\t\tstd::vector<uint32_t> buffer;\n\n\t\t// These functions aren't overloaded because of implicit numeric conversions.\n\n\t\tvoid emit_word(uint32_t word) {\n\t\t\tif (position + 1 == buffer.size())\n\t\t\t\tflush();\n\t\t\tbuffer[position++] = word;\n\t\t}\n\n\t\tvoid emit_dword(uint64_t dword) {\n\t\t\temit_word(dword >> 0);\n\t\t\temit_word(dword >> 32);\n\t\t}\n\n\t\tvoid emit_ident(ident_t ident) {\n\t\t\tassert(ident <= MAXIMUM_IDENT);\n\t\t\temit_word(ident);\n\t\t}\n\n\t\tvoid emit_size(size_t size) {\n\t\t\tassert(size <= std::numeric_limits<uint32_t>::max());\n\t\t\temit_word(size);\n\t\t}\n\n\t\t// Same implementation as `emit_size()`, different declared intent.\n\t\tvoid emit_index(size_t index) {\n\t\t\tassert(index <= std::numeric_limits<uint32_t>::max());\n\t\t\temit_word(index);\n\t\t}\n\n\t\tvoid emit_string(std::string str) {\n\t\t\t// Align to a word boundary, and add at least one terminating \\0.\n\t\t\tstr.resize(str.size() + (sizeof(uint32_t) - (str.size() + sizeof(uint32_t)) % sizeof(uint32_t)));\n\t\t\tfor (size_t index = 0; index < str.size(); index += sizeof(uint32_t)) {\n\t\t\t\tuint32_t word;\n\t\t\t\tmemcpy(&word, &str[index], sizeof(uint32_t));\n\t\t\t\temit_word(word);\n\t\t\t}\n\t\t}\n\n\t\tvoid emit_time(const time ×tamp) {\n\t\t\tconst value<time::bits> &raw_timestamp(timestamp);\n\t\t\temit_word(raw_timestamp.data[0]);\n\t\t\temit_word(raw_timestamp.data[1]);\n\t\t\temit_word(raw_timestamp.data[2]);\n\t\t}\n\n\tpublic:\n\t\t// Creates a writer, and transfers ownership of `fd`, which must be open for appending.\n\t\t//\n\t\t// The buffer size is currently fixed to a \"reasonably large\" size, determined empirically by measuring writer\n\t\t// performance on a representative design; large but not so large it would e.g. cause address space exhaustion\n\t\t// on 32-bit platforms.\n\t\twriter(spool &spool) : fd(spool.take_write()), position(0), buffer(32 * 1024 * 1024) {\n\t\t\tassert(fd != -1);\n#if !defined(WIN32)\n\t\t\tint result = ftruncate(fd, 0);\n#else\n\t\t\tint result = _chsize_s(fd, 0);\n#endif\n\t\t\tassert(result == 0);\n\t\t}\n\n\t\twriter(writer &&moved) : fd(moved.fd), position(moved.position), buffer(moved.buffer) {\n\t\t\tmoved.fd = -1;\n\t\t\tmoved.position = 0;\n\t\t}\n\n\t\twriter(const writer &) = delete;\n\t\twriter &operator=(const writer &) = delete;\n\n\t\t// Both write() calls and fwrite() calls are too expensive to perform implicitly. The API consumer must determine\n\t\t// the optimal time to flush the writer and do that explicitly for best performance.\n\t\tvoid flush() {\n\t\t\tassert(fd != -1);\n\t\t\tsize_t data_size = position * sizeof(uint32_t);\n\t\t\tsize_t data_written = write(fd, buffer.data(), data_size);\n\t\t\tassert(data_size == data_written);\n\t\t\tposition = 0;\n\t\t}\n\n\t\t~writer() {\n\t\t\tif (fd != -1) {\n\t\t\t\tflush();\n\t\t\t\tclose(fd);\n\t\t\t}\n\t\t}\n\n\t\tvoid write_magic() {\n\t\t\t// `CXXRTL` followed by version in binary. This header will read backwards on big-endian machines, which allows\n\t\t\t// detection of this case, both visually and programmatically.\n\t\t\temit_dword(((uint64_t)VERSION << 48) | HEADER_MAGIC);\n\t\t}\n\n\t\tvoid write_define(ident_t ident, const std::string &name, size_t part_index, size_t chunks, size_t depth) {\n\t\t\temit_word(PACKET_DEFINE);\n\t\t\temit_ident(ident);\n\t\t\temit_string(name);\n\t\t\temit_index(part_index);\n\t\t\temit_size(chunks);\n\t\t\temit_size(depth);\n\t\t}\n\n\t\tvoid write_sample(bool incremental, pointer_t pointer, const time ×tamp) {\n\t\t\tuint32_t flags = (incremental ? sample_flag::INCREMENTAL : 0);\n\t\t\temit_word(PACKET_SAMPLE);\n\t\t\temit_word(flags);\n\t\t\temit_word(pointer);\n\t\t\temit_time(timestamp);\n\t\t}\n\n\t\tvoid write_change(ident_t ident, size_t chunks, const chunk_t *data) {\n\t\t\tassert(ident <= MAXIMUM_IDENT);\n\n\t\t\tif (chunks == 1 && *data == 0) {\n\t\t\t\temit_word(PACKET_CHANGEL | ident);\n\t\t\t} else if (chunks == 1 && *data == 1) {\n\t\t\t\temit_word(PACKET_CHANGEH | ident);\n\t\t\t} else {\n\t\t\t\temit_word(PACKET_CHANGE | ident);\n\t\t\t\tfor (size_t offset = 0; offset < chunks; offset++)\n\t\t\t\t\temit_word(data[offset]);\n\t\t\t}\n\t\t}\n\n\t\tvoid write_change(ident_t ident, size_t chunks, const chunk_t *data, size_t index) {\n\t\t\tassert(ident <= MAXIMUM_IDENT);\n\n\t\t\temit_word(PACKET_CHANGEI | ident);\n\t\t\temit_index(index);\n\t\t\tfor (size_t offset = 0; offset < chunks; offset++)\n\t\t\t\temit_word(data[offset]);\n\t\t}\n\n\t\tvoid write_end() {\n\t\t\temit_word(PACKET_END);\n\t\t}\n\t};\n\n\t// Reading spools.\n\n\tclass reader {\n\t\tFILE *f;\n\n\t\tuint32_t absorb_word() {\n\t\t\t// If we're at end of file, `fread` will not write to `word`, and `PACKET_END` will be returned.\n\t\t\tuint32_t word = PACKET_END;\n\t\t\tfread(&word, sizeof(word), 1, f);\n\t\t\treturn word;\n\t\t}\n\n\t\tuint64_t absorb_dword() {\n\t\t\tuint32_t lo = absorb_word();\n\t\t\tuint32_t hi = absorb_word();\n\t\t\treturn ((uint64_t)hi << 32) | lo;\n\t\t}\n\n\t\tident_t absorb_ident() {\n\t\t\tident_t ident = absorb_word();\n\t\t\tassert(ident <= MAXIMUM_IDENT);\n\t\t\treturn ident;\n\t\t}\n\n\t\tsize_t absorb_size() {\n\t\t\treturn absorb_word();\n\t\t}\n\n\t\tsize_t absorb_index() {\n\t\t\treturn absorb_word();\n\t\t}\n\n\t\tstd::string absorb_string() {\n\t\t\tstd::string str;\n\t\t\tdo {\n\t\t\t\tsize_t end = str.size();\n\t\t\t\tstr.resize(end + 4);\n\t\t\t\tuint32_t word = absorb_word();\n\t\t\t\tmemcpy(&str[end], &word, sizeof(uint32_t));\n\t\t\t} while (str.back() != '\\0');\n\t\t\t// Strings have no embedded zeroes besides the terminating one(s).\n\t\t\treturn str.substr(0, str.find('\\0'));\n\t\t}\n\n\t\ttime absorb_time() {\n\t\t\tvalue<time::bits> raw_timestamp;\n\t\t\traw_timestamp.data[0] = absorb_word();\n\t\t\traw_timestamp.data[1] = absorb_word();\n\t\t\traw_timestamp.data[2] = absorb_word();\n\t\t\treturn time(raw_timestamp);\n\t\t}\n\n\tpublic:\n\t\ttypedef uint64_t pos_t;\n\n\t\t// Creates a reader, and transfers ownership of `fd`, which must be open for reading.\n\t\treader(spool &spool) : f(fdopen(spool.take_read(), \"r\")) {\n\t\t\tassert(f != nullptr);\n\t\t}\n\n\t\treader(reader &&moved) : f(moved.f) {\n\t\t\tmoved.f = nullptr;\n\t\t}\n\n\t\treader(const reader &) = delete;\n\t\treader &operator=(const reader &) = delete;\n\n\t\t~reader() {\n\t\t\tif (f != nullptr)\n\t\t\t\tfclose(f);\n\t\t}\n\n\t\tpos_t position() {\n\t\t\treturn ftell(f);\n\t\t}\n\n\t\tvoid rewind(pos_t position) {\n\t\t\tfseek(f, position, SEEK_SET);\n\t\t}\n\n\t\tvoid read_magic() {\n\t\t\tuint64_t magic = absorb_dword();\n\t\t\tassert((magic & ~VERSION_MASK) == HEADER_MAGIC);\n\t\t\tassert((magic >> 48) == VERSION);\n\t\t}\n\n\t\tbool read_define(ident_t &ident, std::string &name, size_t &part_index, size_t &chunks, size_t &depth) {\n\t\t\tuint32_t header = absorb_word();\n\t\t\tif (header == PACKET_END)\n\t\t\t\treturn false;\n\t\t\tassert(header == PACKET_DEFINE);\n\t\t\tident = absorb_ident();\n\t\t\tname = absorb_string();\n\t\t\tpart_index = absorb_index();\n\t\t\tchunks = absorb_size();\n\t\t\tdepth = absorb_size();\n\t\t\treturn true;\n\t\t}\n\n\t\tbool read_sample(bool &incremental, pointer_t &pointer, time ×tamp) {\n\t\t\tuint32_t header = absorb_word();\n\t\t\tif (header == PACKET_END)\n\t\t\t\treturn false;\n\t\t\tassert(header == PACKET_SAMPLE);\n\t\t\tuint32_t flags = absorb_word();\n\t\t\tincremental = (flags & sample_flag::INCREMENTAL);\n\t\t\tpointer = absorb_word();\n\t\t\ttimestamp = absorb_time();\n\t\t\treturn true;\n\t\t}\n\n\t\tbool read_change_header(uint32_t &header, ident_t &ident) {\n\t\t\theader = absorb_word();\n\t\t\tif (header == PACKET_END)\n\t\t\t\treturn false;\n\t\t\tassert((header & ~(CHANGE_MASK | MAXIMUM_IDENT)) == 0);\n\t\t\tident = header & MAXIMUM_IDENT;\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid read_change_data(uint32_t header, size_t chunks, size_t depth, chunk_t *data) {\n\t\t\tuint32_t index = 0;\n\t\t\tswitch (header & CHANGE_MASK) {\n\t\t\t\tcase PACKET_CHANGEL:\n\t\t\t\t\t*data = 0;\n\t\t\t\t\treturn;\n\t\t\t\tcase PACKET_CHANGEH:\n\t\t\t\t\t*data = 1;\n\t\t\t\t\treturn;\n\t\t\t\tcase PACKET_CHANGE:\n\t\t\t\t\tbreak;\n\t\t\t\tcase PACKET_CHANGEI:\n\t\t\t\t\tindex = absorb_word();\n\t\t\t\t\tassert(index < depth);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tassert(false && \"Unrecognized change packet\");\n\t\t\t}\n\t\t\tfor (size_t offset = 0; offset < chunks; offset++)\n\t\t\t\tdata[chunks * index + offset] = absorb_word();\n\t\t}\n\t};\n\n\t// Opening spools. For certain uses of the record/replay mechanism, two distinct open files (two open files, i.e.\n\t// two distinct file pointers, and not just file descriptors, which share the file pointer if duplicated) are used,\n\t// for a reader and writer thread. This class manages the lifetime of the descriptors for these files. When only\n\t// one of them is used, the other is closed harmlessly when the spool is destroyed.\nprivate:\n\tstd::atomic<int> writefd;\n\tstd::atomic<int> readfd;\n\npublic:\n\tspool(const std::string &filename)\n\t\t: writefd(open(filename.c_str(), O_CREAT|O_BINARY|O_WRONLY|O_APPEND, 0644)),\n\t\t readfd(open(filename.c_str(), O_BINARY|O_RDONLY)) {\n\t\tassert(writefd.load() != -1 && readfd.load() != -1);\n\t}\n\n\tspool(spool &&moved) : writefd(moved.writefd.exchange(-1)), readfd(moved.readfd.exchange(-1)) {}\n\n\tspool(const spool &) = delete;\n\tspool &operator=(const spool &) = delete;\n\n\t~spool() {\n\t\tif (int fd = writefd.exchange(-1))\n\t\t\tclose(fd);\n\t\tif (int fd = readfd.exchange(-1))\n\t\t\tclose(fd);\n\t}\n\n\t// Atomically acquire a write file descriptor for the spool. Can be called once, and will return -1 the next time\n\t// it is called. Thread-safe.\n\tint take_write() {\n\t\treturn writefd.exchange(-1);\n\t}\n\n\t// Atomically acquire a read file descriptor for the spool. Can be called once, and will return -1 the next time\n\t// it is called. Thread-safe.\n\tint take_read() {\n\t\treturn readfd.exchange(-1);\n\t}\n};\n\n// A CXXRTL recorder samples design state, producing complete or incremental updates, and writes them to a spool.\nclass recorder {\n\tstruct variable {\n\t\tspool::ident_t ident; /* <= spool::MAXIMUM_IDENT */\n\t\tsize_t chunks;\n\t\tsize_t depth; /* == 1 for wires */\n\t\tchunk_t *curr;\n\t\tbool memory;\n\t};\n\n\tspool::writer writer;\n\tstd::vector<variable> variables;\n\tstd::vector<size_t> inputs; // values of inputs must be recorded explicitly, as their changes are not observed\n\tstd::unordered_map<const chunk_t*, spool::ident_t> ident_lookup;\n\tbool streaming = false; // whether variable definitions have been written\n\tspool::pointer_t pointer = 0;\n\ttime timestamp;\n\npublic:\n\ttemplate<typename ...Args>\n\trecorder(Args &&...args) : writer(std::forward<Args>(args)...) {}\n\n\tvoid start(module &module, std::string top_path = \"\") {\n\t\tdebug_items items;\n\t\tmodule.debug_info(&items, /*scopes=*/nullptr, top_path);\n\t\tstart(items);\n\t}\n\n\tvoid start(const debug_items &items) {\n\t\tassert(!streaming);\n\n\t\twriter.write_magic();\n\t\tfor (auto item : items.table)\n\t\t\tfor (size_t part_index = 0; part_index < item.second.size(); part_index++) {\n\t\t\t\tauto &part = item.second[part_index];\n\t\t\t\tif ((part.flags & debug_item::INPUT) || (part.flags & debug_item::DRIVEN_SYNC) ||\n\t\t\t\t\t\t(part.type == debug_item::MEMORY)) {\n\t\t\t\t\tvariable var;\n\t\t\t\t\tvar.ident = variables.size() + 1;\n\t\t\t\t\tvar.chunks = (part.width + sizeof(chunk_t) * 8 - 1) / (sizeof(chunk_t) * 8);\n\t\t\t\t\tvar.depth = part.depth;\n\t\t\t\t\tvar.curr = part.curr;\n\t\t\t\t\tvar.memory = (part.type == debug_item::MEMORY);\n\t\t\t\t\tident_lookup[var.curr] = var.ident;\n\n\t\t\t\t\tassert(variables.size() < spool::MAXIMUM_IDENT);\n\t\t\t\t\tif (part.flags & debug_item::INPUT)\n\t\t\t\t\t\tinputs.push_back(variables.size());\n\t\t\t\t\tvariables.push_back(var);\n\n\t\t\t\t\twriter.write_define(var.ident, item.first, part_index, var.chunks, var.depth);\n\t\t\t\t}\n\t\t\t}\n\t\twriter.write_end();\n\t\tstreaming = true;\n\t}\n\n\tconst time &latest_time() {\n\t\treturn timestamp;\n\t}\n\n\tconst time &advance_time(const time &delta) {\n\t\tassert(!delta.is_negative());\n\t\ttimestamp += delta;\n\t\treturn timestamp;\n\t}\n\n\tvoid record_complete() {\n\t\tassert(streaming);\n\n\t\twriter.write_sample(/*incremental=*/false, pointer++, timestamp);\n\t\tfor (auto var : variables) {\n\t\t\tassert(var.ident != 0);\n\t\t\tif (!var.memory)\n\t\t\t\twriter.write_change(var.ident, var.chunks, var.curr);\n\t\t\telse\n\t\t\t\tfor (size_t index = 0; index < var.depth; index++)\n\t\t\t\t\twriter.write_change(var.ident, var.chunks, &var.curr[var.chunks * index], index);\n\t\t}\n\t\twriter.write_end();\n\t}\n\n\t// This function is generic over ModuleT to encourage observer callbacks to be inlined into the commit function.\n\ttemplate<class ModuleT>\n\tbool record_incremental(ModuleT &module) {\n\t\tassert(streaming);\n\n\t\tstruct : observer {\n\t\t\tstd::unordered_map<const chunk_t*, spool::ident_t> *ident_lookup;\n\t\t\tspool::writer *writer;\n\n\t\t\tCXXRTL_ALWAYS_INLINE\n\t\t\tvoid on_update(size_t chunks, const chunk_t *base, const chunk_t *value) {\n\t\t\t\twriter->write_change(ident_lookup->at(base), chunks, value);\n\t\t\t}\n\n\t\t\tCXXRTL_ALWAYS_INLINE\n\t\t\tvoid on_update(size_t chunks, const chunk_t *base, const chunk_t *value, size_t index) {\n\t\t\t\twriter->write_change(ident_lookup->at(base), chunks, value, index);\n\t\t\t}\n\t\t} record_observer;\n\t\trecord_observer.ident_lookup = &ident_lookup;\n\t\trecord_observer.writer = &writer;\n\n\t\twriter.write_sample(/*incremental=*/true, pointer++, timestamp);\n\t\tfor (auto input_index : inputs) {\n\t\t\tvariable &var = variables.at(input_index);\n\t\t\tassert(!var.memory);\n\t\t\twriter.write_change(var.ident, var.chunks, var.curr);\n\t\t}\n\t\tbool changed = module.commit(record_observer);\n\t\twriter.write_end();\n\t\treturn changed;\n\t}\n\n\tvoid flush() {\n\t\twriter.flush();\n\t}\n};\n\n// A CXXRTL player reads samples from a spool, and changes the design state accordingly. To start reading samples,\n// a spool must have been initialized: the recorder must have been started and an initial complete sample must have\n// been written.\nclass player {\n\tstruct variable {\n\t\tsize_t chunks;\n\t\tsize_t depth; /* == 1 for wires */\n\t\tchunk_t *curr;\n\t};\n\n\tspool::reader reader;\n\tstd::unordered_map<spool::ident_t, variable> variables;\n\tbool streaming = false; // whether variable definitions have been read\n\tbool initialized = false; // whether a sample has ever been read\n\tspool::pointer_t pointer = 0;\n\ttime timestamp;\n\n\tstd::map<spool::pointer_t, spool::reader::pos_t, std::greater<spool::pointer_t>> index_by_pointer;\n\tstd::map<time, spool::reader::pos_t, std::greater<time>> index_by_timestamp;\n\n\tbool peek_sample(spool::pointer_t &pointer, time ×tamp) {\n\t\tbool incremental;\n\t\tauto position = reader.position();\n\t\tbool success = reader.read_sample(incremental, pointer, timestamp);\n\t\treader.rewind(position);\n\t\treturn success;\n\t}\n\npublic:\n\ttemplate<typename ...Args>\n\tplayer(Args &&...args) : reader(std::forward<Args>(args)...) {}\n\n\t// The `top_path` must match the one given to the recorder.\n\tvoid start(module &module, std::string top_path = \"\") {\n\t\tdebug_items items;\n\t\tmodule.debug_info(&items, /*scopes=*/nullptr, top_path);\n\t\tstart(items);\n\t}\n\n\tvoid start(const debug_items &items) {\n\t\tassert(!streaming);\n\n\t\treader.read_magic();\n\t\twhile (true) {\n\t\t\tspool::ident_t ident;\n\t\t\tstd::string name;\n\t\t\tsize_t part_index;\n\t\t\tsize_t chunks;\n\t\t\tsize_t depth;\n\t\t\tif (!reader.read_define(ident, name, part_index, chunks, depth))\n\t\t\t\tbreak;\n\t\t\tassert(variables.count(ident) == 0);\n\t\t\tassert(items.count(name) != 0);\n\t\t\tassert(part_index < items.count(name));\n\n\t\t\tconst debug_item &part = items.at(name).at(part_index);\n\t\t\tassert(chunks == (part.width + sizeof(chunk_t) * 8 - 1) / (sizeof(chunk_t) * 8));\n\t\t\tassert(depth == part.depth);\n\n\t\t\tvariable &var = variables[ident];\n\t\t\tvar.chunks = chunks;\n\t\t\tvar.depth = depth;\n\t\t\tvar.curr = part.curr;\n\t\t}\n\t\tassert(variables.size() > 0);\n\t\tstreaming = true;\n\n\t\t// Establish the initial state of the design.\n\t\tinitialized = replay();\n\t\tassert(initialized);\n\t}\n\n\t// Returns the pointer of the current sample.\n\tspool::pointer_t current_pointer() {\n\t\tassert(initialized);\n\t\treturn pointer;\n\t}\n\n\t// Returns the time of the current sample.\n\tconst time ¤t_time() {\n\t\tassert(initialized);\n\t\treturn timestamp;\n\t}\n\n\t// Returns `true` if there is a next sample to read, and sets `pointer` to its pointer if there is.\n\tbool get_next_pointer(spool::pointer_t &pointer) {\n\t\tassert(streaming);\n\t\ttime timestamp;\n\t\treturn peek_sample(pointer, timestamp);\n\t}\n\n\t// Returns `true` if there is a next sample to read, and sets `timestamp` to its time if there is.\n\tbool get_next_time(time ×tamp) {\n\t\tassert(streaming);\n\t\tuint32_t pointer;\n\t\treturn peek_sample(pointer, timestamp);\n\t}\n\n\t// If this function returns `true`, then `current_pointer() == at_pointer`, and the module contains values that\n\t// correspond to this pointer in the replay log. To obtain a valid pointer, call `current_pointer()`; while pointers\n\t// are monotonically increasing for each consecutive sample, using arithmetic operations to create a new pointer is\n\t// not allowed.\n\tbool rewind_to(spool::pointer_t at_pointer) {\n\t\tassert(initialized);\n\n\t\t// The pointers in the replay log start from one that is greater than `at_pointer`. In this case the pointer will\n\t\t// never be reached.\n\t\tassert(index_by_pointer.size() > 0);\n\t\tif (at_pointer < index_by_pointer.rbegin()->first)\n\t\t\treturn false;\n\n\t\t// Find the last complete sample whose pointer is less than or equal to `at_pointer`. Note that the comparison\n\t\t// function used here is `std::greater`, inverting the direction of `lower_bound`.\n\t\tauto position_it = index_by_pointer.lower_bound(at_pointer);\n\t\tassert(position_it != index_by_pointer.end());\n\t\treader.rewind(position_it->second);\n\n\t\t// Replay samples until eventually arriving to `at_pointer` or encountering end of file.\n\t\twhile(replay()) {\n\t\t\tif (pointer == at_pointer)\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t// If this function returns `true`, then `current_time() <= at_or_before_timestamp`, and the module contains values\n\t// that correspond to `current_time()` in the replay log. If `current_time() == at_or_before_timestamp` and there\n\t// are several consecutive samples with the same time, the module contains values that correspond to the first of\n\t// these samples.\n\tbool rewind_to_or_before(const time &at_or_before_timestamp) {\n\t\tassert(initialized);\n\n\t\t// The timestamps in the replay log start from one that is greater than `at_or_before_timestamp`. In this case\n\t\t// the timestamp will never be reached. Otherwise, this function will always succeed.\n\t\tassert(index_by_timestamp.size() > 0);\n\t\tif (at_or_before_timestamp < index_by_timestamp.rbegin()->first)\n\t\t\treturn false;\n\n\t\t// Find the last complete sample whose timestamp is less than or equal to `at_or_before_timestamp`. Note that\n\t\t// the comparison function used here is `std::greater`, inverting the direction of `lower_bound`.\n\t\tauto position_it = index_by_timestamp.lower_bound(at_or_before_timestamp);\n\t\tassert(position_it != index_by_timestamp.end());\n\t\treader.rewind(position_it->second);\n\n\t\t// Replay samples until eventually arriving to or past `at_or_before_timestamp` or encountering end of file.\n\t\twhile (replay()) {\n\t\t\tif (timestamp == at_or_before_timestamp)\n\t\t\t\tbreak;\n\n\t\t\ttime next_timestamp;\n\t\t\tif (!get_next_time(next_timestamp))\n\t\t\t\tbreak;\n\t\t\tif (next_timestamp > at_or_before_timestamp)\n\t\t\t\tbreak;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// If this function returns `true`, then `current_pointer()` and `current_time()` are updated for the next sample\n\t// and the module now contains values that correspond to that sample. If it returns `false`, there was no next sample\n\t// to read.\n\tbool replay() {\n\t\tassert(streaming);\n\n\t\tbool incremental;\n\t\tauto position = reader.position();\n\t\tif (!reader.read_sample(incremental, pointer, timestamp))\n\t\t\treturn false;\n\n\t\t// The very first sample that is read must be a complete sample. This is required for the rewind functions to work.\n\t\tassert(initialized || !incremental);\n\n\t\t// It is possible (though not very useful) to have several complete samples with the same timestamp in a row.\n\t\t// Ensure that we associate the timestamp with the position of the first such complete sample. (This condition\n\t\t// works because the player never jumps over a sample.)\n\t\tif (!incremental && !index_by_pointer.count(pointer)) {\n\t\t\tassert(!index_by_timestamp.count(timestamp));\n\t\t\tindex_by_pointer[pointer] = position;\n\t\t\tindex_by_timestamp[timestamp] = position;\n\t\t}\n\n\t\tuint32_t header;\n\t\tspool::ident_t ident;\n\t\tvariable var;\n\t\twhile (reader.read_change_header(header, ident)) {\n\t\t\tvariable &var = variables.at(ident);\n\t\t\treader.read_change_data(header, var.chunks, var.depth, var.curr);\n\t\t}\n\t\treturn true;\n\t}\n};\n\n}\n\n#endif\n",
|
|
135
|
+
"cxxrtl_replay.h": "/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2023 Catherine <whitequark@whitequark.org>\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n */\n\n#ifndef CXXRTL_REPLAY_H\n#define CXXRTL_REPLAY_H\n\n#if !defined(WIN32)\n#include <unistd.h>\n#define O_BINARY 0\n#else\n#include <io.h>\n#endif\n\n#include <fcntl.h>\n#include <cstring>\n#include <cstdio>\n#include <atomic>\n#include <unordered_map>\n\n#include <cxxrtl/cxxrtl.h>\n#include <cxxrtl/cxxrtl_time.h>\n\n// Theory of operation\n// ===================\n//\n// Log format\n// ----------\n//\n// The replay log is a simple data format based on a sequence of 32-bit words. The following BNF-like grammar describes\n// enough detail to understand the overall structure of the log data and be able to read hex dumps. For a greater\n// degree of detail see the source code. The format is considered fully internal to CXXRTL and is subject to change\n// without notice.\n//\n// <file> ::= <file-header> <definitions> <sample>+\n// <file-header> ::= 0x52585843 0x00004c54\n// <definitions> ::= <packet-define>* <packet-end>\n// <sample> ::= <packet-sample> (<packet-change> | <packet-diag>)* <packet-end>\n// <packet-define> ::= 0xc0000000 ...\n// <packet-sample> ::= 0xc0000001 ...\n// <packet-change> ::= 0x0??????? <chunk>+ | 0x1??????? <index> <chunk>+ | 0x2??????? | 0x3???????\n// <chunk>, <index> ::= 0x????????\n// <packet-diag> ::= <packet-break> | <packet-print> | <packet-assert> | <packet-assume>\n// <packet-break> ::= 0xc0000010 <message> <source-location>\n// <packet-print> ::= 0xc0000011 <message> <source-location>\n// <packet-assert> ::= 0xc0000012 <message> <source-location>\n// <packet-assume> ::= 0xc0000013 <message> <source-location>\n// <packet-end> ::= 0xFFFFFFFF\n//\n// The replay log contains sample data, however, it does not cover the entire design. Rather, it only contains sample\n// data for the subset of debug items containing _design state_: inputs and registers/latches. This keeps its size to\n// a minimum, and recording speed to a maximum. The player samples any missing data by setting the design state items\n// to the same values they had during recording, and re-evaluating the design.\n//\n// Packets for diagnostics (prints, breakpoints, assertions, and assumptions) are used solely for diagnostics emitted\n// by the C++ testbench driving the simulation, and are not recorded while evaluating the design. (Diagnostics emitted\n// by the RTL can be reconstructed at replay time, so recording them would be a waste of space.)\n//\n// Limits\n// ------\n//\n// The log may contain:\n//\n// * Up to 2**28-1 debug items containing design state.\n// * Up to 2**32 chunks per debug item.\n// * Up to 2**32 rows per memory.\n// * Up to 2**32 samples.\n//\n// Of these limits, the last two are most likely to be eventually exceeded by practical recordings. However, other\n// performance considerations will likely limit the size of such practical recordings first, so the log data format\n// will undergo a breaking change at that point.\n//\n// Operations\n// ----------\n//\n// As suggested by the name \"replay log\", this format is designed for recording (writing) once and playing (reading)\n// many times afterwards, such that reading the format can be done linearly and quickly. The log format is designed to\n// support three primary read operations:\n//\n// 1. Initialization\n// 2. Rewinding (to time T)\n// 3. Replaying (for N samples)\n//\n// During initialization, the player establishes the mapping between debug item names and their 28-bit identifiers in\n// the log. It is done once.\n//\n// During rewinding, the player begins reading at the latest non-incremental sample that still lies before the requested\n// sample time. It continues reading incremental samples after that point until it reaches the requested sample time.\n// This process is very cheap as the design is not evaluated; it is essentially a (convoluted) memory copy operation.\n//\n// During replaying, the player evaluates the design at the current time, which causes all debug items to assume\n// the values they had before recording. This process is expensive. Once done, the player advances to the next state\n// by reading the next (complete or incremental) sample, as above. Since a range of samples is replayed, this process\n// is repeated several times in a row.\n//\n// In principle, when replaying, the player could only read the state of the inputs and the time delta and use a normal\n// eval/commit loop to progress the simulation, which is fully deterministic so its calculated design state should be\n// exactly the same as the recorded design state. In practice, it is both faster and more reliable (in presence of e.g.\n// user-defined black boxes) to read the recorded values instead of calculating them.\n//\n// Note: The operations described above are conceptual and do not correspond exactly to methods on `cxxrtl::player`.\n// The `cxxrtl::player::replay()` method does not evaluate the design. This is so that delta cycles could be ignored\n// if they are not of interest while replaying.\n\nnamespace cxxrtl {\n\n// A single diagnostic that can be manipulated as an object (including being written to and read from a file).\n// This differs from the base CXXRTL interface, where diagnostics can only be emitted via a procedure call, and are\n// not materialized as objects.\nstruct diagnostic {\n\t// The `BREAK` flavor corresponds to a breakpoint, which is a diagnostic type that can currently only be emitted\n\t// by the C++ testbench code.\n\tenum flavor {\n\t\tBREAK = 0,\n\t\tPRINT = 1,\n\t\tASSERT = 2,\n\t\tASSUME = 3,\n\t};\n\n\tflavor type;\n\tstd::string message;\n\tstd::string location; // same format as the `src` attribute of `$print` or `$check` cell\n\n\tdiagnostic()\n\t: type(BREAK) {}\n\n\tdiagnostic(flavor type, const std::string &message, const std::string &location)\n\t: type(type), message(message), location(location) {}\n\n\tdiagnostic(flavor type, const std::string &message, const char *file, unsigned line)\n\t: type(type), message(message), location(std::string(file) + ':' + std::to_string(line)) {}\n};\n\n// A spool stores CXXRTL design state changes in a file.\nclass spool {\npublic:\n\t// Unique pointer to a specific sample within a replay log. (Timestamps are not unique.)\n\ttypedef uint32_t pointer_t;\n\n\t// Numeric identifier assigned to a debug item within a replay log. Range limited to [1, MAXIMUM_IDENT].\n\ttypedef uint32_t ident_t;\n\n\tstatic constexpr uint16_t VERSION = 0x0400;\n\n\tstatic constexpr uint64_t HEADER_MAGIC = 0x00004c5452585843;\n\tstatic constexpr uint64_t VERSION_MASK = 0xffff000000000000;\n\n\tstatic constexpr uint32_t PACKET_DEFINE = 0xc0000000;\n\n\tstatic constexpr uint32_t PACKET_SAMPLE = 0xc0000001;\n\tenum sample_flag : uint32_t {\n\t\tEMPTY = 0,\n\t\tINCREMENTAL = 1,\n\t};\n\n\tstatic constexpr uint32_t MAXIMUM_IDENT = 0x0fffffff;\n\tstatic constexpr uint32_t CHANGE_MASK = 0x30000000;\n\n\tstatic constexpr uint32_t PACKET_CHANGE = 0x00000000/* | ident */;\n\tstatic constexpr uint32_t PACKET_CHANGEI = 0x10000000/* | ident */;\n\tstatic constexpr uint32_t PACKET_CHANGEL = 0x20000000/* | ident */;\n\tstatic constexpr uint32_t PACKET_CHANGEH = 0x30000000/* | ident */;\n\n\tstatic constexpr uint32_t PACKET_DIAGNOSTIC = 0xc0000010/* | diagnostic::flavor */;\n\tstatic constexpr uint32_t DIAGNOSTIC_MASK = 0x0000000f;\n\n\tstatic constexpr uint32_t PACKET_END = 0xffffffff;\n\n\t// Writing spools.\n\n\tclass writer {\n\t\tint fd;\n\t\tsize_t position;\n\t\tstd::vector<uint32_t> buffer;\n\n\t\t// These functions aren't overloaded because of implicit numeric conversions.\n\n\t\tvoid emit_word(uint32_t word) {\n\t\t\tif (position + 1 == buffer.size())\n\t\t\t\tflush();\n\t\t\tbuffer[position++] = word;\n\t\t}\n\n\t\tvoid emit_dword(uint64_t dword) {\n\t\t\temit_word(dword >> 0);\n\t\t\temit_word(dword >> 32);\n\t\t}\n\n\t\tvoid emit_ident(ident_t ident) {\n\t\t\tassert(ident <= MAXIMUM_IDENT);\n\t\t\temit_word(ident);\n\t\t}\n\n\t\tvoid emit_size(size_t size) {\n\t\t\tassert(size <= std::numeric_limits<uint32_t>::max());\n\t\t\temit_word(size);\n\t\t}\n\n\t\t// Same implementation as `emit_size()`, different declared intent.\n\t\tvoid emit_index(size_t index) {\n\t\t\tassert(index <= std::numeric_limits<uint32_t>::max());\n\t\t\temit_word(index);\n\t\t}\n\n\t\tvoid emit_string(std::string str) {\n\t\t\t// Align to a word boundary, and add at least one terminating \\0.\n\t\t\tstr.resize(str.size() + (sizeof(uint32_t) - (str.size() + sizeof(uint32_t)) % sizeof(uint32_t)));\n\t\t\tfor (size_t index = 0; index < str.size(); index += sizeof(uint32_t)) {\n\t\t\t\tuint32_t word;\n\t\t\t\tmemcpy(&word, &str[index], sizeof(uint32_t));\n\t\t\t\temit_word(word);\n\t\t\t}\n\t\t}\n\n\t\tvoid emit_time(const time ×tamp) {\n\t\t\tconst value<time::bits> &raw_timestamp(timestamp);\n\t\t\temit_word(raw_timestamp.data[0]);\n\t\t\temit_word(raw_timestamp.data[1]);\n\t\t\temit_word(raw_timestamp.data[2]);\n\t\t}\n\n\tpublic:\n\t\t// Creates a writer, and transfers ownership of `fd`, which must be open for appending.\n\t\t//\n\t\t// The buffer size is currently fixed to a \"reasonably large\" size, determined empirically by measuring writer\n\t\t// performance on a representative design; large but not so large it would e.g. cause address space exhaustion\n\t\t// on 32-bit platforms.\n\t\twriter(spool &spool) : fd(spool.take_write()), position(0), buffer(32 * 1024 * 1024) {\n\t\t\tassert(fd != -1);\n#if !defined(WIN32)\n\t\t\tint result = ftruncate(fd, 0);\n#else\n\t\t\tint result = _chsize_s(fd, 0);\n#endif\n\t\t\tassert(result == 0);\n\t\t}\n\n\t\twriter(writer &&moved) : fd(moved.fd), position(moved.position), buffer(moved.buffer) {\n\t\t\tmoved.fd = -1;\n\t\t\tmoved.position = 0;\n\t\t}\n\n\t\twriter(const writer &) = delete;\n\t\twriter &operator=(const writer &) = delete;\n\n\t\t// Both write() calls and fwrite() calls are too expensive to perform implicitly. The API consumer must determine\n\t\t// the optimal time to flush the writer and do that explicitly for best performance.\n\t\tvoid flush() {\n\t\t\tassert(fd != -1);\n\t\t\tsize_t data_size = position * sizeof(uint32_t);\n\t\t\tsize_t data_written = write(fd, buffer.data(), data_size);\n\t\t\tassert(data_size == data_written);\n\t\t\tposition = 0;\n\t\t}\n\n\t\t~writer() {\n\t\t\tif (fd != -1) {\n\t\t\t\tflush();\n\t\t\t\tclose(fd);\n\t\t\t}\n\t\t}\n\n\t\tvoid write_magic() {\n\t\t\t// `CXXRTL` followed by version in binary. This header will read backwards on big-endian machines, which allows\n\t\t\t// detection of this case, both visually and programmatically.\n\t\t\temit_dword(((uint64_t)VERSION << 48) | HEADER_MAGIC);\n\t\t}\n\n\t\tvoid write_define(ident_t ident, const std::string &name, size_t part_index, size_t chunks, size_t depth) {\n\t\t\temit_word(PACKET_DEFINE);\n\t\t\temit_ident(ident);\n\t\t\temit_string(name);\n\t\t\temit_index(part_index);\n\t\t\temit_size(chunks);\n\t\t\temit_size(depth);\n\t\t}\n\n\t\tvoid write_sample(bool incremental, pointer_t pointer, const time ×tamp) {\n\t\t\tuint32_t flags = (incremental ? sample_flag::INCREMENTAL : 0);\n\t\t\temit_word(PACKET_SAMPLE);\n\t\t\temit_word(flags);\n\t\t\temit_word(pointer);\n\t\t\temit_time(timestamp);\n\t\t}\n\n\t\tvoid write_change(ident_t ident, size_t chunks, const chunk_t *data) {\n\t\t\tassert(ident <= MAXIMUM_IDENT);\n\n\t\t\tif (chunks == 1 && *data == 0) {\n\t\t\t\temit_word(PACKET_CHANGEL | ident);\n\t\t\t} else if (chunks == 1 && *data == 1) {\n\t\t\t\temit_word(PACKET_CHANGEH | ident);\n\t\t\t} else {\n\t\t\t\temit_word(PACKET_CHANGE | ident);\n\t\t\t\tfor (size_t offset = 0; offset < chunks; offset++)\n\t\t\t\t\temit_word(data[offset]);\n\t\t\t}\n\t\t}\n\n\t\tvoid write_change(ident_t ident, size_t chunks, const chunk_t *data, size_t index) {\n\t\t\tassert(ident <= MAXIMUM_IDENT);\n\n\t\t\temit_word(PACKET_CHANGEI | ident);\n\t\t\temit_index(index);\n\t\t\tfor (size_t offset = 0; offset < chunks; offset++)\n\t\t\t\temit_word(data[offset]);\n\t\t}\n\n\t\tvoid write_diagnostic(const diagnostic &diagnostic) {\n\t\t\temit_word(PACKET_DIAGNOSTIC | diagnostic.type);\n\t\t\temit_string(diagnostic.message);\n\t\t\temit_string(diagnostic.location);\n\t\t}\n\n\t\tvoid write_end() {\n\t\t\temit_word(PACKET_END);\n\t\t}\n\t};\n\n\t// Reading spools.\n\n\tclass reader {\n\t\tFILE *f;\n\n\t\tuint32_t absorb_word() {\n\t\t\t// If we're at end of file, `fread` will not write to `word`, and `PACKET_END` will be returned.\n\t\t\tuint32_t word = PACKET_END;\n\t\t\tfread(&word, sizeof(word), 1, f);\n\t\t\treturn word;\n\t\t}\n\n\t\tuint64_t absorb_dword() {\n\t\t\tuint32_t lo = absorb_word();\n\t\t\tuint32_t hi = absorb_word();\n\t\t\treturn ((uint64_t)hi << 32) | lo;\n\t\t}\n\n\t\tident_t absorb_ident() {\n\t\t\tident_t ident = absorb_word();\n\t\t\tassert(ident <= MAXIMUM_IDENT);\n\t\t\treturn ident;\n\t\t}\n\n\t\tsize_t absorb_size() {\n\t\t\treturn absorb_word();\n\t\t}\n\n\t\tsize_t absorb_index() {\n\t\t\treturn absorb_word();\n\t\t}\n\n\t\tstd::string absorb_string() {\n\t\t\tstd::string str;\n\t\t\tdo {\n\t\t\t\tsize_t end = str.size();\n\t\t\t\tstr.resize(end + 4);\n\t\t\t\tuint32_t word = absorb_word();\n\t\t\t\tmemcpy(&str[end], &word, sizeof(uint32_t));\n\t\t\t} while (str.back() != '\\0');\n\t\t\t// Strings have no embedded zeroes besides the terminating one(s).\n\t\t\treturn str.substr(0, str.find('\\0'));\n\t\t}\n\n\t\ttime absorb_time() {\n\t\t\tvalue<time::bits> raw_timestamp;\n\t\t\traw_timestamp.data[0] = absorb_word();\n\t\t\traw_timestamp.data[1] = absorb_word();\n\t\t\traw_timestamp.data[2] = absorb_word();\n\t\t\treturn time(raw_timestamp);\n\t\t}\n\n\tpublic:\n\t\ttypedef uint64_t pos_t;\n\n\t\t// Creates a reader, and transfers ownership of `fd`, which must be open for reading.\n\t\treader(spool &spool) : f(fdopen(spool.take_read(), \"r\")) {\n\t\t\tassert(f != nullptr);\n\t\t}\n\n\t\treader(reader &&moved) : f(moved.f) {\n\t\t\tmoved.f = nullptr;\n\t\t}\n\n\t\treader(const reader &) = delete;\n\t\treader &operator=(const reader &) = delete;\n\n\t\t~reader() {\n\t\t\tif (f != nullptr)\n\t\t\t\tfclose(f);\n\t\t}\n\n\t\tpos_t position() {\n\t\t\treturn ftell(f);\n\t\t}\n\n\t\tvoid rewind(pos_t position) {\n\t\t\tfseek(f, position, SEEK_SET);\n\t\t}\n\n\t\tvoid read_magic() {\n\t\t\tuint64_t magic = absorb_dword();\n\t\t\tassert((magic & ~VERSION_MASK) == HEADER_MAGIC);\n\t\t\tassert((magic >> 48) == VERSION);\n\t\t}\n\n\t\tbool read_define(ident_t &ident, std::string &name, size_t &part_index, size_t &chunks, size_t &depth) {\n\t\t\tuint32_t header = absorb_word();\n\t\t\tif (header == PACKET_END)\n\t\t\t\treturn false;\n\t\t\tassert(header == PACKET_DEFINE);\n\t\t\tident = absorb_ident();\n\t\t\tname = absorb_string();\n\t\t\tpart_index = absorb_index();\n\t\t\tchunks = absorb_size();\n\t\t\tdepth = absorb_size();\n\t\t\treturn true;\n\t\t}\n\n\t\tbool read_sample(bool &incremental, pointer_t &pointer, time ×tamp) {\n\t\t\tuint32_t header = absorb_word();\n\t\t\tif (header == PACKET_END)\n\t\t\t\treturn false;\n\t\t\tassert(header == PACKET_SAMPLE);\n\t\t\tuint32_t flags = absorb_word();\n\t\t\tincremental = (flags & sample_flag::INCREMENTAL);\n\t\t\tpointer = absorb_word();\n\t\t\ttimestamp = absorb_time();\n\t\t\treturn true;\n\t\t}\n\n\t\tbool read_header(uint32_t &header) {\n\t\t\theader = absorb_word();\n\t\t\treturn header != PACKET_END;\n\t\t}\n\n\t\t// This method must be separate from `read_change_data` because `chunks` and `depth` can only be looked up\n\t\t// if `ident` is known.\n\t\tbool read_change_ident(uint32_t header, ident_t &ident) {\n\t\t\tif ((header & ~(CHANGE_MASK | MAXIMUM_IDENT)) != 0)\n\t\t\t\treturn false; // some other packet\n\t\t\tident = header & MAXIMUM_IDENT;\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid read_change_data(uint32_t header, size_t chunks, size_t depth, chunk_t *data) {\n\t\t\tuint32_t index = 0;\n\t\t\tswitch (header & CHANGE_MASK) {\n\t\t\t\tcase PACKET_CHANGEL:\n\t\t\t\t\t*data = 0;\n\t\t\t\t\treturn;\n\t\t\t\tcase PACKET_CHANGEH:\n\t\t\t\t\t*data = 1;\n\t\t\t\t\treturn;\n\t\t\t\tcase PACKET_CHANGE:\n\t\t\t\t\tbreak;\n\t\t\t\tcase PACKET_CHANGEI:\n\t\t\t\t\tindex = absorb_word();\n\t\t\t\t\tassert(index < depth);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tassert(false && \"Unrecognized change packet\");\n\t\t\t}\n\t\t\tfor (size_t offset = 0; offset < chunks; offset++)\n\t\t\t\tdata[chunks * index + offset] = absorb_word();\n\t\t}\n\n\t\tbool read_diagnostic(uint32_t header, diagnostic &diagnostic) {\n\t\t\tif ((header & ~DIAGNOSTIC_MASK) != PACKET_DIAGNOSTIC)\n\t\t\t\treturn false; // some other packet\n\t\t\tuint32_t type = header & DIAGNOSTIC_MASK;\n\t\t\tassert(type == diagnostic::BREAK || type == diagnostic::PRINT ||\n\t\t\t type == diagnostic::ASSERT || type == diagnostic::ASSUME);\n\t\t\tdiagnostic.type = (diagnostic::flavor)type;\n\t\t\tdiagnostic.message = absorb_string();\n\t\t\tdiagnostic.location = absorb_string();\n\t\t\treturn true;\n\t\t}\n\t};\n\n\t// Opening spools. For certain uses of the record/replay mechanism, two distinct open files (two open files, i.e.\n\t// two distinct file pointers, and not just file descriptors, which share the file pointer if duplicated) are used,\n\t// for a reader and writer thread. This class manages the lifetime of the descriptors for these files. When only\n\t// one of them is used, the other is closed harmlessly when the spool is destroyed.\nprivate:\n\tstd::atomic<int> writefd;\n\tstd::atomic<int> readfd;\n\npublic:\n\tspool(const std::string &filename)\n\t\t: writefd(open(filename.c_str(), O_CREAT|O_BINARY|O_WRONLY|O_APPEND, 0644)),\n\t\t readfd(open(filename.c_str(), O_BINARY|O_RDONLY)) {\n\t\tassert(writefd.load() != -1 && readfd.load() != -1);\n\t}\n\n\tspool(spool &&moved) : writefd(moved.writefd.exchange(-1)), readfd(moved.readfd.exchange(-1)) {}\n\n\tspool(const spool &) = delete;\n\tspool &operator=(const spool &) = delete;\n\n\t~spool() {\n\t\tif (int fd = writefd.exchange(-1))\n\t\t\tclose(fd);\n\t\tif (int fd = readfd.exchange(-1))\n\t\t\tclose(fd);\n\t}\n\n\t// Atomically acquire a write file descriptor for the spool. Can be called once, and will return -1 the next time\n\t// it is called. Thread-safe.\n\tint take_write() {\n\t\treturn writefd.exchange(-1);\n\t}\n\n\t// Atomically acquire a read file descriptor for the spool. Can be called once, and will return -1 the next time\n\t// it is called. Thread-safe.\n\tint take_read() {\n\t\treturn readfd.exchange(-1);\n\t}\n};\n\n// A CXXRTL recorder samples design state, producing complete or incremental updates, and writes them to a spool.\nclass recorder {\n\tstruct variable {\n\t\tspool::ident_t ident; /* <= spool::MAXIMUM_IDENT */\n\t\tsize_t chunks;\n\t\tsize_t depth; /* == 1 for wires */\n\t\tchunk_t *curr;\n\t\tbool memory;\n\t};\n\n\tspool::writer writer;\n\tstd::vector<variable> variables;\n\tstd::vector<size_t> inputs; // values of inputs must be recorded explicitly, as their changes are not observed\n\tstd::unordered_map<const chunk_t*, spool::ident_t> ident_lookup;\n\tbool streaming = false; // whether variable definitions have been written\n\tspool::pointer_t pointer = 0;\n\ttime timestamp;\n\npublic:\n\ttemplate<typename ...Args>\n\trecorder(Args &&...args) : writer(std::forward<Args>(args)...) {}\n\n\tvoid start(module &module, std::string top_path = \"\") {\n\t\tdebug_items items;\n\t\tmodule.debug_info(&items, /*scopes=*/nullptr, top_path);\n\t\tstart(items);\n\t}\n\n\tvoid start(const debug_items &items) {\n\t\tassert(!streaming);\n\n\t\twriter.write_magic();\n\t\tfor (auto item : items.table)\n\t\t\tfor (size_t part_index = 0; part_index < item.second.size(); part_index++) {\n\t\t\t\tauto &part = item.second[part_index];\n\t\t\t\tif ((part.flags & debug_item::INPUT) || (part.flags & debug_item::DRIVEN_SYNC) ||\n\t\t\t\t\t\t(part.type == debug_item::MEMORY)) {\n\t\t\t\t\tvariable var;\n\t\t\t\t\tvar.ident = variables.size() + 1;\n\t\t\t\t\tvar.chunks = (part.width + sizeof(chunk_t) * 8 - 1) / (sizeof(chunk_t) * 8);\n\t\t\t\t\tvar.depth = part.depth;\n\t\t\t\t\tvar.curr = part.curr;\n\t\t\t\t\tvar.memory = (part.type == debug_item::MEMORY);\n\t\t\t\t\tident_lookup[var.curr] = var.ident;\n\n\t\t\t\t\tassert(variables.size() < spool::MAXIMUM_IDENT);\n\t\t\t\t\tif (part.flags & debug_item::INPUT)\n\t\t\t\t\t\tinputs.push_back(variables.size());\n\t\t\t\t\tvariables.push_back(var);\n\n\t\t\t\t\twriter.write_define(var.ident, item.first, part_index, var.chunks, var.depth);\n\t\t\t\t}\n\t\t\t}\n\t\twriter.write_end();\n\t\tstreaming = true;\n\t}\n\n\tconst time &latest_time() {\n\t\treturn timestamp;\n\t}\n\n\tconst time &advance_time(const time &delta) {\n\t\tassert(!delta.is_negative());\n\t\ttimestamp += delta;\n\t\treturn timestamp;\n\t}\n\n\tvoid record_complete() {\n\t\tassert(streaming);\n\n\t\twriter.write_sample(/*incremental=*/false, pointer++, timestamp);\n\t\tfor (auto var : variables) {\n\t\t\tassert(var.ident != 0);\n\t\t\tif (!var.memory)\n\t\t\t\twriter.write_change(var.ident, var.chunks, var.curr);\n\t\t\telse\n\t\t\t\tfor (size_t index = 0; index < var.depth; index++)\n\t\t\t\t\twriter.write_change(var.ident, var.chunks, &var.curr[var.chunks * index], index);\n\t\t}\n\t\twriter.write_end();\n\t}\n\n\t// This function is generic over ModuleT to encourage observer callbacks to be inlined into the commit function.\n\ttemplate<class ModuleT>\n\tbool record_incremental(ModuleT &module) {\n\t\tassert(streaming);\n\n\t\tstruct : observer {\n\t\t\tstd::unordered_map<const chunk_t*, spool::ident_t> *ident_lookup;\n\t\t\tspool::writer *writer;\n\n\t\t\tCXXRTL_ALWAYS_INLINE\n\t\t\tvoid on_update(size_t chunks, const chunk_t *base, const chunk_t *value) {\n\t\t\t\twriter->write_change(ident_lookup->at(base), chunks, value);\n\t\t\t}\n\n\t\t\tCXXRTL_ALWAYS_INLINE\n\t\t\tvoid on_update(size_t chunks, const chunk_t *base, const chunk_t *value, size_t index) {\n\t\t\t\twriter->write_change(ident_lookup->at(base), chunks, value, index);\n\t\t\t}\n\t\t} record_observer;\n\t\trecord_observer.ident_lookup = &ident_lookup;\n\t\trecord_observer.writer = &writer;\n\n\t\twriter.write_sample(/*incremental=*/true, pointer++, timestamp);\n\t\tfor (auto input_index : inputs) {\n\t\t\tvariable &var = variables.at(input_index);\n\t\t\tassert(!var.memory);\n\t\t\twriter.write_change(var.ident, var.chunks, var.curr);\n\t\t}\n\t\tbool changed = module.commit(record_observer);\n\t\twriter.write_end();\n\t\treturn changed;\n\t}\n\n\tvoid record_diagnostic(const diagnostic &diagnostic) {\n\t\tassert(streaming);\n\n\t\t// Emit an incremental delta cycle per diagnostic to simplify the logic of the recorder. This is inefficient, but\n\t\t// diagnostics should be rare enough that this inefficiency does not matter. If it turns out to be an issue, this\n\t\t// code should be changed to accumulate diagnostics to a buffer that is flushed in `record_{complete,incremental}`\n\t\t// and also in `advance_time` before the timestamp is changed. (Right now `advance_time` never writes to the spool.)\n\t\twriter.write_sample(/*incremental=*/true, pointer++, timestamp);\n\t\twriter.write_diagnostic(diagnostic);\n\t\twriter.write_end();\n\t}\n\n\tvoid flush() {\n\t\twriter.flush();\n\t}\n};\n\n// A CXXRTL player reads samples from a spool, and changes the design state accordingly. To start reading samples,\n// a spool must have been initialized: the recorder must have been started and an initial complete sample must have\n// been written.\nclass player {\n\tstruct variable {\n\t\tsize_t chunks;\n\t\tsize_t depth; /* == 1 for wires */\n\t\tchunk_t *curr;\n\t};\n\n\tspool::reader reader;\n\tstd::unordered_map<spool::ident_t, variable> variables;\n\tbool streaming = false; // whether variable definitions have been read\n\tbool initialized = false; // whether a sample has ever been read\n\tspool::pointer_t pointer = 0;\n\ttime timestamp;\n\n\tstd::map<spool::pointer_t, spool::reader::pos_t, std::greater<spool::pointer_t>> index_by_pointer;\n\tstd::map<time, spool::reader::pos_t, std::greater<time>> index_by_timestamp;\n\n\tbool peek_sample(spool::pointer_t &pointer, time ×tamp) {\n\t\tbool incremental;\n\t\tauto position = reader.position();\n\t\tbool success = reader.read_sample(incremental, pointer, timestamp);\n\t\treader.rewind(position);\n\t\treturn success;\n\t}\n\npublic:\n\ttemplate<typename ...Args>\n\tplayer(Args &&...args) : reader(std::forward<Args>(args)...) {}\n\n\t// The `top_path` must match the one given to the recorder.\n\tvoid start(module &module, std::string top_path = \"\") {\n\t\tdebug_items items;\n\t\tmodule.debug_info(&items, /*scopes=*/nullptr, top_path);\n\t\tstart(items);\n\t}\n\n\tvoid start(const debug_items &items) {\n\t\tassert(!streaming);\n\n\t\treader.read_magic();\n\t\twhile (true) {\n\t\t\tspool::ident_t ident;\n\t\t\tstd::string name;\n\t\t\tsize_t part_index;\n\t\t\tsize_t chunks;\n\t\t\tsize_t depth;\n\t\t\tif (!reader.read_define(ident, name, part_index, chunks, depth))\n\t\t\t\tbreak;\n\t\t\tassert(variables.count(ident) == 0);\n\t\t\tassert(items.count(name) != 0);\n\t\t\tassert(part_index < items.count(name));\n\n\t\t\tconst debug_item &part = items.at(name).at(part_index);\n\t\t\tassert(chunks == (part.width + sizeof(chunk_t) * 8 - 1) / (sizeof(chunk_t) * 8));\n\t\t\tassert(depth == part.depth);\n\n\t\t\tvariable &var = variables[ident];\n\t\t\tvar.chunks = chunks;\n\t\t\tvar.depth = depth;\n\t\t\tvar.curr = part.curr;\n\t\t}\n\t\tassert(variables.size() > 0);\n\t\tstreaming = true;\n\n\t\t// Establish the initial state of the design.\n\t\tstd::vector<diagnostic> diagnostics;\n\t\tinitialized = replay(&diagnostics);\n\t\tassert(initialized && diagnostics.empty());\n\t}\n\n\t// Returns the pointer of the current sample.\n\tspool::pointer_t current_pointer() {\n\t\tassert(initialized);\n\t\treturn pointer;\n\t}\n\n\t// Returns the time of the current sample.\n\tconst time ¤t_time() {\n\t\tassert(initialized);\n\t\treturn timestamp;\n\t}\n\n\t// Returns `true` if there is a next sample to read, and sets `pointer` to its pointer if there is.\n\tbool get_next_pointer(spool::pointer_t &pointer) {\n\t\tassert(streaming);\n\t\ttime timestamp;\n\t\treturn peek_sample(pointer, timestamp);\n\t}\n\n\t// Returns `true` if there is a next sample to read, and sets `timestamp` to its time if there is.\n\tbool get_next_time(time ×tamp) {\n\t\tassert(streaming);\n\t\tuint32_t pointer;\n\t\treturn peek_sample(pointer, timestamp);\n\t}\n\n\t// If this function returns `true`, then `current_pointer() == at_pointer`, and the module contains values that\n\t// correspond to this pointer in the replay log. To obtain a valid pointer, call `current_pointer()`; while pointers\n\t// are monotonically increasing for each consecutive sample, using arithmetic operations to create a new pointer is\n\t// not allowed. The `diagnostics` argument, if not `nullptr`, receives the diagnostics recorded in this sample.\n\tbool rewind_to(spool::pointer_t at_pointer, std::vector<diagnostic> *diagnostics) {\n\t\tassert(initialized);\n\n\t\t// The pointers in the replay log start from one that is greater than `at_pointer`. In this case the pointer will\n\t\t// never be reached.\n\t\tassert(index_by_pointer.size() > 0);\n\t\tif (at_pointer < index_by_pointer.rbegin()->first)\n\t\t\treturn false;\n\n\t\t// Find the last complete sample whose pointer is less than or equal to `at_pointer`. Note that the comparison\n\t\t// function used here is `std::greater`, inverting the direction of `lower_bound`.\n\t\tauto position_it = index_by_pointer.lower_bound(at_pointer);\n\t\tassert(position_it != index_by_pointer.end());\n\t\treader.rewind(position_it->second);\n\n\t\t// Replay samples until eventually arriving to `at_pointer` or encountering end of file.\n\t\twhile(replay(diagnostics)) {\n\t\t\tif (pointer == at_pointer)\n\t\t\t\treturn true;\n\n\t\t\tif (diagnostics)\n\t\t\t\tdiagnostics->clear();\n\t\t}\n\t\treturn false;\n\t}\n\n\t// If this function returns `true`, then `current_time() <= at_or_before_timestamp`, and the module contains values\n\t// that correspond to `current_time()` in the replay log. If `current_time() == at_or_before_timestamp` and there\n\t// are several consecutive samples with the same time, the module contains values that correspond to the first of\n\t// these samples. The `diagnostics` argument, if not `nullptr`, receives the diagnostics recorded in this sample.\n\tbool rewind_to_or_before(const time &at_or_before_timestamp, std::vector<diagnostic> *diagnostics) {\n\t\tassert(initialized);\n\n\t\t// The timestamps in the replay log start from one that is greater than `at_or_before_timestamp`. In this case\n\t\t// the timestamp will never be reached. Otherwise, this function will always succeed.\n\t\tassert(index_by_timestamp.size() > 0);\n\t\tif (at_or_before_timestamp < index_by_timestamp.rbegin()->first)\n\t\t\treturn false;\n\n\t\t// Find the last complete sample whose timestamp is less than or equal to `at_or_before_timestamp`. Note that\n\t\t// the comparison function used here is `std::greater`, inverting the direction of `lower_bound`.\n\t\tauto position_it = index_by_timestamp.lower_bound(at_or_before_timestamp);\n\t\tassert(position_it != index_by_timestamp.end());\n\t\treader.rewind(position_it->second);\n\n\t\t// Replay samples until eventually arriving to or past `at_or_before_timestamp` or encountering end of file.\n\t\twhile (replay(diagnostics)) {\n\t\t\tif (timestamp == at_or_before_timestamp)\n\t\t\t\tbreak;\n\n\t\t\ttime next_timestamp;\n\t\t\tif (!get_next_time(next_timestamp))\n\t\t\t\tbreak;\n\t\t\tif (next_timestamp > at_or_before_timestamp)\n\t\t\t\tbreak;\n\n\t\t\tif (diagnostics)\n\t\t\t\tdiagnostics->clear();\n\t\t}\n\t\treturn true;\n\t}\n\n\t// If this function returns `true`, then `current_pointer()` and `current_time()` are updated for the next sample\n\t// and the module now contains values that correspond to that sample. If it returns `false`, there was no next sample\n\t// to read. The `diagnostics` argument, if not `nullptr`, receives the diagnostics recorded in the next sample.\n\tbool replay(std::vector<diagnostic> *diagnostics) {\n\t\tassert(streaming);\n\n\t\tbool incremental;\n\t\tauto position = reader.position();\n\t\tif (!reader.read_sample(incremental, pointer, timestamp))\n\t\t\treturn false;\n\n\t\t// The very first sample that is read must be a complete sample. This is required for the rewind functions to work.\n\t\tassert(initialized || !incremental);\n\n\t\t// It is possible (though not very useful) to have several complete samples with the same timestamp in a row.\n\t\t// Ensure that we associate the timestamp with the position of the first such complete sample. (This condition\n\t\t// works because the player never jumps over a sample.)\n\t\tif (!incremental && !index_by_pointer.count(pointer)) {\n\t\t\tassert(!index_by_timestamp.count(timestamp));\n\t\t\tindex_by_pointer[pointer] = position;\n\t\t\tindex_by_timestamp[timestamp] = position;\n\t\t}\n\n\t\tuint32_t header;\n\t\twhile (reader.read_header(header)) {\n\t\t\tspool::ident_t ident;\n\t\t\tdiagnostic diag;\n\t\t\tif (reader.read_change_ident(header, ident)) {\n\t\t\t\tvariable &var = variables.at(ident);\n\t\t\t\treader.read_change_data(header, var.chunks, var.depth, var.curr);\n\t\t\t} else if (reader.read_diagnostic(header, diag)) {\n\t\t\t\tif (diagnostics)\n\t\t\t\t\tdiagnostics->push_back(diag);\n\t\t\t} else assert(false && \"Unrecognized packet header\");\n\t\t}\n\t\treturn true;\n\t}\n};\n\n}\n\n#endif\n",
|
|
136
136
|
"cxxrtl_time.h": "/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2023 Catherine <whitequark@whitequark.org>\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n */\n\n#ifndef CXXRTL_TIME_H\n#define CXXRTL_TIME_H\n\n#include <cinttypes>\n#include <string>\n\n#include <cxxrtl/cxxrtl.h>\n\nnamespace cxxrtl {\n\n// A timestamp or a difference in time, stored as a 96-bit number of femtoseconds (10e-15 s). The range and resolution\n// of this format can represent any VCD timestamp within approx. ±1255321.2 years, without the need for a timescale.\nclass time {\npublic:\n\tstatic constexpr size_t bits = 96; // 3 chunks\n\nprivate:\n\tstatic constexpr size_t resolution_digits = 15;\n\n\tstatic_assert(sizeof(chunk_t) == 4, \"a chunk is expected to be 32-bit\");\n\tstatic constexpr value<bits> resolution = value<bits> {\n\t\tchunk_t(1000000000000000ull & 0xffffffffull), chunk_t(1000000000000000ull >> 32), 0u\n\t};\n\n\t// Signed number of femtoseconds from the beginning of time.\n\tvalue<bits> raw;\n\npublic:\n\tconstexpr time() {}\n\n\texplicit constexpr time(const value<bits> &raw) : raw(raw) {}\n\texplicit operator const value<bits> &() const { return raw; }\n\n\tstatic constexpr time maximum() {\n\t\treturn time(value<bits> { 0xffffffffu, 0xffffffffu, 0x7fffffffu });\n\t}\n\n\ttime(int64_t secs, int64_t femtos) {\n\t\tvalue<64> secs_val;\n\t\tsecs_val.set(secs);\n\t\tvalue<64> femtos_val;\n\t\tfemtos_val.set(femtos);\n\t\traw = secs_val.sext<bits>().mul<bits>(resolution).add(femtos_val.sext<bits>());\n\t}\n\n\tbool is_zero() const {\n\t\treturn raw.is_zero();\n\t}\n\n\t// Extracts the sign of the value.\n\tbool is_negative() const {\n\t\treturn raw.is_neg();\n\t}\n\n\t// Extracts the number of whole seconds. Negative if the value is negative.\n\tint64_t secs() const {\n\t\treturn raw.sdivmod(resolution).first.trunc<64>().get<int64_t>();\n\t}\n\n\t// Extracts the number of femtoseconds in the fractional second. Negative if the value is negative.\n\tint64_t femtos() const {\n\t\treturn raw.sdivmod(resolution).second.trunc<64>().get<int64_t>();\n\t}\n\n\tbool operator==(const time &other) const {\n\t\treturn raw == other.raw;\n\t}\n\n\tbool operator!=(const time &other) const {\n\t\treturn raw != other.raw;\n\t}\n\n\tbool operator>(const time &other) const {\n\t\treturn other.raw.scmp(raw);\n\t}\n\n\tbool operator>=(const time &other) const {\n\t\treturn !raw.scmp(other.raw);\n\t}\n\n\tbool operator<(const time &other) const {\n\t\treturn raw.scmp(other.raw);\n\t}\n\n\tbool operator<=(const time &other) const {\n\t\treturn !other.raw.scmp(raw);\n\t}\n\n\ttime operator+(const time &other) const {\n\t\treturn time(raw.add(other.raw));\n\t}\n\n\ttime &operator+=(const time &other) {\n\t\t*this = *this + other;\n\t\treturn *this;\n\t}\n\n\ttime operator-() const {\n\t\treturn time(raw.neg());\n\t}\n\n\ttime operator-(const time &other) const {\n\t\treturn *this + (-other);\n\t}\n\n\ttime &operator-=(const time &other) {\n\t\t*this = *this - other;\n\t\treturn *this;\n\t}\n\n\toperator std::string() const {\n\t\tchar buf[48]; // x=2**95; len(f\"-{x/1_000_000_000_000_000}.{x^1_000_000_000_000_000}\") == 48\n\t\tint64_t secs = this->secs();\n\t\tint64_t femtos = this->femtos();\n\t\tsnprintf(buf, sizeof(buf), \"%s%\" PRIi64 \".%015\" PRIi64,\n\t\t\tis_negative() ? \"-\" : \"\", secs >= 0 ? secs : -secs, femtos >= 0 ? femtos : -femtos);\n\t\treturn buf;\n\t}\n\n#if __cplusplus >= 201603L\n\t[[nodiscard(\"ignoring parse errors\")]]\n#endif\n\tbool parse(const std::string &str) {\n\t\tenum {\n\t\t\tparse_sign_opt,\n\t\t\tparse_integral,\n\t\t\tparse_fractional,\n\t\t} state = parse_sign_opt;\n\t\tbool negative = false;\n\t\tint64_t integral = 0;\n\t\tint64_t fractional = 0;\n\t\tsize_t frac_digits = 0;\n\t\tfor (auto chr : str) {\n\t\t\tswitch (state) {\n\t\t\t\tcase parse_sign_opt:\n\t\t\t\t\tstate = parse_integral;\n\t\t\t\t\tif (chr == '+' || chr == '-') {\n\t\t\t\t\t\tnegative = (chr == '-');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t/* fallthrough */\n\t\t\t\tcase parse_integral:\n\t\t\t\t\tif (chr >= '0' && chr <= '9') {\n\t\t\t\t\t\tintegral *= 10;\n\t\t\t\t\t\tintegral += chr - '0';\n\t\t\t\t\t} else if (chr == '.') {\n\t\t\t\t\t\tstate = parse_fractional;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase parse_fractional:\n\t\t\t\t\tif (chr >= '0' && chr <= '9' && frac_digits < resolution_digits) {\n\t\t\t\t\t\tfractional *= 10;\n\t\t\t\t\t\tfractional += chr - '0';\n\t\t\t\t\t\tfrac_digits++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (frac_digits == 0)\n\t\t\treturn false;\n\t\twhile (frac_digits++ < resolution_digits)\n\t\t\tfractional *= 10;\n\t\t*this = negative ? -time { integral, fractional} : time { integral, fractional };\n\t\treturn true;\n\t}\n};\n\n// Out-of-line definition required until C++17.\nconstexpr value<time::bits> time::resolution;\n\nstd::ostream &operator<<(std::ostream &os, const time &val) {\n\tos << (std::string)val;\n\treturn os;\n}\n\n// These literals are (confusingly) compatible with the ones from `std::chrono`: the `std::chrono` literals do not\n// have an underscore (e.g. 1ms) and the `cxxrtl::time` literals do (e.g. 1_ms). This syntactic difference is\n// a requirement of the C++ standard. Despite being compatible the literals should not be mixed in the same namespace.\nnamespace time_literals {\n\ntime operator\"\"_s(unsigned long long seconds) {\n\treturn time { (int64_t)seconds, 0 };\n}\n\ntime operator\"\"_ms(unsigned long long milliseconds) {\n\treturn time { 0, (int64_t)milliseconds * 1000000000000 };\n}\n\ntime operator\"\"_us(unsigned long long microseconds) {\n\treturn time { 0, (int64_t)microseconds * 1000000000 };\n}\n\ntime operator\"\"_ns(unsigned long long nanoseconds) {\n\treturn time { 0, (int64_t)nanoseconds * 1000000 };\n}\n\ntime operator\"\"_ps(unsigned long long picoseconds) {\n\treturn time { 0, (int64_t)picoseconds * 1000 };\n}\n\ntime operator\"\"_fs(unsigned long long femtoseconds) {\n\treturn time { 0, (int64_t)femtoseconds };\n}\n\n};\n\n};\n\n#endif\n",
|
|
137
137
|
"cxxrtl_vcd.h": "/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2020 whitequark <whitequark@whitequark.org>\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n */\n\n#ifndef CXXRTL_VCD_H\n#define CXXRTL_VCD_H\n\n#include <cxxrtl/cxxrtl.h>\n\nnamespace cxxrtl {\n\nclass vcd_writer {\n\tstruct variable {\n\t\tsize_t ident;\n\t\tsize_t width;\n\t\tchunk_t *curr;\n\t\tsize_t cache_offset;\n\t\tdebug_outline *outline;\n\t\tbool *outline_warm;\n\t};\n\n\tstd::vector<std::string> current_scope;\n\tstd::map<debug_outline*, bool> outlines;\n\tstd::vector<variable> variables;\n\tstd::vector<chunk_t> cache;\n\tstd::map<chunk_t*, size_t> aliases;\n\tbool streaming = false;\n\n\tvoid emit_timescale(unsigned number, const std::string &unit) {\n\t\tassert(!streaming);\n\t\tassert(number == 1 || number == 10 || number == 100);\n\t\tassert(unit == \"s\" || unit == \"ms\" || unit == \"us\" ||\n\t\t unit == \"ns\" || unit == \"ps\" || unit == \"fs\");\n\t\tbuffer += \"$timescale \" + std::to_string(number) + \" \" + unit + \" $end\\n\";\n\t}\n\n\tvoid emit_scope(const std::vector<std::string> &scope) {\n\t\tassert(!streaming);\n\t\twhile (current_scope.size() > scope.size() ||\n\t\t (current_scope.size() > 0 &&\n\t\t\tcurrent_scope[current_scope.size() - 1] != scope[current_scope.size() - 1])) {\n\t\t\tbuffer += \"$upscope $end\\n\";\n\t\t\tcurrent_scope.pop_back();\n\t\t}\n\t\twhile (current_scope.size() < scope.size()) {\n\t\t\tbuffer += \"$scope module \" + scope[current_scope.size()] + \" $end\\n\";\n\t\t\tcurrent_scope.push_back(scope[current_scope.size()]);\n\t\t}\n\t}\n\n\tvoid emit_ident(size_t ident) {\n\t\tdo {\n\t\t\tbuffer += '!' + ident % 94; // \"base94\"\n\t\t\tident /= 94;\n\t\t} while (ident != 0);\n\t}\n\n\tvoid emit_name(const std::string &name) {\n\t\tfor (char c : name) {\n\t\t\tif (c == ':') {\n\t\t\t\t// Due to a bug, GTKWave cannot parse a colon in the variable name, causing the VCD file\n\t\t\t\t// to be unreadable. It cannot be escaped either, so replace it with the sideways colon.\n\t\t\t\tbuffer += \"..\";\n\t\t\t} else {\n\t\t\t\tbuffer += c;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid emit_var(const variable &var, const std::string &type, const std::string &name,\n\t size_t lsb_at, bool multipart) {\n\t\tassert(!streaming);\n\t\tbuffer += \"$var \" + type + \" \" + std::to_string(var.width) + \" \";\n\t\temit_ident(var.ident);\n\t\tbuffer += \" \";\n\t\temit_name(name);\n\t\tif (multipart || name.back() == ']' || lsb_at != 0) {\n\t\t\tif (var.width == 1)\n\t\t\t\tbuffer += \" [\" + std::to_string(lsb_at) + \"]\";\n\t\t\telse\n\t\t\t\tbuffer += \" [\" + std::to_string(lsb_at + var.width - 1) + \":\" + std::to_string(lsb_at) + \"]\";\n\t\t}\n\t\tbuffer += \" $end\\n\";\n\t}\n\n\tvoid emit_enddefinitions() {\n\t\tassert(!streaming);\n\t\tbuffer += \"$enddefinitions $end\\n\";\n\t\tstreaming = true;\n\t}\n\n\tvoid emit_time(uint64_t timestamp) {\n\t\tassert(streaming);\n\t\tbuffer += \"#\" + std::to_string(timestamp) + \"\\n\";\n\t}\n\n\tvoid emit_scalar(const variable &var) {\n\t\tassert(streaming);\n\t\tassert(var.width == 1);\n\t\tbuffer += (*var.curr ? '1' : '0');\n\t\temit_ident(var.ident);\n\t\tbuffer += '\\n';\n\t}\n\n\tvoid emit_vector(const variable &var) {\n\t\tassert(streaming);\n\t\tbuffer += 'b';\n\t\tfor (size_t bit = var.width - 1; bit != (size_t)-1; bit--) {\n\t\t\tbool bit_curr = var.curr[bit / (8 * sizeof(chunk_t))] & (1 << (bit % (8 * sizeof(chunk_t))));\n\t\t\tbuffer += (bit_curr ? '1' : '0');\n\t\t}\n\t\tbuffer += ' ';\n\t\temit_ident(var.ident);\n\t\tbuffer += '\\n';\n\t}\n\n\tvoid reset_outlines() {\n\t\tfor (auto &outline_it : outlines)\n\t\t\toutline_it.second = /*warm=*/(outline_it.first == nullptr);\n\t}\n\n\tvariable ®ister_variable(size_t width, chunk_t *curr, bool constant = false, debug_outline *outline = nullptr) {\n\t\tif (aliases.count(curr)) {\n\t\t\treturn variables[aliases[curr]];\n\t\t} else {\n\t\t\tauto outline_it = outlines.emplace(outline, /*warm=*/(outline == nullptr)).first;\n\t\t\tconst size_t chunks = (width + (sizeof(chunk_t) * 8 - 1)) / (sizeof(chunk_t) * 8);\n\t\t\taliases[curr] = variables.size();\n\t\t\tif (constant) {\n\t\t\t\tvariables.emplace_back(variable { variables.size(), width, curr, (size_t)-1, outline_it->first, &outline_it->second });\n\t\t\t} else {\n\t\t\t\tvariables.emplace_back(variable { variables.size(), width, curr, cache.size(), outline_it->first, &outline_it->second });\n\t\t\t\tcache.insert(cache.end(), &curr[0], &curr[chunks]);\n\t\t\t}\n\t\t\treturn variables.back();\n\t\t}\n\t}\n\n\tbool test_variable(const variable &var) {\n\t\tif (var.cache_offset == (size_t)-1)\n\t\t\treturn false; // constant\n\t\tif (!*var.outline_warm) {\n\t\t\tvar.outline->eval();\n\t\t\t*var.outline_warm = true;\n\t\t}\n\t\tconst size_t chunks = (var.width + (sizeof(chunk_t) * 8 - 1)) / (sizeof(chunk_t) * 8);\n\t\tif (std::equal(&var.curr[0], &var.curr[chunks], &cache[var.cache_offset])) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\tstd::copy(&var.curr[0], &var.curr[chunks], &cache[var.cache_offset]);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tstatic std::vector<std::string> split_hierarchy(const std::string &hier_name) {\n\t\tstd::vector<std::string> hierarchy;\n\t\tsize_t prev = 0;\n\t\twhile (true) {\n\t\t\tsize_t curr = hier_name.find_first_of(' ', prev);\n\t\t\tif (curr == std::string::npos) {\n\t\t\t\thierarchy.push_back(hier_name.substr(prev));\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\thierarchy.push_back(hier_name.substr(prev, curr - prev));\n\t\t\t\tprev = curr + 1;\n\t\t\t}\n\t\t}\n\t\treturn hierarchy;\n\t}\n\npublic:\n\tstd::string buffer;\n\n\tvoid timescale(unsigned number, const std::string &unit) {\n\t\temit_timescale(number, unit);\n\t}\n\n\tvoid add(const std::string &hier_name, const debug_item &item, bool multipart = false) {\n\t\tstd::vector<std::string> scope = split_hierarchy(hier_name);\n\t\tstd::string name = scope.back();\n\t\tscope.pop_back();\n\n\t\temit_scope(scope);\n\t\tswitch (item.type) {\n\t\t\t// Not the best naming but oh well...\n\t\t\tcase debug_item::VALUE:\n\t\t\t\temit_var(register_variable(item.width, item.curr, /*constant=*/item.next == nullptr),\n\t\t\t\t \"wire\", name, item.lsb_at, multipart);\n\t\t\t\tbreak;\n\t\t\tcase debug_item::WIRE:\n\t\t\t\temit_var(register_variable(item.width, item.curr),\n\t\t\t\t \"reg\", name, item.lsb_at, multipart);\n\t\t\t\tbreak;\n\t\t\tcase debug_item::MEMORY: {\n\t\t\t\tconst size_t stride = (item.width + (sizeof(chunk_t) * 8 - 1)) / (sizeof(chunk_t) * 8);\n\t\t\t\tfor (size_t index = 0; index < item.depth; index++) {\n\t\t\t\t\tchunk_t *nth_curr = &item.curr[stride * index];\n\t\t\t\t\tstd::string nth_name = name + '[' + std::to_string(index) + ']';\n\t\t\t\t\temit_var(register_variable(item.width, nth_curr),\n\t\t\t\t\t \"reg\", nth_name, item.lsb_at, multipart);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase debug_item::ALIAS:\n\t\t\t\t// Like VALUE, but, even though `item.next == nullptr` always holds, the underlying value\n\t\t\t\t// can actually change, and must be tracked. In most cases the VCD identifier will be\n\t\t\t\t// unified with the aliased reg, but we should handle the case where only the alias is\n\t\t\t\t// added to the VCD writer, too.\n\t\t\t\temit_var(register_variable(item.width, item.curr),\n\t\t\t\t \"wire\", name, item.lsb_at, multipart);\n\t\t\t\tbreak;\n\t\t\tcase debug_item::OUTLINE:\n\t\t\t\temit_var(register_variable(item.width, item.curr, /*constant=*/false, item.outline),\n\t\t\t\t \"wire\", name, item.lsb_at, multipart);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\ttemplate<class Filter>\n\tvoid add(const debug_items &items, const Filter &filter) {\n\t\t// `debug_items` is a map, so the items are already sorted in an order optimal for emitting\n\t\t// VCD scope sections.\n\t\tfor (auto &it : items.table)\n\t\t\tfor (auto &part : it.second)\n\t\t\t\tif (filter(it.first, part))\n\t\t\t\t\tadd(it.first, part, it.second.size() > 1);\n\t}\n\n\tvoid add(const debug_items &items) {\n\t\tthis->add(items, [](const std::string &, const debug_item &) {\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tvoid add_without_memories(const debug_items &items) {\n\t\tthis->add(items, [](const std::string &, const debug_item &item) {\n\t\t\treturn item.type != debug_item::MEMORY;\n\t\t});\n\t}\n\n\tvoid sample(uint64_t timestamp) {\n\t\tbool first_sample = !streaming;\n\t\tif (first_sample) {\n\t\t\temit_scope({});\n\t\t\temit_enddefinitions();\n\t\t}\n\t\treset_outlines();\n\t\temit_time(timestamp);\n\t\tfor (auto var : variables)\n\t\t\tif (test_variable(var) || first_sample) {\n\t\t\t\tif (var.width == 1)\n\t\t\t\t\temit_scalar(var);\n\t\t\t\telse\n\t\t\t\t\temit_vector(var);\n\t\t\t}\n\t}\n};\n\n}\n\n#endif\n",
|
|
138
138
|
},
|
|
@@ -293,7 +293,7 @@ export const filesystem = {
|
|
|
293
293
|
},
|
|
294
294
|
"pmux2mux.v": "module \\$pmux (A, B, S, Y);\n\nwire [1023:0] _TECHMAP_DO_ = \"proc; clean\";\n\nparameter WIDTH = 1;\nparameter S_WIDTH = 1;\n\ninput [WIDTH-1:0] A;\ninput [WIDTH*S_WIDTH-1:0] B;\ninput [S_WIDTH-1:0] S;\noutput reg [WIDTH-1:0] Y;\n\ninteger i;\n\nalways @* begin\n\tY <= A;\n\tfor (i = 0; i < S_WIDTH; i=i+1)\n\t\tif (S[i]) Y <= B[WIDTH*i +: WIDTH];\nend\n\nendmodule\n",
|
|
295
295
|
"python3": {
|
|
296
|
-
"smtio.py": "#\n# yosys -- Yosys Open SYnthesis Suite\n#\n# Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport sys, re, os, signal, json\nimport subprocess\nif os.name == \"posix\":\n import resource\nfrom copy import copy\nfrom select import select\nfrom time import time\nfrom queue import Queue, Empty\nfrom threading import Thread\n\n\n# This is needed so that the recursive SMT2 S-expression parser\n# does not run out of stack frames when parsing large expressions\nif os.name == \"posix\":\n smtio_reclimit = 64 * 1024\n if sys.getrecursionlimit() < smtio_reclimit:\n sys.setrecursionlimit(smtio_reclimit)\n\n current_rlimit_stack = resource.getrlimit(resource.RLIMIT_STACK)\n if current_rlimit_stack[0] != resource.RLIM_INFINITY:\n smtio_stacksize = 128 * 1024 * 1024\n if os.uname().sysname == \"Darwin\":\n # MacOS has rather conservative stack limits\n smtio_stacksize = 8 * 1024 * 1024\n if current_rlimit_stack[1] != resource.RLIM_INFINITY:\n smtio_stacksize = min(smtio_stacksize, current_rlimit_stack[1])\n if current_rlimit_stack[0] < smtio_stacksize:\n try:\n resource.setrlimit(resource.RLIMIT_STACK, (smtio_stacksize, current_rlimit_stack[1]))\n except ValueError:\n # couldn't get more stack, just run with what we have\n pass\n\n\n# currently running solvers (so we can kill them)\nrunning_solvers = dict()\nforced_shutdown = False\nsolvers_index = 0\n\ndef force_shutdown(signum, frame):\n global forced_shutdown\n if not forced_shutdown:\n forced_shutdown = True\n if signum is not None:\n print(\"<%s>\" % signal.Signals(signum).name)\n for p in running_solvers.values():\n # os.killpg(os.getpgid(p.pid), signal.SIGTERM)\n os.kill(p.pid, signal.SIGTERM)\n sys.exit(1)\n\nif os.name == \"posix\":\n signal.signal(signal.SIGHUP, force_shutdown)\nsignal.signal(signal.SIGINT, force_shutdown)\nsignal.signal(signal.SIGTERM, force_shutdown)\n\ndef except_hook(exctype, value, traceback):\n if not forced_shutdown:\n sys.__excepthook__(exctype, value, traceback)\n force_shutdown(None, None)\n\nsys.excepthook = except_hook\n\n\nhex_dict = {\n \"0\": \"0000\", \"1\": \"0001\", \"2\": \"0010\", \"3\": \"0011\",\n \"4\": \"0100\", \"5\": \"0101\", \"6\": \"0110\", \"7\": \"0111\",\n \"8\": \"1000\", \"9\": \"1001\", \"A\": \"1010\", \"B\": \"1011\",\n \"C\": \"1100\", \"D\": \"1101\", \"E\": \"1110\", \"F\": \"1111\",\n \"a\": \"1010\", \"b\": \"1011\", \"c\": \"1100\", \"d\": \"1101\",\n \"e\": \"1110\", \"f\": \"1111\"\n}\n\n\nclass SmtModInfo:\n def __init__(self):\n self.inputs = set()\n self.outputs = set()\n self.registers = set()\n self.memories = dict()\n self.wires = set()\n self.wsize = dict()\n self.clocks = dict()\n self.cells = dict()\n self.asserts = dict()\n self.covers = dict()\n self.maximize = set()\n self.minimize = set()\n self.anyconsts = dict()\n self.anyseqs = dict()\n self.allconsts = dict()\n self.allseqs = dict()\n self.asize = dict()\n self.witness = []\n\n\nclass SmtIo:\n def __init__(self, opts=None):\n global solvers_index\n\n self.logic = None\n self.logic_qf = True\n self.logic_ax = True\n self.logic_uf = True\n self.logic_bv = True\n self.logic_dt = False\n self.forall = False\n self.timeout = 0\n self.produce_models = True\n self.recheck = False\n self.smt2cache = [list()]\n self.smt2_options = dict()\n self.p = None\n self.p_index = solvers_index\n solvers_index += 1\n\n if opts is not None:\n self.logic = opts.logic\n self.solver = opts.solver\n self.solver_opts = opts.solver_opts\n self.debug_print = opts.debug_print\n self.debug_file = opts.debug_file\n self.dummy_file = opts.dummy_file\n self.timeinfo = opts.timeinfo\n self.timeout = opts.timeout\n self.unroll = opts.unroll\n self.noincr = opts.noincr\n self.info_stmts = opts.info_stmts\n self.nocomments = opts.nocomments\n\n else:\n self.solver = \"yices\"\n self.solver_opts = list()\n self.debug_print = False\n self.debug_file = None\n self.dummy_file = None\n self.timeinfo = os.name != \"nt\"\n self.timeout = 0\n self.unroll = False\n self.noincr = False\n self.info_stmts = list()\n self.nocomments = False\n\n self.start_time = time()\n\n self.modinfo = dict()\n self.curmod = None\n self.topmod = None\n self.setup_done = False\n\n def __del__(self):\n if self.p is not None and not forced_shutdown:\n os.killpg(os.getpgid(self.p.pid), signal.SIGTERM)\n if running_solvers is not None:\n del running_solvers[self.p_index]\n\n def setup(self):\n assert not self.setup_done\n\n if self.forall:\n self.unroll = False\n\n if self.solver == \"yices\":\n if self.forall:\n self.noincr = True\n\n if self.noincr:\n self.popen_vargs = ['yices-smt2'] + self.solver_opts\n else:\n self.popen_vargs = ['yices-smt2', '--incremental'] + self.solver_opts\n if self.timeout != 0:\n self.popen_vargs.append('-t')\n self.popen_vargs.append('%d' % self.timeout);\n\n if self.solver == \"z3\":\n self.popen_vargs = ['z3', '-smt2', '-in'] + self.solver_opts\n if self.timeout != 0:\n self.popen_vargs.append('-T:%d' % self.timeout);\n\n if self.solver in [\"cvc4\", \"cvc5\"]:\n self.recheck = True\n if self.noincr:\n self.popen_vargs = [self.solver, '--lang', 'smt2.6' if self.logic_dt else 'smt2'] + self.solver_opts\n else:\n self.popen_vargs = [self.solver, '--incremental', '--lang', 'smt2.6' if self.logic_dt else 'smt2'] + self.solver_opts\n if self.timeout != 0:\n self.popen_vargs.append('--tlimit=%d000' % self.timeout);\n\n if self.solver == \"mathsat\":\n self.popen_vargs = ['mathsat'] + self.solver_opts\n if self.timeout != 0:\n print('timeout option is not supported for mathsat.')\n sys.exit(1)\n\n if self.solver in [\"boolector\", \"bitwuzla\"]:\n if self.noincr:\n self.popen_vargs = [self.solver, '--smt2'] + self.solver_opts\n else:\n self.popen_vargs = [self.solver, '--smt2', '-i'] + self.solver_opts\n self.unroll = True\n if self.timeout != 0:\n print('timeout option is not supported for %s.' % self.solver)\n sys.exit(1)\n\n if self.solver == \"abc\":\n if len(self.solver_opts) > 0:\n self.popen_vargs = ['yosys-abc', '-S', '; '.join(self.solver_opts)]\n else:\n self.popen_vargs = ['yosys-abc', '-S', '%blast; &sweep -C 5000; &syn4; &cec -s -m -C 2000']\n self.logic_ax = False\n self.unroll = True\n self.noincr = True\n if self.timeout != 0:\n print('timeout option is not supported for abc.')\n sys.exit(1)\n\n if self.solver == \"dummy\":\n assert self.dummy_file is not None\n self.dummy_fd = open(self.dummy_file, \"r\")\n else:\n if self.dummy_file is not None:\n self.dummy_fd = open(self.dummy_file, \"w\")\n if not self.noincr:\n self.p_open()\n\n if self.unroll:\n assert not self.forall\n self.logic_uf = False\n self.unroll_idcnt = 0\n self.unroll_buffer = \"\"\n self.unroll_level = 0\n self.unroll_sorts = set()\n self.unroll_objs = set()\n self.unroll_decls = dict()\n self.unroll_cache = dict()\n self.unroll_stack = list()\n\n if self.logic is None:\n self.logic = \"\"\n if self.logic_qf: self.logic += \"QF_\"\n if self.logic_ax: self.logic += \"A\"\n if self.logic_uf: self.logic += \"UF\"\n if self.logic_bv: self.logic += \"BV\"\n if self.logic_dt: self.logic = \"ALL\"\n if self.solver == \"yices\" and self.forall: self.logic = \"BV\"\n\n self.setup_done = True\n\n for stmt in self.info_stmts:\n self.write(stmt)\n\n if self.produce_models:\n self.write(\"(set-option :produce-models true)\")\n\n #See the SMT-LIB Standard, Section 4.1.7\n modestart_options = [\":global-declarations\", \":interactive-mode\", \":produce-assertions\", \":produce-assignments\", \":produce-models\", \":produce-proofs\", \":produce-unsat-assumptions\", \":produce-unsat-cores\", \":random-seed\"]\n for key, val in self.smt2_options.items():\n if key in modestart_options:\n self.write(\"(set-option {} {})\".format(key, val))\n\n self.write(\"(set-logic %s)\" % self.logic)\n\n if self.forall and self.solver == \"yices\":\n self.write(\"(set-option :yices-ef-max-iters 1000000000)\")\n\n for key, val in self.smt2_options.items():\n if key not in modestart_options:\n self.write(\"(set-option {} {})\".format(key, val))\n\n def timestamp(self):\n secs = int(time() - self.start_time)\n return \"## %3d:%02d:%02d \" % (secs // (60*60), (secs // 60) % 60, secs % 60)\n\n def replace_in_stmt(self, stmt, pat, repl):\n if stmt == pat:\n return repl\n\n if isinstance(stmt, list):\n return [self.replace_in_stmt(s, pat, repl) for s in stmt]\n\n return stmt\n\n def unroll_stmt(self, stmt):\n if not isinstance(stmt, list):\n return stmt\n\n stmt = [self.unroll_stmt(s) for s in stmt]\n\n if len(stmt) >= 2 and not isinstance(stmt[0], list) and stmt[0] in self.unroll_decls:\n assert stmt[1] in self.unroll_objs\n\n key = tuple(stmt)\n if key not in self.unroll_cache:\n decl = copy(self.unroll_decls[key[0]])\n\n self.unroll_cache[key] = \"|UNROLL#%d|\" % self.unroll_idcnt\n decl[1] = self.unroll_cache[key]\n self.unroll_idcnt += 1\n\n if decl[0] == \"declare-fun\":\n if isinstance(decl[3], list) or decl[3] not in self.unroll_sorts:\n self.unroll_objs.add(decl[1])\n decl[2] = list()\n else:\n self.unroll_objs.add(decl[1])\n decl = list()\n\n elif decl[0] == \"define-fun\":\n arg_index = 1\n for arg_name, arg_sort in decl[2]:\n decl[4] = self.replace_in_stmt(decl[4], arg_name, key[arg_index])\n arg_index += 1\n decl[2] = list()\n\n if len(decl) > 0:\n decl = self.unroll_stmt(decl)\n self.write(self.unparse(decl), unroll=False)\n\n return self.unroll_cache[key]\n\n return stmt\n\n def p_thread_main(self):\n while True:\n data = self.p.stdout.readline().decode(\"utf-8\")\n if data == \"\": break\n self.p_queue.put(data)\n self.p_queue.put(\"\")\n self.p_running = False\n\n def p_open(self):\n assert self.p is None\n try:\n self.p = subprocess.Popen(self.popen_vargs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n except FileNotFoundError:\n print(\"%s SMT Solver '%s' not found in path.\" % (self.timestamp(), self.popen_vargs[0]), flush=True)\n sys.exit(1)\n running_solvers[self.p_index] = self.p\n self.p_running = True\n self.p_next = None\n self.p_queue = Queue()\n self.p_thread = Thread(target=self.p_thread_main)\n self.p_thread.start()\n\n def p_write(self, data, flush):\n assert self.p is not None\n self.p.stdin.write(bytes(data, \"utf-8\"))\n if flush: self.p.stdin.flush()\n\n def p_read(self):\n assert self.p is not None\n if self.p_next is not None:\n data = self.p_next\n self.p_next = None\n return data\n if not self.p_running:\n return \"\"\n return self.p_queue.get()\n\n def p_poll(self, timeout=0.1):\n assert self.p is not None\n assert self.p_running\n if self.p_next is not None:\n return False\n try:\n self.p_next = self.p_queue.get(True, timeout)\n return False\n except Empty:\n return True\n\n def p_close(self):\n assert self.p is not None\n self.p.stdin.close()\n self.p_thread.join()\n assert not self.p_running\n del running_solvers[self.p_index]\n self.p = None\n self.p_next = None\n self.p_queue = None\n self.p_thread = None\n\n def write(self, stmt, unroll=True):\n if stmt.startswith(\";\"):\n self.info(stmt)\n if not self.setup_done:\n self.info_stmts.append(stmt)\n return\n elif not self.setup_done:\n self.setup()\n\n stmt = stmt.strip()\n\n if self.nocomments or self.unroll:\n stmt = re.sub(r\" *;.*\", \"\", stmt)\n if stmt == \"\": return\n\n recheck = None\n\n if self.solver != \"dummy\":\n if self.noincr:\n # Don't close the solver yet, if we're just unrolling definitions\n # required for a (get-...) statement\n if self.p is not None and not stmt.startswith(\"(get-\") and unroll:\n self.p_close()\n\n if unroll and self.unroll:\n s = re.sub(r\"\\|[^|]*\\|\", \"\", stmt)\n self.unroll_level += s.count(\"(\") - s.count(\")\")\n if self.unroll_level > 0:\n self.unroll_buffer += stmt\n self.unroll_buffer += \" \"\n return\n else:\n stmt = self.unroll_buffer + stmt\n self.unroll_buffer = \"\"\n\n s = self.parse(stmt)\n\n if self.recheck and s and s[0].startswith(\"get-\"):\n recheck = self.unroll_idcnt\n\n if self.debug_print:\n print(\"-> %s\" % s)\n\n if len(s) == 3 and s[0] == \"declare-sort\" and s[2] == \"0\":\n self.unroll_sorts.add(s[1])\n return\n\n elif len(s) == 4 and s[0] == \"declare-fun\" and s[2] == [] and s[3] in self.unroll_sorts:\n self.unroll_objs.add(s[1])\n return\n\n elif len(s) >= 4 and s[0] == \"declare-fun\":\n for arg_sort in s[2]:\n if arg_sort in self.unroll_sorts:\n self.unroll_decls[s[1]] = s\n return\n\n elif len(s) >= 4 and s[0] == \"define-fun\":\n for arg_name, arg_sort in s[2]:\n if arg_sort in self.unroll_sorts:\n self.unroll_decls[s[1]] = s\n return\n\n stmt = self.unparse(self.unroll_stmt(s))\n\n if recheck is not None and recheck != self.unroll_idcnt:\n self.check_sat([\"sat\"])\n\n if stmt == \"(push 1)\":\n self.unroll_stack.append((\n copy(self.unroll_sorts),\n copy(self.unroll_objs),\n copy(self.unroll_decls),\n copy(self.unroll_cache),\n ))\n\n if stmt == \"(pop 1)\":\n self.unroll_sorts, self.unroll_objs, self.unroll_decls, self.unroll_cache = self.unroll_stack.pop()\n\n if self.debug_print:\n print(\"> %s\" % stmt)\n\n if self.debug_file:\n print(stmt, file=self.debug_file)\n self.debug_file.flush()\n\n if self.solver != \"dummy\":\n if self.noincr:\n if stmt == \"(push 1)\":\n self.smt2cache.append(list())\n elif stmt == \"(pop 1)\":\n self.smt2cache.pop()\n else:\n if self.p is not None:\n self.p_write(stmt + \"\\n\", True)\n self.smt2cache[-1].append(stmt)\n else:\n self.p_write(stmt + \"\\n\", True)\n\n def info(self, stmt):\n if not stmt.startswith(\"; yosys-smt2-\"):\n return\n\n fields = stmt.split()\n\n if fields[1] == \"yosys-smt2-solver-option\":\n self.smt2_options[fields[2]] = fields[3]\n\n if fields[1] == \"yosys-smt2-nomem\":\n if self.logic is None:\n self.logic_ax = False\n\n if fields[1] == \"yosys-smt2-nobv\":\n if self.logic is None:\n self.logic_bv = False\n\n if fields[1] == \"yosys-smt2-stdt\":\n if self.logic is None:\n self.logic_dt = True\n\n if fields[1] == \"yosys-smt2-forall\":\n if self.logic is None:\n self.logic_qf = False\n self.forall = True\n\n if fields[1] == \"yosys-smt2-module\":\n self.curmod = fields[2]\n self.modinfo[self.curmod] = SmtModInfo()\n\n if fields[1] == \"yosys-smt2-cell\":\n self.modinfo[self.curmod].cells[fields[3]] = fields[2]\n\n if fields[1] == \"yosys-smt2-topmod\":\n self.topmod = fields[2]\n\n if fields[1] == \"yosys-smt2-input\":\n self.modinfo[self.curmod].inputs.add(fields[2])\n self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-output\":\n self.modinfo[self.curmod].outputs.add(fields[2])\n self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-register\":\n self.modinfo[self.curmod].registers.add(fields[2])\n self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-memory\":\n self.modinfo[self.curmod].memories[fields[2]] = (int(fields[3]), int(fields[4]), int(fields[5]), int(fields[6]), fields[7] == \"async\")\n\n if fields[1] == \"yosys-smt2-wire\":\n self.modinfo[self.curmod].wires.add(fields[2])\n self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-clock\":\n for edge in fields[3:]:\n if fields[2] not in self.modinfo[self.curmod].clocks:\n self.modinfo[self.curmod].clocks[fields[2]] = edge\n elif self.modinfo[self.curmod].clocks[fields[2]] != edge:\n self.modinfo[self.curmod].clocks[fields[2]] = \"event\"\n\n if fields[1] == \"yosys-smt2-assert\":\n if len(fields) > 4:\n self.modinfo[self.curmod].asserts[\"%s_a %s\" % (self.curmod, fields[2])] = f'{fields[4]} ({fields[3]})'\n else:\n self.modinfo[self.curmod].asserts[\"%s_a %s\" % (self.curmod, fields[2])] = fields[3]\n\n if fields[1] == \"yosys-smt2-cover\":\n if len(fields) > 4:\n self.modinfo[self.curmod].covers[\"%s_c %s\" % (self.curmod, fields[2])] = f'{fields[4]} ({fields[3]})'\n else:\n self.modinfo[self.curmod].covers[\"%s_c %s\" % (self.curmod, fields[2])] = fields[3]\n\n if fields[1] == \"yosys-smt2-maximize\":\n self.modinfo[self.curmod].maximize.add(fields[2])\n\n if fields[1] == \"yosys-smt2-minimize\":\n self.modinfo[self.curmod].minimize.add(fields[2])\n\n if fields[1] == \"yosys-smt2-anyconst\":\n self.modinfo[self.curmod].anyconsts[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5])\n self.modinfo[self.curmod].asize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-anyseq\":\n self.modinfo[self.curmod].anyseqs[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5])\n self.modinfo[self.curmod].asize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-allconst\":\n self.modinfo[self.curmod].allconsts[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5])\n self.modinfo[self.curmod].asize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-allseq\":\n self.modinfo[self.curmod].allseqs[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5])\n self.modinfo[self.curmod].asize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-witness\":\n data = json.loads(stmt.split(None, 2)[2])\n if data.get(\"type\") in [\"cell\", \"mem\", \"posedge\", \"negedge\", \"input\", \"reg\", \"init\", \"seq\", \"blackbox\"]:\n self.modinfo[self.curmod].witness.append(data)\n\n def hiernets(self, top, regs_only=False):\n def hiernets_worker(nets, mod, cursor):\n for netname in sorted(self.modinfo[mod].wsize.keys()):\n if not regs_only or netname in self.modinfo[mod].registers:\n nets.append(cursor + [netname])\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n hiernets_worker(nets, celltype, cursor + [cellname])\n\n nets = list()\n hiernets_worker(nets, top, [])\n return nets\n\n def hieranyconsts(self, top):\n def worker(results, mod, cursor):\n for name, value in sorted(self.modinfo[mod].anyconsts.items()):\n width = self.modinfo[mod].asize[name]\n results.append((cursor, name, value[0], value[1], width))\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n worker(results, celltype, cursor + [cellname])\n\n results = list()\n worker(results, top, [])\n return results\n\n def hieranyseqs(self, top):\n def worker(results, mod, cursor):\n for name, value in sorted(self.modinfo[mod].anyseqs.items()):\n width = self.modinfo[mod].asize[name]\n results.append((cursor, name, value[0], value[1], width))\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n worker(results, celltype, cursor + [cellname])\n\n results = list()\n worker(results, top, [])\n return results\n\n def hierallconsts(self, top):\n def worker(results, mod, cursor):\n for name, value in sorted(self.modinfo[mod].allconsts.items()):\n width = self.modinfo[mod].asize[name]\n results.append((cursor, name, value[0], value[1], width))\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n worker(results, celltype, cursor + [cellname])\n\n results = list()\n worker(results, top, [])\n return results\n\n def hierallseqs(self, top):\n def worker(results, mod, cursor):\n for name, value in sorted(self.modinfo[mod].allseqs.items()):\n width = self.modinfo[mod].asize[name]\n results.append((cursor, name, value[0], value[1], width))\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n worker(results, celltype, cursor + [cellname])\n\n results = list()\n worker(results, top, [])\n return results\n\n def hiermems(self, top):\n def hiermems_worker(mems, mod, cursor):\n for memname in sorted(self.modinfo[mod].memories.keys()):\n mems.append(cursor + [memname])\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n hiermems_worker(mems, celltype, cursor + [cellname])\n\n mems = list()\n hiermems_worker(mems, top, [])\n return mems\n\n def hierwitness(self, top, allregs=False, blackbox=True):\n init_witnesses = []\n seq_witnesses = []\n clk_witnesses = []\n mem_witnesses = []\n\n def absolute(path, cursor, witness):\n return {\n **witness,\n \"path\": path + tuple(witness[\"path\"]),\n \"smtpath\": cursor + [witness[\"smtname\"]],\n }\n\n for witness in self.modinfo[top].witness:\n if witness[\"type\"] == \"input\":\n seq_witnesses.append(absolute((), [], witness))\n if witness[\"type\"] in (\"posedge\", \"negedge\"):\n clk_witnesses.append(absolute((), [], witness))\n\n init_types = [\"init\"]\n if allregs:\n init_types.append(\"reg\")\n\n seq_types = [\"seq\"]\n if blackbox:\n seq_types.append(\"blackbox\")\n\n def worker(mod, path, cursor):\n cell_paths = {}\n for witness in self.modinfo[mod].witness:\n if witness[\"type\"] in init_types:\n init_witnesses.append(absolute(path, cursor, witness))\n if witness[\"type\"] in seq_types:\n seq_witnesses.append(absolute(path, cursor, witness))\n if witness[\"type\"] == \"mem\":\n if allregs and not witness[\"rom\"]:\n width, size = witness[\"width\"], witness[\"size\"]\n witness = {**witness, \"uninitialized\": [{\"width\": width * size, \"offset\": 0}]}\n if not witness[\"uninitialized\"]:\n continue\n\n mem_witnesses.append(absolute(path, cursor, witness))\n if witness[\"type\"] == \"cell\":\n cell_paths[witness[\"smtname\"]] = tuple(witness[\"path\"])\n\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n worker(celltype, path + cell_paths.get(cellname, (\"?\" + cellname,)), cursor + [cellname])\n\n worker(top, (), [])\n return init_witnesses, seq_witnesses, clk_witnesses, mem_witnesses\n\n def read(self):\n stmt = []\n count_brackets = 0\n\n while True:\n if self.solver == \"dummy\":\n line = self.dummy_fd.readline().strip()\n else:\n line = self.p_read().strip()\n if self.dummy_file is not None:\n self.dummy_fd.write(line + \"\\n\")\n\n count_brackets += line.count(\"(\")\n count_brackets -= line.count(\")\")\n stmt.append(line)\n\n if self.debug_print:\n print(\"< %s\" % line)\n if count_brackets == 0:\n break\n if self.solver != \"dummy\" and self.p.poll():\n print(\"%s Solver terminated unexpectedly: %s\" % (self.timestamp(), \"\".join(stmt)), flush=True)\n sys.exit(1)\n\n stmt = \"\".join(stmt)\n if stmt.startswith(\"(error\"):\n print(\"%s Solver Error: %s\" % (self.timestamp(), stmt), flush=True)\n if self.solver != \"dummy\":\n self.p_close()\n sys.exit(1)\n\n return stmt\n\n def check_sat(self, expected=[\"sat\", \"unsat\", \"unknown\", \"timeout\", \"interrupted\"]):\n if self.debug_print:\n print(\"> (check-sat)\")\n if self.debug_file and not self.nocomments:\n print(\"; running check-sat..\", file=self.debug_file)\n self.debug_file.flush()\n\n if self.solver != \"dummy\":\n if self.noincr:\n if self.p is not None:\n self.p_close()\n self.p_open()\n for cache_ctx in self.smt2cache:\n for cache_stmt in cache_ctx:\n self.p_write(cache_stmt + \"\\n\", False)\n\n self.p_write(\"(check-sat)\\n\", True)\n\n if self.timeinfo:\n i = 0\n s = r\"/-\\|\"\n\n count = 0\n num_bs = 0\n while self.p_poll():\n count += 1\n\n if count < 25:\n continue\n\n if count % 10 == 0 or count == 25:\n secs = count // 10\n\n if secs < 60:\n m = \"(%d seconds)\" % secs\n elif secs < 60*60:\n m = \"(%d seconds -- %d:%02d)\" % (secs, secs // 60, secs % 60)\n else:\n m = \"(%d seconds -- %d:%02d:%02d)\" % (secs, secs // (60*60), (secs // 60) % 60, secs % 60)\n\n print(\"%s %s %c\" % (\"\\b \\b\" * num_bs, m, s[i]), end=\"\", file=sys.stderr)\n num_bs = len(m) + 3\n\n else:\n print(\"\\b\" + s[i], end=\"\", file=sys.stderr)\n\n sys.stderr.flush()\n i = (i + 1) % len(s)\n\n if num_bs != 0:\n print(\"\\b \\b\" * num_bs, end=\"\", file=sys.stderr)\n sys.stderr.flush()\n\n else:\n count = 0\n while self.p_poll(60):\n count += 1\n msg = None\n\n if count == 1:\n msg = \"1 minute\"\n\n elif count in [5, 10, 15, 30]:\n msg = \"%d minutes\" % count\n\n elif count == 60:\n msg = \"1 hour\"\n\n elif count % 60 == 0:\n msg = \"%d hours\" % (count // 60)\n\n if msg is not None:\n print(\"%s waiting for solver (%s)\" % (self.timestamp(), msg), flush=True)\n\n if self.forall:\n result = self.read()\n while result not in [\"sat\", \"unsat\", \"unknown\", \"timeout\", \"interrupted\", \"\"]:\n print(\"%s %s: %s\" % (self.timestamp(), self.solver, result))\n result = self.read()\n else:\n result = self.read()\n\n if self.debug_file:\n print(\"(set-info :status %s)\" % result, file=self.debug_file)\n print(\"(check-sat)\", file=self.debug_file)\n self.debug_file.flush()\n\n if result not in expected:\n if result == \"\":\n print(\"%s Unexpected EOF response from solver.\" % (self.timestamp()), flush=True)\n else:\n print(\"%s Unexpected response from solver: %s\" % (self.timestamp(), result), flush=True)\n if self.solver != \"dummy\":\n self.p_close()\n sys.exit(1)\n\n return result\n\n def parse(self, stmt):\n def worker(stmt, cursor=0):\n while stmt[cursor] in [\" \", \"\\t\", \"\\r\", \"\\n\"]:\n cursor += 1\n\n if stmt[cursor] == '(':\n expr = []\n cursor += 1\n while stmt[cursor] != ')':\n el, cursor = worker(stmt, cursor)\n expr.append(el)\n return expr, cursor+1\n\n if stmt[cursor] == '|':\n expr = \"|\"\n cursor += 1\n while stmt[cursor] != '|':\n expr += stmt[cursor]\n cursor += 1\n expr += \"|\"\n return expr, cursor+1\n\n expr = \"\"\n while stmt[cursor] not in [\"(\", \")\", \"|\", \" \", \"\\t\", \"\\r\", \"\\n\"]:\n expr += stmt[cursor]\n cursor += 1\n return expr, cursor\n return worker(stmt)[0]\n\n def unparse(self, stmt):\n if isinstance(stmt, list):\n return \"(\" + \" \".join([self.unparse(s) for s in stmt]) + \")\"\n return stmt\n\n def bv2hex(self, v):\n h = \"\"\n v = self.bv2bin(v)\n while len(v) > 0:\n d = 0\n if len(v) > 0 and v[-1] == \"1\": d += 1\n if len(v) > 1 and v[-2] == \"1\": d += 2\n if len(v) > 2 and v[-3] == \"1\": d += 4\n if len(v) > 3 and v[-4] == \"1\": d += 8\n h = hex(d)[2:] + h\n if len(v) < 4: break\n v = v[:-4]\n return h\n\n def bv2bin(self, v):\n if type(v) is list and len(v) == 3 and v[0] == \"_\" and v[1].startswith(\"bv\"):\n x, n = int(v[1][2:]), int(v[2])\n return \"\".join(\"1\" if (x & (1 << i)) else \"0\" for i in range(n-1, -1, -1))\n if v == \"true\": return \"1\"\n if v == \"false\": return \"0\"\n if v.startswith(\"#b\"):\n return v[2:]\n if v.startswith(\"#x\"):\n return \"\".join(hex_dict.get(x) for x in v[2:])\n assert False\n\n def bv2int(self, v):\n return int(self.bv2bin(v), 2)\n\n def get(self, expr):\n self.write(\"(get-value (%s))\" % (expr))\n return self.parse(self.read())[0][1]\n\n def get_list(self, expr_list):\n if len(expr_list) == 0:\n return []\n self.write(\"(get-value (%s))\" % \" \".join(expr_list))\n return [n[1] for n in self.parse(self.read()) if n]\n\n def get_path(self, mod, path):\n assert mod in self.modinfo\n path = path.replace(\"\\\\\", \"/\").split(\".\")\n\n for i in range(len(path)-1):\n first = \".\".join(path[0:i+1])\n second = \".\".join(path[i+1:])\n\n if first in self.modinfo[mod].cells:\n nextmod = self.modinfo[mod].cells[first]\n return [first] + self.get_path(nextmod, second)\n\n return [\".\".join(path)]\n\n def net_expr(self, mod, base, path):\n if len(path) == 0:\n return base\n\n if len(path) == 1:\n assert mod in self.modinfo\n if path[0] == \"\":\n return base\n if isinstance(path[0], int):\n return \"(|%s#%d| %s)\" % (mod, path[0], base)\n if path[0] in self.modinfo[mod].cells:\n return \"(|%s_h %s| %s)\" % (mod, path[0], base)\n if path[0] in self.modinfo[mod].wsize:\n return \"(|%s_n %s| %s)\" % (mod, path[0], base)\n if path[0] in self.modinfo[mod].memories:\n return \"(|%s_m %s| %s)\" % (mod, path[0], base)\n assert 0\n\n assert mod in self.modinfo\n assert path[0] in self.modinfo[mod].cells\n\n nextmod = self.modinfo[mod].cells[path[0]]\n nextbase = \"(|%s_h %s| %s)\" % (mod, path[0], base)\n return self.net_expr(nextmod, nextbase, path[1:])\n\n def witness_net_expr(self, mod, base, witness):\n net = self.net_expr(mod, base, witness[\"smtpath\"])\n is_bool = self.net_width(mod, witness[\"smtpath\"]) == 1\n if is_bool:\n assert witness[\"width\"] == 1\n assert witness[\"smtoffset\"] == 0\n return net\n return \"((_ extract %d %d) %s)\" % (witness[\"smtoffset\"] + witness[\"width\"] - 1, witness[\"smtoffset\"], net)\n\n def net_width(self, mod, net_path):\n for i in range(len(net_path)-1):\n assert mod in self.modinfo\n assert net_path[i] in self.modinfo[mod].cells\n mod = self.modinfo[mod].cells[net_path[i]]\n\n assert mod in self.modinfo\n if isinstance(net_path[-1], int):\n return None\n assert net_path[-1] in self.modinfo[mod].wsize\n return self.modinfo[mod].wsize[net_path[-1]]\n\n def net_clock(self, mod, net_path):\n for i in range(len(net_path)-1):\n assert mod in self.modinfo\n assert net_path[i] in self.modinfo[mod].cells\n mod = self.modinfo[mod].cells[net_path[i]]\n\n assert mod in self.modinfo\n if net_path[-1] not in self.modinfo[mod].clocks:\n return None\n return self.modinfo[mod].clocks[net_path[-1]]\n\n def net_exists(self, mod, net_path):\n for i in range(len(net_path)-1):\n if mod not in self.modinfo: return False\n if net_path[i] not in self.modinfo[mod].cells: return False\n mod = self.modinfo[mod].cells[net_path[i]]\n\n if mod not in self.modinfo: return False\n if net_path[-1] not in self.modinfo[mod].wsize: return False\n return True\n\n def mem_exists(self, mod, mem_path):\n for i in range(len(mem_path)-1):\n if mod not in self.modinfo: return False\n if mem_path[i] not in self.modinfo[mod].cells: return False\n mod = self.modinfo[mod].cells[mem_path[i]]\n\n if mod not in self.modinfo: return False\n if mem_path[-1] not in self.modinfo[mod].memories: return False\n return True\n\n def mem_expr(self, mod, base, path, port=None, infomode=False):\n if len(path) == 1:\n assert mod in self.modinfo\n assert path[0] in self.modinfo[mod].memories\n if infomode:\n return self.modinfo[mod].memories[path[0]]\n return \"(|%s_m%s %s| %s)\" % (mod, \"\" if port is None else \":%s\" % port, path[0], base)\n\n assert mod in self.modinfo\n assert path[0] in self.modinfo[mod].cells\n\n nextmod = self.modinfo[mod].cells[path[0]]\n nextbase = \"(|%s_h %s| %s)\" % (mod, path[0], base)\n return self.mem_expr(nextmod, nextbase, path[1:], port=port, infomode=infomode)\n\n def mem_info(self, mod, path):\n return self.mem_expr(mod, \"\", path, infomode=True)\n\n def get_net(self, mod_name, net_path, state_name):\n return self.get(self.net_expr(mod_name, state_name, net_path))\n\n def get_net_list(self, mod_name, net_path_list, state_name):\n return self.get_list([self.net_expr(mod_name, state_name, n) for n in net_path_list])\n\n def get_net_hex(self, mod_name, net_path, state_name):\n return self.bv2hex(self.get_net(mod_name, net_path, state_name))\n\n def get_net_hex_list(self, mod_name, net_path_list, state_name):\n return [self.bv2hex(v) for v in self.get_net_list(mod_name, net_path_list, state_name)]\n\n def get_net_bin(self, mod_name, net_path, state_name):\n return self.bv2bin(self.get_net(mod_name, net_path, state_name))\n\n def get_net_bin_list(self, mod_name, net_path_list, state_name):\n return [self.bv2bin(v) for v in self.get_net_list(mod_name, net_path_list, state_name)]\n\n def wait(self):\n if self.p is not None:\n self.p.wait()\n self.p_close()\n\n\nclass SmtOpts:\n def __init__(self):\n self.shortopts = \"s:S:v\"\n self.longopts = [\"unroll\", \"noincr\", \"noprogress\", \"timeout=\", \"dump-smt2=\", \"logic=\", \"dummy=\", \"info=\", \"nocomments\"]\n self.solver = \"yices\"\n self.solver_opts = list()\n self.debug_print = False\n self.debug_file = None\n self.dummy_file = None\n self.unroll = False\n self.noincr = False\n self.timeinfo = os.name != \"nt\"\n self.timeout = 0\n self.logic = None\n self.info_stmts = list()\n self.nocomments = False\n\n def handle(self, o, a):\n if o == \"-s\":\n self.solver = a\n elif o == \"-S\":\n self.solver_opts.append(a)\n elif o == \"--timeout\":\n self.timeout = int(a)\n elif o == \"-v\":\n self.debug_print = True\n elif o == \"--unroll\":\n self.unroll = True\n elif o == \"--noincr\":\n self.noincr = True\n elif o == \"--noprogress\":\n self.timeinfo = False\n elif o == \"--dump-smt2\":\n self.debug_file = open(a, \"w\")\n elif o == \"--logic\":\n self.logic = a\n elif o == \"--dummy\":\n self.dummy_file = a\n elif o == \"--info\":\n self.info_stmts.append(a)\n elif o == \"--nocomments\":\n self.nocomments = True\n else:\n return False\n return True\n\n def helpmsg(self):\n return \"\"\"\n -s <solver>\n set SMT solver: z3, yices, boolector, bitwuzla, cvc4, mathsat, dummy\n default: yices\n\n -S <opt>\n pass <opt> as command line argument to the solver\n\n --timeout <value>\n set the solver timeout to the specified value (in seconds).\n\n --logic <smt2_logic>\n use the specified SMT2 logic (e.g. QF_AUFBV)\n\n --dummy <filename>\n if solver is \"dummy\", read solver output from that file\n otherwise: write solver output to that file\n\n -v\n enable debug output\n\n --unroll\n unroll uninterpreted functions\n\n --noincr\n don't use incremental solving, instead restart solver for\n each (check-sat). This also avoids (push) and (pop).\n\n --noprogress\n disable timer display during solving\n (this option is set implicitly on Windows)\n\n --dump-smt2 <filename>\n write smt2 statements to file\n\n --info <smt2-info-stmt>\n include the specified smt2 info statement in the smt2 output\n\n --nocomments\n strip all comments from the generated smt2 code\n\"\"\"\n\n\nclass MkVcd:\n def __init__(self, f):\n self.f = f\n self.t = -1\n self.nets = dict()\n self.clocks = dict()\n\n def add_net(self, path, width):\n path = tuple(path)\n assert self.t == -1\n key = \"n%d\" % len(self.nets)\n self.nets[path] = (key, width)\n\n def add_clock(self, path, edge):\n path = tuple(path)\n assert self.t == -1\n key = \"n%d\" % len(self.nets)\n self.nets[path] = (key, 1)\n self.clocks[path] = (key, edge)\n\n def set_net(self, path, bits):\n path = tuple(path)\n assert self.t >= 0\n assert path in self.nets\n if path not in self.clocks:\n print(\"b%s %s\" % (bits, self.nets[path][0]), file=self.f)\n\n def escape_name(self, name):\n name = re.sub(r\"\\[([0-9a-zA-Z_]*[a-zA-Z_][0-9a-zA-Z_]*)\\]\", r\"<\\1>\", name)\n if re.match(r\"[\\[\\]]\", name) and name[0] != \"\\\\\":\n name = \"\\\\\" + name\n return name\n\n def set_time(self, t):\n assert t >= self.t\n if t != self.t:\n if self.t == -1:\n print(\"$version Generated by Yosys-SMTBMC $end\", file=self.f)\n print(\"$timescale 1ns $end\", file=self.f)\n print(\"$var integer 32 t smt_step $end\", file=self.f)\n print(\"$var event 1 ! smt_clock $end\", file=self.f)\n\n def vcdescape(n):\n if n.startswith(\"$\") or \":\" in n:\n return \"\\\\\" + n\n return n\n\n scope = []\n for path in sorted(self.nets):\n key, width = self.nets[path]\n\n uipath = list(path)\n if \".\" in uipath[-1] and not uipath[-1].startswith(\"$\"):\n uipath = uipath[0:-1] + uipath[-1].split(\".\")\n for i in range(len(uipath)):\n uipath[i] = re.sub(r\"\\[([^\\]]*)\\]\", r\"<\\1>\", uipath[i])\n\n while uipath[:len(scope)] != scope:\n print(\"$upscope $end\", file=self.f)\n scope = scope[:-1]\n\n while uipath[:-1] != scope:\n scopename = uipath[len(scope)]\n print(\"$scope module %s $end\" % vcdescape(scopename), file=self.f)\n scope.append(uipath[len(scope)])\n\n if path in self.clocks and self.clocks[path][1] == \"event\":\n print(\"$var event 1 %s %s $end\" % (key, vcdescape(uipath[-1])), file=self.f)\n else:\n print(\"$var wire %d %s %s $end\" % (width, key, vcdescape(uipath[-1])), file=self.f)\n\n for i in range(len(scope)):\n print(\"$upscope $end\", file=self.f)\n\n print(\"$enddefinitions $end\", file=self.f)\n\n self.t = t\n assert self.t >= 0\n\n if self.t > 0:\n print(\"#%d\" % (10 * self.t - 5), file=self.f)\n for path in sorted(self.clocks.keys()):\n if self.clocks[path][1] == \"posedge\":\n print(\"b0 %s\" % self.nets[path][0], file=self.f)\n elif self.clocks[path][1] == \"negedge\":\n print(\"b1 %s\" % self.nets[path][0], file=self.f)\n\n print(\"#%d\" % (10 * self.t), file=self.f)\n print(\"1!\", file=self.f)\n print(\"b%s t\" % format(self.t, \"032b\"), file=self.f)\n\n for path in sorted(self.clocks.keys()):\n if self.clocks[path][1] == \"negedge\":\n print(\"b0 %s\" % self.nets[path][0], file=self.f)\n else:\n print(\"b1 %s\" % self.nets[path][0], file=self.f)\n",
|
|
296
|
+
"smtio.py": "#\n# yosys -- Yosys Open SYnthesis Suite\n#\n# Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport sys, re, os, signal, json\nimport subprocess\nif os.name == \"posix\":\n import resource\nfrom copy import copy\nfrom select import select\nfrom time import time\nfrom queue import Queue, Empty\nfrom threading import Thread\n\n\n# This is needed so that the recursive SMT2 S-expression parser\n# does not run out of stack frames when parsing large expressions\nif os.name == \"posix\":\n smtio_reclimit = 64 * 1024\n if sys.getrecursionlimit() < smtio_reclimit:\n sys.setrecursionlimit(smtio_reclimit)\n\n current_rlimit_stack = resource.getrlimit(resource.RLIMIT_STACK)\n if current_rlimit_stack[0] != resource.RLIM_INFINITY:\n smtio_stacksize = 128 * 1024 * 1024\n if os.uname().sysname == \"Darwin\":\n # MacOS has rather conservative stack limits\n smtio_stacksize = 8 * 1024 * 1024\n if current_rlimit_stack[1] != resource.RLIM_INFINITY:\n smtio_stacksize = min(smtio_stacksize, current_rlimit_stack[1])\n if current_rlimit_stack[0] < smtio_stacksize:\n try:\n resource.setrlimit(resource.RLIMIT_STACK, (smtio_stacksize, current_rlimit_stack[1]))\n except ValueError:\n # couldn't get more stack, just run with what we have\n pass\n\n\n# currently running solvers (so we can kill them)\nrunning_solvers = dict()\nforced_shutdown = False\nsolvers_index = 0\n\ndef force_shutdown(signum, frame):\n global forced_shutdown\n if not forced_shutdown:\n forced_shutdown = True\n if signum is not None:\n print(\"<%s>\" % signal.Signals(signum).name)\n for p in running_solvers.values():\n # os.killpg(os.getpgid(p.pid), signal.SIGTERM)\n os.kill(p.pid, signal.SIGTERM)\n sys.exit(1)\n\nif os.name == \"posix\":\n signal.signal(signal.SIGHUP, force_shutdown)\nsignal.signal(signal.SIGINT, force_shutdown)\nsignal.signal(signal.SIGTERM, force_shutdown)\n\ndef except_hook(exctype, value, traceback):\n if not forced_shutdown:\n sys.__excepthook__(exctype, value, traceback)\n force_shutdown(None, None)\n\nsys.excepthook = except_hook\n\n\ndef recursion_helper(iteration, *request):\n stack = [iteration(*request)]\n\n while stack:\n top = stack.pop()\n try:\n request = next(top)\n except StopIteration:\n continue\n\n stack.append(top)\n stack.append(iteration(*request))\n\n\nhex_dict = {\n \"0\": \"0000\", \"1\": \"0001\", \"2\": \"0010\", \"3\": \"0011\",\n \"4\": \"0100\", \"5\": \"0101\", \"6\": \"0110\", \"7\": \"0111\",\n \"8\": \"1000\", \"9\": \"1001\", \"A\": \"1010\", \"B\": \"1011\",\n \"C\": \"1100\", \"D\": \"1101\", \"E\": \"1110\", \"F\": \"1111\",\n \"a\": \"1010\", \"b\": \"1011\", \"c\": \"1100\", \"d\": \"1101\",\n \"e\": \"1110\", \"f\": \"1111\"\n}\n\n\nclass SmtModInfo:\n def __init__(self):\n self.inputs = set()\n self.outputs = set()\n self.registers = set()\n self.memories = dict()\n self.wires = set()\n self.wsize = dict()\n self.clocks = dict()\n self.cells = dict()\n self.asserts = dict()\n self.assumes = dict()\n self.covers = dict()\n self.maximize = set()\n self.minimize = set()\n self.anyconsts = dict()\n self.anyseqs = dict()\n self.allconsts = dict()\n self.allseqs = dict()\n self.asize = dict()\n self.witness = []\n\n\nclass SmtIo:\n def __init__(self, opts=None):\n global solvers_index\n\n self.logic = None\n self.logic_qf = True\n self.logic_ax = True\n self.logic_uf = True\n self.logic_bv = True\n self.logic_dt = False\n self.forall = False\n self.timeout = 0\n self.produce_models = True\n self.recheck = False\n self.smt2cache = [list()]\n self.smt2_options = dict()\n self.smt2_assumptions = dict()\n self.p = None\n self.p_index = solvers_index\n solvers_index += 1\n\n if opts is not None:\n self.logic = opts.logic\n self.solver = opts.solver\n self.solver_opts = opts.solver_opts\n self.debug_print = opts.debug_print\n self.debug_file = opts.debug_file\n self.dummy_file = opts.dummy_file\n self.timeinfo = opts.timeinfo\n self.timeout = opts.timeout\n self.unroll = opts.unroll\n self.noincr = opts.noincr\n self.info_stmts = opts.info_stmts\n self.nocomments = opts.nocomments\n\n else:\n self.solver = \"yices\"\n self.solver_opts = list()\n self.debug_print = False\n self.debug_file = None\n self.dummy_file = None\n self.timeinfo = os.name != \"nt\"\n self.timeout = 0\n self.unroll = False\n self.noincr = False\n self.info_stmts = list()\n self.nocomments = False\n\n self.start_time = time()\n\n self.modinfo = dict()\n self.curmod = None\n self.topmod = None\n self.setup_done = False\n\n def __del__(self):\n if self.p is not None and not forced_shutdown:\n os.killpg(os.getpgid(self.p.pid), signal.SIGTERM)\n if running_solvers is not None:\n del running_solvers[self.p_index]\n\n def setup(self):\n assert not self.setup_done\n\n if self.forall:\n self.unroll = False\n\n if self.solver == \"yices\":\n if self.forall:\n self.noincr = True\n\n if self.noincr:\n self.popen_vargs = ['yices-smt2'] + self.solver_opts\n else:\n self.popen_vargs = ['yices-smt2', '--incremental'] + self.solver_opts\n if self.timeout != 0:\n self.popen_vargs.append('-t')\n self.popen_vargs.append('%d' % self.timeout);\n\n if self.solver == \"z3\":\n self.popen_vargs = ['z3', '-smt2', '-in'] + self.solver_opts\n if self.timeout != 0:\n self.popen_vargs.append('-T:%d' % self.timeout);\n\n if self.solver in [\"cvc4\", \"cvc5\"]:\n self.recheck = True\n if self.noincr:\n self.popen_vargs = [self.solver, '--lang', 'smt2.6' if self.logic_dt else 'smt2'] + self.solver_opts\n else:\n self.popen_vargs = [self.solver, '--incremental', '--lang', 'smt2.6' if self.logic_dt else 'smt2'] + self.solver_opts\n if self.timeout != 0:\n self.popen_vargs.append('--tlimit=%d000' % self.timeout);\n\n if self.solver == \"mathsat\":\n self.popen_vargs = ['mathsat'] + self.solver_opts\n if self.timeout != 0:\n print('timeout option is not supported for mathsat.')\n sys.exit(1)\n\n if self.solver in [\"boolector\", \"bitwuzla\"]:\n if self.noincr:\n self.popen_vargs = [self.solver, '--smt2'] + self.solver_opts\n else:\n self.popen_vargs = [self.solver, '--smt2', '-i'] + self.solver_opts\n self.unroll = True\n if self.timeout != 0:\n print('timeout option is not supported for %s.' % self.solver)\n sys.exit(1)\n\n if self.solver == \"abc\":\n if len(self.solver_opts) > 0:\n self.popen_vargs = ['yosys-abc', '-S', '; '.join(self.solver_opts)]\n else:\n self.popen_vargs = ['yosys-abc', '-S', '%blast; &sweep -C 5000; &syn4; &cec -s -m -C 2000']\n self.logic_ax = False\n self.unroll = True\n self.noincr = True\n if self.timeout != 0:\n print('timeout option is not supported for abc.')\n sys.exit(1)\n\n if self.solver == \"dummy\":\n assert self.dummy_file is not None\n self.dummy_fd = open(self.dummy_file, \"r\")\n else:\n if self.dummy_file is not None:\n self.dummy_fd = open(self.dummy_file, \"w\")\n if not self.noincr:\n self.p_open()\n\n if self.unroll:\n assert not self.forall\n self.logic_uf = False\n self.unroll_idcnt = 0\n self.unroll_buffer = \"\"\n self.unroll_level = 0\n self.unroll_sorts = set()\n self.unroll_objs = set()\n self.unroll_decls = dict()\n self.unroll_cache = dict()\n self.unroll_stack = list()\n\n if self.logic is None:\n self.logic = \"\"\n if self.logic_qf: self.logic += \"QF_\"\n if self.logic_ax: self.logic += \"A\"\n if self.logic_uf: self.logic += \"UF\"\n if self.logic_bv: self.logic += \"BV\"\n if self.logic_dt: self.logic = \"ALL\"\n if self.solver == \"yices\" and self.forall: self.logic = \"BV\"\n\n self.setup_done = True\n\n for stmt in self.info_stmts:\n self.write(stmt)\n\n if self.produce_models:\n self.write(\"(set-option :produce-models true)\")\n\n #See the SMT-LIB Standard, Section 4.1.7\n modestart_options = [\":global-declarations\", \":interactive-mode\", \":produce-assertions\", \":produce-assignments\", \":produce-models\", \":produce-proofs\", \":produce-unsat-assumptions\", \":produce-unsat-cores\", \":random-seed\"]\n for key, val in self.smt2_options.items():\n if key in modestart_options:\n self.write(\"(set-option {} {})\".format(key, val))\n\n self.write(\"(set-logic %s)\" % self.logic)\n\n if self.forall and self.solver == \"yices\":\n self.write(\"(set-option :yices-ef-max-iters 1000000000)\")\n\n for key, val in self.smt2_options.items():\n if key not in modestart_options:\n self.write(\"(set-option {} {})\".format(key, val))\n\n def timestamp(self):\n secs = int(time() - self.start_time)\n return \"## %3d:%02d:%02d \" % (secs // (60*60), (secs // 60) % 60, secs % 60)\n\n def replace_in_stmt(self, stmt, pat, repl):\n if stmt == pat:\n return repl\n\n if isinstance(stmt, list):\n return [self.replace_in_stmt(s, pat, repl) for s in stmt]\n\n return stmt\n\n def unroll_stmt(self, stmt):\n result = []\n recursion_helper(self._unroll_stmt_into, stmt, result)\n return result.pop()\n\n def _unroll_stmt_into(self, stmt, output, depth=128):\n if not isinstance(stmt, list):\n output.append(stmt)\n return\n\n new_stmt = []\n for s in stmt:\n if depth:\n yield from self._unroll_stmt_into(s, new_stmt, depth - 1)\n else:\n yield s, new_stmt\n stmt = new_stmt\n\n if len(stmt) >= 2 and not isinstance(stmt[0], list) and stmt[0] in self.unroll_decls:\n assert stmt[1] in self.unroll_objs\n\n key = tuple(stmt)\n if key not in self.unroll_cache:\n decl = copy(self.unroll_decls[key[0]])\n\n self.unroll_cache[key] = \"|UNROLL#%d|\" % self.unroll_idcnt\n decl[1] = self.unroll_cache[key]\n self.unroll_idcnt += 1\n\n if decl[0] == \"declare-fun\":\n if isinstance(decl[3], list) or decl[3] not in self.unroll_sorts:\n self.unroll_objs.add(decl[1])\n decl[2] = list()\n else:\n self.unroll_objs.add(decl[1])\n decl = list()\n\n elif decl[0] == \"define-fun\":\n arg_index = 1\n for arg_name, arg_sort in decl[2]:\n decl[4] = self.replace_in_stmt(decl[4], arg_name, key[arg_index])\n arg_index += 1\n decl[2] = list()\n\n if len(decl) > 0:\n tmp = []\n if depth:\n yield from self._unroll_stmt_into(decl, tmp, depth - 1)\n else:\n yield decl, tmp\n\n decl = tmp.pop()\n self.write(self.unparse(decl), unroll=False)\n\n output.append(self.unroll_cache[key])\n return\n\n output.append(stmt)\n\n def p_thread_main(self):\n while True:\n data = self.p.stdout.readline().decode(\"utf-8\")\n if data == \"\": break\n self.p_queue.put(data)\n self.p_queue.put(\"\")\n self.p_running = False\n\n def p_open(self):\n assert self.p is None\n try:\n self.p = subprocess.Popen(self.popen_vargs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n except FileNotFoundError:\n print(\"%s SMT Solver '%s' not found in path.\" % (self.timestamp(), self.popen_vargs[0]), flush=True)\n sys.exit(1)\n running_solvers[self.p_index] = self.p\n self.p_running = True\n self.p_next = None\n self.p_queue = Queue()\n self.p_thread = Thread(target=self.p_thread_main)\n self.p_thread.start()\n\n def p_write(self, data, flush):\n assert self.p is not None\n self.p.stdin.write(bytes(data, \"utf-8\"))\n if flush: self.p.stdin.flush()\n\n def p_read(self):\n assert self.p is not None\n if self.p_next is not None:\n data = self.p_next\n self.p_next = None\n return data\n if not self.p_running:\n return \"\"\n return self.p_queue.get()\n\n def p_poll(self, timeout=0.1):\n assert self.p is not None\n assert self.p_running\n if self.p_next is not None:\n return False\n try:\n self.p_next = self.p_queue.get(True, timeout)\n return False\n except Empty:\n return True\n\n def p_close(self):\n assert self.p is not None\n self.p.stdin.close()\n self.p_thread.join()\n assert not self.p_running\n del running_solvers[self.p_index]\n self.p = None\n self.p_next = None\n self.p_queue = None\n self.p_thread = None\n\n def write(self, stmt, unroll=True):\n if stmt.startswith(\";\"):\n self.info(stmt)\n if not self.setup_done:\n self.info_stmts.append(stmt)\n return\n elif not self.setup_done:\n self.setup()\n\n stmt = stmt.strip()\n\n if self.nocomments or self.unroll:\n stmt = re.sub(r\" *;.*\", \"\", stmt)\n if stmt == \"\": return\n\n recheck = None\n\n if self.solver != \"dummy\":\n if self.noincr:\n # Don't close the solver yet, if we're just unrolling definitions\n # required for a (get-...) statement\n if self.p is not None and not stmt.startswith(\"(get-\") and unroll:\n self.p_close()\n\n if unroll and self.unroll:\n s = re.sub(r\"\\|[^|]*\\|\", \"\", stmt)\n self.unroll_level += s.count(\"(\") - s.count(\")\")\n if self.unroll_level > 0:\n self.unroll_buffer += stmt\n self.unroll_buffer += \" \"\n return\n else:\n stmt = self.unroll_buffer + stmt\n self.unroll_buffer = \"\"\n\n s = self.parse(stmt)\n\n if self.recheck and s and s[0].startswith(\"get-\"):\n recheck = self.unroll_idcnt\n\n if self.debug_print:\n print(\"-> %s\" % s)\n\n if len(s) == 3 and s[0] == \"declare-sort\" and s[2] == \"0\":\n self.unroll_sorts.add(s[1])\n return\n\n elif len(s) == 4 and s[0] == \"declare-fun\" and s[2] == [] and s[3] in self.unroll_sorts:\n self.unroll_objs.add(s[1])\n return\n\n elif len(s) >= 4 and s[0] == \"declare-fun\":\n for arg_sort in s[2]:\n if arg_sort in self.unroll_sorts:\n self.unroll_decls[s[1]] = s\n return\n\n elif len(s) >= 4 and s[0] == \"define-fun\":\n for arg_name, arg_sort in s[2]:\n if arg_sort in self.unroll_sorts:\n self.unroll_decls[s[1]] = s\n return\n\n stmt = self.unparse(self.unroll_stmt(s))\n\n if recheck is not None and recheck != self.unroll_idcnt:\n self.check_sat([\"sat\"])\n\n if stmt == \"(push 1)\":\n self.unroll_stack.append((\n copy(self.unroll_sorts),\n copy(self.unroll_objs),\n copy(self.unroll_decls),\n copy(self.unroll_cache),\n ))\n\n if stmt == \"(pop 1)\":\n self.unroll_sorts, self.unroll_objs, self.unroll_decls, self.unroll_cache = self.unroll_stack.pop()\n\n if self.debug_print:\n print(\"> %s\" % stmt)\n\n if self.debug_file:\n print(stmt, file=self.debug_file)\n self.debug_file.flush()\n\n if self.solver != \"dummy\":\n if self.noincr:\n if stmt == \"(push 1)\":\n self.smt2cache.append(list())\n elif stmt == \"(pop 1)\":\n self.smt2cache.pop()\n else:\n if self.p is not None:\n self.p_write(stmt + \"\\n\", True)\n self.smt2cache[-1].append(stmt)\n else:\n self.p_write(stmt + \"\\n\", True)\n\n def info(self, stmt):\n if not stmt.startswith(\"; yosys-smt2-\"):\n return\n\n fields = stmt.split()\n\n if fields[1] == \"yosys-smt2-solver-option\":\n self.smt2_options[fields[2]] = fields[3]\n\n if fields[1] == \"yosys-smt2-nomem\":\n if self.logic is None:\n self.logic_ax = False\n\n if fields[1] == \"yosys-smt2-nobv\":\n if self.logic is None:\n self.logic_bv = False\n\n if fields[1] == \"yosys-smt2-stdt\":\n if self.logic is None:\n self.logic_dt = True\n\n if fields[1] == \"yosys-smt2-forall\":\n if self.logic is None:\n self.logic_qf = False\n self.forall = True\n\n if fields[1] == \"yosys-smt2-module\":\n self.curmod = fields[2]\n self.modinfo[self.curmod] = SmtModInfo()\n\n if fields[1] == \"yosys-smt2-cell\":\n self.modinfo[self.curmod].cells[fields[3]] = fields[2]\n\n if fields[1] == \"yosys-smt2-topmod\":\n self.topmod = fields[2]\n\n if fields[1] == \"yosys-smt2-input\":\n self.modinfo[self.curmod].inputs.add(fields[2])\n self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-output\":\n self.modinfo[self.curmod].outputs.add(fields[2])\n self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-register\":\n self.modinfo[self.curmod].registers.add(fields[2])\n self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-memory\":\n self.modinfo[self.curmod].memories[fields[2]] = (int(fields[3]), int(fields[4]), int(fields[5]), int(fields[6]), fields[7] == \"async\")\n\n if fields[1] == \"yosys-smt2-wire\":\n self.modinfo[self.curmod].wires.add(fields[2])\n self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-clock\":\n for edge in fields[3:]:\n if fields[2] not in self.modinfo[self.curmod].clocks:\n self.modinfo[self.curmod].clocks[fields[2]] = edge\n elif self.modinfo[self.curmod].clocks[fields[2]] != edge:\n self.modinfo[self.curmod].clocks[fields[2]] = \"event\"\n\n if fields[1] == \"yosys-smt2-assert\":\n if len(fields) > 4:\n self.modinfo[self.curmod].asserts[\"%s_a %s\" % (self.curmod, fields[2])] = f'{fields[4]} ({fields[3]})'\n else:\n self.modinfo[self.curmod].asserts[\"%s_a %s\" % (self.curmod, fields[2])] = fields[3]\n\n if fields[1] == \"yosys-smt2-cover\":\n if len(fields) > 4:\n self.modinfo[self.curmod].covers[\"%s_c %s\" % (self.curmod, fields[2])] = f'{fields[4]} ({fields[3]})'\n else:\n self.modinfo[self.curmod].covers[\"%s_c %s\" % (self.curmod, fields[2])] = fields[3]\n\n if fields[1] == \"yosys-smt2-assume\":\n if len(fields) > 4:\n self.modinfo[self.curmod].assumes[\"%s_u %s\" % (self.curmod, fields[2])] = f'{fields[4]} ({fields[3]})'\n else:\n self.modinfo[self.curmod].assumes[\"%s_u %s\" % (self.curmod, fields[2])] = fields[3]\n\n if fields[1] == \"yosys-smt2-maximize\":\n self.modinfo[self.curmod].maximize.add(fields[2])\n\n if fields[1] == \"yosys-smt2-minimize\":\n self.modinfo[self.curmod].minimize.add(fields[2])\n\n if fields[1] == \"yosys-smt2-anyconst\":\n self.modinfo[self.curmod].anyconsts[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5])\n self.modinfo[self.curmod].asize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-anyseq\":\n self.modinfo[self.curmod].anyseqs[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5])\n self.modinfo[self.curmod].asize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-allconst\":\n self.modinfo[self.curmod].allconsts[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5])\n self.modinfo[self.curmod].asize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-allseq\":\n self.modinfo[self.curmod].allseqs[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5])\n self.modinfo[self.curmod].asize[fields[2]] = int(fields[3])\n\n if fields[1] == \"yosys-smt2-witness\":\n data = json.loads(stmt.split(None, 2)[2])\n if data.get(\"type\") in [\"cell\", \"mem\", \"posedge\", \"negedge\", \"input\", \"reg\", \"init\", \"seq\", \"blackbox\"]:\n self.modinfo[self.curmod].witness.append(data)\n\n def hiernets(self, top, regs_only=False):\n def hiernets_worker(nets, mod, cursor):\n for netname in sorted(self.modinfo[mod].wsize.keys()):\n if not regs_only or netname in self.modinfo[mod].registers:\n nets.append(cursor + [netname])\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n hiernets_worker(nets, celltype, cursor + [cellname])\n\n nets = list()\n hiernets_worker(nets, top, [])\n return nets\n\n def hieranyconsts(self, top):\n def worker(results, mod, cursor):\n for name, value in sorted(self.modinfo[mod].anyconsts.items()):\n width = self.modinfo[mod].asize[name]\n results.append((cursor, name, value[0], value[1], width))\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n worker(results, celltype, cursor + [cellname])\n\n results = list()\n worker(results, top, [])\n return results\n\n def hieranyseqs(self, top):\n def worker(results, mod, cursor):\n for name, value in sorted(self.modinfo[mod].anyseqs.items()):\n width = self.modinfo[mod].asize[name]\n results.append((cursor, name, value[0], value[1], width))\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n worker(results, celltype, cursor + [cellname])\n\n results = list()\n worker(results, top, [])\n return results\n\n def hierallconsts(self, top):\n def worker(results, mod, cursor):\n for name, value in sorted(self.modinfo[mod].allconsts.items()):\n width = self.modinfo[mod].asize[name]\n results.append((cursor, name, value[0], value[1], width))\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n worker(results, celltype, cursor + [cellname])\n\n results = list()\n worker(results, top, [])\n return results\n\n def hierallseqs(self, top):\n def worker(results, mod, cursor):\n for name, value in sorted(self.modinfo[mod].allseqs.items()):\n width = self.modinfo[mod].asize[name]\n results.append((cursor, name, value[0], value[1], width))\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n worker(results, celltype, cursor + [cellname])\n\n results = list()\n worker(results, top, [])\n return results\n\n def hiermems(self, top):\n def hiermems_worker(mems, mod, cursor):\n for memname in sorted(self.modinfo[mod].memories.keys()):\n mems.append(cursor + [memname])\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n hiermems_worker(mems, celltype, cursor + [cellname])\n\n mems = list()\n hiermems_worker(mems, top, [])\n return mems\n\n def hierwitness(self, top, allregs=False, blackbox=True):\n init_witnesses = []\n seq_witnesses = []\n clk_witnesses = []\n mem_witnesses = []\n\n def absolute(path, cursor, witness):\n return {\n **witness,\n \"path\": path + tuple(witness[\"path\"]),\n \"smtpath\": cursor + [witness[\"smtname\"]],\n }\n\n for witness in self.modinfo[top].witness:\n if witness[\"type\"] == \"input\":\n seq_witnesses.append(absolute((), [], witness))\n if witness[\"type\"] in (\"posedge\", \"negedge\"):\n clk_witnesses.append(absolute((), [], witness))\n\n init_types = [\"init\"]\n if allregs:\n init_types.append(\"reg\")\n\n seq_types = [\"seq\"]\n if blackbox:\n seq_types.append(\"blackbox\")\n\n def worker(mod, path, cursor):\n cell_paths = {}\n for witness in self.modinfo[mod].witness:\n if witness[\"type\"] in init_types:\n init_witnesses.append(absolute(path, cursor, witness))\n if witness[\"type\"] in seq_types:\n seq_witnesses.append(absolute(path, cursor, witness))\n if witness[\"type\"] == \"mem\":\n if allregs and not witness[\"rom\"]:\n width, size = witness[\"width\"], witness[\"size\"]\n witness = {**witness, \"uninitialized\": [{\"width\": width * size, \"offset\": 0}]}\n if not witness[\"uninitialized\"]:\n continue\n\n mem_witnesses.append(absolute(path, cursor, witness))\n if witness[\"type\"] == \"cell\":\n cell_paths[witness[\"smtname\"]] = tuple(witness[\"path\"])\n\n for cellname, celltype in sorted(self.modinfo[mod].cells.items()):\n worker(celltype, path + cell_paths.get(cellname, (\"?\" + cellname,)), cursor + [cellname])\n\n worker(top, (), [])\n return init_witnesses, seq_witnesses, clk_witnesses, mem_witnesses\n\n def read(self):\n stmt = []\n count_brackets = 0\n\n while True:\n if self.solver == \"dummy\":\n line = self.dummy_fd.readline().strip()\n else:\n line = self.p_read().strip()\n if self.dummy_file is not None:\n self.dummy_fd.write(line + \"\\n\")\n\n count_brackets += line.count(\"(\")\n count_brackets -= line.count(\")\")\n stmt.append(line)\n\n if self.debug_print:\n print(\"< %s\" % line)\n if count_brackets == 0:\n break\n if self.solver != \"dummy\" and self.p.poll():\n print(\"%s Solver terminated unexpectedly: %s\" % (self.timestamp(), \"\".join(stmt)), flush=True)\n sys.exit(1)\n\n stmt = \"\".join(stmt)\n if stmt.startswith(\"(error\"):\n print(\"%s Solver Error: %s\" % (self.timestamp(), stmt), flush=True)\n if self.solver != \"dummy\":\n self.p_close()\n sys.exit(1)\n\n return stmt\n\n def check_sat(self, expected=[\"sat\", \"unsat\", \"unknown\", \"timeout\", \"interrupted\"]):\n if self.smt2_assumptions:\n assume_exprs = \" \".join(self.smt2_assumptions.values())\n check_stmt = f\"(check-sat-assuming ({assume_exprs}))\"\n else:\n check_stmt = \"(check-sat)\"\n if self.debug_print:\n print(f\"> {check_stmt}\")\n if self.debug_file and not self.nocomments:\n print(\"; running check-sat..\", file=self.debug_file)\n self.debug_file.flush()\n\n if self.solver != \"dummy\":\n if self.noincr:\n if self.p is not None:\n self.p_close()\n self.p_open()\n for cache_ctx in self.smt2cache:\n for cache_stmt in cache_ctx:\n self.p_write(cache_stmt + \"\\n\", False)\n\n self.p_write(f\"{check_stmt}\\n\", True)\n\n if self.timeinfo:\n i = 0\n s = r\"/-\\|\"\n\n count = 0\n num_bs = 0\n while self.p_poll():\n count += 1\n\n if count < 25:\n continue\n\n if count % 10 == 0 or count == 25:\n secs = count // 10\n\n if secs < 60:\n m = \"(%d seconds)\" % secs\n elif secs < 60*60:\n m = \"(%d seconds -- %d:%02d)\" % (secs, secs // 60, secs % 60)\n else:\n m = \"(%d seconds -- %d:%02d:%02d)\" % (secs, secs // (60*60), (secs // 60) % 60, secs % 60)\n\n print(\"%s %s %c\" % (\"\\b \\b\" * num_bs, m, s[i]), end=\"\", file=sys.stderr)\n num_bs = len(m) + 3\n\n else:\n print(\"\\b\" + s[i], end=\"\", file=sys.stderr)\n\n sys.stderr.flush()\n i = (i + 1) % len(s)\n\n if num_bs != 0:\n print(\"\\b \\b\" * num_bs, end=\"\", file=sys.stderr)\n sys.stderr.flush()\n\n else:\n count = 0\n while self.p_poll(60):\n count += 1\n msg = None\n\n if count == 1:\n msg = \"1 minute\"\n\n elif count in [5, 10, 15, 30]:\n msg = \"%d minutes\" % count\n\n elif count == 60:\n msg = \"1 hour\"\n\n elif count % 60 == 0:\n msg = \"%d hours\" % (count // 60)\n\n if msg is not None:\n print(\"%s waiting for solver (%s)\" % (self.timestamp(), msg), flush=True)\n\n if self.forall:\n result = self.read()\n while result not in [\"sat\", \"unsat\", \"unknown\", \"timeout\", \"interrupted\", \"\"]:\n print(\"%s %s: %s\" % (self.timestamp(), self.solver, result))\n result = self.read()\n else:\n result = self.read()\n\n if self.debug_file:\n print(\"(set-info :status %s)\" % result, file=self.debug_file)\n print(check_stmt, file=self.debug_file)\n self.debug_file.flush()\n\n if result not in expected:\n if result == \"\":\n print(\"%s Unexpected EOF response from solver.\" % (self.timestamp()), flush=True)\n else:\n print(\"%s Unexpected response from solver: %s\" % (self.timestamp(), result), flush=True)\n if self.solver != \"dummy\":\n self.p_close()\n sys.exit(1)\n\n return result\n\n def parse(self, stmt):\n def worker(stmt, cursor=0):\n while stmt[cursor] in [\" \", \"\\t\", \"\\r\", \"\\n\"]:\n cursor += 1\n\n if stmt[cursor] == '(':\n expr = []\n cursor += 1\n while stmt[cursor] != ')':\n el, cursor = worker(stmt, cursor)\n expr.append(el)\n return expr, cursor+1\n\n if stmt[cursor] == '|':\n expr = \"|\"\n cursor += 1\n while stmt[cursor] != '|':\n expr += stmt[cursor]\n cursor += 1\n expr += \"|\"\n return expr, cursor+1\n\n expr = \"\"\n while stmt[cursor] not in [\"(\", \")\", \"|\", \" \", \"\\t\", \"\\r\", \"\\n\"]:\n expr += stmt[cursor]\n cursor += 1\n return expr, cursor\n return worker(stmt)[0]\n\n def unparse(self, stmt):\n if isinstance(stmt, list):\n return \"(\" + \" \".join([self.unparse(s) for s in stmt]) + \")\"\n return stmt\n\n def bv2hex(self, v):\n h = \"\"\n v = self.bv2bin(v)\n while len(v) > 0:\n d = 0\n if len(v) > 0 and v[-1] == \"1\": d += 1\n if len(v) > 1 and v[-2] == \"1\": d += 2\n if len(v) > 2 and v[-3] == \"1\": d += 4\n if len(v) > 3 and v[-4] == \"1\": d += 8\n h = hex(d)[2:] + h\n if len(v) < 4: break\n v = v[:-4]\n return h\n\n def bv2bin(self, v):\n if type(v) is list and len(v) == 3 and v[0] == \"_\" and v[1].startswith(\"bv\"):\n x, n = int(v[1][2:]), int(v[2])\n return \"\".join(\"1\" if (x & (1 << i)) else \"0\" for i in range(n-1, -1, -1))\n if v == \"true\": return \"1\"\n if v == \"false\": return \"0\"\n if v.startswith(\"#b\"):\n return v[2:]\n if v.startswith(\"#x\"):\n return \"\".join(hex_dict.get(x) for x in v[2:])\n assert False\n\n def bv2int(self, v):\n return int(self.bv2bin(v), 2)\n\n def get_raw_unsat_assumptions(self):\n self.write(\"(get-unsat-assumptions)\")\n exprs = set(self.unparse(part) for part in self.parse(self.read()))\n unsat_assumptions = []\n for key, value in self.smt2_assumptions.items():\n # normalize expression\n value = self.unparse(self.parse(value))\n if value in exprs:\n exprs.remove(value)\n unsat_assumptions.append(key)\n return unsat_assumptions\n\n def get_unsat_assumptions(self, minimize=False):\n if not minimize:\n return self.get_raw_unsat_assumptions()\n required_assumptions = {}\n\n while True:\n candidate_assumptions = {}\n for key in self.get_raw_unsat_assumptions():\n if key not in required_assumptions:\n candidate_assumptions[key] = self.smt2_assumptions[key]\n\n while candidate_assumptions:\n\n candidate_key, candidate_assume = candidate_assumptions.popitem()\n\n self.smt2_assumptions = {}\n for key, assume in candidate_assumptions.items():\n self.smt2_assumptions[key] = assume\n for key, assume in required_assumptions.items():\n self.smt2_assumptions[key] = assume\n result = self.check_sat()\n\n if result == 'unsat':\n candidate_assumptions = None\n else:\n required_assumptions[candidate_key] = candidate_assume\n\n if candidate_assumptions is not None:\n return list(required_assumptions)\n\n def get(self, expr):\n self.write(\"(get-value (%s))\" % (expr))\n return self.parse(self.read())[0][1]\n\n def get_list(self, expr_list):\n if len(expr_list) == 0:\n return []\n self.write(\"(get-value (%s))\" % \" \".join(expr_list))\n return [n[1] for n in self.parse(self.read()) if n]\n\n def get_path(self, mod, path):\n assert mod in self.modinfo\n path = path.replace(\"\\\\\", \"/\").split(\".\")\n\n for i in range(len(path)-1):\n first = \".\".join(path[0:i+1])\n second = \".\".join(path[i+1:])\n\n if first in self.modinfo[mod].cells:\n nextmod = self.modinfo[mod].cells[first]\n return [first] + self.get_path(nextmod, second)\n\n return [\".\".join(path)]\n\n def net_expr(self, mod, base, path):\n if len(path) == 0:\n return base\n\n if len(path) == 1:\n assert mod in self.modinfo\n if path[0] == \"\":\n return base\n if isinstance(path[0], int):\n return \"(|%s#%d| %s)\" % (mod, path[0], base)\n if path[0] in self.modinfo[mod].cells:\n return \"(|%s_h %s| %s)\" % (mod, path[0], base)\n if path[0] in self.modinfo[mod].wsize:\n return \"(|%s_n %s| %s)\" % (mod, path[0], base)\n if path[0] in self.modinfo[mod].memories:\n return \"(|%s_m %s| %s)\" % (mod, path[0], base)\n assert 0\n\n assert mod in self.modinfo\n assert path[0] in self.modinfo[mod].cells\n\n nextmod = self.modinfo[mod].cells[path[0]]\n nextbase = \"(|%s_h %s| %s)\" % (mod, path[0], base)\n return self.net_expr(nextmod, nextbase, path[1:])\n\n def witness_net_expr(self, mod, base, witness):\n net = self.net_expr(mod, base, witness[\"smtpath\"])\n is_bool = self.net_width(mod, witness[\"smtpath\"]) == 1\n if is_bool:\n assert witness[\"width\"] == 1\n assert witness[\"smtoffset\"] == 0\n return net\n return \"((_ extract %d %d) %s)\" % (witness[\"smtoffset\"] + witness[\"width\"] - 1, witness[\"smtoffset\"], net)\n\n def net_width(self, mod, net_path):\n for i in range(len(net_path)-1):\n assert mod in self.modinfo\n assert net_path[i] in self.modinfo[mod].cells\n mod = self.modinfo[mod].cells[net_path[i]]\n\n assert mod in self.modinfo\n if isinstance(net_path[-1], int):\n return None\n assert net_path[-1] in self.modinfo[mod].wsize\n return self.modinfo[mod].wsize[net_path[-1]]\n\n def net_clock(self, mod, net_path):\n for i in range(len(net_path)-1):\n assert mod in self.modinfo\n assert net_path[i] in self.modinfo[mod].cells\n mod = self.modinfo[mod].cells[net_path[i]]\n\n assert mod in self.modinfo\n if net_path[-1] not in self.modinfo[mod].clocks:\n return None\n return self.modinfo[mod].clocks[net_path[-1]]\n\n def net_exists(self, mod, net_path):\n for i in range(len(net_path)-1):\n if mod not in self.modinfo: return False\n if net_path[i] not in self.modinfo[mod].cells: return False\n mod = self.modinfo[mod].cells[net_path[i]]\n\n if mod not in self.modinfo: return False\n if net_path[-1] not in self.modinfo[mod].wsize: return False\n return True\n\n def mem_exists(self, mod, mem_path):\n for i in range(len(mem_path)-1):\n if mod not in self.modinfo: return False\n if mem_path[i] not in self.modinfo[mod].cells: return False\n mod = self.modinfo[mod].cells[mem_path[i]]\n\n if mod not in self.modinfo: return False\n if mem_path[-1] not in self.modinfo[mod].memories: return False\n return True\n\n def mem_expr(self, mod, base, path, port=None, infomode=False):\n if len(path) == 1:\n assert mod in self.modinfo\n assert path[0] in self.modinfo[mod].memories\n if infomode:\n return self.modinfo[mod].memories[path[0]]\n return \"(|%s_m%s %s| %s)\" % (mod, \"\" if port is None else \":%s\" % port, path[0], base)\n\n assert mod in self.modinfo\n assert path[0] in self.modinfo[mod].cells\n\n nextmod = self.modinfo[mod].cells[path[0]]\n nextbase = \"(|%s_h %s| %s)\" % (mod, path[0], base)\n return self.mem_expr(nextmod, nextbase, path[1:], port=port, infomode=infomode)\n\n def mem_info(self, mod, path):\n return self.mem_expr(mod, \"\", path, infomode=True)\n\n def get_net(self, mod_name, net_path, state_name):\n return self.get(self.net_expr(mod_name, state_name, net_path))\n\n def get_net_list(self, mod_name, net_path_list, state_name):\n return self.get_list([self.net_expr(mod_name, state_name, n) for n in net_path_list])\n\n def get_net_hex(self, mod_name, net_path, state_name):\n return self.bv2hex(self.get_net(mod_name, net_path, state_name))\n\n def get_net_hex_list(self, mod_name, net_path_list, state_name):\n return [self.bv2hex(v) for v in self.get_net_list(mod_name, net_path_list, state_name)]\n\n def get_net_bin(self, mod_name, net_path, state_name):\n return self.bv2bin(self.get_net(mod_name, net_path, state_name))\n\n def get_net_bin_list(self, mod_name, net_path_list, state_name):\n return [self.bv2bin(v) for v in self.get_net_list(mod_name, net_path_list, state_name)]\n\n def wait(self):\n if self.p is not None:\n self.p.wait()\n self.p_close()\n\n\nclass SmtOpts:\n def __init__(self):\n self.shortopts = \"s:S:v\"\n self.longopts = [\"unroll\", \"noincr\", \"noprogress\", \"timeout=\", \"dump-smt2=\", \"logic=\", \"dummy=\", \"info=\", \"nocomments\"]\n self.solver = \"yices\"\n self.solver_opts = list()\n self.debug_print = False\n self.debug_file = None\n self.dummy_file = None\n self.unroll = False\n self.noincr = False\n self.timeinfo = os.name != \"nt\"\n self.timeout = 0\n self.logic = None\n self.info_stmts = list()\n self.nocomments = False\n\n def handle(self, o, a):\n if o == \"-s\":\n self.solver = a\n elif o == \"-S\":\n self.solver_opts.append(a)\n elif o == \"--timeout\":\n self.timeout = int(a)\n elif o == \"-v\":\n self.debug_print = True\n elif o == \"--unroll\":\n self.unroll = True\n elif o == \"--noincr\":\n self.noincr = True\n elif o == \"--noprogress\":\n self.timeinfo = False\n elif o == \"--dump-smt2\":\n self.debug_file = open(a, \"w\")\n elif o == \"--logic\":\n self.logic = a\n elif o == \"--dummy\":\n self.dummy_file = a\n elif o == \"--info\":\n self.info_stmts.append(a)\n elif o == \"--nocomments\":\n self.nocomments = True\n else:\n return False\n return True\n\n def helpmsg(self):\n return \"\"\"\n -s <solver>\n set SMT solver: z3, yices, boolector, bitwuzla, cvc4, mathsat, dummy\n default: yices\n\n -S <opt>\n pass <opt> as command line argument to the solver\n\n --timeout <value>\n set the solver timeout to the specified value (in seconds).\n\n --logic <smt2_logic>\n use the specified SMT2 logic (e.g. QF_AUFBV)\n\n --dummy <filename>\n if solver is \"dummy\", read solver output from that file\n otherwise: write solver output to that file\n\n -v\n enable debug output\n\n --unroll\n unroll uninterpreted functions\n\n --noincr\n don't use incremental solving, instead restart solver for\n each (check-sat). This also avoids (push) and (pop).\n\n --noprogress\n disable timer display during solving\n (this option is set implicitly on Windows)\n\n --dump-smt2 <filename>\n write smt2 statements to file\n\n --info <smt2-info-stmt>\n include the specified smt2 info statement in the smt2 output\n\n --nocomments\n strip all comments from the generated smt2 code\n\"\"\"\n\n\nclass MkVcd:\n def __init__(self, f):\n self.f = f\n self.t = -1\n self.nets = dict()\n self.clocks = dict()\n\n def add_net(self, path, width):\n path = tuple(path)\n assert self.t == -1\n key = \"n%d\" % len(self.nets)\n self.nets[path] = (key, width)\n\n def add_clock(self, path, edge):\n path = tuple(path)\n assert self.t == -1\n key = \"n%d\" % len(self.nets)\n self.nets[path] = (key, 1)\n self.clocks[path] = (key, edge)\n\n def set_net(self, path, bits):\n path = tuple(path)\n assert self.t >= 0\n assert path in self.nets\n if path not in self.clocks:\n print(\"b%s %s\" % (bits, self.nets[path][0]), file=self.f)\n\n def escape_name(self, name):\n name = re.sub(r\"\\[([0-9a-zA-Z_]*[a-zA-Z_][0-9a-zA-Z_]*)\\]\", r\"<\\1>\", name)\n if re.match(r\"[\\[\\]]\", name) and name[0] != \"\\\\\":\n name = \"\\\\\" + name\n return name\n\n def set_time(self, t):\n assert t >= self.t\n if t != self.t:\n if self.t == -1:\n print(\"$version Generated by Yosys-SMTBMC $end\", file=self.f)\n print(\"$timescale 1ns $end\", file=self.f)\n print(\"$var integer 32 t smt_step $end\", file=self.f)\n print(\"$var event 1 ! smt_clock $end\", file=self.f)\n\n def vcdescape(n):\n if n.startswith(\"$\") or \":\" in n:\n return \"\\\\\" + n\n return n\n\n scope = []\n for path in sorted(self.nets):\n key, width = self.nets[path]\n\n uipath = list(path)\n if \".\" in uipath[-1] and not uipath[-1].startswith(\"$\"):\n uipath = uipath[0:-1] + uipath[-1].split(\".\")\n for i in range(len(uipath)):\n uipath[i] = re.sub(r\"\\[([^\\]]*)\\]\", r\"<\\1>\", uipath[i])\n\n while uipath[:len(scope)] != scope:\n print(\"$upscope $end\", file=self.f)\n scope = scope[:-1]\n\n while uipath[:-1] != scope:\n scopename = uipath[len(scope)]\n print(\"$scope module %s $end\" % vcdescape(scopename), file=self.f)\n scope.append(uipath[len(scope)])\n\n if path in self.clocks and self.clocks[path][1] == \"event\":\n print(\"$var event 1 %s %s $end\" % (key, vcdescape(uipath[-1])), file=self.f)\n else:\n print(\"$var wire %d %s %s $end\" % (width, key, vcdescape(uipath[-1])), file=self.f)\n\n for i in range(len(scope)):\n print(\"$upscope $end\", file=self.f)\n\n print(\"$enddefinitions $end\", file=self.f)\n\n self.t = t\n assert self.t >= 0\n\n if self.t > 0:\n print(\"#%d\" % (10 * self.t - 5), file=self.f)\n for path in sorted(self.clocks.keys()):\n if self.clocks[path][1] == \"posedge\":\n print(\"b0 %s\" % self.nets[path][0], file=self.f)\n elif self.clocks[path][1] == \"negedge\":\n print(\"b1 %s\" % self.nets[path][0], file=self.f)\n\n print(\"#%d\" % (10 * self.t), file=self.f)\n print(\"1!\", file=self.f)\n print(\"b%s t\" % format(self.t, \"032b\"), file=self.f)\n\n for path in sorted(self.clocks.keys()):\n if self.clocks[path][1] == \"negedge\":\n print(\"b0 %s\" % self.nets[path][0], file=self.f)\n else:\n print(\"b1 %s\" % self.nets[path][0], file=self.f)\n",
|
|
297
297
|
"ywio.py": "#\n# yosys -- Yosys Open SYnthesis Suite\n#\n# Copyright (C) 2022 Jannis Harder <jix@yosyshq.com> <me@jix.one>\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport json, re\n\nfrom functools import total_ordering\n\n\nclass PrettyJson:\n def __init__(self, f):\n self.f = f\n self.indent = 0\n self.state = [\"value\"]\n\n def line(self):\n indent = len(self.state) - bool(self.state and self.state[-1] == \"value\")\n print(\"\\n\", end=\" \" * (2 * indent), file=self.f)\n\n def raw(self, str):\n print(end=str, file=self.f)\n\n def begin_object(self):\n self.begin_value()\n self.raw(\"{\")\n self.state.append(\"object_first\")\n\n def begin_array(self):\n self.begin_value()\n self.raw(\"[\")\n self.state.append(\"array_first\")\n\n def end_object(self):\n state = self.state.pop()\n if state == \"object\":\n self.line()\n else:\n assert state == \"object_first\"\n self.raw(\"}\")\n self.end_value()\n\n def end_array(self):\n state = self.state.pop()\n if state == \"array\":\n self.line()\n else:\n assert state == \"array_first\"\n self.raw(\"]\")\n self.end_value()\n\n def name(self, name):\n if self.state[-1] == \"object_first\":\n self.state[-1] = \"object\"\n else:\n self.raw(\",\")\n self.line()\n json.dump(str(name), self.f)\n self.raw(\": \")\n self.state.append(\"value\")\n\n def begin_value(self):\n if self.state[-1] == \"array_first\":\n self.line()\n self.state[-1] = \"array\"\n elif self.state[-1] == \"array\":\n self.raw(\",\")\n self.line()\n else:\n assert self.state.pop() == \"value\"\n\n def end_value(self):\n if not self.state:\n print(file=self.f, flush=True)\n\n def value(self, value):\n self.begin_value()\n json.dump(value, self.f)\n self.end_value()\n\n def entry(self, name, value):\n self.name(name)\n self.value(value)\n\n def object(self, entries=None):\n if isinstance(entries, dict):\n entries = dict.items()\n self.begin_object()\n for name, value in entries:\n self.entry(name, value)\n self.end_object()\n\n def array(self, values=None):\n self.begin_array()\n for value in values:\n self.value(value)\n self.end_array()\n\n\naddr_re = re.compile(r'\\\\\\[[0-9]+\\]$')\npublic_name_re = re.compile(r\"\\\\([a-zA-Z_][a-zA-Z0-9_]*(\\[[0-9]+\\])?|\\[[0-9]+\\])$\")\n\ndef pretty_name(id):\n if public_name_re.match(id):\n return id.lstrip(\"\\\\\")\n else:\n return id\n\ndef pretty_path(path):\n out = \"\"\n for name in path:\n name = pretty_name(name)\n if name.startswith(\"[\"):\n out += name\n continue\n if out:\n out += \".\"\n if name.startswith(\"\\\\\") or name.startswith(\"$\"):\n out += name + \" \"\n else:\n out += name\n\n return out\n\n@total_ordering\nclass WitnessSig:\n def __init__(self, path, offset, width=1, init_only=False):\n path = tuple(path)\n self.path, self.width, self.offset, self.init_only = path, width, offset, init_only\n\n self.memory_path = None\n self.memory_addr = None\n\n sort_path = path\n sort_id = -1\n if path and addr_re.match(path[-1]):\n self.memory_path = sort_path = path[:-1]\n self.memory_addr = sort_id = int(path[-1][2:-1])\n\n self.sort_key = (init_only, sort_path, sort_id, offset, width)\n\n def bits(self):\n return ((self.path, i) for i in range(self.offset, self.offset + self.width))\n\n def rev_bits(self):\n return ((self.path, i) for i in reversed(range(self.offset, self.offset + self.width)))\n\n def pretty(self):\n if self.width > 1:\n last_offset = self.offset + self.width - 1\n return f\"{pretty_path(self.path)}[{last_offset}:{self.offset}]\"\n else:\n return f\"{pretty_path(self.path)}[{self.offset}]\"\n\n def __eq__(self, other):\n return self.sort_key == other.sort_key\n\n def __hash__(self):\n return hash(self.sort_key)\n\n def __lt__(self, other):\n return self.sort_key < other.sort_key\n\n\ndef coalesce_signals(signals, bits=None):\n if bits is None:\n bits = {}\n for sig in signals:\n for bit in sig.bits():\n if sig.init_only:\n bits.setdefault(bit, False)\n else:\n bits[bit] = True\n\n active = None\n\n out = []\n\n for bit, not_init in sorted(bits.items()):\n if active:\n if active[0] == bit[0] and active[2] == bit[1] and active[3] == not_init:\n active[2] += 1\n else:\n out.append(WitnessSig(active[0], active[1], active[2] - active[1], not active[3]))\n active = None\n\n if active is None:\n active = [bit[0], bit[1], bit[1] + 1, not_init]\n\n if active:\n out.append(WitnessSig(active[0], active[1], active[2] - active[1], not active[3]))\n\n return sorted(out)\n\n\nclass WitnessSigMap:\n def __init__(self, signals=[]):\n self.signals = []\n\n self.id_to_bit = []\n self.bit_to_id = {}\n self.bit_to_sig = {}\n\n for sig in signals:\n self.add_signal(sig)\n\n def add_signal(self, sig):\n self.signals.append(sig)\n for bit in sig.bits():\n self.add_bit(bit)\n self.bit_to_sig[bit] = sig\n\n def add_bit(self, bit, id=None):\n if id is None:\n id = len(self.id_to_bit)\n self.id_to_bit.append(bit)\n else:\n if len(self.id_to_bit) <= id:\n self.id_to_bit += [None] * (id - len(self.id_to_bit) + 1)\n self.id_to_bit[id] = bit\n self.bit_to_id[bit] = id\n\n\nclass WitnessValues:\n def __init__(self):\n self.values = {}\n\n def __setitem__(self, key, value):\n if isinstance(key, tuple) and len(key) == 2:\n if value != \"?\":\n assert isinstance(value, str)\n assert len(value) == 1\n self.values[key] = value\n else:\n assert isinstance(key, WitnessSig)\n assert key.width == len(value)\n if isinstance(value, str):\n value = reversed(value)\n for bit, bit_value in zip(key.bits(), value):\n if bit_value != \"?\":\n self.values[bit] = bit_value\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n return self.values.get(key, \"?\")\n else:\n assert isinstance(key, WitnessSig)\n return \"\".join([self.values.get(bit, \"?\") for bit in key.rev_bits()])\n\n def pack_present(self, sigmap):\n missing = []\n\n max_id = max((sigmap.bit_to_id.get(bit, -1) for bit in self.values), default=-1)\n\n vector = [\"?\"] * (max_id + 1)\n for bit, bit_value in self.values.items():\n id = sigmap.bit_to_id.get(bit, - 1)\n if id < 0:\n missing.append(bit)\n else:\n vector[max_id - sigmap.bit_to_id[bit]] = bit_value\n\n return \"\".join(vector), missing\n\n def pack(self, sigmap):\n packed, missing = self.pack_present(sigmap)\n if missing:\n raise RuntimeError(f\"Cannot pack bits {missing!r}\")\n return packed\n\n def unpack(self, sigmap, bits):\n for i, bit_value in enumerate(reversed(bits)):\n if bit_value != \"?\":\n self.values[sigmap.id_to_bit[i]] = bit_value\n\n def present_signals(self, sigmap):\n signals = set(sigmap.bit_to_sig.get(bit) for bit in self.values)\n missing_signals = None in signals\n if missing_signals:\n signals.discard(None)\n\n return sorted(signals), missing_signals\n\n def __add__(self, other: \"WitnessValues\"):\n new = WitnessValues()\n new += self\n new += other\n return new\n\n def __iadd__(self, other: \"WitnessValues\"):\n for key, value in other.values.items():\n self.values.setdefault(key, value)\n return self\n\nclass WriteWitness:\n def __init__(self, f, generator):\n self.out = PrettyJson(f)\n self.t = 0\n self.header_written = False\n self.clocks = []\n self.signals = []\n\n self.out.begin_object()\n self.out.entry(\"format\", \"Yosys Witness Trace\")\n self.out.entry(\"generator\", generator)\n\n def add_clock(self, path, offset, edge):\n assert not self.header_written\n self.clocks.append({\n \"path\": path,\n \"edge\": edge,\n \"offset\": offset,\n })\n\n def add_sig(self, path, offset, width=1, init_only=False):\n assert not self.header_written\n sig = WitnessSig(path, offset, width, init_only)\n self.signals.append(sig)\n return sig\n\n def write_header(self):\n assert not self.header_written\n self.header_written = True\n self.out.name(\"clocks\")\n self.out.array(self.clocks)\n\n self.signals = coalesce_signals(self.signals)\n self.sigmap = WitnessSigMap(self.signals)\n\n self.out.name(\"signals\")\n self.out.array({\n \"path\": sig.path,\n \"width\": sig.width,\n \"offset\": sig.offset,\n \"init_only\": sig.init_only,\n } for sig in self.signals)\n\n self.out.name(\"steps\")\n self.out.begin_array()\n\n def step(self, values, skip_x=False):\n if not self.header_written:\n self.write_header()\n\n packed = values.pack(self.sigmap)\n if skip_x:\n packed = packed.replace('x', '?')\n self.out.value({\"bits\": packed})\n\n self.t += 1\n\n def end_trace(self):\n if not self.header_written:\n self.write_header()\n self.out.end_array()\n self.out.end_object()\n\n\nclass ReadWitness:\n def __init__(self, f):\n data = json.load(f)\n if not isinstance(data, dict):\n data = {}\n\n data_format = data.get(\"format\", \"Unknown Format\")\n\n if data_format != \"Yosys Witness Trace\":\n raise ValueError(f\"unsupported format {data_format!r}\")\n\n self.clocks = data[\"clocks\"]\n for clock in self.clocks:\n clock[\"path\"] = tuple(clock[\"path\"])\n\n self.signals = [\n WitnessSig(sig[\"path\"], sig[\"offset\"], sig[\"width\"], sig[\"init_only\"])\n for sig in data[\"signals\"]\n ]\n\n self.sigmap = WitnessSigMap(self.signals)\n\n self.bits = [step[\"bits\"] for step in data[\"steps\"]]\n\n def skip_x(self):\n self.bits = [step.replace('x', '?') for step in self.bits]\n\n def init_step(self):\n return self.step(0)\n \n def non_init_bits(self):\n if len(self) > 1:\n return len(self.bits[1])\n else:\n return sum([sig.width for sig in self.signals if not sig.init_only])\n \n def first_step(self):\n values = WitnessValues()\n # may have issues when non_init_bits is 0\n values.unpack(WitnessSigMap([sig for sig in self.signals if not sig.init_only]), self.bits[0][-self.non_init_bits():])\n return values\n\n def step(self, t):\n values = WitnessValues()\n values.unpack(self.sigmap, self.bits[t])\n return values\n\n def steps(self, start=0):\n for i in range(start, len(self.bits)):\n yield i, self.step(i)\n\n def append_steps(self, t):\n if not t:\n pass\n elif t < 0:\n self.bits = self.bits[:t]\n else:\n self.bits.extend([\"0\"*self.non_init_bits()]*t)\n\n def __len__(self):\n return len(self.bits)\n",
|
|
298
298
|
},
|
|
299
299
|
"quicklogic": {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// **AUTOGENERATED FILE** **DO NOT EDIT**
|
|
2
|
-
// Generated by ../yosys-src/techlibs/quicklogic/qlf_k6n10f/generate_bram_types_sim.py at 2024-
|
|
2
|
+
// Generated by ../yosys-src/techlibs/quicklogic/qlf_k6n10f/generate_bram_types_sim.py at 2024-03-13 01:02:00.071786+00:00
|
|
3
3
|
`timescale 1ns /10ps
|
|
4
4
|
|
|
5
5
|
module TDP36K_BRAM_A_X1_B_X1_nonsplit (
|
package/gen/yosys.core.wasm
CHANGED
|
Binary file
|