From 01a015747e274480fc5ae8d0fab18d89d04ea8b0 Mon Sep 17 00:00:00 2001
From: Rasmus Munk Larsen <rmlarsen@google.com>
Date: Wed, 27 Sep 2023 17:16:13 -0700
Subject: [PATCH 1/2] Speed up RTLIL::Const::decode_string by 1.7x.

---
 kernel/rtlil.cc | 33 ++++++++++++++++++++++++---------
 1 file changed, 24 insertions(+), 9 deletions(-)

diff --git a/kernel/rtlil.cc b/kernel/rtlil.cc
index 1b57af60a..3663ca864 100644
--- a/kernel/rtlil.cc
+++ b/kernel/rtlil.cc
@@ -313,18 +313,33 @@ RTLIL::Const RTLIL::Const::from_string(const std::string &str)
 
 std::string RTLIL::Const::decode_string() const
 {
-	std::string string;
-	string.reserve(GetSize(bits)/8);
-	for (int i = 0; i < GetSize(bits); i += 8) {
+	const int n = GetSize(bits);
+	const int n_over_8 = n / 8;
+	std::string s;
+	s.reserve(n_over_8);
+	int i = n_over_8 * 8;
+	if (i < n) {
 		char ch = 0;
-		for (int j = 0; j < 8 && i + j < int (bits.size()); j++)
-			if (bits[i + j] == RTLIL::State::S1)
+		for (int j = 0; j < (n - i); j++) {
+			if (bits[j + i] == RTLIL::State::S1) {
 				ch |= 1 << j;
+			}
+		}
 		if (ch != 0)
-			string.append({ch});
+			s.append({ch});
 	}
-	std::reverse(string.begin(), string.end());
-	return string;
+	i -= 8;
+	for (; i >= 0; i -= 8) {
+		char ch = 0;
+		for (int j = 0; j < 8; j++) {
+			if (bits[j + i] == RTLIL::State::S1) {
+				ch |= 1 << j;
+			}
+		}
+		if (ch != 0)
+			s.append({ch});
+	}
+	return s;
 }
 
 bool RTLIL::Const::is_fully_zero() const
@@ -4044,7 +4059,7 @@ void RTLIL::SigSpec::replace(const RTLIL::SigSpec &pattern, const RTLIL::SigSpec
 			other->bits_[j] = with.bits_[it->second];
 		}
 	}
-	
+
 	other->check();
 }
 

From 12218a4c744cb3877e5d9e78d15b7c2d90667907 Mon Sep 17 00:00:00 2001
From: Rasmus Munk Larsen <rmlarsen@google.com>
Date: Thu, 28 Sep 2023 19:39:09 -0700
Subject: [PATCH 2/2] Unflip i and j.

---
 kernel/rtlil.cc | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/kernel/rtlil.cc b/kernel/rtlil.cc
index 3663ca864..9834a0d37 100644
--- a/kernel/rtlil.cc
+++ b/kernel/rtlil.cc
@@ -321,7 +321,7 @@ std::string RTLIL::Const::decode_string() const
 	if (i < n) {
 		char ch = 0;
 		for (int j = 0; j < (n - i); j++) {
-			if (bits[j + i] == RTLIL::State::S1) {
+			if (bits[i + j] == RTLIL::State::S1) {
 				ch |= 1 << j;
 			}
 		}
@@ -332,7 +332,7 @@ std::string RTLIL::Const::decode_string() const
 	for (; i >= 0; i -= 8) {
 		char ch = 0;
 		for (int j = 0; j < 8; j++) {
-			if (bits[j + i] == RTLIL::State::S1) {
+			if (bits[i + j] == RTLIL::State::S1) {
 				ch |= 1 << j;
 			}
 		}