SILICON
Loading...
Searching...
No Matches
wire.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 "wire.hpp"
19
20#include <algorithm>
21#include <ranges>
22#include <stdexcept>
23#include <utility>
24
25#include <core/wireUtils.hpp>
26#include <logging/logger.hpp>
27
30
31namespace SILICON::core {
32
33State operator&&(const State& a, const State& b)
34{
35 if (a == State::HIGH && b == State::HIGH)
36 return State::HIGH;
37 if (a == State::ERROR || b == State::ERROR)
38 return State::ERROR;
39 if (a == State::LOW || b == State::LOW)
40 return State::LOW;
41 return State::UNKNOWN;
42}
43
44State operator||(const State& a, const State& b)
45{
46 if (a == State::LOW && b == State::LOW)
47 return State::LOW;
48 if (a == State::ERROR || b == State::ERROR)
49 return State::ERROR;
50 if (a == State::HIGH || b == State::HIGH)
51 return State::HIGH;
52 return State::UNKNOWN;
53}
54
56{
57 if (a == State::ERROR)
58 return State::ERROR;
59 if (a == State::UNKNOWN)
60 return State::UNKNOWN;
61 if (a == State::LOW)
62 return State::HIGH;
63 return State::LOW;
64}
65
66State operator^(const State& a, const State& b)
67{
68 if (a == State::ERROR || b == State::ERROR)
69 return State::ERROR;
70 if (a == State::UNKNOWN || b == State::UNKNOWN)
71 return State::UNKNOWN;
72 if (a != b)
73 return State::HIGH;
74 return State::LOW;
75}
76
77std::string to_str(State s)
78{
79 switch (s) {
80 case State::HIGH: return "HIGH";
81 case State::LOW: return "LOW";
82 case State::UNKNOWN: return "UNKNOWN";
83 case State::ERROR: return "ERROR";
84 }
85 throw std::logic_error("Unhandled State enum value");
86}
87
88} // namespace SILICON::core
89
91
92using namespace SILICON::core;
93
94bool busValueOverflowsWidth(const BusValue& value, const std::size_t width)
95{ return !fitsUnsigned(value, width); }
96
97bool fitsUnsigned(const BusValue& value, const std::size_t width)
98{
99 return value.size() <= width
100 || std::ranges::all_of(value.begin() + static_cast<std::ptrdiff_t>(width),
101 value.end(),
102 [](const State state) { return state == State::LOW; });
103}
104
105bool fitsSigned(const BusValue& value, const std::size_t width)
106{
107 if (value.empty() || width == 0)
108 return false;
109 if (value.size() <= width)
110 return true;
111
112 const State sign = value[width - 1];
113 if (!isKnownBinary(sign))
114 return false;
115
116 return std::ranges::all_of(value.begin() + static_cast<std::ptrdiff_t>(width),
117 value.end(),
118 [sign](const State state) { return state == sign; });
119}
120
121BusValue normalizeBusValue(const BusValue& value, const std::size_t width,
122 const State extension)
123{
124 BusValue normalized(value.begin(),
125 value.begin()
126 + static_cast<std::ptrdiff_t>(std::min(value.size(), width)));
127 normalized.resize(width, extension);
128 return normalized;
129}
130
131bool busWillChangeToValue(const Bus& bus, const BusValue& value)
132{
133 return bus.getCurrentValue() != normalizeBusValue(value, bus.size());
134}
135
136bool isKnownBinary(const State state)
137{
138 return state == State::LOW || state == State::HIGH;
139}
140
141bool mayBe(const State actual, const State expected)
142{
143 return actual == expected || !isKnownBinary(actual);
144}
145
147{
148 return isKnownBinary(state) ? state : State::UNKNOWN;
149}
150
151} // namespace SILICON::wireUtils
152
153namespace SILICON::core {
154
156{
157 this->id = nextId.fetch_add(1, std::memory_order_relaxed);
159}
160
162{
163 this->id = nextId.fetch_add(1, std::memory_order_relaxed);
164 this->currentState = s;
165}
166
167Wire::Wire(const uint64_t id, const State s) : currentState(s), id(id)
168{
169 auto next = nextId.load(std::memory_order_relaxed);
170 while (next <= id
171 && !nextId.compare_exchange_weak(next, id + 1, std::memory_order_relaxed)) {}
172}
173
174Wire::Wire(const Wire& other)
175 : currentState(other.getCurrentState()),
177 id(other.id)
178{
179 // Wire copies intentionally retain identity to preserve existing Bus initializer-list
180 // semantics. Only the state transfer needs special handling because it is atomic.
181}
182
184{
185 if (this == &other)
186 return *this;
187
188 currentState.store(other.getCurrentState(), std::memory_order_relaxed);
190 id = other.id;
191 return *this;
192}
193
195{
196 // State synchronization does not order other wire fields; simulation topology and
197 // authorization are immutable while the UI concurrently reads state for painting.
198 return this->currentState.load(std::memory_order_relaxed);
199}
200
202{
203 this->currentState.store(newState, std::memory_order_relaxed);
204}
205
207{
208 this->authorizedComponent.reset();
209}
210
212 const Component_weakPtr& authorizedBy)
213{
214 this->authorizedComponent = authorizedBy;
215 this->currentState.store(newState, std::memory_order_relaxed);
216}
217
218void Wire::setCurrentState(const State newState, const Component_weakPtr& requestedBy)
219{
220 // Every wire has a mechanism to detect graphs error: the component that
221 // controls the wire can be only one at a time and it's stored in the
222 // authorizedComponent pointer. If another component tries to modify its
223 // status then the wire go into the ERROR state, since the graph is malformed.
224 if (!this->authorizedComponent.lock())
225 this->authorizedComponent = requestedBy;
226
227 const bool changeIsAuthorized = this->authorizedComponent.lock() == requestedBy.lock();
228
229 if (!changeIsAuthorized) {
230 static const SILICON::logging::Logger log("wire");
231 log.error("Unauthorized wire state change detected");
232 }
233
234 this->forceSetCurrentState(changeIsAuthorized ? newState : State::ERROR);
235}
236
237void Wire::safeSetCurrentState(const std::weak_ptr<Wire>& w, State newState,
238 const Component_weakPtr& requestedBy)
239{
240 if (const auto lockedWire = w.lock()) {
241 lockedWire->setCurrentState(newState, requestedBy);
242 }
243}
244
245State Wire::safeGetCurrentState(const std::weak_ptr<Wire>& w)
246{
247 const auto lockedWire = w.lock();
248 return lockedWire ? lockedWire->getCurrentState() : State::ERROR;
249}
250
252{
253 // +1 safely accommodates the maximum possible carry-out bit
254 const auto width = std::max(a.size(), b.size()) + 1;
255
257 const BusValue extB = wireUtils::normalizeBusValue(b, width);
258
259 auto carry = State::LOW;
260
261 for (auto&& [idx, s] : res | SILICON::views::enumerate) {
262 const State valA = s;
263 const State valB = extB[idx];
264
265 s = valA ^ valB ^ carry;
266 carry = (valA && valB) || (carry && (valA ^ valB));
267 }
268
269 return res;
270}
271
273{
274 BusValue res = n | std::views::transform([](const State s) { return !s; })
275 | std::ranges::to<BusValue>();
276
277 State carry = State::HIGH;
278
279 for (State& s : res) {
280 const State currentBit = s;
281
282 s = currentBit ^ carry;
283 carry = currentBit && carry;
284 }
285
286 return res;
287}
288
289std::partial_ordering compare(const BusValue& lhs, const BusValue& rhs,
290 const Signedness signedness)
291{
292 const auto isError = [](const BusValue& value) {
293 return std::ranges::any_of(value,
294 [](const State state) { return state == State::ERROR; });
295 };
296
297 if (isError(lhs) || isError(rhs) || lhs.empty() || rhs.empty())
298 return std::partial_ordering::unordered;
299
300 // Helper: if the value contains unknowns then the value can express a range of states
301 const auto bounds = [signedness](const BusValue& value) {
302 BusValue min = value;
303 BusValue max = value;
304
305 for (std::size_t i = 0; i < value.size(); ++i) {
306 if (value[i] != State::UNKNOWN)
307 continue;
308
309 const bool isSignBit = signedness == Signedness::SIGNED && i == value.size() - 1;
310
311 min[i] = isSignBit ? State::HIGH : State::LOW;
312 max[i] = isSignBit ? State::LOW : State::HIGH;
313 }
314
315 return std::pair{std::move(min), std::move(max)};
316 };
317
318 // Helper: get the ordering for known values (no unknown state)
319 const auto compareKnown = [signedness](const BusValue& lhs, const BusValue& rhs) {
320 if (signedness == Signedness::SIGNED && lhs.back() != rhs.back()) {
321 return lhs.back() == State::HIGH ? std::partial_ordering::less
322 : std::partial_ordering::greater;
323 }
324
325 for (std::size_t i = lhs.size(); i-- > 0;) {
326 if (lhs[i] == rhs[i])
327 continue;
328
329 return lhs[i] == State::HIGH ? std::partial_ordering::greater
330 : std::partial_ordering::less;
331 }
332
333 return std::partial_ordering::equivalent;
334 };
335
336 auto [aMin, aMax] = bounds(lhs);
337 auto [bMin, bMax] = bounds(rhs);
338
339 const auto width = std::max(lhs.size(), rhs.size());
340
341 const auto extend = [signedness, width](const BusValue& value) {
342 const State extension = signedness == Signedness::SIGNED ? value.back() : State::LOW;
343
344 return wireUtils::normalizeBusValue(value, width, extension);
345 };
346
347 aMin = extend(aMin);
348 aMax = extend(aMax);
349 bMin = extend(bMin);
350 bMax = extend(bMax);
351
352 if (compareKnown(aMin, bMax) == std::partial_ordering::greater)
353 return std::partial_ordering::greater;
354
355 if (compareKnown(aMax, bMin) == std::partial_ordering::less)
356 return std::partial_ordering::less;
357
358 // It should not happen but just to be sure...
359 [[unlikely]] if (aMin == aMax && bMin == bMax
360 && compareKnown(aMin, bMin) == std::partial_ordering::equivalent) {
361 return std::partial_ordering::equivalent;
362 }
363
364 return std::partial_ordering::unordered;
365}
366
367BusValue shift(const BusValue& v, const ptrdiff_t amount, const Signedness signedness)
368{
369 if (v.empty() || amount == 0)
370 return v;
371
372 BusValue res = v;
373
374 const State filler =
375 amount > 0 && signedness == Signedness::SIGNED ? v.back() : State::LOW;
376
377 for (auto&& [index, value] : SILICON::views::enumerate(res)) {
378 const ptrdiff_t source = index + amount;
379
380 const bool sourceInBounds = source >= 0 && source < std::ssize(v);
381
382 value = sourceInBounds ? v[source] : filler;
383 }
384
385 return res;
386}
387
388BusValue multiply(const BusValue& a, const BusValue& b, const Signedness signedness)
389{
390 if (a.empty() || b.empty())
391 throw std::invalid_argument("BusValue multiplication arguments can't be empty");
392
393 const auto width = a.size() + b.size();
394 const auto aExtension = (signedness == Signedness::SIGNED) ? a.back() : State::LOW;
395 const auto aExtended = wireUtils::normalizeBusValue(a, width, aExtension);
396
397 BusValue res(width, State::LOW);
398
399 for (auto [index, s] : b | SILICON::views::enumerate) {
400 // If s is LOW then the partial sum would be 0 and can be ignored
401 if (s == State::LOW)
402 continue;
403
404 // The partial sum bit is 1 iff both operands bit are 1 (follow and semantics)
405 const auto intermediateResult = aExtended
406 | std::views::transform([s](const State bit) {
407 return bit && s;
408 })
409 | std::ranges::to<BusValue>();
410
411 // Calculate the partial sum
412 auto partial = shift(intermediateResult, -index);
413
414 // In two's complement, the sign bit has negative weight.
415 const bool isSignBit = index == static_cast<long>(b.size() - 1);
416 if (signedness == Signedness::SIGNED && isSignBit)
417 partial = twosComplement(partial);
418
419 res = wireUtils::normalizeBusValue(res + partial, width);
420 }
421
422 return res;
423}
424
425std::pair<BusValue, BusValue> divide(const BusValue& a, const BusValue& b,
426 Signedness signedness)
427{
428 if (a.empty() || b.empty())
429 throw std::invalid_argument("BusValue division arguments can't be empty");
430
431 if (std::ranges::all_of(b, [](const auto s) { return s == State::LOW; })) {
432 throw std::invalid_argument("BusValue division by 0");
433 }
434
435 const auto hasState = [](const BusValue& v, const State s) {
436 return std::ranges::contains(v, s);
437 };
438
439 if (hasState(a, State::ERROR) || hasState(b, State::ERROR))
440 return {BusValue(a.size(), State::ERROR), BusValue(b.size(), State::ERROR)};
441
442 if (hasState(a, State::UNKNOWN) || hasState(b, State::UNKNOWN))
443 return {BusValue(a.size(), State::UNKNOWN), BusValue(b.size(), State::UNKNOWN)};
444
445 const BigInt dividend = integerFromBusValue(a, signedness);
446 const BigInt divisor = integerFromBusValue(b, signedness);
447
448 BigInt quotient;
449 BigInt remainder;
450 boost::multiprecision::divide_qr(dividend, divisor, quotient, remainder);
451
452 return {busValueFromInteger(quotient, a.size()),
453 busValueFromInteger(remainder, b.size())};
454}
455
456Bus::Bus(const unsigned short size)
457{
458 this->busData.reserve(size);
459 for (unsigned short i = 0; i < size; i++)
460 this->busData.push_back(std::make_shared<Wire>(State::UNKNOWN));
461}
462
463void Bus::setSize(const unsigned short size)
464{
465 const size_t oldSize = this->busData.size();
466 this->busData.resize(size);
467 for (size_t i = oldSize; i < size; i++)
468 this->busData[i] = std::make_shared<Wire>(State::UNKNOWN);
469}
470
471Bus::Bus(std::vector<Wire_ptr> busData)
472{ this->busData = std::move(busData); }
473
474Bus::Bus(std::initializer_list<Wire_ptr> initList)
475 : busData(initList.begin(), initList.end())
476{
477}
478
479Bus::Bus(std::initializer_list<Wire> initList) : busData(initList.size())
480{
481 size_t i = 0;
482 for (const auto& val : initList) {
483 busData[i++] = std::make_shared<Wire>(val);
484 }
485}
486
488{
489 const auto normalized = SILICON::wireUtils::normalizeBusValue(value, size());
490 for (auto i = 0uz; i < size(); ++i) {
491 const auto currentWire = this->busData[i];
492
493 if (!currentWire)
494 continue;
495
496 currentWire->forceSetCurrentState(normalized[i]);
497 }
499}
500
502 const Component_weakPtr& authorizedBy)
503{
504 const auto normalized = SILICON::wireUtils::normalizeBusValue(value, size());
505 for (auto i = 0uz; i < size(); ++i) {
506 const auto currentWire = this->busData[i];
507
508 if (!currentWire)
509 continue;
510
511 currentWire->forceSetCurrentState(normalized[i], authorizedBy);
512 }
514}
515
516bool Bus::setCurrentValue(const BusValue& value, const Component_weakPtr& requestedBy)
517{
518 const auto normalized = SILICON::wireUtils::normalizeBusValue(value, size());
519 for (auto i = 0uz; i < size(); ++i) {
520 const auto currentWire = this->busData[i];
521
522 if (!currentWire)
523 continue;
524
525 Wire::safeSetCurrentState(currentWire, normalized[i], requestedBy);
526 }
528}
529
531{
532 return this->busData | std::views::transform([](const auto& wire) {
533 return Wire::safeGetCurrentState(wire);
534 })
535 | std::ranges::to<BusValue>();
536}
537
539{
540 return std::ranges::any_of(busData, [](const auto& el) {
542 });
543}
544
546{
547 return std::ranges::any_of(busData, [](const auto& el) {
549 });
550}
551
552bool Bus::sharesWireWith(const Bus& other) const
553{
554 for (const auto& localWire : busData) {
555 if (!localWire)
556 continue;
557
558 for (const auto& otherWire : other.busData) {
559 if (otherWire && localWire.get() == otherWire.get())
560 return true;
561 }
562 }
563 return false;
564}
565
566std::strong_ordering Bus::operator<=>(const Bus& other) const
567{
568 return std::lexicographical_compare_three_way(
569 busData.begin(), busData.end(), other.busData.begin(), other.busData.end(),
570 [](const auto& a, const auto& b) {
571 if (!a && !b)
572 return std::strong_ordering::equal;
573 if (!a)
574 return std::strong_ordering::less;
575 if (!b)
576 return std::strong_ordering::greater;
577
578 return a->getId() <=> b->getId();
579 });
580}
581
582bool Bus::operator==(const Bus& other) const
583{
584 return std::ranges::equal(busData, other.busData, [](const auto& a, const auto& b) {
585 return a.get() == b.get();
586 });
587}
588
589} // namespace SILICON::core
bool setCurrentValue(const BusValue &value, const Component_weakPtr &requestedBy)
Definition wire.cpp:516
bool hasUnknowns() const
Definition wire.cpp:545
bool forceSetCurrentValue(const BusValue &value)
Definition wire.cpp:487
bool operator==(const Bus &other) const
Definition wire.cpp:582
std::vector< Wire_ptr > busData
Definition wire.hpp:140
bool isInErrorState() const
Definition wire.cpp:538
bool sharesWireWith(const Bus &other) const
Definition wire.cpp:552
void setSize(unsigned short size)
Definition wire.cpp:463
std::strong_ordering operator<=>(const Bus &other) const
Definition wire.cpp:566
BusValue getCurrentValue() const
Definition wire.cpp:530
State getCurrentState() const
Reads the current state safely while simulation may update it.
Definition wire.cpp:194
static State safeGetCurrentState(const std::weak_ptr< Wire > &w)
Definition wire.cpp:245
void clearAuthorizedComponent()
Clears the component currently authorized to drive this wire.
Definition wire.cpp:206
static std::atomic< uint64_t > nextId
Definition wire.hpp:58
Component_weakPtr authorizedComponent
Definition wire.hpp:62
void setCurrentState(State newState, const Component_weakPtr &requestedBy)
Definition wire.cpp:218
static void safeSetCurrentState(const std::weak_ptr< Wire > &w, State newState, const Component_weakPtr &requestedBy)
Definition wire.cpp:237
std::atomic< State > currentState
State shared between the simulation worker and UI readers.
Definition wire.hpp:61
Wire & operator=(const Wire &other)
Assigns state, authorization, and identifier from another wire.
Definition wire.cpp:183
void forceSetCurrentState(State newState)
Definition wire.cpp:201
static void error(std::string_view category, std::string_view message)
Definition logger.cpp:292
BusValue shift(const BusValue &v, const ptrdiff_t amount, const Signedness signedness)
Definition wire.cpp:367
State operator!(const State &a)
Definition wire.cpp:55
BusValue operator+(const BusValue &a, const BusValue &b)
Definition wire.cpp:251
std::partial_ordering compare(const BusValue &lhs, const BusValue &rhs, const Signedness signedness)
Definition wire.cpp:289
State operator||(const State &a, const State &b)
Definition wire.cpp:44
boost::multiprecision::cpp_int BigInt
std::pair< BusValue, BusValue > divide(const BusValue &a, const BusValue &b, Signedness signedness)
Definition wire.cpp:425
State operator&&(const State &a, const State &b)
Definition wire.cpp:33
BigInt integerFromBusValue(const BusValue &value, const Signedness signedness)
Decodes an LSB-first BusValue as an unsigned arbitrary-precision integer. Empty values yield zero....
State operator^(const State &a, const State &b)
Definition wire.cpp:66
BusValue twosComplement(const BusValue &n)
Definition wire.cpp:272
std::weak_ptr< Component > Component_weakPtr
Definition wire.hpp:52
std::string to_str(State s)
Definition wire.cpp:77
BusValue busValueFromInteger(const BigInt &value, const std::size_t width)
Builds an LSB-first BusValue from the low width bits of an integer. Negative values use two's complem...
BusValue multiply(const BusValue &a, const BusValue &b, const Signedness signedness)
Definition wire.cpp:388
std::vector< State > BusValue
Definition wire.hpp:120
bool busWillChangeToValue(const Bus &bus, const BusValue &value)
Checks whether assigning a binary value would change any driven bus wire.
Definition wire.cpp:131
BusValue normalizeBusValue(const BusValue &value, const std::size_t width, const State extension)
Resize an LSB-first value to an exact bus width.
Definition wire.cpp:121
State normalizeBinaryOrUnknown(const State state)
Normalizes non-binary states for stored binary elements.
Definition wire.cpp:146
bool fitsUnsigned(const BusValue &value, const std::size_t width)
Tests whether an LSB-first value is representable as an unsigned value.
Definition wire.cpp:97
bool fitsSigned(const BusValue &value, const std::size_t width)
Tests whether an LSB-first two's-complement value fits a signed width.
Definition wire.cpp:105
bool busValueOverflowsWidth(const BusValue &value, const std::size_t width)
True when truncating to width would discard a non-low bit.
Definition wire.cpp:94
bool mayBe(const State actual, const State expected)
Tests whether an actual state could represent an expected binary state.
Definition wire.cpp:141
bool isKnownBinary(const State state)
Tests whether a state is a concrete binary logic value.
Definition wire.cpp:136