@yowasp/yosys 0.42.734 → 0.43.750

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.
@@ -129,12 +129,12 @@ export const filesystem = {
129
129
  "runtime": {
130
130
  "cxxrtl": {
131
131
  "capi": {
132
- "cxxrtl_capi.cc": "/*\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// This file is a part of the CXXRTL C API. It should be used together with `cxxrtl/capi/cxxrtl_capi.h`.\n\n#include <cxxrtl/capi/cxxrtl_capi.h>\n#include <cxxrtl/cxxrtl.h>\n\nstruct _cxxrtl_handle {\n\tstd::unique_ptr<cxxrtl::module> module;\n\tcxxrtl::debug_items objects;\n};\n\n// Private function for use by other units of the C API.\nconst cxxrtl::debug_items &cxxrtl_debug_items_from_handle(cxxrtl_handle handle) {\n\treturn handle->objects;\n}\n\ncxxrtl_handle cxxrtl_create(cxxrtl_toplevel design) {\n\treturn cxxrtl_create_at(design, \"\");\n}\n\ncxxrtl_handle cxxrtl_create_at(cxxrtl_toplevel design, const char *top_path_) {\n\tstd::string top_path = top_path_;\n\tif (!top_path.empty()) {\n\t\t// module::debug_info() accepts either an empty path, or a path ending in space to simplify\n\t\t// the logic in generated code. While this is sketchy at best to expose in the C++ API, this\n\t\t// would be a lot worse in the C API, so don't expose it here.\n\t\tassert(top_path.back() != ' ');\n\t\ttop_path += ' ';\n\t}\n\n\tcxxrtl_handle handle = new _cxxrtl_handle;\n\thandle->module = std::move(design->module);\n\thandle->module->debug_info(handle->objects, top_path);\n\tdelete design;\n\treturn handle;\n}\n\nvoid cxxrtl_destroy(cxxrtl_handle handle) {\n\tdelete handle;\n}\n\nvoid cxxrtl_reset(cxxrtl_handle handle) {\n\thandle->module->reset();\n}\n\nint cxxrtl_eval(cxxrtl_handle handle) {\n\treturn handle->module->eval();\n}\n\nint cxxrtl_commit(cxxrtl_handle handle) {\n\treturn handle->module->commit();\n}\n\nsize_t cxxrtl_step(cxxrtl_handle handle) {\n\treturn handle->module->step();\n}\n\nstruct cxxrtl_object *cxxrtl_get_parts(cxxrtl_handle handle, const char *name, size_t *parts) {\n\tauto it = handle->objects.table.find(name);\n\tif (it == handle->objects.table.end())\n\t\treturn nullptr;\n\t*parts = it->second.size();\n\treturn static_cast<cxxrtl_object*>(&it->second[0]);\n}\n\nvoid cxxrtl_enum(cxxrtl_handle handle, void *data,\n void (*callback)(void *data, const char *name,\n cxxrtl_object *object, size_t parts)) {\n\tfor (auto &it : handle->objects.table)\n\t\tcallback(data, it.first.c_str(), static_cast<cxxrtl_object*>(&it.second[0]), it.second.size());\n}\n\nvoid cxxrtl_outline_eval(cxxrtl_outline outline) {\n\toutline->eval();\n}\n\nint cxxrtl_attr_type(cxxrtl_attr_set attrs_, const char *name) {\n\tauto attrs = (cxxrtl::metadata_map*)attrs_;\n\tif (!attrs->count(name))\n\t\treturn CXXRTL_ATTR_NONE;\n\tswitch (attrs->at(name).value_type) {\n\t\tcase cxxrtl::metadata::UINT:\n\t\t\treturn CXXRTL_ATTR_UNSIGNED_INT;\n\t\tcase cxxrtl::metadata::SINT:\n\t\t\treturn CXXRTL_ATTR_SIGNED_INT;\n\t\tcase cxxrtl::metadata::STRING:\n\t\t\treturn CXXRTL_ATTR_STRING;\n\t\tcase cxxrtl::metadata::DOUBLE:\n\t\t\treturn CXXRTL_ATTR_DOUBLE;\n\t\tdefault:\n\t\t\t// Present unsupported attribute type the same way as no attribute at all.\n\t\t\treturn CXXRTL_ATTR_NONE;\n\t}\n}\n\nuint64_t cxxrtl_attr_get_unsigned_int(cxxrtl_attr_set attrs_, const char *name) {\n\tauto &attrs = *(cxxrtl::metadata_map*)attrs_;\n\tassert(attrs.count(name) && attrs.at(name).value_type == cxxrtl::metadata::UINT);\n\treturn attrs[name].as_uint();\n}\n\nint64_t cxxrtl_attr_get_signed_int(cxxrtl_attr_set attrs_, const char *name) {\n\tauto &attrs = *(cxxrtl::metadata_map*)attrs_;\n\tassert(attrs.count(name) && attrs.at(name).value_type == cxxrtl::metadata::SINT);\n\treturn attrs[name].as_sint();\n}\n\nconst char *cxxrtl_attr_get_string(cxxrtl_attr_set attrs_, const char *name) {\n\tauto &attrs = *(cxxrtl::metadata_map*)attrs_;\n\tassert(attrs.count(name) && attrs.at(name).value_type == cxxrtl::metadata::STRING);\n\treturn attrs[name].as_string().c_str();\n}\n\ndouble cxxrtl_attr_get_double(cxxrtl_attr_set attrs_, const char *name) {\n\tauto &attrs = *(cxxrtl::metadata_map*)attrs_;\n\tassert(attrs.count(name) && attrs.at(name).value_type == cxxrtl::metadata::DOUBLE);\n\treturn attrs[name].as_double();\n}\n",
132
+ "cxxrtl_capi.cc": "/*\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// This file is a part of the CXXRTL C API. It should be used together with `cxxrtl/capi/cxxrtl_capi.h`.\n\n#include <cxxrtl/capi/cxxrtl_capi.h>\n#include <cxxrtl/cxxrtl.h>\n\nstruct _cxxrtl_handle {\n\tstd::unique_ptr<cxxrtl::module> module;\n\tcxxrtl::debug_items objects;\n};\n\n// Private function for use by other units of the C API.\nconst cxxrtl::debug_items &cxxrtl_debug_items_from_handle(cxxrtl_handle handle) {\n\treturn handle->objects;\n}\n\ncxxrtl_handle cxxrtl_create(cxxrtl_toplevel design) {\n\treturn cxxrtl_create_at(design, \"\");\n}\n\ncxxrtl_handle cxxrtl_create_at(cxxrtl_toplevel design, const char *top_path_) {\n\tstd::string top_path = top_path_;\n\tif (!top_path.empty()) {\n\t\t// module::debug_info() accepts either an empty path, or a path ending in space to simplify\n\t\t// the logic in generated code. While this is sketchy at best to expose in the C++ API, this\n\t\t// would be a lot worse in the C API, so don't expose it here.\n\t\tassert(top_path.back() != ' ');\n\t\ttop_path += ' ';\n\t}\n\n\tcxxrtl_handle handle = new _cxxrtl_handle;\n\thandle->module = std::move(design->module);\n\thandle->module->debug_info(&handle->objects, nullptr, top_path);\n\tdelete design;\n\treturn handle;\n}\n\nvoid cxxrtl_destroy(cxxrtl_handle handle) {\n\tdelete handle;\n}\n\nvoid cxxrtl_reset(cxxrtl_handle handle) {\n\thandle->module->reset();\n}\n\nint cxxrtl_eval(cxxrtl_handle handle) {\n\treturn handle->module->eval();\n}\n\nint cxxrtl_commit(cxxrtl_handle handle) {\n\treturn handle->module->commit();\n}\n\nsize_t cxxrtl_step(cxxrtl_handle handle) {\n\treturn handle->module->step();\n}\n\nstruct cxxrtl_object *cxxrtl_get_parts(cxxrtl_handle handle, const char *name, size_t *parts) {\n\tauto it = handle->objects.table.find(name);\n\tif (it == handle->objects.table.end())\n\t\treturn nullptr;\n\t*parts = it->second.size();\n\treturn static_cast<cxxrtl_object*>(&it->second[0]);\n}\n\nvoid cxxrtl_enum(cxxrtl_handle handle, void *data,\n void (*callback)(void *data, const char *name,\n cxxrtl_object *object, size_t parts)) {\n\tfor (auto &it : handle->objects.table)\n\t\tcallback(data, it.first.c_str(), static_cast<cxxrtl_object*>(&it.second[0]), it.second.size());\n}\n\nvoid cxxrtl_outline_eval(cxxrtl_outline outline) {\n\toutline->eval();\n}\n\nint cxxrtl_attr_type(cxxrtl_attr_set attrs_, const char *name) {\n\tauto attrs = (cxxrtl::metadata_map*)attrs_;\n\tif (!attrs->count(name))\n\t\treturn CXXRTL_ATTR_NONE;\n\tswitch (attrs->at(name).value_type) {\n\t\tcase cxxrtl::metadata::UINT:\n\t\t\treturn CXXRTL_ATTR_UNSIGNED_INT;\n\t\tcase cxxrtl::metadata::SINT:\n\t\t\treturn CXXRTL_ATTR_SIGNED_INT;\n\t\tcase cxxrtl::metadata::STRING:\n\t\t\treturn CXXRTL_ATTR_STRING;\n\t\tcase cxxrtl::metadata::DOUBLE:\n\t\t\treturn CXXRTL_ATTR_DOUBLE;\n\t\tdefault:\n\t\t\t// Present unsupported attribute type the same way as no attribute at all.\n\t\t\treturn CXXRTL_ATTR_NONE;\n\t}\n}\n\nuint64_t cxxrtl_attr_get_unsigned_int(cxxrtl_attr_set attrs_, const char *name) {\n\tauto &attrs = *(cxxrtl::metadata_map*)attrs_;\n\tassert(attrs.count(name) && attrs.at(name).value_type == cxxrtl::metadata::UINT);\n\treturn attrs[name].as_uint();\n}\n\nint64_t cxxrtl_attr_get_signed_int(cxxrtl_attr_set attrs_, const char *name) {\n\tauto &attrs = *(cxxrtl::metadata_map*)attrs_;\n\tassert(attrs.count(name) && attrs.at(name).value_type == cxxrtl::metadata::SINT);\n\treturn attrs[name].as_sint();\n}\n\nconst char *cxxrtl_attr_get_string(cxxrtl_attr_set attrs_, const char *name) {\n\tauto &attrs = *(cxxrtl::metadata_map*)attrs_;\n\tassert(attrs.count(name) && attrs.at(name).value_type == cxxrtl::metadata::STRING);\n\treturn attrs[name].as_string().c_str();\n}\n\ndouble cxxrtl_attr_get_double(cxxrtl_attr_set attrs_, const char *name) {\n\tauto &attrs = *(cxxrtl::metadata_map*)attrs_;\n\tassert(attrs.count(name) && attrs.at(name).value_type == cxxrtl::metadata::DOUBLE);\n\treturn attrs[name].as_double();\n}\n",
133
133
  "cxxrtl_capi.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_H\n#define CXXRTL_CAPI_H\n\n// This file is a part of the CXXRTL C API. It should be used together with `cxxrtl_capi.cc`.\n//\n// The CXXRTL C API makes it possible to drive CXXRTL designs using C or any other language that\n// supports the C ABI, for example, Python. It does not provide a way to implement black boxes.\n\n#include <stddef.h>\n#include <stdint.h>\n#include <assert.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// Opaque reference to a design toplevel.\n//\n// A design toplevel can only be used to create a design handle.\ntypedef struct _cxxrtl_toplevel *cxxrtl_toplevel;\n\n// The constructor for a design toplevel is provided as a part of generated code for that design.\n// Its prototype matches:\n//\n// cxxrtl_toplevel <design-name>_create();\n\n// Opaque reference to a design handle.\n//\n// A design handle is required by all operations in the C API.\ntypedef struct _cxxrtl_handle *cxxrtl_handle;\n\n// Create a design handle from a design toplevel.\n//\n// The `design` is consumed by this operation and cannot be used afterwards.\ncxxrtl_handle cxxrtl_create(cxxrtl_toplevel design);\n\n// Create a design handle at a given hierarchy position from a design toplevel.\n//\n// This operation is similar to `cxxrtl_create`, except the full hierarchical name of every object\n// is prepended with `top_path`.\ncxxrtl_handle cxxrtl_create_at(cxxrtl_toplevel design, const char *top_path);\n\n// Release all resources used by a design and its handle.\nvoid cxxrtl_destroy(cxxrtl_handle handle);\n\n// Reinitialize the design, replacing the internal state with the reset values while preserving\n// black boxes.\n//\n// This operation is essentially equivalent to a power-on reset. Values, wires, and memories are\n// returned to their reset state while preserving the state of black boxes and keeping all of\n// the interior pointers obtained with e.g. `cxxrtl_get` valid.\nvoid cxxrtl_reset(cxxrtl_handle handle);\n\n// Evaluate the design, propagating changes on inputs to the `next` value of internal state and\n// output wires.\n//\n// Returns 1 if the design is known to immediately converge, 0 otherwise.\nint cxxrtl_eval(cxxrtl_handle handle);\n\n// Commit the design, replacing the `curr` value of internal state and output wires with the `next`\n// value.\n//\n// Return 1 if any of the `curr` values were updated, 0 otherwise.\nint cxxrtl_commit(cxxrtl_handle handle);\n\n// Simulate the design to a fixed point.\n//\n// Returns the number of delta cycles.\nsize_t cxxrtl_step(cxxrtl_handle handle);\n\n// Type of a simulated object.\n//\n// The type of a simulated object indicates the way it is stored and the operations that are legal\n// to perform on it (i.e. won't crash the simulation). It says very little about object semantics,\n// which is specified through flags.\nenum cxxrtl_type {\n\t// Values correspond to singly buffered netlist nodes, i.e. nodes driven exclusively by\n\t// combinatorial cells, or toplevel input nodes.\n\t//\n\t// Values can be inspected via the `curr` pointer. If the `next` pointer is NULL, the value is\n\t// driven by a constant and can never be modified. Otherwise, the value can be modified through\n\t// the `next` pointer (which is equal to `curr` if not NULL). Note that changes to the bits\n\t// driven by combinatorial cells will be ignored.\n\t//\n\t// Values always have depth 1.\n\tCXXRTL_VALUE = 0,\n\n\t// Wires correspond to doubly buffered netlist nodes, i.e. nodes driven, at least in part, by\n\t// storage cells, or by combinatorial cells that are a part of a feedback path. They are also\n\t// present in non-optimized builds.\n\t//\n\t// Wires can be inspected via the `curr` pointer and modified via the `next` pointer (which are\n\t// distinct for wires). Note that changes to the bits driven by combinatorial cells will be\n\t// ignored.\n\t//\n\t// Wires always have depth 1.\n\tCXXRTL_WIRE = 1,\n\n\t// Memories correspond to memory cells.\n\t//\n\t// Memories can be inspected and modified via the `curr` pointer. Due to a limitation of this\n\t// API, memories cannot yet be modified in a guaranteed race-free way, and the `next` pointer is\n\t// always NULL.\n\tCXXRTL_MEMORY = 2,\n\n\t// Aliases correspond to netlist nodes driven by another node such that their value is always\n\t// exactly equal.\n\t//\n\t// Aliases can be inspected via the `curr` pointer. They cannot be modified, and the `next`\n\t// pointer is always NULL.\n\tCXXRTL_ALIAS = 3,\n\n\t// Outlines correspond to netlist nodes that were optimized in a way that makes them inaccessible\n\t// outside of a module's `eval()` function. At the highest debug information level, every inlined\n\t// node has a corresponding outline object.\n\t//\n\t// Outlines can be inspected via the `curr` pointer and can never be modified; the `next` pointer\n\t// is always NULL. Unlike all other objects, the bits of an outline object are meaningful only\n\t// after a call to `cxxrtl_outline_eval` and until any subsequent modification to the netlist.\n\t// Observing this requirement is the responsibility of the caller; it is not enforced.\n\t//\n\t// Outlines always correspond to combinatorial netlist nodes that are not ports.\n\tCXXRTL_OUTLINE = 4,\n\n\t// More object types may be added in the future, but the existing ones will never change.\n};\n\n// Flags of a simulated object.\n//\n// The flags of a simulated object indicate its role in the netlist:\n// * The flags `CXXRTL_INPUT` and `CXXRTL_OUTPUT` designate module ports.\n// * The flags `CXXRTL_DRIVEN_SYNC`, `CXXRTL_DRIVEN_COMB`, and `CXXRTL_UNDRIVEN` specify\n// the semantics of node state. An object with several of these flags set has different bits\n// follow different semantics.\nenum cxxrtl_flag {\n\t// Node is a module input port.\n\t//\n\t// This flag can be set on objects of type `CXXRTL_VALUE` and `CXXRTL_WIRE`. It may be combined\n\t// with `CXXRTL_OUTPUT`, as well as other flags.\n\tCXXRTL_INPUT = 1 << 0,\n\n\t// Node is a module output port.\n\t//\n\t// This flag can be set on objects of type `CXXRTL_WIRE`. It may be combined with `CXXRTL_INPUT`,\n\t// as well as other flags.\n\tCXXRTL_OUTPUT = 1 << 1,\n\n\t// Node is a module inout port.\n\t//\n\t// This flag can be set on objects of type `CXXRTL_WIRE`. It may be combined with other flags.\n\tCXXRTL_INOUT = (CXXRTL_INPUT|CXXRTL_OUTPUT),\n\n\t// Node has bits that are driven by a storage cell.\n\t//\n\t// This flag can be set on objects of type `CXXRTL_WIRE`. It may be combined with\n\t// `CXXRTL_DRIVEN_COMB` and `CXXRTL_UNDRIVEN`, as well as other flags.\n\t//\n\t// This flag is set on wires that have bits connected directly to the output of a flip-flop or\n\t// a latch, and hold its state. Many `CXXRTL_WIRE` objects may not have the `CXXRTL_DRIVEN_SYNC`\n\t// flag set; for example, output ports and feedback wires generally won't. Writing to the `next`\n\t// pointer of these wires updates stored state, and for designs without combinatorial loops,\n\t// capturing the value from every of these wires through the `curr` pointer creates a complete\n\t// snapshot of the design state.\n\tCXXRTL_DRIVEN_SYNC = 1 << 2,\n\n\t// Node has bits that are driven by a combinatorial cell or another node.\n\t//\n\t// This flag can be set on objects of type `CXXRTL_VALUE`, `CXXRTL_WIRE`, and `CXXRTL_OUTLINE`.\n\t// It may be combined with `CXXRTL_DRIVEN_SYNC` and `CXXRTL_UNDRIVEN`, as well as other flags.\n\t//\n\t// This flag is set on objects that have bits connected to the output of a combinatorial cell,\n\t// or directly to another node. For designs without combinatorial loops, writing to such bits\n\t// through the `next` pointer (if it is not NULL) has no effect.\n\tCXXRTL_DRIVEN_COMB = 1 << 3,\n\n\t// Node has bits that are not driven.\n\t//\n\t// This flag can be set on objects of type `CXXRTL_VALUE` and `CXXRTL_WIRE`. It may be combined\n\t// with `CXXRTL_DRIVEN_SYNC` and `CXXRTL_DRIVEN_COMB`, as well as other flags.\n\t//\n\t// This flag is set on objects that have bits not driven by an output of any cell or by another\n\t// node, such as inputs and dangling wires.\n\tCXXRTL_UNDRIVEN = 1 << 4,\n\n\t// More object flags may be added in the future, but the existing ones will never change.\n};\n\n// Description of a simulated object.\n//\n// The `curr` and `next` arrays can be accessed directly to inspect and, if applicable, modify\n// the bits stored in the object.\nstruct cxxrtl_object {\n\t// Type of the object.\n\t//\n\t// All objects have the same memory layout determined by `width` and `depth`, but the type\n\t// determines all other properties of the object.\n\tuint32_t type; // actually `enum cxxrtl_type`\n\n\t// Flags of the object.\n\tuint32_t flags; // actually bit mask of `enum cxxrtl_flags`\n\n\t// Width of the object in bits.\n\tsize_t width;\n\n\t// Index of the least significant bit.\n\tsize_t lsb_at;\n\n\t// Depth of the object. Only meaningful for memories; for other objects, always 1.\n\tsize_t depth;\n\n\t// Index of the first word. Only meaningful for memories; for other objects, always 0;\n\tsize_t zero_at;\n\n\t// Bits stored in the object, as 32-bit chunks, least significant bits first.\n\t//\n\t// The width is rounded up to a multiple of 32; the padding bits are always set to 0 by\n\t// the simulation code, and must be always written as 0 when modified by user code.\n\t// In memories, every element is stored contiguously. Therefore, the total number of chunks\n\t// in any object is `((width + 31) / 32) * depth`.\n\t//\n\t// To allow the simulation to be partitioned into multiple independent units communicating\n\t// through wires, the bits are double buffered. To avoid race conditions, user code should\n\t// always read from `curr` and write to `next`. The `curr` pointer is always valid; for objects\n\t// that cannot be modified, or cannot be modified in a race-free way, `next` is NULL.\n\t//\n\t// In case where `width == 0`, `curr` is a non-NULL pointer unique for the wire. That is,\n\t// there is a 1-to-1 correspondence between simulation objects and `curr` pointers, regardless\n\t// of whether they have storage or not. (Aliases' `curr` pointer equals that of some other\n\t// simulated object.)\n\tuint32_t *curr;\n\tuint32_t *next;\n\n\t// Opaque reference to an outline. Only meaningful for outline objects.\n\t//\n\t// See the documentation of `cxxrtl_outline` for details. When creating a `cxxrtl_object`, set\n\t// this field to NULL.\n\tstruct _cxxrtl_outline *outline;\n\n\t// Opaque reference to an attribute set.\n\t//\n\t// See the documentation of `cxxrtl_attr_set` for details. When creating a `cxxrtl_object`, set\n\t// this field to NULL.\n\t//\n\t// The lifetime of the pointers returned by `cxxrtl_attr_*` family of functions is the same as\n\t// the lifetime of this structure.\n\tstruct _cxxrtl_attr_set *attrs;\n\n\t// More description fields may be added in the future, but the existing ones will never change.\n};\n\n// Retrieve description of a simulated object.\n//\n// The `name` is the full hierarchical name of the object in the Yosys notation, where public names\n// have a `\\` prefix and hierarchy levels are separated by single spaces. For example, if\n// the top-level module instantiates a module `foo`, which in turn contains a wire `bar`, the full\n// hierarchical name is `\\foo \\bar`.\n//\n// The storage of a single abstract object may be split (usually with the `splitnets` pass) into\n// many physical parts, all of which correspond to the same hierarchical name. To handle such cases,\n// this function returns an array and writes its length to `parts`. The array is sorted by `lsb_at`.\n//\n// Returns the object parts if it was found, NULL otherwise. The returned parts are valid until\n// the design is destroyed.\nstruct cxxrtl_object *cxxrtl_get_parts(cxxrtl_handle handle, const char *name, size_t *parts);\n\n// Retrieve description of a single part simulated object.\n//\n// This function is a shortcut for the most common use of `cxxrtl_get_parts`. It asserts that,\n// if the object exists, it consists of a single part. If assertions are disabled, it returns NULL\n// for multi-part objects.\nstatic inline struct cxxrtl_object *cxxrtl_get(cxxrtl_handle handle, const char *name) {\n\tsize_t parts = 0;\n\tstruct cxxrtl_object *object = cxxrtl_get_parts(handle, name, &parts);\n\tassert(object == NULL || parts == 1);\n\tif (object == NULL || parts == 1)\n\t\treturn object;\n\treturn NULL;\n}\n\n// Enumerate simulated objects.\n//\n// For every object in the simulation, `callback` is called with the provided `data`, the full\n// hierarchical name of the object (see `cxxrtl_get` for details), and the object parts.\n// The provided `name` and `object` values are valid until the design is destroyed.\nvoid cxxrtl_enum(cxxrtl_handle handle, void *data,\n void (*callback)(void *data, const char *name,\n struct cxxrtl_object *object, size_t parts));\n\n// Opaque reference to an outline.\n//\n// An outline is a group of outline objects that are evaluated simultaneously. The identity of\n// an outline can be compared to determine whether any two objects belong to the same outline.\ntypedef struct _cxxrtl_outline *cxxrtl_outline;\n\n// Evaluate an outline.\n//\n// After evaluating an outline, the bits of every outline object contained in it are consistent\n// with the current state of the netlist. In general, any further modification to the netlist\n// causes every outline object to become stale, after which the corresponding outline must be\n// re-evaluated, otherwise the bits read from that object are meaningless.\nvoid cxxrtl_outline_eval(cxxrtl_outline outline);\n\n// Opaque reference to an attribute set.\n//\n// An attribute set is a map between attribute names (always strings) and values (which may have\n// several different types). To find out the type of an attribute, use `cxxrtl_attr_type`, and\n// to retrieve the value of an attribute, use `cxxrtl_attr_as_string`.\ntypedef struct _cxxrtl_attr_set *cxxrtl_attr_set;\n\n// Type of an attribute.\nenum cxxrtl_attr_type {\n\t// Attribute is not present.\n\tCXXRTL_ATTR_NONE = 0,\n\n\t// Attribute has an unsigned integer value.\n\tCXXRTL_ATTR_UNSIGNED_INT = 1,\n\n\t// Attribute has an unsigned integer value.\n\tCXXRTL_ATTR_SIGNED_INT = 2,\n\n\t// Attribute has a string value.\n\tCXXRTL_ATTR_STRING = 3,\n\n\t// Attribute has a double precision floating point value.\n\tCXXRTL_ATTR_DOUBLE = 4,\n\n\t// More attribute types may be defined in the future, but the existing values will never change.\n};\n\n// Determine the presence and type of an attribute in an attribute set.\n//\n// This function returns one of the possible `cxxrtl_attr_type` values.\nint cxxrtl_attr_type(cxxrtl_attr_set attrs, const char *name);\n\n// Retrieve an unsigned integer valued attribute from an attribute set.\n//\n// This function asserts that `cxxrtl_attr_type(attrs, name) == CXXRTL_ATTR_UNSIGNED_INT`.\n// If assertions are disabled, returns 0 if the attribute is missing or has an incorrect type.\nuint64_t cxxrtl_attr_get_unsigned_int(cxxrtl_attr_set attrs, const char *name);\n\n// Retrieve a signed integer valued attribute from an attribute set.\n//\n// This function asserts that `cxxrtl_attr_type(attrs, name) == CXXRTL_ATTR_SIGNED_INT`.\n// If assertions are disabled, returns 0 if the attribute is missing or has an incorrect type.\nint64_t cxxrtl_attr_get_signed_int(cxxrtl_attr_set attrs, const char *name);\n\n// Retrieve a string valued attribute from an attribute set. The returned string is zero-terminated.\n//\n// This function asserts that `cxxrtl_attr_type(attrs, name) == CXXRTL_ATTR_STRING`. If assertions\n// are disabled, returns NULL if the attribute is missing or has an incorrect type.\nconst char *cxxrtl_attr_get_string(cxxrtl_attr_set attrs, const char *name);\n\n// Retrieve a double precision floating point valued attribute from an attribute set.\n//\n// This function asserts that `cxxrtl_attr_type(attrs, name) == CXXRTL_ATTR_DOUBLE`. If assertions\n// are disabled, returns NULL if the attribute is missing or has an incorrect type.\ndouble cxxrtl_attr_get_double(cxxrtl_attr_set attrs, const char *name);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n",
134
134
  "cxxrtl_capi_vcd.cc": "/*\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// This file is a part of the CXXRTL C API. It should be used together with `cxxrtl/capi/cxxrtl_capi_vcd.h`.\n\n#include <cxxrtl/capi/cxxrtl_capi_vcd.h>\n#include <cxxrtl/cxxrtl_vcd.h>\n\nextern const cxxrtl::debug_items &cxxrtl_debug_items_from_handle(cxxrtl_handle handle);\n\nstruct _cxxrtl_vcd {\n\tcxxrtl::vcd_writer writer;\n\tbool flush = false;\n};\n\ncxxrtl_vcd cxxrtl_vcd_create() {\n\treturn new _cxxrtl_vcd;\n}\n\nvoid cxxrtl_vcd_destroy(cxxrtl_vcd vcd) {\n\tdelete vcd;\n}\n\nvoid cxxrtl_vcd_timescale(cxxrtl_vcd vcd, int number, const char *unit) {\n\tvcd->writer.timescale(number, unit);\n}\n\nvoid cxxrtl_vcd_add(cxxrtl_vcd vcd, const char *name, cxxrtl_object *object) {\n\t// Note the copy. We don't know whether `object` came from a design (in which case it is\n\t// an instance of `debug_item`), or from user code (in which case it is an instance of\n\t// `cxxrtl_object`), so casting the pointer wouldn't be safe.\n\tvcd->writer.add(name, cxxrtl::debug_item(*object));\n}\n\nvoid cxxrtl_vcd_add_from(cxxrtl_vcd vcd, cxxrtl_handle handle) {\n\tvcd->writer.add(cxxrtl_debug_items_from_handle(handle));\n}\n\nvoid cxxrtl_vcd_add_from_if(cxxrtl_vcd vcd, cxxrtl_handle handle, void *data,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tint (*filter)(void *data, const char *name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t const cxxrtl_object *object)) {\n\tvcd->writer.add(cxxrtl_debug_items_from_handle(handle),\n\t\t[=](const std::string &name, const cxxrtl::debug_item &item) {\n\t\t\treturn filter(data, name.c_str(), static_cast<const cxxrtl_object*>(&item));\n\t\t});\n}\n\nvoid cxxrtl_vcd_add_from_without_memories(cxxrtl_vcd vcd, cxxrtl_handle handle) {\n\tvcd->writer.add_without_memories(cxxrtl_debug_items_from_handle(handle));\n}\n\nvoid cxxrtl_vcd_sample(cxxrtl_vcd vcd, uint64_t time) {\n\tif (vcd->flush) {\n\t\tvcd->writer.buffer.clear();\n\t\tvcd->flush = false;\n\t}\n\tvcd->writer.sample(time);\n}\n\nvoid cxxrtl_vcd_read(cxxrtl_vcd vcd, const char **data, size_t *size) {\n\tif (vcd->flush) {\n\t\tvcd->writer.buffer.clear();\n\t\tvcd->flush = false;\n\t}\n\t*data = vcd->writer.buffer.c_str();\n\t*size = vcd->writer.buffer.size();\n\tvcd->flush = true;\n}\n",
135
135
  "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",
136
136
  },
137
- "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 (is_neg()) dividend = dividend.neg();\n\t\tif (other.is_neg()) divisor = divisor.neg();\n\t\tstd::tie(quotient, remainder) = dividend.udivmod(divisor);\n\t\tif (is_neg() != other.is_neg()) quotient = quotient.neg();\n\t\tif (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\t// Internal CXXRTL use only.\n\tstatic std::map<std::string, metadata> deserialize(const char *ptr) {\n\t\tstd::map<std::string, metadata> result;\n\t\tstd::string name;\n\t\t// Grammar:\n\t\t// string ::= [^\\0]+ \\0\n\t\t// metadata ::= [uid] .{8} | s <string>\n\t\t// map ::= ( <string> <metadata> )* \\0\n\t\tfor (;;) {\n\t\t\tif (*ptr) {\n\t\t\t\tname += *ptr++;\n\t\t\t} else if (!name.empty()) {\n\t\t\t\tptr++;\n\t\t\t\tauto get_u64 = [&]() {\n\t\t\t\t\tuint64_t result = 0;\n\t\t\t\t\tfor (size_t count = 0; count < 8; count++)\n\t\t\t\t\t\tresult = (result << 8) | *ptr++;\n\t\t\t\t\treturn result;\n\t\t\t\t};\n\t\t\t\tchar type = *ptr++;\n\t\t\t\tif (type == 'u') {\n\t\t\t\t\tuint64_t value = get_u64();\n\t\t\t\t\tresult.emplace(name, value);\n\t\t\t\t} else if (type == 'i') {\n\t\t\t\t\tint64_t value = (int64_t)get_u64();\n\t\t\t\t\tresult.emplace(name, value);\n\t\t\t\t} else if (type == 'd') {\n\t\t\t\t\tdouble dvalue;\n\t\t\t\t\tuint64_t uvalue = get_u64();\n\t\t\t\t\tstatic_assert(sizeof(dvalue) == sizeof(uvalue), \"double must be 64 bits in size\");\n\t\t\t\t\tmemcpy(&dvalue, &uvalue, sizeof(dvalue));\n\t\t\t\t\tresult.emplace(name, dvalue);\n\t\t\t\t} else if (type == 's') {\n\t\t\t\t\tstd::string value;\n\t\t\t\t\twhile (*ptr)\n\t\t\t\t\t\tvalue += *ptr++;\n\t\t\t\t\tptr++;\n\t\t\t\t\tresult.emplace(name, value);\n\t\t\t\t} else {\n\t\t\t\t\tassert(false && \"Unknown type specifier\");\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tname.clear();\n\t\t\t} else {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\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\tLITERAL = 0,\n\t\tINTEGER = 1,\n\t\tSTRING = 2,\n\t\tUNICHAR = 3,\n\t\tVLOG_TIME = 4,\n\t} type;\n\n\t// LITERAL type\n\tstd::string str;\n\n\t// INTEGER/STRING/UNICHAR types\n\t// + value<Bits> val;\n\n\t// INTEGER/STRING/VLOG_TIME types\n\tenum {\n\t\tRIGHT\t= 0,\n\t\tLEFT\t= 1,\n\t\tNUMERIC\t= 2,\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\tenum {\n\t\tMINUS\t\t= 0,\n\t\tPLUS_MINUS\t= 1,\n\t\tSPACE_MINUS\t= 2,\n\t} sign; // = MINUS;\n\tbool hex_upper; // = false;\n\tbool show_base; // = false;\n\tbool group; // = 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\tstd::string prefix;\n\t\tswitch (type) {\n\t\t\tcase LITERAL:\n\t\t\t\treturn str;\n\n\t\t\tcase STRING: {\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 UNICHAR: {\n\t\t\t\tuint32_t codepoint = val.template get<uint32_t>();\n\t\t\t\tif (codepoint >= 0x10000)\n\t\t\t\t\tbuf += (char)(0xf0 | (codepoint >> 18));\n\t\t\t\telse if (codepoint >= 0x800)\n\t\t\t\t\tbuf += (char)(0xe0 | (codepoint >> 12));\n\t\t\t\telse if (codepoint >= 0x80)\n\t\t\t\t\tbuf += (char)(0xc0 | (codepoint >> 6));\n\t\t\t\telse\n\t\t\t\t\tbuf += (char)codepoint;\n\t\t\t\tif (codepoint >= 0x10000)\n\t\t\t\t\tbuf += (char)(0x80 | ((codepoint >> 12) & 0x3f));\n\t\t\t\tif (codepoint >= 0x800)\n\t\t\t\t\tbuf += (char)(0x80 | ((codepoint >> 6) & 0x3f));\n\t\t\t\tif (codepoint >= 0x80)\n\t\t\t\t\tbuf += (char)(0x80 | ((codepoint >> 0) & 0x3f));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase INTEGER: {\n\t\t\t\tbool negative = signed_ && val.is_neg();\n\t\t\t\tif (negative) {\n\t\t\t\t\tprefix = \"-\";\n\t\t\t\t\tval = val.neg();\n\t\t\t\t} else {\n\t\t\t\t\tswitch (sign) {\n\t\t\t\t\t\tcase MINUS: break;\n\t\t\t\t\t\tcase PLUS_MINUS: prefix = \"+\"; break;\n\t\t\t\t\t\tcase SPACE_MINUS: prefix = \" \"; break;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsize_t val_width = Bits;\n\t\t\t\tif (base != 10) {\n\t\t\t\t\tval_width = 1;\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\tval_width = index + 1;\n\t\t\t\t}\n\n\t\t\t\tif (base == 2) {\n\t\t\t\t\tif (show_base)\n\t\t\t\t\t\tprefix += \"0b\";\n\t\t\t\t\tfor (size_t index = 0; index < val_width; index++) {\n\t\t\t\t\t\tif (group && index > 0 && index % 4 == 0)\n\t\t\t\t\t\t\tbuf += '_';\n\t\t\t\t\t\tbuf += (val.bit(index) ? '1' : '0');\n\t\t\t\t\t}\n\t\t\t\t} else if (base == 8 || base == 16) {\n\t\t\t\t\tif (show_base)\n\t\t\t\t\t\tprefix += (base == 16) ? (hex_upper ? \"0X\" : \"0x\") : \"0o\";\n\t\t\t\t\tsize_t step = (base == 16) ? 4 : 3;\n\t\t\t\t\tfor (size_t index = 0; index < val_width; index += step) {\n\t\t\t\t\t\tif (group && index > 0 && index % (4 * step) == 0)\n\t\t\t\t\t\t\tbuf += '_';\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 += (hex_upper ? \"0123456789ABCDEF\" : \"0123456789abcdef\")[value];\n\t\t\t\t\t}\n\t\t\t\t} else if (base == 10) {\n\t\t\t\t\tif (show_base)\n\t\t\t\t\t\tprefix += \"0d\";\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\tsize_t index = 0;\n\t\t\t\t\twhile (!xval.is_zero()) {\n\t\t\t\t\t\tif (group && index > 0 && index % 3 == 0)\n\t\t\t\t\t\t\tbuf += '_';\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\tindex++;\n\t\t\t\t\t}\n\t\t\t\t} else assert(false && \"Unsupported base for fmt_part\");\n\t\t\t\tif (justify == NUMERIC && group && padding == '0') {\n\t\t\t\t\tint group_size = base == 10 ? 3 : 4;\n\t\t\t\t\twhile (prefix.size() + buf.size() < width) {\n\t\t\t\t\t\tif (buf.size() % (group_size + 1) == group_size)\n\t\t\t\t\t\t\tbuf += '_';\n\t\t\t\t\t\tbuf += '0';\n\t\t\t\t\t}\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 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 (prefix.size() + buf.size() < width) {\n\t\t\tsize_t pad_width = width - prefix.size() - buf.size();\n\t\t\tswitch (justify) {\n\t\t\t\tcase LEFT:\n\t\t\t\t\tstr += prefix;\n\t\t\t\t\tstr += buf;\n\t\t\t\t\tstr += std::string(pad_width, padding);\n\t\t\t\t\tbreak;\n\t\t\t\tcase RIGHT:\n\t\t\t\t\tstr += std::string(pad_width, padding);\n\t\t\t\t\tstr += prefix;\n\t\t\t\t\tstr += buf;\n\t\t\t\t\tbreak;\n\t\t\t\tcase NUMERIC:\n\t\t\t\t\tstr += prefix;\n\t\t\t\t\tstr += std::string(pad_width, padding);\n\t\t\t\t\tstr += buf;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t} else {\n\t\t\tstr += prefix;\n\t\t\tstr += buf;\n\t\t}\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\t// This overload exists to reduce excessive stack slot allocation in `CXXRTL_EXTREMELY_COLD void debug_info()`.\n\ttemplate<class... T>\n\tvoid add(const std::string &base_path, const char *path, const char *serialized_item_attrs, T&&... args) {\n\t\tadd(base_path + path, debug_item(std::forward<T>(args)...), metadata::deserialize(serialized_item_attrs));\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\t// This overload exists to reduce excessive stack slot allocation in `CXXRTL_EXTREMELY_COLD void debug_info()`.\n\tvoid add(const std::string &base_path, const char *path, const char *module_name, const char *serialized_module_attrs, const char *serialized_cell_attrs) {\n\t\tadd(base_path + path, module_name, metadata::deserialize(serialized_module_attrs), metadata::deserialize(serialized_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",
137
+ "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 (is_neg()) dividend = dividend.neg();\n\t\tif (other.is_neg()) divisor = divisor.neg();\n\t\tstd::tie(quotient, remainder) = dividend.udivmod(divisor);\n\t\tif (is_neg() != other.is_neg()) quotient = quotient.neg();\n\t\tif (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\t// Internal CXXRTL use only.\n\tstatic std::map<std::string, metadata> deserialize(const char *ptr) {\n\t\tstd::map<std::string, metadata> result;\n\t\tstd::string name;\n\t\t// Grammar:\n\t\t// string ::= [^\\0]+ \\0\n\t\t// metadata ::= [uid] .{8} | s <string>\n\t\t// map ::= ( <string> <metadata> )* \\0\n\t\tfor (;;) {\n\t\t\tif (*ptr) {\n\t\t\t\tname += *ptr++;\n\t\t\t} else if (!name.empty()) {\n\t\t\t\tptr++;\n\t\t\t\tauto get_u64 = [&]() {\n\t\t\t\t\tuint64_t result = 0;\n\t\t\t\t\tfor (size_t count = 0; count < 8; count++)\n\t\t\t\t\t\tresult = (result << 8) | *ptr++;\n\t\t\t\t\treturn result;\n\t\t\t\t};\n\t\t\t\tchar type = *ptr++;\n\t\t\t\tif (type == 'u') {\n\t\t\t\t\tuint64_t value = get_u64();\n\t\t\t\t\tresult.emplace(name, value);\n\t\t\t\t} else if (type == 'i') {\n\t\t\t\t\tint64_t value = (int64_t)get_u64();\n\t\t\t\t\tresult.emplace(name, value);\n\t\t\t\t} else if (type == 'd') {\n\t\t\t\t\tdouble dvalue;\n\t\t\t\t\tuint64_t uvalue = get_u64();\n\t\t\t\t\tstatic_assert(sizeof(dvalue) == sizeof(uvalue), \"double must be 64 bits in size\");\n\t\t\t\t\tmemcpy(&dvalue, &uvalue, sizeof(dvalue));\n\t\t\t\t\tresult.emplace(name, dvalue);\n\t\t\t\t} else if (type == 's') {\n\t\t\t\t\tstd::string value;\n\t\t\t\t\twhile (*ptr)\n\t\t\t\t\t\tvalue += *ptr++;\n\t\t\t\t\tptr++;\n\t\t\t\t\tresult.emplace(name, value);\n\t\t\t\t} else {\n\t\t\t\t\tassert(false && \"Unknown type specifier\");\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tname.clear();\n\t\t\t} else {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\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\tLITERAL = 0,\n\t\tINTEGER = 1,\n\t\tSTRING = 2,\n\t\tUNICHAR = 3,\n\t\tVLOG_TIME = 4,\n\t} type;\n\n\t// LITERAL type\n\tstd::string str;\n\n\t// INTEGER/STRING/UNICHAR types\n\t// + value<Bits> val;\n\n\t// INTEGER/STRING/VLOG_TIME types\n\tenum {\n\t\tRIGHT\t= 0,\n\t\tLEFT\t= 1,\n\t\tNUMERIC\t= 2,\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\tenum {\n\t\tMINUS\t\t= 0,\n\t\tPLUS_MINUS\t= 1,\n\t\tSPACE_MINUS\t= 2,\n\t} sign; // = MINUS;\n\tbool hex_upper; // = false;\n\tbool show_base; // = false;\n\tbool group; // = 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\tstd::string prefix;\n\t\tswitch (type) {\n\t\t\tcase LITERAL:\n\t\t\t\treturn str;\n\n\t\t\tcase STRING: {\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 UNICHAR: {\n\t\t\t\tuint32_t codepoint = val.template get<uint32_t>();\n\t\t\t\tif (codepoint >= 0x10000)\n\t\t\t\t\tbuf += (char)(0xf0 | (codepoint >> 18));\n\t\t\t\telse if (codepoint >= 0x800)\n\t\t\t\t\tbuf += (char)(0xe0 | (codepoint >> 12));\n\t\t\t\telse if (codepoint >= 0x80)\n\t\t\t\t\tbuf += (char)(0xc0 | (codepoint >> 6));\n\t\t\t\telse\n\t\t\t\t\tbuf += (char)codepoint;\n\t\t\t\tif (codepoint >= 0x10000)\n\t\t\t\t\tbuf += (char)(0x80 | ((codepoint >> 12) & 0x3f));\n\t\t\t\tif (codepoint >= 0x800)\n\t\t\t\t\tbuf += (char)(0x80 | ((codepoint >> 6) & 0x3f));\n\t\t\t\tif (codepoint >= 0x80)\n\t\t\t\t\tbuf += (char)(0x80 | ((codepoint >> 0) & 0x3f));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase INTEGER: {\n\t\t\t\tbool negative = signed_ && val.is_neg();\n\t\t\t\tif (negative) {\n\t\t\t\t\tprefix = \"-\";\n\t\t\t\t\tval = val.neg();\n\t\t\t\t} else {\n\t\t\t\t\tswitch (sign) {\n\t\t\t\t\t\tcase MINUS: break;\n\t\t\t\t\t\tcase PLUS_MINUS: prefix = \"+\"; break;\n\t\t\t\t\t\tcase SPACE_MINUS: prefix = \" \"; break;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsize_t val_width = Bits;\n\t\t\t\tif (base != 10) {\n\t\t\t\t\tval_width = 1;\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\tval_width = index + 1;\n\t\t\t\t}\n\n\t\t\t\tif (base == 2) {\n\t\t\t\t\tif (show_base)\n\t\t\t\t\t\tprefix += \"0b\";\n\t\t\t\t\tfor (size_t index = 0; index < val_width; index++) {\n\t\t\t\t\t\tif (group && index > 0 && index % 4 == 0)\n\t\t\t\t\t\t\tbuf += '_';\n\t\t\t\t\t\tbuf += (val.bit(index) ? '1' : '0');\n\t\t\t\t\t}\n\t\t\t\t} else if (base == 8 || base == 16) {\n\t\t\t\t\tif (show_base)\n\t\t\t\t\t\tprefix += (base == 16) ? (hex_upper ? \"0X\" : \"0x\") : \"0o\";\n\t\t\t\t\tsize_t step = (base == 16) ? 4 : 3;\n\t\t\t\t\tfor (size_t index = 0; index < val_width; index += step) {\n\t\t\t\t\t\tif (group && index > 0 && index % (4 * step) == 0)\n\t\t\t\t\t\t\tbuf += '_';\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 += (hex_upper ? \"0123456789ABCDEF\" : \"0123456789abcdef\")[value];\n\t\t\t\t\t}\n\t\t\t\t} else if (base == 10) {\n\t\t\t\t\tif (show_base)\n\t\t\t\t\t\tprefix += \"0d\";\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\tsize_t index = 0;\n\t\t\t\t\twhile (!xval.is_zero()) {\n\t\t\t\t\t\tif (group && index > 0 && index % 3 == 0)\n\t\t\t\t\t\t\tbuf += '_';\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\tindex++;\n\t\t\t\t\t}\n\t\t\t\t} else assert(false && \"Unsupported base for fmt_part\");\n\t\t\t\tif (justify == NUMERIC && group && padding == '0') {\n\t\t\t\t\tint group_size = base == 10 ? 3 : 4;\n\t\t\t\t\twhile (prefix.size() + buf.size() < width) {\n\t\t\t\t\t\tif (buf.size() % (group_size + 1) == group_size)\n\t\t\t\t\t\t\tbuf += '_';\n\t\t\t\t\t\tbuf += '0';\n\t\t\t\t\t}\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 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 (prefix.size() + buf.size() < width) {\n\t\t\tsize_t pad_width = width - prefix.size() - buf.size();\n\t\t\tswitch (justify) {\n\t\t\t\tcase LEFT:\n\t\t\t\t\tstr += prefix;\n\t\t\t\t\tstr += buf;\n\t\t\t\t\tstr += std::string(pad_width, padding);\n\t\t\t\t\tbreak;\n\t\t\t\tcase RIGHT:\n\t\t\t\t\tstr += std::string(pad_width, padding);\n\t\t\t\t\tstr += prefix;\n\t\t\t\t\tstr += buf;\n\t\t\t\t\tbreak;\n\t\t\t\tcase NUMERIC:\n\t\t\t\t\tstr += prefix;\n\t\t\t\t\tstr += std::string(pad_width, padding);\n\t\t\t\t\tstr += buf;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t} else {\n\t\t\tstr += prefix;\n\t\t\tstr += buf;\n\t\t}\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\t// This overload exists to reduce excessive stack slot allocation in `CXXRTL_EXTREMELY_COLD void debug_info()`.\n\ttemplate<class... T>\n\tvoid add(const std::string &base_path, const char *path, const char *serialized_item_attrs, T&&... args) {\n\t\tadd(base_path + path, debug_item(std::forward<T>(args)...), metadata::deserialize(serialized_item_attrs));\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\t// This overload exists to reduce excessive stack slot allocation in `CXXRTL_EXTREMELY_COLD void debug_info()`.\n\tvoid add(const std::string &base_path, const char *path, const char *module_name, const char *serialized_module_attrs, const char *serialized_cell_attrs) {\n\t\tadd(base_path + path, module_name, metadata::deserialize(serialized_module_attrs), metadata::deserialize(serialized_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(&items, /*scopes=*/nullptr, path);` instead.\")))\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",
138
138
  "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 &timestamp) {\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 &timestamp) {\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 &timestamp) {\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\tint fd;\n\t\tif ((fd = writefd.exchange(-1)) != -1)\n\t\t\tclose(fd);\n\t\tif ((fd = readfd.exchange(-1)) != -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 &timestamp) {\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 &current_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 &timestamp) {\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",
139
139
  "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",
140
140
  "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 &register_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",
@@ -147,7 +147,7 @@ export const filesystem = {
147
147
  },
148
148
  "frontends": {
149
149
  "ast": {
150
- "ast.h": "/* -*- c++ -*-\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 * ---\n *\n * This is the AST frontend library.\n *\n * The AST frontend library is not a frontend on it's own but provides a\n * generic abstract syntax tree (AST) abstraction for HDL code and can be\n * used by HDL frontends. See \"ast.h\" for an overview of the API and the\n * Verilog frontend for an usage example.\n *\n */\n\n#ifndef AST_H\n#define AST_H\n\n#include \"kernel/rtlil.h\"\n#include \"kernel/fmt.h\"\n#include <stdint.h>\n#include <set>\n\nYOSYS_NAMESPACE_BEGIN\n\nnamespace AST\n{\n\t// all node types, type2str() must be extended\n\t// whenever a new node type is added here\n\tenum AstNodeType\n\t{\n\t\tAST_NONE,\n\t\tAST_DESIGN,\n\t\tAST_MODULE,\n\t\tAST_TASK,\n\t\tAST_FUNCTION,\n\t\tAST_DPI_FUNCTION,\n\n\t\tAST_WIRE,\n\t\tAST_MEMORY,\n\t\tAST_AUTOWIRE,\n\t\tAST_PARAMETER,\n\t\tAST_LOCALPARAM,\n\t\tAST_DEFPARAM,\n\t\tAST_PARASET,\n\t\tAST_ARGUMENT,\n\t\tAST_RANGE,\n\t\tAST_MULTIRANGE,\n\t\tAST_CONSTANT,\n\t\tAST_REALVALUE,\n\t\tAST_CELLTYPE,\n\t\tAST_IDENTIFIER,\n\t\tAST_PREFIX,\n\t\tAST_ASSERT,\n\t\tAST_ASSUME,\n\t\tAST_LIVE,\n\t\tAST_FAIR,\n\t\tAST_COVER,\n\t\tAST_ENUM,\n\t\tAST_ENUM_ITEM,\n\n\t\tAST_FCALL,\n\t\tAST_TO_BITS,\n\t\tAST_TO_SIGNED,\n\t\tAST_TO_UNSIGNED,\n\t\tAST_SELFSZ,\n\t\tAST_CAST_SIZE,\n\t\tAST_CONCAT,\n\t\tAST_REPLICATE,\n\t\tAST_BIT_NOT,\n\t\tAST_BIT_AND,\n\t\tAST_BIT_OR,\n\t\tAST_BIT_XOR,\n\t\tAST_BIT_XNOR,\n\t\tAST_REDUCE_AND,\n\t\tAST_REDUCE_OR,\n\t\tAST_REDUCE_XOR,\n\t\tAST_REDUCE_XNOR,\n\t\tAST_REDUCE_BOOL,\n\t\tAST_SHIFT_LEFT,\n\t\tAST_SHIFT_RIGHT,\n\t\tAST_SHIFT_SLEFT,\n\t\tAST_SHIFT_SRIGHT,\n\t\tAST_SHIFTX,\n\t\tAST_SHIFT,\n\t\tAST_LT,\n\t\tAST_LE,\n\t\tAST_EQ,\n\t\tAST_NE,\n\t\tAST_EQX,\n\t\tAST_NEX,\n\t\tAST_GE,\n\t\tAST_GT,\n\t\tAST_ADD,\n\t\tAST_SUB,\n\t\tAST_MUL,\n\t\tAST_DIV,\n\t\tAST_MOD,\n\t\tAST_POW,\n\t\tAST_POS,\n\t\tAST_NEG,\n\t\tAST_LOGIC_AND,\n\t\tAST_LOGIC_OR,\n\t\tAST_LOGIC_NOT,\n\t\tAST_TERNARY,\n\t\tAST_MEMRD,\n\t\tAST_MEMWR,\n\t\tAST_MEMINIT,\n\n\t\tAST_TCALL,\n\t\tAST_ASSIGN,\n\t\tAST_CELL,\n\t\tAST_PRIMITIVE,\n\t\tAST_CELLARRAY,\n\t\tAST_ALWAYS,\n\t\tAST_INITIAL,\n\t\tAST_BLOCK,\n\t\tAST_ASSIGN_EQ,\n\t\tAST_ASSIGN_LE,\n\t\tAST_CASE,\n\t\tAST_COND,\n\t\tAST_CONDX,\n\t\tAST_CONDZ,\n\t\tAST_DEFAULT,\n\t\tAST_FOR,\n\t\tAST_WHILE,\n\t\tAST_REPEAT,\n\n\t\tAST_GENVAR,\n\t\tAST_GENFOR,\n\t\tAST_GENIF,\n\t\tAST_GENCASE,\n\t\tAST_GENBLOCK,\n\t\tAST_TECALL,\n\n\t\tAST_POSEDGE,\n\t\tAST_NEGEDGE,\n\t\tAST_EDGE,\n\n\t\tAST_INTERFACE,\n\t\tAST_INTERFACEPORT,\n\t\tAST_INTERFACEPORTTYPE,\n\t\tAST_MODPORT,\n\t\tAST_MODPORTMEMBER,\n\t\tAST_PACKAGE,\n\n\t\tAST_WIRETYPE,\n\t\tAST_TYPEDEF,\n\t\tAST_STRUCT,\n\t\tAST_UNION,\n\t\tAST_STRUCT_ITEM,\n\t\tAST_BIND\n\t};\n\n\tstruct AstSrcLocType {\n\t\tunsigned int first_line, last_line;\n\t\tunsigned int first_column, last_column;\n\t\tAstSrcLocType() : first_line(0), last_line(0), first_column(0), last_column(0) {}\n\t\tAstSrcLocType(int _first_line, int _first_column, int _last_line, int _last_column) : first_line(_first_line), last_line(_last_line), first_column(_first_column), last_column(_last_column) {}\n\t};\n\n\t// convert an node type to a string (e.g. for debug output)\n\tstd::string type2str(AstNodeType type);\n\n\t// The AST is built using instances of this struct\n\tstruct AstNode\n\t{\n\t\t// for dict<> and pool<>\n\t\tunsigned int hashidx_;\n\t\tunsigned int hash() const { return hashidx_; }\n\n\t\t// this nodes type\n\t\tAstNodeType type;\n\n\t\t// the list of child nodes for this node\n\t\tstd::vector<AstNode*> children;\n\n\t\t// the list of attributes assigned to this node\n\t\tstd::map<RTLIL::IdString, AstNode*> attributes;\n\t\tbool get_bool_attribute(RTLIL::IdString id);\n\n\t\t// node content - most of it is unused in most node types\n\t\tstd::string str;\n\t\tstd::vector<RTLIL::State> bits;\n\t\tbool is_input, is_output, is_reg, is_logic, is_signed, is_string, is_wand, is_wor, range_valid, range_swapped, was_checked, is_unsized, is_custom_type;\n\t\tint port_id, range_left, range_right;\n\t\tuint32_t integer;\n\t\tdouble realvalue;\n\t\t// set for IDs typed to an enumeration, not used\n\t\tbool is_enum;\n\n\t\t// Declared range for array dimension.\n\t\tstruct dimension_t {\n\t\t\tint range_right; // lsb in [msb:lsb]\n\t\t\tint range_width; // msb - lsb + 1\n\t\t\tbool range_swapped; // if the declared msb < lsb, msb and lsb above are swapped\n\t\t};\n\t\t// Packed and unpacked dimensions for arrays.\n\t\t// Unpacked dimensions go first, to follow the order of indexing.\n\t\tstd::vector<dimension_t> dimensions;\n\t\t// Number of unpacked dimensions.\n\t\tint unpacked_dimensions;\n\n\t\t// this is set by simplify and used during RTLIL generation\n\t\tAstNode *id2ast;\n\n\t\t// this is used by simplify to detect if basic analysis has been performed already on the node\n\t\tbool basic_prep;\n\n\t\t// this is used for ID references in RHS expressions that should use the \"new\" value for non-blocking assignments\n\t\tbool lookahead;\n\n\t\t// this is the original sourcecode location that resulted in this AST node\n\t\t// it is automatically set by the constructor using AST::current_filename and\n\t\t// the AST::get_line_num() callback function.\n\t\tstd::string filename;\n\t\tAstSrcLocType location;\n\n\t\t// are we embedded in an lvalue, param?\n\t\t// (see fixup_hierarchy_flags)\n\t\tbool in_lvalue;\n\t\tbool in_param;\n\t\tbool in_lvalue_from_above;\n\t\tbool in_param_from_above;\n\n\t\t// creating and deleting nodes\n\t\tAstNode(AstNodeType type = AST_NONE, AstNode *child1 = nullptr, AstNode *child2 = nullptr, AstNode *child3 = nullptr, AstNode *child4 = nullptr);\n\t\tAstNode *clone() const;\n\t\tvoid cloneInto(AstNode *other) const;\n\t\tvoid delete_children();\n\t\t~AstNode();\n\n\t\tenum mem2reg_flags\n\t\t{\n\t\t\t/* status flags */\n\t\t\tMEM2REG_FL_ALL = 0x00000001,\n\t\t\tMEM2REG_FL_ASYNC = 0x00000002,\n\t\t\tMEM2REG_FL_INIT = 0x00000004,\n\n\t\t\t/* candidate flags */\n\t\t\tMEM2REG_FL_FORCED = 0x00000100,\n\t\t\tMEM2REG_FL_SET_INIT = 0x00000200,\n\t\t\tMEM2REG_FL_SET_ELSE = 0x00000400,\n\t\t\tMEM2REG_FL_SET_ASYNC = 0x00000800,\n\t\t\tMEM2REG_FL_EQ2 = 0x00001000,\n\t\t\tMEM2REG_FL_CMPLX_LHS = 0x00002000,\n\t\t\tMEM2REG_FL_CONST_LHS = 0x00004000,\n\t\t\tMEM2REG_FL_VAR_LHS = 0x00008000,\n\n\t\t\t/* proc flags */\n\t\t\tMEM2REG_FL_EQ1 = 0x01000000,\n\t\t};\n\n\t\t// simplify() creates a simpler AST by unrolling for-loops, expanding generate blocks, etc.\n\t\t// it also sets the id2ast pointers so that identifier lookups are fast in genRTLIL()\n\t\tbool simplify(bool const_fold, int stage, int width_hint, bool sign_hint);\n\t\tvoid replace_result_wire_name_in_function(const std::string &from, const std::string &to);\n\t\tAstNode *readmem(bool is_readmemh, std::string mem_filename, AstNode *memory, int start_addr, int finish_addr, bool unconditional_init);\n\t\tvoid expand_genblock(const std::string &prefix);\n\t\tvoid label_genblks(std::set<std::string>& existing, int &counter);\n\t\tvoid mem2reg_as_needed_pass1(dict<AstNode*, pool<std::string>> &mem2reg_places,\n\t\t\t\tdict<AstNode*, uint32_t> &mem2reg_flags, dict<AstNode*, uint32_t> &proc_flags, uint32_t &status_flags);\n\t\tbool mem2reg_as_needed_pass2(pool<AstNode*> &mem2reg_set, AstNode *mod, AstNode *block, AstNode *&async_block);\n\t\tbool mem2reg_check(pool<AstNode*> &mem2reg_set);\n\t\tvoid mem2reg_remove(pool<AstNode*> &mem2reg_set, vector<AstNode*> &delnodes);\n\t\tvoid meminfo(int &mem_width, int &mem_size, int &addr_bits);\n\t\tbool detect_latch(const std::string &var);\n\t\tconst RTLIL::Module* lookup_cell_module();\n\n\t\t// additional functionality for evaluating constant functions\n\t\tstruct varinfo_t {\n\t\t\tRTLIL::Const val;\n\t\t\tint offset;\n\t\t\tbool range_swapped;\n\t\t\tbool is_signed;\n\t\t\tAstNode *arg = nullptr;\n\t\t\tbool explicitly_sized;\n\t\t};\n\t\tbool has_const_only_constructs();\n\t\tbool replace_variables(std::map<std::string, varinfo_t> &variables, AstNode *fcall, bool must_succeed);\n\t\tAstNode *eval_const_function(AstNode *fcall, bool must_succeed);\n\t\tbool is_simple_const_expr();\n\n\t\t// helper for parsing format strings\n\t\tFmt processFormat(int stage, bool sformat_like, int default_base = 10, size_t first_arg_at = 0, bool may_fail = false);\n\n\t\tbool is_recursive_function() const;\n\t\tstd::pair<AstNode*, AstNode*> get_tern_choice();\n\n\t\t// create a human-readable text representation of the AST (for debugging)\n\t\tvoid dumpAst(FILE *f, std::string indent) const;\n\t\tvoid dumpVlog(FILE *f, std::string indent) const;\n\n\t\t// Generate RTLIL for a bind construct\n\t\tstd::vector<RTLIL::Binding *> genBindings() const;\n\n\t\t// used by genRTLIL() for detecting expression width and sign\n\t\tvoid detectSignWidthWorker(int &width_hint, bool &sign_hint, bool *found_real = NULL);\n\t\tvoid detectSignWidth(int &width_hint, bool &sign_hint, bool *found_real = NULL);\n\n\t\t// create RTLIL code for this AST node\n\t\t// for expressions the resulting signal vector is returned\n\t\t// all generated cell instances, etc. are written to the RTLIL::Module pointed to by AST_INTERNAL::current_module\n\t\tRTLIL::SigSpec genRTLIL(int width_hint = -1, bool sign_hint = false);\n\t\tRTLIL::SigSpec genWidthRTLIL(int width, bool sgn, const dict<RTLIL::SigBit, RTLIL::SigBit> *new_subst_ptr = NULL);\n\n\t\t// compare AST nodes\n\t\tbool operator==(const AstNode &other) const;\n\t\tbool operator!=(const AstNode &other) const;\n\t\tbool contains(const AstNode *other) const;\n\n\t\t// helper functions for creating AST nodes for constants\n\t\tstatic AstNode *mkconst_int(uint32_t v, bool is_signed, int width = 32);\n\t\tstatic AstNode *mkconst_bits(const std::vector<RTLIL::State> &v, bool is_signed, bool is_unsized);\n\t\tstatic AstNode *mkconst_bits(const std::vector<RTLIL::State> &v, bool is_signed);\n\t\tstatic AstNode *mkconst_str(const std::vector<RTLIL::State> &v);\n\t\tstatic AstNode *mkconst_str(const std::string &str);\n\n\t\t// helper function to create an AST node for a temporary register\n\t\tAstNode *mktemp_logic(const std::string &name, AstNode *mod, bool nosync, int range_left, int range_right, bool is_signed);\n\n\t\t// helper function for creating sign-extended const objects\n\t\tRTLIL::Const bitsAsConst(int width, bool is_signed);\n\t\tRTLIL::Const bitsAsConst(int width = -1);\n\t\tRTLIL::Const bitsAsUnsizedConst(int width);\n\t\tRTLIL::Const asAttrConst() const;\n\t\tRTLIL::Const asParaConst() const;\n\t\tuint64_t asInt(bool is_signed);\n\t\tbool bits_only_01() const;\n\t\tbool asBool() const;\n\n\t\t// helper functions for real valued const eval\n\t\tint isConst() const; // return '1' for AST_CONSTANT and '2' for AST_REALVALUE\n\t\tdouble asReal(bool is_signed);\n\t\tRTLIL::Const realAsConst(int width);\n\n\t\t// helpers for enum\n\t\tvoid allocateDefaultEnumValues();\n\t\tvoid annotateTypedEnums(AstNode *template_node);\n\n\t\t// helpers for locations\n\t\tstd::string loc_string() const;\n\n\t\t// Helper for looking up identifiers which are prefixed with the current module name\n\t\tstd::string try_pop_module_prefix() const;\n\n\t\t// helper to clone the node with some of its subexpressions replaced with zero (this is used\n\t\t// to evaluate widths of dynamic ranges)\n\t\tAstNode *clone_at_zero();\n\n\t\tvoid set_attribute(RTLIL::IdString key, AstNode *node)\n\t\t{\n\t\t\tattributes[key] = node;\n\t\t\tnode->set_in_param_flag(true);\n\t\t}\n\n\t\t// helper to set in_lvalue/in_param flags from the hierarchy context (the actual flag\n\t\t// can be overridden based on the intrinsic properties of this node, i.e. based on its type)\n\t\tvoid set_in_lvalue_flag(bool flag, bool no_descend = false);\n\t\tvoid set_in_param_flag(bool flag, bool no_descend = false);\n\n\t\t// fix up the hierarchy flags (in_lvalue/in_param) of this node and its children\n\t\t//\n\t\t// to keep the flags in sync, fixup_hierarchy_flags(true) needs to be called once after\n\t\t// parsing the AST to walk the full tree, then plain fixup_hierarchy_flags() performs\n\t\t// localized fixups after modifying children/attributes of a particular node\n\t\tvoid fixup_hierarchy_flags(bool force_descend = false);\n\n\t\t// helpers for indexing\n\t\tAstNode *make_index_range(AstNode *node, bool unpacked_range = false);\n\t\tAstNode *get_struct_member() const;\n\n\t\t// helper to print errors from simplify/genrtlil code\n\t\t[[noreturn]] void input_error(const char *format, ...) const YS_ATTRIBUTE(format(printf, 2, 3));\n\t};\n\n\t// process an AST tree (ast must point to an AST_DESIGN node) and generate RTLIL code\n\tvoid process(RTLIL::Design *design, AstNode *ast, bool nodisplay, bool dump_ast1, bool dump_ast2, bool no_dump_ptr, bool dump_vlog1, bool dump_vlog2, bool dump_rtlil, bool nolatches, bool nomeminit,\n\t\t\tbool nomem2reg, bool mem2reg, bool noblackbox, bool lib, bool nowb, bool noopt, bool icells, bool pwires, bool nooverwrite, bool overwrite, bool defer, bool autowire);\n\n\t// parametric modules are supported directly by the AST library\n\t// therefore we need our own derivate of RTLIL::Module with overloaded virtual functions\n\tstruct AstModule : RTLIL::Module {\n\t\tAstNode *ast;\n\t\tbool nolatches, nomeminit, nomem2reg, mem2reg, noblackbox, lib, nowb, noopt, icells, pwires, autowire;\n\t\t~AstModule() override;\n\t\tRTLIL::IdString derive(RTLIL::Design *design, const dict<RTLIL::IdString, RTLIL::Const> &parameters, bool mayfail) override;\n\t\tRTLIL::IdString derive(RTLIL::Design *design, const dict<RTLIL::IdString, RTLIL::Const> &parameters, const dict<RTLIL::IdString, RTLIL::Module*> &interfaces, const dict<RTLIL::IdString, RTLIL::IdString> &modports, bool mayfail) override;\n\t\tstd::string derive_common(RTLIL::Design *design, const dict<RTLIL::IdString, RTLIL::Const> &parameters, AstNode **new_ast_out, bool quiet = false);\n\t\tvoid expand_interfaces(RTLIL::Design *design, const dict<RTLIL::IdString, RTLIL::Module *> &local_interfaces) override;\n\t\tbool reprocess_if_necessary(RTLIL::Design *design) override;\n\t\tRTLIL::Module *clone() const override;\n\t\tvoid loadconfig() const;\n\t};\n\n\t// this must be set by the language frontend before parsing the sources\n\t// the AstNode constructor then uses current_filename and get_line_num()\n\t// to initialize the filename and linenum properties of new nodes\n\textern std::string current_filename;\n\textern void (*set_line_num)(int);\n\textern int (*get_line_num)();\n\n\t// set set_line_num and get_line_num to internal dummy functions (done by simplify() and AstModule::derive\n\t// to control the filename and linenum properties of new nodes not generated by a frontend parser)\n\tvoid use_internal_line_num();\n\n\t// call a DPI function\n\tAstNode *dpi_call(const std::string &rtype, const std::string &fname, const std::vector<std::string> &argtypes, const std::vector<AstNode*> &args);\n\n\t// Helper functions related to handling SystemVerilog interfaces\n\tstd::pair<std::string,std::string> split_modport_from_type(std::string name_type);\n\tAstNode * find_modport(AstNode *intf, std::string name);\n\tvoid explode_interface_port(AstNode *module_ast, RTLIL::Module * intfmodule, std::string intfname, AstNode *modport);\n\n\t// Helper for setting the src attribute.\n\tvoid set_src_attr(RTLIL::AttrObject *obj, const AstNode *ast);\n\n\t// generate standard $paramod... derived module name; parameters should be\n\t// in the order they are declared in the instantiated module\n\tstd::string derived_module_name(std::string stripped_name, const std::vector<std::pair<RTLIL::IdString, RTLIL::Const>> &parameters);\n\n\t// used to provide simplify() access to the current design for looking up\n\t// modules, ports, wires, etc.\n\tvoid set_simplify_design_context(const RTLIL::Design *design);\n}\n\nnamespace AST_INTERNAL\n{\n\t// internal state variables\n\textern bool flag_nodisplay, flag_dump_ast1, flag_dump_ast2, flag_no_dump_ptr, flag_dump_rtlil, flag_nolatches, flag_nomeminit;\n\textern bool flag_nomem2reg, flag_mem2reg, flag_lib, flag_noopt, flag_icells, flag_pwires, flag_autowire;\n\textern AST::AstNode *current_ast, *current_ast_mod;\n\textern std::map<std::string, AST::AstNode*> current_scope;\n\textern const dict<RTLIL::SigBit, RTLIL::SigBit> *genRTLIL_subst_ptr;\n\textern RTLIL::SigSpec ignoreThisSignalsInInitial;\n\textern AST::AstNode *current_always, *current_top_block, *current_block, *current_block_child;\n\textern RTLIL::Module *current_module;\n\textern bool current_always_clocked;\n\textern dict<std::string, int> current_memwr_count;\n\textern dict<std::string, pool<int>> current_memwr_visible;\n\tstruct LookaheadRewriter;\n\tstruct ProcessGenerator;\n\n\t// Create and add a new AstModule from new_ast, then use it to replace\n\t// old_module in design, renaming old_module to move it out of the way.\n\t// Return the new module.\n\t//\n\t// If original_ast is not null, it will be used as the AST node for the\n\t// new module. Otherwise, new_ast will be used.\n\tRTLIL::Module *\n\tprocess_and_replace_module(RTLIL::Design *design,\n\t RTLIL::Module *old_module,\n\t AST::AstNode *new_ast,\n\t AST::AstNode *original_ast = nullptr);\n}\n\nYOSYS_NAMESPACE_END\n\n#endif\n",
150
+ "ast.h": "/* -*- c++ -*-\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 * ---\n *\n * This is support code for the Verilog frontend at frontends/verilog\n *\n */\n\n#ifndef AST_H\n#define AST_H\n\n#include \"kernel/rtlil.h\"\n#include \"kernel/fmt.h\"\n#include <stdint.h>\n#include <set>\n\nYOSYS_NAMESPACE_BEGIN\n\nnamespace AST\n{\n\t// all node types, type2str() must be extended\n\t// whenever a new node type is added here\n\tenum AstNodeType\n\t{\n\t\tAST_NONE,\n\t\tAST_DESIGN,\n\t\tAST_MODULE,\n\t\tAST_TASK,\n\t\tAST_FUNCTION,\n\t\tAST_DPI_FUNCTION,\n\n\t\tAST_WIRE,\n\t\tAST_MEMORY,\n\t\tAST_AUTOWIRE,\n\t\tAST_PARAMETER,\n\t\tAST_LOCALPARAM,\n\t\tAST_DEFPARAM,\n\t\tAST_PARASET,\n\t\tAST_ARGUMENT,\n\t\tAST_RANGE,\n\t\tAST_MULTIRANGE,\n\t\tAST_CONSTANT,\n\t\tAST_REALVALUE,\n\t\tAST_CELLTYPE,\n\t\tAST_IDENTIFIER,\n\t\tAST_PREFIX,\n\t\tAST_ASSERT,\n\t\tAST_ASSUME,\n\t\tAST_LIVE,\n\t\tAST_FAIR,\n\t\tAST_COVER,\n\t\tAST_ENUM,\n\t\tAST_ENUM_ITEM,\n\n\t\tAST_FCALL,\n\t\tAST_TO_BITS,\n\t\tAST_TO_SIGNED,\n\t\tAST_TO_UNSIGNED,\n\t\tAST_SELFSZ,\n\t\tAST_CAST_SIZE,\n\t\tAST_CONCAT,\n\t\tAST_REPLICATE,\n\t\tAST_BIT_NOT,\n\t\tAST_BIT_AND,\n\t\tAST_BIT_OR,\n\t\tAST_BIT_XOR,\n\t\tAST_BIT_XNOR,\n\t\tAST_REDUCE_AND,\n\t\tAST_REDUCE_OR,\n\t\tAST_REDUCE_XOR,\n\t\tAST_REDUCE_XNOR,\n\t\tAST_REDUCE_BOOL,\n\t\tAST_SHIFT_LEFT,\n\t\tAST_SHIFT_RIGHT,\n\t\tAST_SHIFT_SLEFT,\n\t\tAST_SHIFT_SRIGHT,\n\t\tAST_SHIFTX,\n\t\tAST_SHIFT,\n\t\tAST_LT,\n\t\tAST_LE,\n\t\tAST_EQ,\n\t\tAST_NE,\n\t\tAST_EQX,\n\t\tAST_NEX,\n\t\tAST_GE,\n\t\tAST_GT,\n\t\tAST_ADD,\n\t\tAST_SUB,\n\t\tAST_MUL,\n\t\tAST_DIV,\n\t\tAST_MOD,\n\t\tAST_POW,\n\t\tAST_POS,\n\t\tAST_NEG,\n\t\tAST_LOGIC_AND,\n\t\tAST_LOGIC_OR,\n\t\tAST_LOGIC_NOT,\n\t\tAST_TERNARY,\n\t\tAST_MEMRD,\n\t\tAST_MEMWR,\n\t\tAST_MEMINIT,\n\n\t\tAST_TCALL,\n\t\tAST_ASSIGN,\n\t\tAST_CELL,\n\t\tAST_PRIMITIVE,\n\t\tAST_CELLARRAY,\n\t\tAST_ALWAYS,\n\t\tAST_INITIAL,\n\t\tAST_BLOCK,\n\t\tAST_ASSIGN_EQ,\n\t\tAST_ASSIGN_LE,\n\t\tAST_CASE,\n\t\tAST_COND,\n\t\tAST_CONDX,\n\t\tAST_CONDZ,\n\t\tAST_DEFAULT,\n\t\tAST_FOR,\n\t\tAST_WHILE,\n\t\tAST_REPEAT,\n\n\t\tAST_GENVAR,\n\t\tAST_GENFOR,\n\t\tAST_GENIF,\n\t\tAST_GENCASE,\n\t\tAST_GENBLOCK,\n\t\tAST_TECALL,\n\n\t\tAST_POSEDGE,\n\t\tAST_NEGEDGE,\n\t\tAST_EDGE,\n\n\t\tAST_INTERFACE,\n\t\tAST_INTERFACEPORT,\n\t\tAST_INTERFACEPORTTYPE,\n\t\tAST_MODPORT,\n\t\tAST_MODPORTMEMBER,\n\t\tAST_PACKAGE,\n\n\t\tAST_WIRETYPE,\n\t\tAST_TYPEDEF,\n\t\tAST_STRUCT,\n\t\tAST_UNION,\n\t\tAST_STRUCT_ITEM,\n\t\tAST_BIND\n\t};\n\n\tstruct AstSrcLocType {\n\t\tunsigned int first_line, last_line;\n\t\tunsigned int first_column, last_column;\n\t\tAstSrcLocType() : first_line(0), last_line(0), first_column(0), last_column(0) {}\n\t\tAstSrcLocType(int _first_line, int _first_column, int _last_line, int _last_column) : first_line(_first_line), last_line(_last_line), first_column(_first_column), last_column(_last_column) {}\n\t};\n\n\t// convert an node type to a string (e.g. for debug output)\n\tstd::string type2str(AstNodeType type);\n\n\t// The AST is built using instances of this struct\n\tstruct AstNode\n\t{\n\t\t// for dict<> and pool<>\n\t\tunsigned int hashidx_;\n\t\tunsigned int hash() const { return hashidx_; }\n\n\t\t// this nodes type\n\t\tAstNodeType type;\n\n\t\t// the list of child nodes for this node\n\t\tstd::vector<AstNode*> children;\n\n\t\t// the list of attributes assigned to this node\n\t\tstd::map<RTLIL::IdString, AstNode*> attributes;\n\t\tbool get_bool_attribute(RTLIL::IdString id);\n\n\t\t// node content - most of it is unused in most node types\n\t\tstd::string str;\n\t\tstd::vector<RTLIL::State> bits;\n\t\tbool is_input, is_output, is_reg, is_logic, is_signed, is_string, is_wand, is_wor, range_valid, range_swapped, was_checked, is_unsized, is_custom_type;\n\t\tint port_id, range_left, range_right;\n\t\tuint32_t integer;\n\t\tdouble realvalue;\n\t\t// set for IDs typed to an enumeration, not used\n\t\tbool is_enum;\n\n\t\t// Declared range for array dimension.\n\t\tstruct dimension_t {\n\t\t\tint range_right; // lsb in [msb:lsb]\n\t\t\tint range_width; // msb - lsb + 1\n\t\t\tbool range_swapped; // if the declared msb < lsb, msb and lsb above are swapped\n\t\t};\n\t\t// Packed and unpacked dimensions for arrays.\n\t\t// Unpacked dimensions go first, to follow the order of indexing.\n\t\tstd::vector<dimension_t> dimensions;\n\t\t// Number of unpacked dimensions.\n\t\tint unpacked_dimensions;\n\n\t\t// this is set by simplify and used during RTLIL generation\n\t\tAstNode *id2ast;\n\n\t\t// this is used by simplify to detect if basic analysis has been performed already on the node\n\t\tbool basic_prep;\n\n\t\t// this is used for ID references in RHS expressions that should use the \"new\" value for non-blocking assignments\n\t\tbool lookahead;\n\n\t\t// this is the original sourcecode location that resulted in this AST node\n\t\t// it is automatically set by the constructor using AST::current_filename and\n\t\t// the AST::get_line_num() callback function.\n\t\tstd::string filename;\n\t\tAstSrcLocType location;\n\n\t\t// are we embedded in an lvalue, param?\n\t\t// (see fixup_hierarchy_flags)\n\t\tbool in_lvalue;\n\t\tbool in_param;\n\t\tbool in_lvalue_from_above;\n\t\tbool in_param_from_above;\n\n\t\t// creating and deleting nodes\n\t\tAstNode(AstNodeType type = AST_NONE, AstNode *child1 = nullptr, AstNode *child2 = nullptr, AstNode *child3 = nullptr, AstNode *child4 = nullptr);\n\t\tAstNode *clone() const;\n\t\tvoid cloneInto(AstNode *other) const;\n\t\tvoid delete_children();\n\t\t~AstNode();\n\n\t\tenum mem2reg_flags\n\t\t{\n\t\t\t/* status flags */\n\t\t\tMEM2REG_FL_ALL = 0x00000001,\n\t\t\tMEM2REG_FL_ASYNC = 0x00000002,\n\t\t\tMEM2REG_FL_INIT = 0x00000004,\n\n\t\t\t/* candidate flags */\n\t\t\tMEM2REG_FL_FORCED = 0x00000100,\n\t\t\tMEM2REG_FL_SET_INIT = 0x00000200,\n\t\t\tMEM2REG_FL_SET_ELSE = 0x00000400,\n\t\t\tMEM2REG_FL_SET_ASYNC = 0x00000800,\n\t\t\tMEM2REG_FL_EQ2 = 0x00001000,\n\t\t\tMEM2REG_FL_CMPLX_LHS = 0x00002000,\n\t\t\tMEM2REG_FL_CONST_LHS = 0x00004000,\n\t\t\tMEM2REG_FL_VAR_LHS = 0x00008000,\n\n\t\t\t/* proc flags */\n\t\t\tMEM2REG_FL_EQ1 = 0x01000000,\n\t\t};\n\n\t\t// simplify() creates a simpler AST by unrolling for-loops, expanding generate blocks, etc.\n\t\t// it also sets the id2ast pointers so that identifier lookups are fast in genRTLIL()\n\t\tbool simplify(bool const_fold, int stage, int width_hint, bool sign_hint);\n\t\tvoid replace_result_wire_name_in_function(const std::string &from, const std::string &to);\n\t\tAstNode *readmem(bool is_readmemh, std::string mem_filename, AstNode *memory, int start_addr, int finish_addr, bool unconditional_init);\n\t\tvoid expand_genblock(const std::string &prefix);\n\t\tvoid label_genblks(std::set<std::string>& existing, int &counter);\n\t\tvoid mem2reg_as_needed_pass1(dict<AstNode*, pool<std::string>> &mem2reg_places,\n\t\t\t\tdict<AstNode*, uint32_t> &mem2reg_flags, dict<AstNode*, uint32_t> &proc_flags, uint32_t &status_flags);\n\t\tbool mem2reg_as_needed_pass2(pool<AstNode*> &mem2reg_set, AstNode *mod, AstNode *block, AstNode *&async_block);\n\t\tbool mem2reg_check(pool<AstNode*> &mem2reg_set);\n\t\tvoid mem2reg_remove(pool<AstNode*> &mem2reg_set, vector<AstNode*> &delnodes);\n\t\tvoid meminfo(int &mem_width, int &mem_size, int &addr_bits);\n\t\tbool detect_latch(const std::string &var);\n\t\tconst RTLIL::Module* lookup_cell_module();\n\n\t\t// additional functionality for evaluating constant functions\n\t\tstruct varinfo_t {\n\t\t\tRTLIL::Const val;\n\t\t\tint offset;\n\t\t\tbool range_swapped;\n\t\t\tbool is_signed;\n\t\t\tAstNode *arg = nullptr;\n\t\t\tbool explicitly_sized;\n\t\t};\n\t\tbool has_const_only_constructs();\n\t\tbool replace_variables(std::map<std::string, varinfo_t> &variables, AstNode *fcall, bool must_succeed);\n\t\tAstNode *eval_const_function(AstNode *fcall, bool must_succeed);\n\t\tbool is_simple_const_expr();\n\n\t\t// helper for parsing format strings\n\t\tFmt processFormat(int stage, bool sformat_like, int default_base = 10, size_t first_arg_at = 0, bool may_fail = false);\n\n\t\tbool is_recursive_function() const;\n\t\tstd::pair<AstNode*, AstNode*> get_tern_choice();\n\n\t\t// create a human-readable text representation of the AST (for debugging)\n\t\tvoid dumpAst(FILE *f, std::string indent) const;\n\t\tvoid dumpVlog(FILE *f, std::string indent) const;\n\n\t\t// Generate RTLIL for a bind construct\n\t\tstd::vector<RTLIL::Binding *> genBindings() const;\n\n\t\t// used by genRTLIL() for detecting expression width and sign\n\t\tvoid detectSignWidthWorker(int &width_hint, bool &sign_hint, bool *found_real = NULL);\n\t\tvoid detectSignWidth(int &width_hint, bool &sign_hint, bool *found_real = NULL);\n\n\t\t// create RTLIL code for this AST node\n\t\t// for expressions the resulting signal vector is returned\n\t\t// all generated cell instances, etc. are written to the RTLIL::Module pointed to by AST_INTERNAL::current_module\n\t\tRTLIL::SigSpec genRTLIL(int width_hint = -1, bool sign_hint = false);\n\t\tRTLIL::SigSpec genWidthRTLIL(int width, bool sgn, const dict<RTLIL::SigBit, RTLIL::SigBit> *new_subst_ptr = NULL);\n\n\t\t// compare AST nodes\n\t\tbool operator==(const AstNode &other) const;\n\t\tbool operator!=(const AstNode &other) const;\n\t\tbool contains(const AstNode *other) const;\n\n\t\t// helper functions for creating AST nodes for constants\n\t\tstatic AstNode *mkconst_int(uint32_t v, bool is_signed, int width = 32);\n\t\tstatic AstNode *mkconst_bits(const std::vector<RTLIL::State> &v, bool is_signed, bool is_unsized);\n\t\tstatic AstNode *mkconst_bits(const std::vector<RTLIL::State> &v, bool is_signed);\n\t\tstatic AstNode *mkconst_str(const std::vector<RTLIL::State> &v);\n\t\tstatic AstNode *mkconst_str(const std::string &str);\n\n\t\t// helper function to create an AST node for a temporary register\n\t\tAstNode *mktemp_logic(const std::string &name, AstNode *mod, bool nosync, int range_left, int range_right, bool is_signed);\n\n\t\t// helper function for creating sign-extended const objects\n\t\tRTLIL::Const bitsAsConst(int width, bool is_signed);\n\t\tRTLIL::Const bitsAsConst(int width = -1);\n\t\tRTLIL::Const bitsAsUnsizedConst(int width);\n\t\tRTLIL::Const asAttrConst() const;\n\t\tRTLIL::Const asParaConst() const;\n\t\tuint64_t asInt(bool is_signed);\n\t\tbool bits_only_01() const;\n\t\tbool asBool() const;\n\n\t\t// helper functions for real valued const eval\n\t\tint isConst() const; // return '1' for AST_CONSTANT and '2' for AST_REALVALUE\n\t\tdouble asReal(bool is_signed);\n\t\tRTLIL::Const realAsConst(int width);\n\n\t\t// helpers for enum\n\t\tvoid allocateDefaultEnumValues();\n\t\tvoid annotateTypedEnums(AstNode *template_node);\n\n\t\t// helpers for locations\n\t\tstd::string loc_string() const;\n\n\t\t// Helper for looking up identifiers which are prefixed with the current module name\n\t\tstd::string try_pop_module_prefix() const;\n\n\t\t// helper to clone the node with some of its subexpressions replaced with zero (this is used\n\t\t// to evaluate widths of dynamic ranges)\n\t\tAstNode *clone_at_zero();\n\n\t\tvoid set_attribute(RTLIL::IdString key, AstNode *node)\n\t\t{\n\t\t\tattributes[key] = node;\n\t\t\tnode->set_in_param_flag(true);\n\t\t}\n\n\t\t// helper to set in_lvalue/in_param flags from the hierarchy context (the actual flag\n\t\t// can be overridden based on the intrinsic properties of this node, i.e. based on its type)\n\t\tvoid set_in_lvalue_flag(bool flag, bool no_descend = false);\n\t\tvoid set_in_param_flag(bool flag, bool no_descend = false);\n\n\t\t// fix up the hierarchy flags (in_lvalue/in_param) of this node and its children\n\t\t//\n\t\t// to keep the flags in sync, fixup_hierarchy_flags(true) needs to be called once after\n\t\t// parsing the AST to walk the full tree, then plain fixup_hierarchy_flags() performs\n\t\t// localized fixups after modifying children/attributes of a particular node\n\t\tvoid fixup_hierarchy_flags(bool force_descend = false);\n\n\t\t// helpers for indexing\n\t\tAstNode *make_index_range(AstNode *node, bool unpacked_range = false);\n\t\tAstNode *get_struct_member() const;\n\n\t\t// helper to print errors from simplify/genrtlil code\n\t\t[[noreturn]] void input_error(const char *format, ...) const YS_ATTRIBUTE(format(printf, 2, 3));\n\t};\n\n\t// process an AST tree (ast must point to an AST_DESIGN node) and generate RTLIL code\n\tvoid process(RTLIL::Design *design, AstNode *ast, bool nodisplay, bool dump_ast1, bool dump_ast2, bool no_dump_ptr, bool dump_vlog1, bool dump_vlog2, bool dump_rtlil, bool nolatches, bool nomeminit,\n\t\t\tbool nomem2reg, bool mem2reg, bool noblackbox, bool lib, bool nowb, bool noopt, bool icells, bool pwires, bool nooverwrite, bool overwrite, bool defer, bool autowire);\n\n\t// parametric modules are supported directly by the AST library\n\t// therefore we need our own derivate of RTLIL::Module with overloaded virtual functions\n\tstruct AstModule : RTLIL::Module {\n\t\tAstNode *ast;\n\t\tbool nolatches, nomeminit, nomem2reg, mem2reg, noblackbox, lib, nowb, noopt, icells, pwires, autowire;\n\t\t~AstModule() override;\n\t\tRTLIL::IdString derive(RTLIL::Design *design, const dict<RTLIL::IdString, RTLIL::Const> &parameters, bool mayfail) override;\n\t\tRTLIL::IdString derive(RTLIL::Design *design, const dict<RTLIL::IdString, RTLIL::Const> &parameters, const dict<RTLIL::IdString, RTLIL::Module*> &interfaces, const dict<RTLIL::IdString, RTLIL::IdString> &modports, bool mayfail) override;\n\t\tstd::string derive_common(RTLIL::Design *design, const dict<RTLIL::IdString, RTLIL::Const> &parameters, AstNode **new_ast_out, bool quiet = false);\n\t\tvoid expand_interfaces(RTLIL::Design *design, const dict<RTLIL::IdString, RTLIL::Module *> &local_interfaces) override;\n\t\tbool reprocess_if_necessary(RTLIL::Design *design) override;\n\t\tRTLIL::Module *clone() const override;\n\t\tvoid loadconfig() const;\n\t};\n\n\t// this must be set by the language frontend before parsing the sources\n\t// the AstNode constructor then uses current_filename and get_line_num()\n\t// to initialize the filename and linenum properties of new nodes\n\textern std::string current_filename;\n\textern void (*set_line_num)(int);\n\textern int (*get_line_num)();\n\n\t// set set_line_num and get_line_num to internal dummy functions (done by simplify() and AstModule::derive\n\t// to control the filename and linenum properties of new nodes not generated by a frontend parser)\n\tvoid use_internal_line_num();\n\n\t// call a DPI function\n\tAstNode *dpi_call(const std::string &rtype, const std::string &fname, const std::vector<std::string> &argtypes, const std::vector<AstNode*> &args);\n\n\t// Helper functions related to handling SystemVerilog interfaces\n\tstd::pair<std::string,std::string> split_modport_from_type(std::string name_type);\n\tAstNode * find_modport(AstNode *intf, std::string name);\n\tvoid explode_interface_port(AstNode *module_ast, RTLIL::Module * intfmodule, std::string intfname, AstNode *modport);\n\n\t// Helper for setting the src attribute.\n\tvoid set_src_attr(RTLIL::AttrObject *obj, const AstNode *ast);\n\n\t// generate standard $paramod... derived module name; parameters should be\n\t// in the order they are declared in the instantiated module\n\tstd::string derived_module_name(std::string stripped_name, const std::vector<std::pair<RTLIL::IdString, RTLIL::Const>> &parameters);\n\n\t// used to provide simplify() access to the current design for looking up\n\t// modules, ports, wires, etc.\n\tvoid set_simplify_design_context(const RTLIL::Design *design);\n}\n\nnamespace AST_INTERNAL\n{\n\t// internal state variables\n\textern bool flag_nodisplay, flag_dump_ast1, flag_dump_ast2, flag_no_dump_ptr, flag_dump_rtlil, flag_nolatches, flag_nomeminit;\n\textern bool flag_nomem2reg, flag_mem2reg, flag_lib, flag_noopt, flag_icells, flag_pwires, flag_autowire;\n\textern AST::AstNode *current_ast, *current_ast_mod;\n\textern std::map<std::string, AST::AstNode*> current_scope;\n\textern const dict<RTLIL::SigBit, RTLIL::SigBit> *genRTLIL_subst_ptr;\n\textern RTLIL::SigSpec ignoreThisSignalsInInitial;\n\textern AST::AstNode *current_always, *current_top_block, *current_block, *current_block_child;\n\textern RTLIL::Module *current_module;\n\textern bool current_always_clocked;\n\textern dict<std::string, int> current_memwr_count;\n\textern dict<std::string, pool<int>> current_memwr_visible;\n\tstruct LookaheadRewriter;\n\tstruct ProcessGenerator;\n\n\t// Create and add a new AstModule from new_ast, then use it to replace\n\t// old_module in design, renaming old_module to move it out of the way.\n\t// Return the new module.\n\t//\n\t// If original_ast is not null, it will be used as the AST node for the\n\t// new module. Otherwise, new_ast will be used.\n\tRTLIL::Module *\n\tprocess_and_replace_module(RTLIL::Design *design,\n\t RTLIL::Module *old_module,\n\t AST::AstNode *new_ast,\n\t AST::AstNode *original_ast = nullptr);\n}\n\nYOSYS_NAMESPACE_END\n\n#endif\n",
151
151
  "ast_binding.h": "/* -*- c++ -*-\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 * ---\n *\n * This header declares the AST::Binding class\n *\n * This is used to support the bind directive and is to RTLIL::Binding as\n * AST::AstModule is to RTLIL::Module, holding a syntax-level representation of\n * cells until we get to a stage where they make sense. In the case of a bind\n * directive, this is when we elaborate the design in the hierarchy pass.\n *\n */\n\n#ifndef AST_BINDING_H\n#define AST_BINDING_H\n\n#include \"kernel/rtlil.h\"\n#include \"kernel/binding.h\"\n\n#include <memory>\n\nYOSYS_NAMESPACE_BEGIN\n\nnamespace AST\n{\n\tclass Binding : public RTLIL::Binding\n\t{\n\tpublic:\n\t\tBinding(RTLIL::IdString target_type,\n\t\t RTLIL::IdString target_name,\n\t\t const AstNode &cell);\n\n\t\tstd::string describe() const override;\n\n\tprivate:\n\t\t// The syntax-level representation of the cell to be bound.\n\t\tstd::unique_ptr<AstNode> ast_node;\n\t};\n}\n\nYOSYS_NAMESPACE_END\n\n#endif\n",
152
152
  },
153
153
  "blif": {
@@ -181,7 +181,7 @@ export const filesystem = {
181
181
  "timinginfo.h": "/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>\n * (C) 2020 Eddie Hung <eddie@fpgeh.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 */\n\n#ifndef TIMINGINFO_H\n#define TIMINGINFO_H\n\n#include \"kernel/yosys.h\"\n\nYOSYS_NAMESPACE_BEGIN\n\nstruct TimingInfo\n{\n\tstruct NameBit\n\t{\n\t\tRTLIL::IdString name;\n\t\tint offset;\n\t\tNameBit() : offset(0) {}\n\t\tNameBit(const RTLIL::IdString name, int offset) : name(name), offset(offset) {}\n\t\texplicit NameBit(const RTLIL::SigBit &b) : name(b.wire->name), offset(b.offset) {}\n\t\tbool operator==(const NameBit& nb) const { return nb.name == name && nb.offset == offset; }\n\t\tbool operator!=(const NameBit& nb) const { return !operator==(nb); }\n\t\tunsigned int hash() const { return mkhash_add(name.hash(), offset); }\n\t};\n\tstruct BitBit\n\t{\n\t\tNameBit first, second;\n\t\tBitBit(const NameBit &first, const NameBit &second) : first(first), second(second) {}\n\t\tBitBit(const SigBit &first, const SigBit &second) : first(first), second(second) {}\n\t\tbool operator==(const BitBit& bb) const { return bb.first == first && bb.second == second; }\n\t\tunsigned int hash() const { return mkhash_add(first.hash(), second.hash()); }\n\t};\n\n\tstruct ModuleTiming\n\t{\n\t\tdict<BitBit, int> comb;\n\t\tdict<NameBit, std::pair<int,NameBit>> arrival, required;\n\t\tbool has_inputs;\n\t};\n\n\tdict<RTLIL::IdString, ModuleTiming> data;\n\n\tTimingInfo()\n\t{\n\t}\n\n\tTimingInfo(RTLIL::Design *design)\n\t{\n\t\tsetup(design);\n\t}\n\n\tvoid setup(RTLIL::Design *design)\n\t{\n\t\tfor (auto module : design->modules()) {\n\t\t\tif (!module->get_blackbox_attribute())\n\t\t\t\tcontinue;\n\t\t\tsetup_module(module);\n\t\t}\n\t}\n\n\tconst ModuleTiming& setup_module(RTLIL::Module *module)\n\t{\n\t\tauto r = data.insert(module->name);\n\t\tlog_assert(r.second);\n\t\tauto &t = r.first->second;\n\n\t\tfor (auto cell : module->cells()) {\n\t\t\tif (cell->type == ID($specify2)) {\n\t\t\t\tauto en = cell->getPort(ID::EN);\n\t\t\t\tif (en.is_fully_const() && !en.as_bool())\n\t\t\t\t\tcontinue;\n\t\t\t\tauto src = cell->getPort(ID::SRC);\n\t\t\t\tauto dst = cell->getPort(ID::DST);\n\t\t\t\tfor (const auto &c : src.chunks())\n\t\t\t\t\tif (!c.wire || !c.wire->port_input)\n\t\t\t\t\t\tlog_error(\"Module '%s' contains specify cell '%s' where SRC '%s' is not a module input.\\n\", log_id(module), log_id(cell), log_signal(src));\n\t\t\t\tfor (const auto &c : dst.chunks())\n\t\t\t\t\tif (!c.wire || !c.wire->port_output)\n\t\t\t\t\t\tlog_error(\"Module '%s' contains specify cell '%s' where DST '%s' is not a module output.\\n\", log_id(module), log_id(cell), log_signal(dst));\n\t\t\t\tint rise_max = cell->getParam(ID::T_RISE_MAX).as_int();\n\t\t\t\tint fall_max = cell->getParam(ID::T_FALL_MAX).as_int();\n\t\t\t\tint max = std::max(rise_max,fall_max);\n\t\t\t\tif (max < 0)\n\t\t\t\t\tlog_error(\"Module '%s' contains specify cell '%s' with T_{RISE,FALL}_MAX < 0.\\n\", log_id(module), log_id(cell));\n\t\t\t\tif (cell->getParam(ID::FULL).as_bool()) {\n\t\t\t\t\tfor (const auto &s : src)\n\t\t\t\t\t\tfor (const auto &d : dst) {\n\t\t\t\t\t\t\tauto r = t.comb.insert(BitBit(s,d));\n\t\t\t\t\t\t\tif (!r.second)\n\t\t\t\t\t\t\t\tlog_error(\"Module '%s' contains multiple specify cells for SRC '%s' and DST '%s'.\\n\", log_id(module), log_signal(s), log_signal(d));\n\t\t\t\t\t\t\tr.first->second = max;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlog_assert(GetSize(src) == GetSize(dst));\n\t\t\t\t\tfor (auto i = 0; i < GetSize(src); i++) {\n\t\t\t\t\t\tconst auto &s = src[i];\n\t\t\t\t\t\tconst auto &d = dst[i];\n\t\t\t\t\t\tauto r = t.comb.insert(BitBit(s,d));\n\t\t\t\t\t\tif (!r.second)\n\t\t\t\t\t\t\tlog_error(\"Module '%s' contains multiple specify cells for SRC '%s' and DST '%s'.\\n\", log_id(module), log_signal(s), log_signal(d));\n\t\t\t\t\t\tr.first->second = max;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cell->type == ID($specify3)) {\n\t\t\t\tauto src = cell->getPort(ID::SRC).as_bit();\n\t\t\t\tauto dst = cell->getPort(ID::DST);\n\t\t\t\tif (!src.wire || !src.wire->port_input)\n\t\t\t\t\tlog_error(\"Module '%s' contains specify cell '%s' where SRC '%s' is not a module input.\\n\", log_id(module), log_id(cell), log_signal(src));\n\t\t\t\tfor (const auto &c : dst.chunks())\n\t\t\t\t\tif (!c.wire->port_output)\n\t\t\t\t\t\tlog_error(\"Module '%s' contains specify cell '%s' where DST '%s' is not a module output.\\n\", log_id(module), log_id(cell), log_signal(dst));\n\t\t\t\tint rise_max = cell->getParam(ID::T_RISE_MAX).as_int();\n\t\t\t\tint fall_max = cell->getParam(ID::T_FALL_MAX).as_int();\n\t\t\t\tint max = std::max(rise_max,fall_max);\n\t\t\t\tif (max < 0) {\n\t\t\t\t\tlog_warning(\"Module '%s' contains specify cell '%s' with T_{RISE,FALL}_MAX < 0 which is currently unsupported. Clamping to 0.\\n\", log_id(module), log_id(cell));\n\t\t\t\t\tmax = 0;\n\t\t\t\t}\n\t\t\t\tfor (const auto &d : dst) {\n\t\t\t\t\tauto r = t.arrival.insert(NameBit(d));\n\t\t\t\t\tauto &v = r.first->second;\n\t\t\t\t\tif (r.second || v.first < max) {\n\t\t\t\t\t\tv.first = max;\n\t\t\t\t\t\tv.second = NameBit(src);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cell->type == ID($specrule)) {\n\t\t\t\tIdString type = cell->getParam(ID::TYPE).decode_string();\n\t\t\t\tif (type != ID($setup) && type != ID($setuphold))\n\t\t\t\t\tcontinue;\n\t\t\t\tauto src = cell->getPort(ID::SRC);\n\t\t\t\tauto dst = cell->getPort(ID::DST).as_bit();\n\t\t\t\tfor (const auto &c : src.chunks())\n\t\t\t\t\tif (!c.wire || !c.wire->port_input)\n\t\t\t\t\t\tlog_error(\"Module '%s' contains specify cell '%s' where SRC '%s' is not a module input.\\n\", log_id(module), log_id(cell), log_signal(src));\n\t\t\t\tif (!dst.wire || !dst.wire->port_input)\n\t\t\t\t\tlog_error(\"Module '%s' contains specify cell '%s' where DST '%s' is not a module input.\\n\", log_id(module), log_id(cell), log_signal(dst));\n\t\t\t\tint max = cell->getParam(ID::T_LIMIT_MAX).as_int();\n\t\t\t\tif (max < 0) {\n\t\t\t\t\tlog_warning(\"Module '%s' contains specify cell '%s' with T_LIMIT_MAX < 0 which is currently unsupported. Clamping to 0.\\n\", log_id(module), log_id(cell));\n\t\t\t\t\tmax = 0;\n\t\t\t\t}\n\t\t\t\tfor (const auto &s : src) {\n\t\t\t\t\tauto r = t.required.insert(NameBit(s));\n\t\t\t\t\tauto &v = r.first->second;\n\t\t\t\t\tif (r.second || v.first < max) {\n\t\t\t\t\t\tv.first = max;\n\t\t\t\t\t\tv.second = NameBit(dst);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (auto port_name : module->ports) {\n\t\t\tauto wire = module->wire(port_name);\n\t\t\tif (wire->port_input) {\n\t\t\t\tt.has_inputs = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn t;\n\t}\n\n\tdecltype(data)::const_iterator find(RTLIL::IdString module_name) const { return data.find(module_name); }\n\tdecltype(data)::const_iterator end() const { return data.end(); }\n\tint count(RTLIL::IdString module_name) const { return data.count(module_name); }\n\tconst ModuleTiming& at(RTLIL::IdString module_name) const { return data.at(module_name); }\n};\n\nYOSYS_NAMESPACE_END\n\n#endif\n",
182
182
  "utils.h": "/*\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 */\n\n// This file contains various c++ utility routines and helper classes that\n// do not depend on any other components of yosys (except stuff like log_*).\n\n#include \"kernel/yosys.h\"\n\n#ifndef UTILS_H\n#define UTILS_H\n\nYOSYS_NAMESPACE_BEGIN\n\n// ------------------------------------------------\n// A map-like container, but you can save and restore the state\n// ------------------------------------------------\n\ntemplate<typename Key, typename T, typename OPS = hash_ops<Key>>\nstruct stackmap\n{\nprivate:\n\tstd::vector<dict<Key, T*, OPS>> backup_state;\n\tdict<Key, T, OPS> current_state;\n\tstatic T empty_tuple;\n\npublic:\n\tstackmap() { }\n\tstackmap(const dict<Key, T, OPS> &other) : current_state(other) { }\n\n\ttemplate<typename Other>\n\tvoid operator=(const Other &other)\n\t{\n\t\tfor (auto &it : current_state)\n\t\t\tif (!backup_state.empty() && backup_state.back().count(it.first) == 0)\n\t\t\t\tbackup_state.back()[it.first] = new T(it.second);\n\t\tcurrent_state.clear();\n\n\t\tfor (auto &it : other)\n\t\t\tset(it.first, it.second);\n\t}\n\n\tbool has(const Key &k)\n\t{\n\t\treturn current_state.count(k) != 0;\n\t}\n\n\tvoid set(const Key &k, const T &v)\n\t{\n\t\tif (!backup_state.empty() && backup_state.back().count(k) == 0)\n\t\t\tbackup_state.back()[k] = current_state.count(k) ? new T(current_state.at(k)) : nullptr;\n\t\tcurrent_state[k] = v;\n\t}\n\n\tvoid unset(const Key &k)\n\t{\n\t\tif (!backup_state.empty() && backup_state.back().count(k) == 0)\n\t\t\tbackup_state.back()[k] = current_state.count(k) ? new T(current_state.at(k)) : nullptr;\n\t\tcurrent_state.erase(k);\n\t}\n\n\tconst T &get(const Key &k)\n\t{\n\t\tif (current_state.count(k) == 0)\n\t\t\treturn empty_tuple;\n\t\treturn current_state.at(k);\n\t}\n\n\tvoid reset(const Key &k)\n\t{\n\t\tfor (int i = GetSize(backup_state)-1; i >= 0; i--)\n\t\t\tif (backup_state[i].count(k) != 0) {\n\t\t\t\tif (backup_state[i].at(k) == nullptr)\n\t\t\t\t\tcurrent_state.erase(k);\n\t\t\t\telse\n\t\t\t\t\tcurrent_state[k] = *backup_state[i].at(k);\n\t\t\t\treturn;\n\t\t\t}\n\t\tcurrent_state.erase(k);\n\t}\n\n\tconst dict<Key, T, OPS> &stdmap()\n\t{\n\t\treturn current_state;\n\t}\n\n\tvoid save()\n\t{\n\t\tbackup_state.resize(backup_state.size()+1);\n\t}\n\n\tvoid restore()\n\t{\n\t\tlog_assert(!backup_state.empty());\n\t\tfor (auto &it : backup_state.back())\n\t\t\tif (it.second != nullptr) {\n\t\t\t\tcurrent_state[it.first] = *it.second;\n\t\t\t\tdelete it.second;\n\t\t\t} else\n\t\t\t\tcurrent_state.erase(it.first);\n\t\tbackup_state.pop_back();\n\t}\n\n\t~stackmap()\n\t{\n\t\twhile (!backup_state.empty())\n\t\t\trestore();\n\t}\n};\n\n\n// ------------------------------------------------\n// A simple class for topological sorting\n// ------------------------------------------------\n\ntemplate <typename T, typename C = std::less<T>, typename OPS = hash_ops<T>> class TopoSort\n{\n public:\n\t// We use this ordering of the edges in the adjacency matrix for\n\t// exact compatibility with an older implementation.\n\tstruct IndirectCmp {\n IndirectCmp(const std::vector<T> &nodes) : node_cmp_(), nodes_(nodes) {}\n\t\tbool operator()(int a, int b) const\n\t\t{\n log_assert(static_cast<size_t>(a) < nodes_.size());\n\t\t\tlog_assert(static_cast<size_t>(b) < nodes_.size());\n\t\t\treturn node_cmp_(nodes_[a], nodes_[b]);\n\t\t}\n\t\tconst C node_cmp_;\n\t\tconst std::vector<T> &nodes_;\n\t};\n\n\tbool analyze_loops;\n\tstd::map<T, int, C> node_to_index;\n\tstd::vector<std::set<int, IndirectCmp>> edges;\n\tstd::vector<T> sorted;\n\tstd::set<std::vector<T>> loops;\n\n\tTopoSort() : indirect_cmp(nodes)\n\t{\n\t\tanalyze_loops = true;\n\t\tfound_loops = false;\n\t}\n\n\tint node(T n)\n\t{\n auto rv = node_to_index.emplace(n, static_cast<int>(nodes.size()));\n if (rv.second) {\n \t nodes.push_back(n);\n\t\t edges.push_back(std::set<int, IndirectCmp>(indirect_cmp));\n\t\t}\n\t\treturn rv.first->second;\n\t}\n\n\tvoid edge(int l_index, int r_index) { edges[r_index].insert(l_index); }\n\n\tvoid edge(T left, T right) { edge(node(left), node(right)); }\n\n\tbool has_node(const T &node) { return node_to_index.find(node) != node_to_index.end(); }\n\n\tbool sort()\n\t{\n\t\tlog_assert(GetSize(node_to_index) == GetSize(edges));\n\t\tlog_assert(GetSize(nodes) == GetSize(edges));\n\n\t\tloops.clear();\n\t\tsorted.clear();\n\t\tfound_loops = false;\n\n\t\tstd::vector<bool> marked_cells(edges.size(), false);\n\t\tstd::vector<bool> active_cells(edges.size(), false);\n\t\tstd::vector<int> active_stack;\n\t\tsorted.reserve(edges.size());\n\n\t\tfor (const auto &it : node_to_index)\n\t\t\tsort_worker(it.second, marked_cells, active_cells, active_stack);\n\n\t\tlog_assert(GetSize(sorted) == GetSize(nodes));\n\n\t\treturn !found_loops;\n\t}\n\n\t// Build the more expensive representation of edges for\n\t// a few passes that use it directly.\n\tstd::map<T, std::set<T, C>, C> get_database()\n\t{\n\t\tstd::map<T, std::set<T, C>, C> database;\n\t\tfor (size_t i = 0; i < nodes.size(); ++i) {\n\t\t\tstd::set<T, C> converted_edge_set;\n\t\t\tfor (int other_node : edges[i]) {\n\t\t\t\tconverted_edge_set.insert(nodes[other_node]);\n\t\t\t}\n\t\t\tdatabase.emplace(nodes[i], converted_edge_set);\n\t\t}\n\t\treturn database;\n\t}\n\n private:\n\tbool found_loops;\n\tstd::vector<T> nodes;\n\tconst IndirectCmp indirect_cmp;\n\n\tvoid sort_worker(const int root_index, std::vector<bool> &marked_cells, std::vector<bool> &active_cells, std::vector<int> &active_stack)\n\t{\n\t\tif (active_cells[root_index]) {\n\t\t\tfound_loops = true;\n\t\t\tif (analyze_loops) {\n\t\t\t\tstd::vector<T> loop;\n\t\t\t\tfor (int i = GetSize(active_stack) - 1; i >= 0; i--) {\n\t\t\t\t\tconst int index = active_stack[i];\n\t\t\t\t\tloop.push_back(nodes[index]);\n\t\t\t\t\tif (index == root_index)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tloops.insert(loop);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (marked_cells[root_index])\n\t\t\treturn;\n\n\t\tif (!edges[root_index].empty()) {\n\t\t\tif (analyze_loops)\n\t\t\t\tactive_stack.push_back(root_index);\n\t\t\tactive_cells[root_index] = true;\n\n\t\t\tfor (int left_n : edges[root_index])\n\t\t\t\tsort_worker(left_n, marked_cells, active_cells, active_stack);\n\n\t\t\tif (analyze_loops)\n\t\t\t\tactive_stack.pop_back();\n\t\t\tactive_cells[root_index] = false;\n\t\t}\n\n\t\tmarked_cells[root_index] = true;\n\t\tsorted.push_back(nodes[root_index]);\n\t}\n};\n\nYOSYS_NAMESPACE_END\n\n#endif\n",
183
183
  "yosys.h": "/* -*- c++ -*-\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 */\n\n\n// *** NOTE TO THE READER ***\n//\n// Maybe you have just opened this file in the hope to learn more about the\n// Yosys API. Let me congratulate you on this great decision! ;)\n//\n// If you want to know how the design is represented by Yosys in the memory,\n// you should read \"kernel/rtlil.h\".\n//\n// If you want to know how to register a command with Yosys, you could read\n// \"kernel/register.h\", but it would be easier to just look at a simple\n// example instead. A simple one would be \"passes/cmds/log.cc\".\n//\n// This header is very boring. It just defines some general things that\n// belong nowhere else and includes the interesting headers.\n//\n// Find more information in the \"guidelines/GettingStarted\" file.\n\n\n#ifndef YOSYS_H\n#define YOSYS_H\n\n#include \"kernel/yosys_common.h\"\n\n#include \"kernel/log.h\"\n#include \"kernel/rtlil.h\"\n#include \"kernel/register.h\"\n\nYOSYS_NAMESPACE_BEGIN\n\nvoid yosys_setup();\n\n#ifdef WITH_PYTHON\nbool yosys_already_setup();\n#endif\n\nvoid yosys_shutdown();\n\n#ifdef YOSYS_ENABLE_TCL\nTcl_Interp *yosys_get_tcl_interp();\n#endif\n\nextern RTLIL::Design *yosys_design;\n\nRTLIL::Design *yosys_get_design();\nstd::string proc_self_dirname();\nstd::string proc_share_dirname();\nstd::string proc_program_prefix();\nconst char *create_prompt(RTLIL::Design *design, int recursion_counter);\nstd::vector<std::string> glob_filename(const std::string &filename_pattern);\nvoid rewrite_filename(std::string &filename);\n\nvoid run_pass(std::string command, RTLIL::Design *design = nullptr);\nbool run_frontend(std::string filename, std::string command, RTLIL::Design *design = nullptr, std::string *from_to_label = nullptr);\nvoid run_backend(std::string filename, std::string command, RTLIL::Design *design = nullptr);\nvoid shell(RTLIL::Design *design);\n\n// journal of all input and output files read (for \"yosys -E\")\nextern std::set<std::string> yosys_input_files, yosys_output_files;\n\n// from kernel/version_*.o (cc source generated from Makefile)\nextern const char *yosys_version_str;\n\n// from passes/cmds/design.cc\nextern std::map<std::string, RTLIL::Design*> saved_designs;\nextern std::vector<RTLIL::Design*> pushed_designs;\n\n// from passes/cmds/pluginc.cc\nextern std::map<std::string, void*> loaded_plugins;\n#ifdef WITH_PYTHON\nextern std::map<std::string, void*> loaded_python_plugins;\n#endif\nextern std::map<std::string, std::string> loaded_plugin_aliases;\nvoid load_plugin(std::string filename, std::vector<std::string> aliases);\n\nextern std::string yosys_share_dirname;\nextern std::string yosys_abc_executable;\n\nYOSYS_NAMESPACE_END\n\n#endif\n",
184
- "yosys_common.h": "/* -*- c++ -*-\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 */\n\n#ifndef YOSYS_COMMON_H\n#define YOSYS_COMMON_H\n\n#include <map>\n#include <set>\n#include <tuple>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <functional>\n#include <unordered_map>\n#include <unordered_set>\n#include <initializer_list>\n#include <stdexcept>\n#include <memory>\n#include <cmath>\n#include <cstddef>\n\n#include <sstream>\n#include <fstream>\n#include <istream>\n#include <ostream>\n#include <iostream>\n\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <limits.h>\n#include <sys/stat.h>\n#include <errno.h>\n\n#ifdef WITH_PYTHON\n#include <Python.h>\n#endif\n\n#ifndef _YOSYS_\n# error It looks like you are trying to build Yosys without the config defines set. \\\n When building Yosys with a custom make system, make sure you set all the \\\n defines the Yosys Makefile would set for your build configuration.\n#endif\n\n#ifdef YOSYS_ENABLE_TCL\n# include <tcl.h>\n# ifdef YOSYS_MXE_HACKS\nextern Tcl_Command Tcl_CreateCommand(Tcl_Interp *interp, const char *cmdName, Tcl_CmdProc *proc, ClientData clientData, Tcl_CmdDeleteProc *deleteProc);\nextern Tcl_Interp *Tcl_CreateInterp(void);\nextern void Tcl_Preserve(ClientData data);\nextern void Tcl_Release(ClientData clientData);\nextern int Tcl_InterpDeleted(Tcl_Interp *interp);\nextern void Tcl_DeleteInterp(Tcl_Interp *interp);\nextern int Tcl_Eval(Tcl_Interp *interp, const char *script);\nextern int Tcl_EvalFile(Tcl_Interp *interp, const char *fileName);\nextern void Tcl_Finalize(void);\nextern int Tcl_GetCommandInfo(Tcl_Interp *interp, const char *cmdName, Tcl_CmdInfo *infoPtr);\nextern const char *Tcl_GetStringResult(Tcl_Interp *interp);\nextern Tcl_Obj *Tcl_NewStringObj(const char *bytes, int length);\nextern Tcl_Obj *Tcl_NewIntObj(int intValue);\nextern Tcl_Obj *Tcl_NewListObj(int objc, Tcl_Obj *const objv[]);\nextern Tcl_Obj *Tcl_ObjSetVar2(Tcl_Interp *interp, Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr, Tcl_Obj *newValuePtr, int flags);\n# endif\n# undef CONST\n# undef INLINE\n#endif\n\n#ifdef _WIN32\n# undef NOMINMAX\n# define NOMINMAX 1\n# undef YY_NO_UNISTD_H\n# define YY_NO_UNISTD_H 1\n\n# include <windows.h>\n# include <io.h>\n# include <direct.h>\n\n# define strtok_r strtok_s\n# define strdup _strdup\n# define snprintf _snprintf\n# define getcwd _getcwd\n# define mkdir _mkdir\n# define popen _popen\n# define pclose _pclose\n\n# ifndef __MINGW32__\n# define PATH_MAX MAX_PATH\n# define isatty _isatty\n# define fileno _fileno\n# endif\n\n// The following defines conflict with our identifiers:\n# undef CONST\n// `wingdi.h` defines a TRANSPARENT macro that conflicts with X(TRANSPARENT) entry in kernel/constids.inc\n# undef TRANSPARENT\n#endif\n\n#ifndef PATH_MAX\n# define PATH_MAX 4096\n#endif\n\n\n#define YOSYS_NAMESPACE Yosys\n#define PRIVATE_NAMESPACE_BEGIN namespace {\n#define PRIVATE_NAMESPACE_END }\n#define YOSYS_NAMESPACE_BEGIN namespace Yosys {\n#define YOSYS_NAMESPACE_END }\n#define YOSYS_NAMESPACE_PREFIX Yosys::\n#define USING_YOSYS_NAMESPACE using namespace Yosys;\n\n#if defined(__GNUC__) || defined(__clang__)\n# define YS_ATTRIBUTE(...) __attribute__((__VA_ARGS__))\n#elif defined(_MSC_VER)\n# define YS_ATTRIBUTE(...)\n#else\n# define YS_ATTRIBUTE(...)\n#endif\n\n#if defined(__GNUC__) || defined(__clang__)\n# define YS_MAYBE_UNUSED __attribute__((__unused__))\n#else\n# define YS_MAYBE_UNUSED\n#endif\n\n#if __cplusplus >= 201703L\n# define YS_FALLTHROUGH [[fallthrough]];\n#elif defined(__clang__)\n# define YS_FALLTHROUGH [[clang::fallthrough]];\n#elif defined(__GNUC__)\n# define YS_FALLTHROUGH [[gnu::fallthrough]];\n#else\n# define YS_FALLTHROUGH\n#endif\n\n\nYOSYS_NAMESPACE_BEGIN\n\n// Note: All headers included in hashlib.h must be included\n// outside of YOSYS_NAMESPACE before this or bad things will happen.\n#ifdef HASHLIB_H\n# undef HASHLIB_H\n# include \"kernel/hashlib.h\"\n#else\n# include \"kernel/hashlib.h\"\n# undef HASHLIB_H\n#endif\n\n\nusing std::vector;\nusing std::string;\nusing std::tuple;\nusing std::pair;\n\nusing std::make_tuple;\nusing std::make_pair;\nusing std::get;\nusing std::min;\nusing std::max;\n\n// A primitive shared string implementation that does not\n// move its .c_str() when the object is copied or moved.\nstruct shared_str {\n\tstd::shared_ptr<string> content;\n\tshared_str() { }\n\tshared_str(string s) { content = std::shared_ptr<string>(new string(s)); }\n\tshared_str(const char *s) { content = std::shared_ptr<string>(new string(s)); }\n\tconst char *c_str() const { return content->c_str(); }\n\tconst string &str() const { return *content; }\n\tbool operator==(const shared_str &other) const { return *content == *other.content; }\n\tunsigned int hash() const { return hashlib::hash_ops<std::string>::hash(*content); }\n};\n\nusing hashlib::mkhash;\nusing hashlib::mkhash_init;\nusing hashlib::mkhash_add;\nusing hashlib::mkhash_xorshift;\nusing hashlib::hash_ops;\nusing hashlib::hash_cstr_ops;\nusing hashlib::hash_ptr_ops;\nusing hashlib::hash_obj_ops;\nusing hashlib::dict;\nusing hashlib::idict;\nusing hashlib::pool;\nusing hashlib::mfp;\n\nnamespace RTLIL {\n\tstruct IdString;\n\tstruct Const;\n\tstruct SigBit;\n\tstruct SigSpec;\n\tstruct Wire;\n\tstruct Cell;\n\tstruct Memory;\n\tstruct Process;\n\tstruct Module;\n\tstruct Design;\n\tstruct Monitor;\n struct Selection;\n\tstruct SigChunk;\n\tenum State : unsigned char;\n\n\ttypedef std::pair<SigSpec, SigSpec> SigSig;\n\n namespace ID {}\n}\n\nnamespace AST {\n\tstruct AstNode;\n}\n\nusing RTLIL::IdString;\nusing RTLIL::Const;\nusing RTLIL::SigBit;\nusing RTLIL::SigSpec;\nusing RTLIL::Wire;\nusing RTLIL::Cell;\nusing RTLIL::Module;\nusing RTLIL::Design;\n\nusing RTLIL::State;\nusing RTLIL::SigChunk;\nusing RTLIL::SigSig;\n\nnamespace hashlib {\n\ttemplate<> struct hash_ops<RTLIL::Wire*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Cell*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Memory*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Process*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Module*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Design*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Monitor*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<AST::AstNode*> : hash_obj_ops {};\n\n\ttemplate<> struct hash_ops<const RTLIL::Wire*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Cell*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Memory*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Process*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Module*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Design*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Monitor*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const AST::AstNode*> : hash_obj_ops {};\n}\n\nvoid memhasher_on();\nvoid memhasher_off();\nvoid memhasher_do();\n\nextern bool memhasher_active;\ninline void memhasher() { if (memhasher_active) memhasher_do(); }\n\nvoid yosys_banner();\nint ceil_log2(int x) YS_ATTRIBUTE(const);\n\ninline std::string vstringf(const char *fmt, va_list ap)\n{\n // For the common case of strings shorter than 128, save a heap\n // allocation by using a stack allocated buffer.\n const int kBufSize = 128;\n char buf[kBufSize];\n buf[0] = '\\0';\n va_list apc;\n va_copy(apc, ap);\n int n = vsnprintf(buf, kBufSize, fmt, apc);\n va_end(apc);\n if (n < kBufSize)\n return std::string(buf);\n\n std::string string;\n char *str = NULL;\n#if defined(_WIN32 )|| defined(__CYGWIN__)\n int sz = 2 * kBufSize, rc;\n while (1) {\n\t\tva_copy(apc, ap);\n\t\tstr = (char*)realloc(str, sz);\n\t\trc = vsnprintf(str, sz, fmt, apc);\n\t\tva_end(apc);\n\t\tif (rc >= 0 && rc < sz)\n\t\t\tbreak;\n\t\tsz *= 2;\n\t}\n\tif (str != NULL) {\n\t\tstring = str;\n\t\tfree(str);\n\t}\n\treturn string;\n#else\n if (vasprintf(&str, fmt, ap) < 0)\n str = NULL;\n if (str != NULL) {\n string = str;\n free(str);\n }\n\treturn string;\n#endif\n}\n\nstd::string stringf(const char *fmt, ...) YS_ATTRIBUTE(format(printf, 1, 2));\n\ninline std::string stringf(const char *fmt, ...)\n{\n\tstd::string string;\n\tva_list ap;\n\n\tva_start(ap, fmt);\n\tstring = vstringf(fmt, ap);\n\tva_end(ap);\n\n\treturn string;\n}\n\nint readsome(std::istream &f, char *s, int n);\nstd::string next_token(std::string &text, const char *sep = \" \\t\\r\\n\", bool long_strings = false);\nstd::vector<std::string> split_tokens(const std::string &text, const char *sep = \" \\t\\r\\n\");\nbool patmatch(const char *pattern, const char *string);\n#if !defined(YOSYS_DISABLE_SPAWN)\nint run_command(const std::string &command, std::function<void(const std::string&)> process_line = std::function<void(const std::string&)>());\n#endif\nstd::string get_base_tmpdir();\nstd::string make_temp_file(std::string template_str = get_base_tmpdir() + \"/yosys_XXXXXX\");\nstd::string make_temp_dir(std::string template_str = get_base_tmpdir() + \"/yosys_XXXXXX\");\nbool check_file_exists(std::string filename, bool is_exec = false);\nbool check_directory_exists(const std::string& dirname);\nbool is_absolute_path(std::string filename);\nvoid remove_directory(std::string dirname);\nbool create_directory(const std::string& dirname);\nstd::string escape_filename_spaces(const std::string& filename);\n\ntemplate<typename T> int GetSize(const T &obj) { return obj.size(); }\ninline int GetSize(RTLIL::Wire *wire);\n\nextern int autoidx;\nextern int yosys_xtrace;\n\nRTLIL::IdString new_id(std::string file, int line, std::string func);\nRTLIL::IdString new_id_suffix(std::string file, int line, std::string func, std::string suffix);\n\n#define NEW_ID \\\n\tYOSYS_NAMESPACE_PREFIX new_id(__FILE__, __LINE__, __FUNCTION__)\n#define NEW_ID_SUFFIX(suffix) \\\n\tYOSYS_NAMESPACE_PREFIX new_id_suffix(__FILE__, __LINE__, __FUNCTION__, suffix)\n\n// Create a statically allocated IdString object, using for example ID::A or ID($add).\n//\n// Recipe for Converting old code that is using conversion of strings like ID::A and\n// \"$add\" for creating IdStrings: Run below SED command on the .cc file and then use for\n// example \"meld foo.cc foo.cc.orig\" to manually compile errors, if necessary.\n//\n// sed -i.orig -r 's/\"\\\\\\\\([a-zA-Z0-9_]+)\"/ID(\\1)/g; s/\"(\\$[a-zA-Z0-9_]+)\"/ID(\\1)/g;' <filename>\n//\n#define ID(_id) ([]() { const char *p = \"\\\\\" #_id, *q = p[1] == '$' ? p+1 : p; \\\n static const YOSYS_NAMESPACE_PREFIX RTLIL::IdString id(q); return id; })()\nnamespace ID = RTLIL::ID;\n\nnamespace hashlib {\n\ttemplate<> struct hash_ops<RTLIL::State> : hash_ops<int> {};\n}\n\n\nYOSYS_NAMESPACE_END\n\n#endif\n",
184
+ "yosys_common.h": "/* -*- c++ -*-\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 */\n\n#ifndef YOSYS_COMMON_H\n#define YOSYS_COMMON_H\n\n#include <map>\n#include <set>\n#include <tuple>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <functional>\n#include <unordered_map>\n#include <unordered_set>\n#include <initializer_list>\n#include <stdexcept>\n#include <memory>\n#include <cmath>\n#include <cstddef>\n\n#include <sstream>\n#include <fstream>\n#include <istream>\n#include <ostream>\n#include <iostream>\n\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <limits.h>\n#include <sys/stat.h>\n#include <errno.h>\n\n#ifdef WITH_PYTHON\n#include <Python.h>\n#endif\n\n#ifndef _YOSYS_\n# error It looks like you are trying to build Yosys without the config defines set. \\\n When building Yosys with a custom make system, make sure you set all the \\\n defines the Yosys Makefile would set for your build configuration.\n#endif\n\n#ifdef YOSYS_ENABLE_TCL\n# include <tcl.h>\n# ifdef YOSYS_MXE_HACKS\nextern Tcl_Command Tcl_CreateCommand(Tcl_Interp *interp, const char *cmdName, Tcl_CmdProc *proc, ClientData clientData, Tcl_CmdDeleteProc *deleteProc);\nextern Tcl_Interp *Tcl_CreateInterp(void);\nextern void Tcl_Preserve(ClientData data);\nextern void Tcl_Release(ClientData clientData);\nextern int Tcl_InterpDeleted(Tcl_Interp *interp);\nextern void Tcl_DeleteInterp(Tcl_Interp *interp);\nextern int Tcl_Eval(Tcl_Interp *interp, const char *script);\nextern int Tcl_EvalFile(Tcl_Interp *interp, const char *fileName);\nextern void Tcl_Finalize(void);\nextern int Tcl_GetCommandInfo(Tcl_Interp *interp, const char *cmdName, Tcl_CmdInfo *infoPtr);\nextern const char *Tcl_GetStringResult(Tcl_Interp *interp);\nextern Tcl_Obj *Tcl_NewStringObj(const char *bytes, int length);\nextern Tcl_Obj *Tcl_NewIntObj(int intValue);\nextern Tcl_Obj *Tcl_NewListObj(int objc, Tcl_Obj *const objv[]);\nextern Tcl_Obj *Tcl_ObjSetVar2(Tcl_Interp *interp, Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr, Tcl_Obj *newValuePtr, int flags);\n# endif\n# undef CONST\n# undef INLINE\n#endif\n\n#ifdef _WIN32\n# undef NOMINMAX\n# define NOMINMAX 1\n# undef YY_NO_UNISTD_H\n# define YY_NO_UNISTD_H 1\n\n# include <windows.h>\n# include <io.h>\n# include <direct.h>\n\n# define strtok_r strtok_s\n# define strdup _strdup\n# define snprintf _snprintf\n# define getcwd _getcwd\n# define mkdir _mkdir\n# define popen _popen\n# define pclose _pclose\n\n# ifndef __MINGW32__\n# define PATH_MAX MAX_PATH\n# define isatty _isatty\n# define fileno _fileno\n# endif\n\n// The following defines conflict with our identifiers:\n# undef CONST\n// `wingdi.h` defines a TRANSPARENT macro that conflicts with X(TRANSPARENT) entry in kernel/constids.inc\n# undef TRANSPARENT\n#endif\n\n#ifndef PATH_MAX\n# define PATH_MAX 4096\n#endif\n\n\n#define YOSYS_NAMESPACE Yosys\n#define PRIVATE_NAMESPACE_BEGIN namespace {\n#define PRIVATE_NAMESPACE_END }\n#define YOSYS_NAMESPACE_BEGIN namespace Yosys {\n#define YOSYS_NAMESPACE_END }\n#define YOSYS_NAMESPACE_PREFIX Yosys::\n#define USING_YOSYS_NAMESPACE using namespace Yosys;\n\n#if defined(__GNUC__) || defined(__clang__)\n# define YS_ATTRIBUTE(...) __attribute__((__VA_ARGS__))\n#elif defined(_MSC_VER)\n# define YS_ATTRIBUTE(...)\n#else\n# define YS_ATTRIBUTE(...)\n#endif\n\n#if defined(__GNUC__) || defined(__clang__)\n# define YS_MAYBE_UNUSED __attribute__((__unused__))\n#else\n# define YS_MAYBE_UNUSED\n#endif\n\n#if __cplusplus >= 201703L\n# define YS_FALLTHROUGH [[fallthrough]];\n#else\n# error \"C++17 or later compatible compiler is required\"\n#endif\n\n\nYOSYS_NAMESPACE_BEGIN\n\n// Note: All headers included in hashlib.h must be included\n// outside of YOSYS_NAMESPACE before this or bad things will happen.\n#ifdef HASHLIB_H\n# undef HASHLIB_H\n# include \"kernel/hashlib.h\"\n#else\n# include \"kernel/hashlib.h\"\n# undef HASHLIB_H\n#endif\n\n\nusing std::vector;\nusing std::string;\nusing std::tuple;\nusing std::pair;\n\nusing std::make_tuple;\nusing std::make_pair;\nusing std::get;\nusing std::min;\nusing std::max;\n\n// A primitive shared string implementation that does not\n// move its .c_str() when the object is copied or moved.\nstruct shared_str {\n\tstd::shared_ptr<string> content;\n\tshared_str() { }\n\tshared_str(string s) { content = std::shared_ptr<string>(new string(s)); }\n\tshared_str(const char *s) { content = std::shared_ptr<string>(new string(s)); }\n\tconst char *c_str() const { return content->c_str(); }\n\tconst string &str() const { return *content; }\n\tbool operator==(const shared_str &other) const { return *content == *other.content; }\n\tunsigned int hash() const { return hashlib::hash_ops<std::string>::hash(*content); }\n};\n\nusing hashlib::mkhash;\nusing hashlib::mkhash_init;\nusing hashlib::mkhash_add;\nusing hashlib::mkhash_xorshift;\nusing hashlib::hash_ops;\nusing hashlib::hash_cstr_ops;\nusing hashlib::hash_ptr_ops;\nusing hashlib::hash_obj_ops;\nusing hashlib::dict;\nusing hashlib::idict;\nusing hashlib::pool;\nusing hashlib::mfp;\n\nnamespace RTLIL {\n\tstruct IdString;\n\tstruct Const;\n\tstruct SigBit;\n\tstruct SigSpec;\n\tstruct Wire;\n\tstruct Cell;\n\tstruct Memory;\n\tstruct Process;\n\tstruct Module;\n\tstruct Design;\n\tstruct Monitor;\n struct Selection;\n\tstruct SigChunk;\n\tenum State : unsigned char;\n\n\ttypedef std::pair<SigSpec, SigSpec> SigSig;\n\n namespace ID {}\n}\n\nnamespace AST {\n\tstruct AstNode;\n}\n\nusing RTLIL::IdString;\nusing RTLIL::Const;\nusing RTLIL::SigBit;\nusing RTLIL::SigSpec;\nusing RTLIL::Wire;\nusing RTLIL::Cell;\nusing RTLIL::Module;\nusing RTLIL::Design;\n\nusing RTLIL::State;\nusing RTLIL::SigChunk;\nusing RTLIL::SigSig;\n\nnamespace hashlib {\n\ttemplate<> struct hash_ops<RTLIL::Wire*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Cell*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Memory*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Process*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Module*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Design*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<RTLIL::Monitor*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<AST::AstNode*> : hash_obj_ops {};\n\n\ttemplate<> struct hash_ops<const RTLIL::Wire*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Cell*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Memory*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Process*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Module*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Design*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const RTLIL::Monitor*> : hash_obj_ops {};\n\ttemplate<> struct hash_ops<const AST::AstNode*> : hash_obj_ops {};\n}\n\nvoid memhasher_on();\nvoid memhasher_off();\nvoid memhasher_do();\n\nextern bool memhasher_active;\ninline void memhasher() { if (memhasher_active) memhasher_do(); }\n\nvoid yosys_banner();\nint ceil_log2(int x) YS_ATTRIBUTE(const);\n\ninline std::string vstringf(const char *fmt, va_list ap)\n{\n // For the common case of strings shorter than 128, save a heap\n // allocation by using a stack allocated buffer.\n const int kBufSize = 128;\n char buf[kBufSize];\n buf[0] = '\\0';\n va_list apc;\n va_copy(apc, ap);\n int n = vsnprintf(buf, kBufSize, fmt, apc);\n va_end(apc);\n if (n < kBufSize)\n return std::string(buf);\n\n std::string string;\n char *str = NULL;\n#if defined(_WIN32 )|| defined(__CYGWIN__)\n int sz = 2 * kBufSize, rc;\n while (1) {\n\t\tva_copy(apc, ap);\n\t\tstr = (char*)realloc(str, sz);\n\t\trc = vsnprintf(str, sz, fmt, apc);\n\t\tva_end(apc);\n\t\tif (rc >= 0 && rc < sz)\n\t\t\tbreak;\n\t\tsz *= 2;\n\t}\n\tif (str != NULL) {\n\t\tstring = str;\n\t\tfree(str);\n\t}\n\treturn string;\n#else\n if (vasprintf(&str, fmt, ap) < 0)\n str = NULL;\n if (str != NULL) {\n string = str;\n free(str);\n }\n\treturn string;\n#endif\n}\n\nstd::string stringf(const char *fmt, ...) YS_ATTRIBUTE(format(printf, 1, 2));\n\ninline std::string stringf(const char *fmt, ...)\n{\n\tstd::string string;\n\tva_list ap;\n\n\tva_start(ap, fmt);\n\tstring = vstringf(fmt, ap);\n\tva_end(ap);\n\n\treturn string;\n}\n\nint readsome(std::istream &f, char *s, int n);\nstd::string next_token(std::string &text, const char *sep = \" \\t\\r\\n\", bool long_strings = false);\nstd::vector<std::string> split_tokens(const std::string &text, const char *sep = \" \\t\\r\\n\");\nbool patmatch(const char *pattern, const char *string);\n#if !defined(YOSYS_DISABLE_SPAWN)\nint run_command(const std::string &command, std::function<void(const std::string&)> process_line = std::function<void(const std::string&)>());\n#endif\nstd::string get_base_tmpdir();\nstd::string make_temp_file(std::string template_str = get_base_tmpdir() + \"/yosys_XXXXXX\");\nstd::string make_temp_dir(std::string template_str = get_base_tmpdir() + \"/yosys_XXXXXX\");\nbool check_file_exists(std::string filename, bool is_exec = false);\nbool check_directory_exists(const std::string& dirname);\nbool is_absolute_path(std::string filename);\nvoid remove_directory(std::string dirname);\nbool create_directory(const std::string& dirname);\nstd::string escape_filename_spaces(const std::string& filename);\n\ntemplate<typename T> int GetSize(const T &obj) { return obj.size(); }\ninline int GetSize(RTLIL::Wire *wire);\n\nextern int autoidx;\nextern int yosys_xtrace;\n\nRTLIL::IdString new_id(std::string file, int line, std::string func);\nRTLIL::IdString new_id_suffix(std::string file, int line, std::string func, std::string suffix);\n\n#define NEW_ID \\\n\tYOSYS_NAMESPACE_PREFIX new_id(__FILE__, __LINE__, __FUNCTION__)\n#define NEW_ID_SUFFIX(suffix) \\\n\tYOSYS_NAMESPACE_PREFIX new_id_suffix(__FILE__, __LINE__, __FUNCTION__, suffix)\n\n// Create a statically allocated IdString object, using for example ID::A or ID($add).\n//\n// Recipe for Converting old code that is using conversion of strings like ID::A and\n// \"$add\" for creating IdStrings: Run below SED command on the .cc file and then use for\n// example \"meld foo.cc foo.cc.orig\" to manually compile errors, if necessary.\n//\n// sed -i.orig -r 's/\"\\\\\\\\([a-zA-Z0-9_]+)\"/ID(\\1)/g; s/\"(\\$[a-zA-Z0-9_]+)\"/ID(\\1)/g;' <filename>\n//\n#define ID(_id) ([]() { const char *p = \"\\\\\" #_id, *q = p[1] == '$' ? p+1 : p; \\\n static const YOSYS_NAMESPACE_PREFIX RTLIL::IdString id(q); return id; })()\nnamespace ID = RTLIL::ID;\n\nnamespace hashlib {\n\ttemplate<> struct hash_ops<RTLIL::State> : hash_ops<int> {};\n}\n\n\nYOSYS_NAMESPACE_END\n\n#endif\n",
185
185
  "yw.h": "/*\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 */\n\n#ifndef YW_H\n#define YW_H\n\n#include \"kernel/yosys.h\"\n#include \"kernel/mem.h\"\n\nYOSYS_NAMESPACE_BEGIN\n\nstruct IdPath : public std::vector<RTLIL::IdString>\n{\n\ttemplate<typename... T>\n\tIdPath(T&&... args) : std::vector<RTLIL::IdString>(std::forward<T>(args)...) { }\n\tIdPath prefix() const { return {begin(), end() - !empty()}; }\n\tstd::string str() const;\n\n\tbool has_address() const { int tmp; return get_address(tmp); };\n\tbool get_address(int &addr) const;\n\n\tint hash() const { return hashlib::hash_ops<std::vector<RTLIL::IdString>>::hash(*this); }\n};\n\nstruct WitnessHierarchyItem {\n\tRTLIL::Module *module;\n\tRTLIL::Wire *wire = nullptr;\n\tRTLIL::Cell *cell = nullptr;\n\tMem *mem = nullptr;\n\n\tWitnessHierarchyItem(RTLIL::Module *module, RTLIL::Wire *wire) : module(module), wire(wire) {}\n\tWitnessHierarchyItem(RTLIL::Module *module, RTLIL::Cell *cell) : module(module), cell(cell) {}\n\tWitnessHierarchyItem(RTLIL::Module *module, Mem *mem) : module(module), mem(mem) {}\n};\n\ntemplate<typename D, typename T>\nvoid witness_hierarchy(RTLIL::Module *module, D data, T callback);\n\ntemplate<class T> static std::vector<std::string> witness_path(T *obj) {\n\tstd::vector<std::string> path;\n\tif (obj->name.isPublic()) {\n\t\tauto hdlname = obj->get_string_attribute(ID::hdlname);\n\t\tfor (auto token : split_tokens(hdlname))\n\t\t\tpath.push_back(\"\\\\\" + token);\n\t}\n\tif (path.empty())\n\t\tpath.push_back(obj->name.str());\n\treturn path;\n}\n\nstruct ReadWitness\n{\n\tstruct Clock {\n\t\tIdPath path;\n\t\tint offset;\n\t\tbool is_posedge = false;\n\t\tbool is_negedge = false;\n\t};\n\n\tstruct Signal {\n\t\tIdPath path;\n\t\tint offset;\n\t\tint width;\n\t\tbool init_only;\n\n\t\tint bits_offset;\n\t};\n\n\tstruct Step {\n\t\tstd::string bits;\n\t};\n\n\tstd::string filename;\n\tstd::vector<Clock> clocks;\n\tstd::vector<Signal> signals;\n\tstd::vector<Step> steps;\n\n\tReadWitness(const std::string &filename);\n\n\tRTLIL::Const get_bits(int t, int bits_offset, int width) const;\n};\n\ntemplate<typename D, typename T>\nvoid witness_hierarchy_recursion(IdPath &path, int hdlname_mode, RTLIL::Module *module, D data, T &callback)\n{\n\tauto const &const_path = path;\n\tsize_t path_size = path.size();\n\tfor (auto wire : module->wires())\n\t{\n\t\tauto hdlname = hdlname_mode < 0 ? std::vector<std::string>() : wire->get_hdlname_attribute();\n\t\tfor (auto item : hdlname)\n\t\t\tpath.push_back(\"\\\\\" + item);\n\t\tif (hdlname.size() == 1 && path.back() == wire->name)\n\t\t\thdlname.clear();\n\t\tif (!hdlname.empty())\n\t\t\tcallback(const_path, WitnessHierarchyItem(module, wire), data);\n\t\tpath.resize(path_size);\n\t\tif (hdlname.empty() || hdlname_mode <= 0) {\n\t\t\tpath.push_back(wire->name);\n\t\t\tcallback(const_path, WitnessHierarchyItem(module, wire), data);\n\t\t\tpath.pop_back();\n\t\t}\n\t}\n\n\tfor (auto cell : module->cells())\n\t{\n\t\tModule *child = module->design->module(cell->type);\n\t\tif (child == nullptr)\n\t\t\tcontinue;\n\n\t\tauto hdlname = hdlname_mode < 0 ? std::vector<std::string>() : cell->get_hdlname_attribute();\n\t\tfor (auto item : hdlname)\n\t\t\tpath.push_back(\"\\\\\" + item);\n\t\tif (hdlname.size() == 1 && path.back() == cell->name)\n\t\t\thdlname.clear();\n\t\tif (!hdlname.empty()) {\n\t\t\tD child_data = callback(const_path, WitnessHierarchyItem(module, cell), data);\n\t\t\twitness_hierarchy_recursion<D, T>(path, 1, child, child_data, callback);\n\t\t}\n\t\tpath.resize(path_size);\n\t\tif (hdlname.empty() || hdlname_mode <= 0) {\n\t\t\tpath.push_back(cell->name);\n\t\t\tD child_data = callback(const_path, WitnessHierarchyItem(module, cell), data);\n\t\t\twitness_hierarchy_recursion<D, T>(path, hdlname.empty() ? hdlname_mode : -1, child, child_data, callback);\n\t\t\tpath.pop_back();\n\t\t}\n\t}\n\n\tfor (auto mem : Mem::get_all_memories(module)) {\n\t\tstd::vector<std::string> hdlname;\n\n\t\tif (hdlname_mode >= 0 && mem.cell != nullptr)\n\t\t\thdlname = mem.cell->get_hdlname_attribute();\n\t\tfor (auto item : hdlname)\n\t\t\tpath.push_back(\"\\\\\" + item);\n\t\tif (hdlname.size() == 1 && path.back() == mem.cell->name)\n\t\t\thdlname.clear();\n\t\tif (!hdlname.empty()) {\n\t\t\tcallback(const_path, WitnessHierarchyItem(module, &mem), data);\n\t\t}\n\t\tpath.resize(path_size);\n\n\t\tif (hdlname.empty() || hdlname_mode <= 0) {\n\t\t\tpath.push_back(mem.memid);\n\t\t\tcallback(const_path, WitnessHierarchyItem(module, &mem), data);\n\t\t\tpath.pop_back();\n\n\t\t\tif (mem.cell != nullptr && mem.cell->name != mem.memid) {\n\t\t\t\tpath.push_back(mem.cell->name);\n\t\t\t\tcallback(const_path, WitnessHierarchyItem(module, &mem), data);\n\t\t\t\tpath.pop_back();\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate<typename D, typename T>\nvoid witness_hierarchy(RTLIL::Module *module, D data, T callback)\n{\n\tIdPath path;\n\twitness_hierarchy_recursion<D, T>(path, 0, module, data, callback);\n}\n\nYOSYS_NAMESPACE_END\n\n#endif\n",
186
186
  },
187
187
  "libs": {
@@ -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-06-28 17:04:25.985999+00:00
2
+ // Generated by ../yosys-src/techlibs/quicklogic/qlf_k6n10f/generate_bram_types_sim.py at 2024-07-10 01:09:42.792938+00:00
3
3
  `timescale 1ns /10ps
4
4
 
5
5
  module TDP36K_BRAM_A_X1_B_X1_nonsplit (
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yowasp/yosys",
3
- "version": "0.42.734",
3
+ "version": "0.43.750",
4
4
  "description": "Yosys Open SYnthesis Suite",
5
5
  "author": "Catherine <whitequark@whitequark.org>",
6
6
  "license": "ISC",