SILICON
Loading...
Searching...
No Matches
flipflops.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 "flipflops.hpp"
19
20#include <stdexcept>
21#include <string>
22#include <utility>
23#include <variant>
24
25#include <core/wireUtils.hpp>
26#include <logging/logger.hpp>
27
28namespace SILICON::core {
29
38
39FlipFlop::FlipFlop(std::vector<Bus> inputs, std::vector<Bus> outputs,
40 const unsigned int clockIndex, const unsigned int clearIndex,
41 const unsigned int presetIndex)
43{
44 this->inputs = std::move(inputs);
45 this->outputs = std::move(outputs);
46}
47
54
56 const SILICON::simulation::Context& context)
57{
58 const State clock = inputState(clockIndex);
59 const State clear = inputState(clearIndex);
60 const State preset = inputState(presetIndex);
61 const Wire_ptr clockWire = inputWire(clockIndex);
62
63 const auto clockEdge = SILICON::simulation::Simulator::edgeType(context, clockWire);
64 const auto previousClock = context.previousState(clockWire);
65 const bool selectedClockEdge = clockEdge == edgeType;
66 const auto currentTime = sim.getCurrentTime();
67 const bool timingInputChanged = hasTimingSensitiveInputChange(context);
68
69 if (timingInputChanged)
70 lastTimingInputChangeTime = currentTime;
71
72 if (clear == State::HIGH && preset == State::LOW) {
74 return;
75 }
76
77 if (clear == State::LOW && preset == State::HIGH) {
79 return;
80 }
81
82 if (clear == State::LOW && preset == State::LOW) {
83 if (selectedClockEdge) {
84 const bool setupViolation = violatesSetupTime(currentTime, timingInputChanged);
85 lastSelectedClockEdgeTime = currentTime;
86 driveOutput(sim, setupViolation ? State::UNKNOWN : captureState());
87 }
88
89 else if (violatesHoldTime(currentTime, timingInputChanged)) {
90 lastTimingInputChangeTime = currentTime;
92 }
93
95 && previousClock && mayHaveSelectedEdge(*previousClock, clock)) {
96 // The clock transition is ambiguous (e.g., LOW -> UNKNOWN). We don't know if the
97 // physical hardware would have triggered, so pessimistically invalidate the data.
98 lastSelectedClockEdgeTime = currentTime;
100 }
101
102 else if (context.initialEvaluation) {
103 clearState();
104 driveOutput(sim, state);
105 }
106
107 return;
108 }
109
111}
112
114{
115 defineProperty("propagationDelay", 5);
116 defineProperty("setupTime", 0);
117 defineProperty("holdTime", 0);
118 defineStringListProperty("triggerEdge", "PET", {"PET", "NET"});
119
120 setPropertyCallback("propagationDelay", [this](const PropertyValue& value) {
121 const PropertyValue validated = requireNonNegative("propagationDelay", value);
122 this->propagationDelay = static_cast<uint64_t>(std::get<int>(validated));
123 return validated;
124 });
125 setPropertyCallback("setupTime", [this](const PropertyValue& value) {
126 const PropertyValue validated = requireNonNegative("setupTime", value);
127 this->setupTime = static_cast<uint64_t>(std::get<int>(validated));
128 return validated;
129 });
130 setPropertyCallback("holdTime", [this](const PropertyValue& value) {
131 const PropertyValue validated = requireNonNegative("holdTime", value);
132 this->holdTime = static_cast<uint64_t>(std::get<int>(validated));
133 return validated;
134 });
135 setPropertyCallback("triggerEdge", [this](const PropertyValue& value) {
136 this->edgeType = std::get<std::string>(value) == "PET"
139 return value;
140 });
141}
142
144{
145 if (outputBusSize(0) == 0 || outputBusSize(1) == 0)
146 return;
147
149 state = newState;
150
151 sim.updateWire(outputWire(0), newState, propagationDelay, weak_from_this());
152 sim.updateWire(outputWire(1), newState == State::UNKNOWN ? State::UNKNOWN : !newState,
153 propagationDelay, weak_from_this());
154}
155
157 const SILICON::simulation::Context& context) const
158{
159 for (unsigned int inputIndex = 0; inputIndex < inputs.size(); ++inputIndex) {
160 if (!isTimingSensitiveInput(inputIndex))
161 continue;
162
163 for (const auto& wire : inputs[inputIndex]) {
164 if (context.changed(wire))
165 return true;
166 }
167 }
168
169 return false;
170}
171
172bool FlipFlop::violatesSetupTime(const uint64_t currentTime,
173 const bool timingInputChanged) const
174{
175 if (setupTime == 0)
176 return false;
177
178 if (timingInputChanged)
179 return true;
180
182 && currentTime - *lastTimingInputChangeTime < setupTime;
183}
184
185bool FlipFlop::violatesHoldTime(const uint64_t currentTime,
186 const bool timingInputChanged) const
187{
188 return holdTime != 0 && timingInputChanged && lastSelectedClockEdgeTime
189 && currentTime - *lastSelectedClockEdgeTime < holdTime;
190}
191
192bool FlipFlop::mayHaveSelectedEdge(const State previousClock,
193 const State currentClock) const
194{
195 const bool isPositiveEdge = edgeType == SILICON::simulation::Simulator::EdgeType::RISE;
196 const State inactiveClock = isPositiveEdge ? State::LOW : State::HIGH;
197 const State activeClock = isPositiveEdge ? State::HIGH : State::LOW;
198
199 return SILICON::wireUtils::mayBe(previousClock, inactiveClock)
200 && SILICON::wireUtils::mayBe(currentClock, activeClock);
201}
202
204 Wire_ptr q, Wire_ptr notQ)
205 : FlipFlop(
206 {{std::move(d)}, {std::move(clock)}, {std::move(clear)}, {std::move(preset)}},
207 {{std::move(q)}, {std::move(notQ)}}, busIndex(Inputs::Clock),
208 busIndex(Inputs::Clear), busIndex(Inputs::Preset))
209{
210}
211
216
217bool DFlipFlop::isTimingSensitiveInput(const unsigned int inputIndex) const
218{
219 return inputIndex == busIndex(Inputs::D);
220}
221
223 Wire_ptr preset, Wire_ptr q, Wire_ptr notQ)
224 : FlipFlop({{std::move(d)},
225 {std::move(enable)},
226 {std::move(clock)},
227 {std::move(clear)},
228 {std::move(preset)}},
229 {{std::move(q)}, {std::move(notQ)}}, busIndex(Inputs::Clock),
230 busIndex(Inputs::Clear), busIndex(Inputs::Preset))
231{
232}
233
235{
236 const State enable = inputState(Inputs::Enable);
237 if (enable == State::LOW)
238 return latchedState();
239 if (enable == State::HIGH)
241 return State::UNKNOWN;
242}
243
244bool EFlipFlop::isTimingSensitiveInput(const unsigned int inputIndex) const
245{
246 return inputIndex == busIndex(Inputs::D) || inputIndex == busIndex(Inputs::Enable);
247}
248
253
255 : Component({{std::move(d)}, {std::move(enable)}}, {{std::move(q)}, {std::move(notQ)}})
256{
257 initializeProperties();
258}
259
261 const SILICON::simulation::Context& context)
262{
263 if (context.initialEvaluation)
265
266 const State enable = inputState(Inputs::Enable);
267 if (enable == State::LOW) {
268 driveOutput(sim, state);
269 return;
270 }
271
272 if (enable == State::HIGH) {
274 return;
275 }
276
278}
279
281{
282 defineProperty("propagationDelay", 5);
283 setPropertyCallback("propagationDelay", [this](const PropertyValue& value) {
284 const PropertyValue validated = requireNonNegative("propagationDelay", value);
285 propagationDelay = static_cast<uint64_t>(std::get<int>(validated));
286 return validated;
287 });
288}
289
291{
292 if (outputBusSize(0) == 0 || outputBusSize(1) == 0)
293 return;
294
296 state = newState;
297
298 sim.updateWire(outputWire(0), newState, propagationDelay, weak_from_this());
299 sim.updateWire(outputWire(1), newState == State::UNKNOWN ? State::UNKNOWN : !newState,
300 propagationDelay, weak_from_this());
301}
302
304 Wire_ptr preset, Wire_ptr q, Wire_ptr notQ)
305 : FlipFlop({{std::move(j)},
306 {std::move(k)},
307 {std::move(clock)},
308 {std::move(clear)},
309 {std::move(preset)}},
310 {{std::move(q)}, {std::move(notQ)}}, busIndex(Inputs::Clock),
311 busIndex(Inputs::Clear), busIndex(Inputs::Preset))
312{
313 /* PIN MAP:
314 J = inputs [0][0];
315 K = inputs [1][0];
316 CLK = inputs [2][0];
317 CLR = inputs [3][0];
318 PRE = inputs [4][0];
319 Q = outputs[0][0];
320 not-Q = outputs[1][0]; */
321}
322
324{
325 const State j = inputState(Inputs::J);
326 const State k = inputState(Inputs::K);
327
329 return State::UNKNOWN;
330
331 if (j == State::LOW) {
332 return (k == State::LOW) ? latchedState() : State::LOW;
333 }
334
335 if (k == State::LOW)
336 return State::HIGH;
337
338 const State current = latchedState();
339 return SILICON::wireUtils::isKnownBinary(current) ? !current : State::UNKNOWN;
340}
341
342bool JKFlipFlop::isTimingSensitiveInput(const unsigned int inputIndex) const
343{
344 return inputIndex == busIndex(Inputs::J) || inputIndex == busIndex(Inputs::K);
345}
346
347} // 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
State inputState(unsigned int input, unsigned short bit=0) const
std::vector< Bus > outputs
Output buses produced by this component.
void defineUnconnectedInputDefault(unsigned int input, State value)
Defines the state read from an input when its wire is unconnected.
std::vector< Bus > inputs
Input buses connected to this component.
void defineStringListProperty(std::string key, std::string defaultValue, StringPropertyOptions allowedValues, PropertyCallback callback=nullptr)
Defines a string property constrained to a fixed set of values.
Definition component.cpp:79
void setPropertyCallback(std::string_view key, PropertyCallback callback)
Sets a callback for property validation/transformation.
Wire_ptr inputWire(unsigned int input, unsigned short bit=0) const
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
@ D
Data input captured on the selected clock edge.
bool isTimingSensitiveInput(unsigned int inputIndex) const override
Returns true for synchronous pins governed by setup/hold timing.
DFlipFlop()
Constructs an unconnected D flip-flop.
State captureState() const override
Computes the state captured on the selected clock edge.
@ Enable
Active-high transparency enable.
@ D
Data input followed while the latch is transparent.
void driveOutput(SILICON::simulation::Simulator &sim, State newState)
DLatch()
Constructs an unconnected D latch.
void simulate(SILICON::simulation::Simulator &sim, const SILICON::simulation::Context &context) override
Executes the component's logic with simulator scheduling context.
@ Enable
Capture enable input.
@ D
Data input captured when Enable is HIGH.
EFlipFlop()
Constructs an unconnected enabled D flip-flop.
bool isTimingSensitiveInput(unsigned int inputIndex) const override
Returns true for synchronous pins governed by setup/hold timing.
State captureState() const override
Computes the state captured on the selected clock edge.
FlipFlop(unsigned int clockIndex, unsigned int clearIndex, unsigned int presetIndex)
Constructs a flip-flop base with the input indices used for control pins.
Definition flipflops.cpp:30
bool violatesSetupTime(uint64_t currentTime, bool timingInputChanged) const
bool mayHaveSelectedEdge(State previousClock, State currentClock) const
Checks if an ambiguous clock transition occurred that might be the triggering edge.
std::optional< uint64_t > lastSelectedClockEdgeTime
bool hasTimingSensitiveInputChange(const SILICON::simulation::Context &context) const
void driveOutput(SILICON::simulation::Simulator &sim, State newState)
bool violatesHoldTime(uint64_t currentTime, bool timingInputChanged) const
void simulate(SILICON::simulation::Simulator &sim, const SILICON::simulation::Context &context) override
Evaluates async controls and selected clock edges.
Definition flipflops.cpp:55
virtual State captureState() const =0
Computes the state captured on the selected clock edge.
State latchedState() const
Returns the currently stored state.
Definition flipflops.hpp:88
std::optional< uint64_t > lastTimingInputChangeTime
virtual bool isTimingSensitiveInput(unsigned int inputIndex) const =0
Returns true for synchronous pins governed by setup/hold timing.
SILICON::simulation::Simulator::EdgeType edgeType
void clearState()
Clear FF internal state (state, last transitions time, ...).
Definition flipflops.cpp:48
bool isTimingSensitiveInput(unsigned int inputIndex) const override
Returns true for synchronous pins governed by setup/hold timing.
JKFlipFlop()
Constructs an unconnected JK flip-flop.
State captureState() const override
Computes the state captured on the selected clock edge.
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
static EdgeType edgeType(const Context &context, const Wire_ptr &wire)
Classifies one wire's transition in a simulation context.
uint64_t getCurrentTime() const
Gets the current simulation time.
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.
std::shared_ptr< Wire > Wire_ptr
Definition wire.hpp:116
std::variant< int, bool, std::string, BusValue > PropertyValue
Variant type for component properties.
PropertyValue requireNonNegative(const std::string_view name, const PropertyValue &value)
Validates that an integer property value is non-negative.
Definition component.cpp:29
State normalizeBinaryOrUnknown(const State state)
Normalizes non-binary states for stored binary elements.
Definition wire.cpp:146
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
Context describing why a component is being evaluated.
Definition component.hpp:90
bool changed(const core::Wire_ptr &wire) const
Returns true when a wire has a captured previous state different from now.
bool initialEvaluation
True for initial or otherwise full-plan evaluation.
Definition component.hpp:92
std::optional< core::State > previousState(const core::Wire_ptr &wire) const
Returns the state a wire had before this reactive evaluation, if captured.