SILICON
Loading...
Searching...
No Matches
memory.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "memory.hpp"
19
20#include <bit>
21#include <limits>
22#include <stdexcept>
23#include <utility>
24
25#include <core/simulator.hpp>
26
27namespace SILICON::core {
28namespace {
29
30 [[nodiscard]] std::size_t packedWordCount(const std::size_t bytes,
31 const std::size_t width)
32 {
33 if (bytes == 0)
34 return 0;
35 if (bytes > std::numeric_limits<std::size_t>::max() / 8)
36 throw std::invalid_argument("ROM binaryContents is too large");
37 const std::size_t bits = bytes * 8;
38 return bits / width + static_cast<std::size_t>(bits % width != 0);
39 }
40
41 [[nodiscard]] unsigned short addressWidthFor(const std::size_t words)
42 {
43 if (words <= 1)
44 return 1;
45 return static_cast<unsigned short>(std::bit_width(words - 1));
46 }
47
48} // namespace
49
51{
52 defineProperty("dataWidth", 8);
53 defineProperty("binaryContents", std::string());
54
55 setPropertyCallback("dataWidth", [this](const PropertyValue& value) {
56 const int width = std::get<int>(requireValidSize("ROM dataWidth", value));
58 return value;
59 });
60 setPropertyCallback("binaryContents", [this](const PropertyValue& value) {
61 const auto& slug = std::get<std::string>(value);
64 return value;
65 });
67}
68
69ROM::ROM(Bus address, Wire_ptr chipSelect, Wire_ptr outputEnable, Bus data) : ROM()
70{
71 if (address.size() == 0)
72 throw std::invalid_argument("ROM address bus must not be empty");
73 if (data.size() == 0)
74 throw std::invalid_argument("ROM data bus must not be empty");
75
76 inputs = {std::move(address), {std::move(chipSelect)}, {std::move(outputEnable)}};
77 outputs = {std::move(data)};
78 setProperty("dataWidth", static_cast<int>(outputs[0].size()));
79}
80
82{
83 return getPropertyValue<int>("dataWidth").value_or(8);
84}
85
87{
88 return getPropertyValue<std::string>("binaryContents").value_or(std::string());
89}
90
91void ROM::configure(const int dataWidth, std::shared_ptr<const std::string> nextContent,
92 const bool rejectInvalid, const bool reshape,
93 const bool preferAddressDepth, const std::size_t explicitWords)
94{
95 const int width = std::get<int>(requireValidSize("ROM dataWidth", PropertyValue{dataWidth}));
96
97 bool nextResolved = false;
98 std::size_t nextWords = 0;
99 if (nextContent) {
100 nextWords = packedWordCount(nextContent->size(), static_cast<std::size_t>(width));
101 if (explicitWords != 0) {
102 if (!std::has_single_bit(explicitWords)
103 || explicitWords > std::numeric_limits<std::size_t>::max() / static_cast<std::size_t>(width)
104 || nextContent->size() != (explicitWords * static_cast<std::size_t>(width) + 7) / 8)
105 throw std::invalid_argument("ROM image does not match its explicit word count");
106 nextWords = explicitWords;
107 } else if (preferAddressDepth && !nextContent->empty() && !inputs.empty()) {
108 const auto& address = inputs[busIndex(Inputs::Address)];
109 const auto addressBits = address.size();
110 if (addressBits < std::numeric_limits<std::size_t>::digits) {
111 const auto candidate = std::size_t{1} << addressBits;
112 if (candidate <= std::numeric_limits<std::size_t>::max() / static_cast<std::size_t>(width)
113 && nextContent->size() == (candidate * static_cast<std::size_t>(width) + 7) / 8)
114 nextWords = candidate;
115 }
116 }
117 nextResolved = nextWords != 0 && std::has_single_bit(nextWords);
118 if (nextWords != 0 && !nextResolved && rejectInvalid)
119 throw std::invalid_argument(
120 "ROM binaryContents must contain a power-of-two number of packed words");
121 }
122
123 content = std::move(nextContent);
124 contentResolved = nextResolved;
125 wordCount = nextResolved ? nextWords : 0;
126 if (reshape)
127 reshapeBuses(width, wordCount);
128}
129
130void ROM::reshapeBuses(const int dataWidth, const std::size_t words)
131{
132 auto newInputs = inputs;
133 newInputs.resize(3);
134 newInputs[busIndex(Inputs::Address)].setSize(addressWidthFor(words));
135 newInputs[busIndex(Inputs::CS)].setSize(1);
136 newInputs[busIndex(Inputs::OE)].setSize(1);
137 setInputs(newInputs);
138
139 auto newOutputs = outputs;
140 newOutputs.resize(1);
141 newOutputs[busIndex(Outputs::Data)].setSize(static_cast<unsigned short>(dataWidth));
142 setOutputs(newOutputs);
143}
144
145void ROM::setBinaryDocument(std::string slug, std::shared_ptr<const std::string> contents)
146{
147 const int width = configuredDataWidth();
148
149 // Validate the proposed snapshot before changing either the property or the
150 // current contents, so an invalid user selection is transactional.
151 if (contents) {
152 const std::size_t words =
153 packedWordCount(contents->size(), static_cast<std::size_t>(width));
154 if (words != 0 && !std::has_single_bit(words))
155 throw std::invalid_argument(
156 "ROM binaryContents must contain a power-of-two number of packed words");
157 }
158
160 try {
161 setProperty("binaryContents", slug);
162 } catch (...) {
163 settingBinaryDocument = false;
164 throw;
165 }
166 settingBinaryDocument = false;
167 configure(width, std::move(contents), true, true);
168}
169
170void ROM::refreshBinaryContents(std::shared_ptr<const std::string> contents)
171{
172 configure(configuredDataWidth(), std::move(contents), false, true, true);
173}
174
175void ROM::refreshBinaryContents(std::shared_ptr<const std::string> contents,
176 const std::size_t words)
177{
178 configure(configuredDataWidth(), std::move(contents), true, true, false, words);
179}
180
181std::shared_ptr<const std::string> ROM::binaryContentsSnapshot() const noexcept
182{
183 return content;
184}
185
187{
188 for (unsigned short bit = 0; bit < outputBusSize(Outputs::Data); ++bit)
189 sim.updateWire(outputWire(Outputs::Data, bit), state, 0, weak_from_this());
190}
191
193{
195 return;
196
197 const State chipSelect = inputState(Inputs::CS);
198 if (chipSelect == State::LOW)
199 return;
200 if (chipSelect == State::UNKNOWN || chipSelect == State::ERROR) {
201 driveState(sim, chipSelect);
202 return;
203 }
204 if (!contentResolved || wordCount == 0) {
206 return;
207 }
208
209 std::size_t address = 0;
210 if (wordCount > 1) {
211 const auto addressSize = inputBuses().size() > busIndex(Inputs::Address)
213 : 0;
214 for (std::size_t bit = 0; bit < addressSize; ++bit) {
215 const State state = inputState(Inputs::Address, static_cast<unsigned short>(bit));
216 if (state == State::ERROR) {
218 return;
219 }
220 if (state == State::UNKNOWN) {
222 return;
223 }
224 if (state == State::HIGH)
225 address |= std::size_t{1} << bit;
226 }
227 }
228
229 const std::size_t dataWidth = static_cast<std::size_t>(configuredDataWidth());
230 BusValue value(dataWidth, State::LOW);
231 const std::size_t firstBit = address * dataWidth;
232 for (std::size_t bit = 0; bit < dataWidth; ++bit) {
233 const std::size_t sourceBit = firstBit + bit;
234 const std::size_t byteIndex = sourceBit / 8;
235 if (!content || byteIndex >= content->size())
236 break;
237 const auto byte = static_cast<unsigned char>((*content)[byteIndex]);
238 value[bit] = (byte & (1U << (sourceBit % 8))) != 0 ? State::HIGH : State::LOW;
239 }
240 sim.updateBus(outputBuses()[busIndex(Outputs::Data)], value, 0, weak_from_this());
241}
242
243} // namespace SILICON::core
static constexpr unsigned int busIndex(Enum value)
Converts a component-local bus enum to its storage index.
Wire_ptr outputWire(unsigned int output, unsigned short bit=0) const
const std::vector< Bus > & inputBuses() const
Gets all input buses without copying.
State inputState(unsigned int input, unsigned short bit=0) const
void setOutputs(const std::vector< Bus > &newOutputs)
Replaces all output buses.
std::optional< T > getPropertyValue(std::string_view key) const
Gets a property value with type deduction.
std::vector< Bus > outputs
Output buses produced by this component.
void setInputs(const std::vector< Bus > &newInputs)
Replaces all input buses.
void setProperty(std::string_view key, const PropertyValue &value)
Sets a property value.
const std::vector< Bus > & outputBuses() const
Gets all output buses without copying.
std::vector< Bus > inputs
Input buses connected to this component.
void setPropertyCallback(std::string_view key, PropertyCallback callback)
Sets a callback for property validation/transformation.
void defineProperty(std::string key, T &&defaultValue, PropertyCallback callback=nullptr)
Defines a property with a default value and optional callback.
std::size_t outputBusSize(unsigned int output) const
bool settingBinaryDocument
Definition memory.hpp:87
void configure(int dataWidth, std::shared_ptr< const std::string > contents, bool rejectInvalid, bool reshape, bool preferAddressDepth=false, std::size_t explicitWords=0)
Definition memory.cpp:91
int configuredDataWidth() const
Definition memory.cpp:81
std::string configuredBinaryContents() const
Definition memory.cpp:86
std::size_t wordCount
Definition memory.hpp:85
bool initializingProperties
Definition memory.hpp:86
void reshapeBuses(int dataWidth, std::size_t words)
Definition memory.cpp:130
void driveState(SILICON::simulation::Simulator &sim, State state)
Definition memory.cpp:186
std::shared_ptr< const std::string > binaryContentsSnapshot() const noexcept
Definition memory.cpp:181
std::shared_ptr< const std::string > content
Definition memory.hpp:83
void simulate(SILICON::simulation::Simulator &sim) override
Executes the component's logic.
Definition memory.cpp:192
void refreshBinaryContents(std::shared_ptr< const std::string > contents)
Definition memory.cpp:170
void setBinaryDocument(std::string slug, std::shared_ptr< const std::string > contents)
Definition memory.cpp:145
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
void updateBus(const Bus &bus, const BusValue &value, uint64_t delay, const Component_weakPtr &source)
Updates a bus to a new value through the normal wire-update path.
void updateWire(const Wire_ptr &target, State newState, uint64_t delay, const Component_weakPtr &source)
Updates a wire with a new state and optional delay.
int width(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
std::shared_ptr< Wire > Wire_ptr
Definition wire.hpp:116
std::variant< int, bool, std::string, BusValue > PropertyValue
Variant type for component properties.
PropertyValue requireValidSize(const std::string_view name, const PropertyValue &value)
Validates that an integer property value is a valid bus size.
Definition component.cpp:38
std::vector< State > BusValue
Definition wire.hpp:120