generateSystemC method
- required String className,
- SystemCModelOptions options = const SystemCModelOptions(),
Generates standalone SystemC using shared sparse storage.
Implementation
String generateSystemC({
required String className,
SystemCModelOptions options = const SystemCModelOptions(),
}) {
if (!RegExp(r'^[A-Za-z_][A-Za-z0-9_]*$').hasMatch(className)) {
throw ArgumentError.value(
className, 'className', 'Invalid C++ identifier.');
}
final twoState = options.portType == SystemCModelPortType.twoState;
String portType(int width) => twoState
? width == 1
? 'bool'
: width <= 64
? 'sc_dt::sc_uint<$width>'
: 'sc_dt::sc_biguint<$width>'
: width == 1
? 'sc_dt::sc_logic'
: 'sc_dt::sc_lv<$width>';
String vector(String port, int width) {
if (width == 1) {
return twoState ? 'scalar(bit($port.read()))' : 'scalar($port.read())';
}
return twoState ? 'sc_dt::sc_lv<$width>($port.read())' : '$port.read()';
}
final source = StringBuffer()
..writeln('#pragma once')
..writeln(systemCSparseStorageDefinition)
..writeln('#include <cctype>')
..writeln('#include <cstdint>')
..writeln('#include <sstream>')
..writeln('SC_MODULE($className) {')
..writeln(' using bit=sc_dt::sc_logic;')
..writeln(' using word=sc_dt::sc_lv<$dataWidth>;')
..writeln(' using address=sc_dt::sc_lv<$addrWidth>;')
..writeln(
' using storage_type=RohdHclSystemCSparseStorage<$dataWidth>;');
for (final (ports, direction) in [
(inputPorts, 'in'),
(outputPorts, 'out')
]) {
for (final port in ports.entries) {
source.writeln(' sc_core::sc_$direction<${portType(port.value)}> '
'${port.key}{"${port.key}"};');
}
}
source.writeln('''
struct image { storage_type::image storage; word output; bool resetSeen; };
storage_type storage;
sc_core::sc_signal<word,sc_core::SC_MANY_WRITERS> output{"output"};
sc_core::sc_signal<bool,sc_core::SC_MANY_WRITERS> resetSeen{"resetSeen"};
static sc_dt::sc_lv<1> scalar(bit value) {
sc_dt::sc_lv<1> result; result[0]=value; return result;
}
static word unknown() { return word(sc_dt::SC_LOGIC_X); }
static bool inRange(const address& addr) {
if(!addr.is_01()) return false;
sc_dt::sc_biguint<$addrWidth> number(addr);
return number < std::uint64_t(${entryCount}ULL);
}
bool contains(const address& addr) const {
if(!inRange(addr)) throw std::out_of_range("Invalid SRAM address");
return storage.contains(addr.to_string());
}
word peek(const address& addr) const {
if(!inRange(addr)) throw std::out_of_range("Invalid SRAM address");
return storage.read(addr.to_string(),unknown());
}
void poke(const address& addr, const word& value) {
if(!inRange(addr)) throw std::out_of_range("Invalid SRAM address");
storage.write(addr.to_string(),value);
}
image snapshot() const {
return {storage.snapshot(),output.read(),resetSeen.read()};
}
void restore(const image& saved) {
if(!saved.storage.uncertain.empty())
throw std::invalid_argument("Invalid SRAM image");
for(const auto& item:saved.storage.entries) {
if(item.first.size()!=$addrWidth ||
item.first.find_first_not_of("01")!=std::string::npos)
throw std::invalid_argument("Invalid SRAM image address");
address addr(item.first.c_str());
if(!inRange(addr)) throw std::invalid_argument("SRAM image out of range");
}
storage.restore(saved.storage);
output.write(saved.output);
resetSeen.write(saved.resetSeen);
}
static std::string encode_portable_state(const image& saved) {
if(!saved.storage.uncertain.empty())
throw std::invalid_argument("Invalid SRAM state");
std::ostringstream result;
result << "RHCL_SRAM_V1 $addrWidth $dataWidth $entryCount "
<< saved.storage.entries.size() << "\\n"
<< saved.output.to_string() << "\\n";
for(const auto& entry:saved.storage.entries)
result << entry.first << " " << entry.second.to_string() << "\\n";
return result.str();
}
image parse_portable_state(const std::string& text, bool reset_seen) const {
std::istringstream input(text);
std::string magic, aw, dw, depth, count_text, output_bits, address_bits, data_bits, extra;
if(!(input >> magic >> aw >> dw >> depth >> count_text) ||
magic!="RHCL_SRAM_V1" || aw!="$addrWidth" || dw!="$dataWidth" ||
depth!="$entryCount" || count_text.empty() ||
(count_text.size()>1 && count_text[0]=='0'))
throw std::invalid_argument("Invalid SRAM state header");
int count=0;
for(char c:count_text) {
if(c<'0' || c>'9' || count>${entryCount ~/ 10} ||
(count==${entryCount ~/ 10} && c-'0'>${entryCount % 10}))
throw std::invalid_argument("Invalid SRAM state entry count");
count=count*10+c-'0';
}
auto validate_bits=[](std::string& bits, std::size_t width, bool allow_z) {
if(bits.size()!=width) throw std::invalid_argument("Invalid SRAM value width");
for(char& c:bits) {
c=static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
if(c!='0' && c!='1' && c!='X' && !(allow_z && c=='Z'))
throw std::invalid_argument("Invalid SRAM value bit");
}
};
if(!(input >> output_bits)) throw std::invalid_argument("Missing SRAM output");
validate_bits(output_bits,$dataWidth,true);
image saved{typename storage_type::image{},word(output_bits.c_str()),reset_seen};
for(int i=0;i<count;++i) {
if(!(input >> address_bits >> data_bits))
throw std::invalid_argument("Missing SRAM entry");
if(address_bits.size()!=$addrWidth ||
address_bits.find_first_not_of("01")!=std::string::npos)
throw std::invalid_argument("Invalid SRAM address");
address addr(address_bits.c_str());
if(!inRange(addr)) throw std::invalid_argument("SRAM address out of range");
validate_bits(data_bits,$dataWidth,false);
if(!saved.storage.entries.emplace(address_bits,word(data_bits.c_str())).second)
throw std::invalid_argument("Duplicate SRAM address");
}
if(input >> extra) throw std::invalid_argument("Trailing SRAM state data");
if(!input.eof()) throw std::invalid_argument("Invalid SRAM state input");
return saved;
}
std::string portable_execution_image() const {
if(sc_core::sc_get_status()==sc_core::SC_RUNNING)
throw std::logic_error("SRAM execution images require a paused simulator");
${twoState ? 'bit clock=bit(clk.read());' : 'bit clock=clk.read();'}
if(clock!=sc_dt::SC_LOGIC_0 && clock!=sc_dt::SC_LOGIC_1)
throw std::logic_error("SRAM execution images require a known clock");
auto saved=snapshot();
std::ostringstream result;
result << "RHCL_SRAM_EXEC_V1 " << clock.to_char() << " "
<< (saved.resetSeen ? "1" : "0") << "\\n"
<< encode_portable_state(saved);
return result.str();
}
void restore_portable_execution_image(const std::string& text) {
if(sc_core::sc_get_status()==sc_core::SC_RUNNING)
throw std::logic_error("SRAM execution images require a paused simulator");
std::istringstream input(text);
std::string magic, phase, reset_history;
if(!(input >> magic >> phase >> reset_history) ||
magic!="RHCL_SRAM_EXEC_V1" || (phase!="0" && phase!="1") ||
(reset_history!="0" && reset_history!="1"))
throw std::invalid_argument("Invalid SRAM execution header");
${twoState ? 'bit clock=bit(clk.read());' : 'bit clock=clk.read();'}
if((clock!=sc_dt::SC_LOGIC_0 && clock!=sc_dt::SC_LOGIC_1) ||
clock.to_char()!=phase[0])
throw std::logic_error("SRAM execution image clock does not match");
std::string state((std::istreambuf_iterator<char>(input)),
std::istreambuf_iterator<char>());
restore(parse_portable_state(state, reset_history=="1"));
}
''');
if (!twoState ||
options.unknownOutputs == SystemCUnknownOutputPolicy.error) {
source.writeln('''
std::string portable_snapshot() const {
return encode_portable_state(snapshot());
}
void restore_portable_snapshot(const std::string& text) {
restore(parse_portable_state(text, resetSeen.read()));
}
''');
}
source.writeln('''
void tick() {
bit rst=${twoState ? 'bit(reset.read())' : 'reset.read()'};
bit we=${twoState ? 'bit(wr_en_0.read())' : 'wr_en_0.read()'};
bit re=${twoState ? 'bit(rd_en_0.read())' : 'rd_en_0.read()'};
if(rst==sc_dt::SC_LOGIC_1) {
resetSeen.write(true);
output.write(word(0));
} else if(we==sc_dt::SC_LOGIC_1) {
address addr=${vector('wr_addr_0', addrWidth)};
if(inRange(addr)) storage.write(addr.to_string(),${vector('wr_data_0', dataWidth)});
} else if(re==sc_dt::SC_LOGIC_1) {
address addr=${vector('rd_addr_0', addrWidth)};
output.write(inRange(addr) ? storage.read(addr.to_string(),unknown()) : unknown());
}
}
void emit() {
word value=output.read();
''');
if (twoState) {
final allow =
options.unknownOutputs == SystemCUnknownOutputPolicy.zeroUntilReset
? '!resetSeen.read()'
: 'false';
final conversion = dataWidth == 1
? 'bit(value[0])==sc_dt::SC_LOGIC_1'
: '${portType(dataWidth)}(value)';
source.writeln('''
if(!value.is_01() && !($allow))
SC_REPORT_ERROR("$className", "Unknown SRAM output at two-state boundary");
if(value.is_01()) rd_data_0.write($conversion);
else rd_data_0.write(0);
''');
} else {
source.writeln(dataWidth == 1
? ' rd_data_0.write(bit(value[0]));'
: ' rd_data_0.write(value);');
}
source.writeln('''
}
SC_CTOR($className) {
output.write(unknown()); resetSeen.write(false);
SC_METHOD(tick); sensitive << clk.pos(); dont_initialize();
SC_METHOD(emit); sensitive << output << resetSeen;
}
};
''');
return source.toString();
}