From 31a1f164d96b9ca09e55c86075ce0adb2589227a Mon Sep 17 00:00:00 2001
From: David Chase <drchase@google.com>
Date: Wed, 17 Jul 2019 04:23:43 -0400
Subject: [PATCH] common/bitutil: use result of TestBytes to prevent dead code
 elimination (#19846)

Gollvm has very aggressive dead code elimination that completely
removes one of these two benchmarks.  To prevent this, use the
result of the benchmark (a boolean), and to be "fair", make the
transformation to both benchmarks.

To be reliably assured of not removing the code, "use" means
assigning to an exported global.  Non-exported globals and
//go:noinline functions are possibly subject to this optimization.
---
 common/bitutil/bitutil_test.go | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/common/bitutil/bitutil_test.go b/common/bitutil/bitutil_test.go
index 93647031e..307bf731f 100644
--- a/common/bitutil/bitutil_test.go
+++ b/common/bitutil/bitutil_test.go
@@ -190,6 +190,8 @@ func benchmarkBaseOR(b *testing.B, size int) {
 	}
 }
 
+var GloBool bool // Exported global will not be dead-code eliminated, at least not yet.
+
 // Benchmarks the potentially optimized bit testing performance.
 func BenchmarkFastTest1KB(b *testing.B) { benchmarkFastTest(b, 1024) }
 func BenchmarkFastTest2KB(b *testing.B) { benchmarkFastTest(b, 2048) }
@@ -197,9 +199,11 @@ func BenchmarkFastTest4KB(b *testing.B) { benchmarkFastTest(b, 4096) }
 
 func benchmarkFastTest(b *testing.B, size int) {
 	p := make([]byte, size)
+	a := false
 	for i := 0; i < b.N; i++ {
-		TestBytes(p)
+		a = a != TestBytes(p)
 	}
+	GloBool = a // Use of benchmark "result" to prevent total dead code elimination.
 }
 
 // Benchmarks the baseline bit testing performance.
@@ -209,7 +213,9 @@ func BenchmarkBaseTest4KB(b *testing.B) { benchmarkBaseTest(b, 4096) }
 
 func benchmarkBaseTest(b *testing.B, size int) {
 	p := make([]byte, size)
+	a := false
 	for i := 0; i < b.N; i++ {
-		safeTestBytes(p)
+		a = a != safeTestBytes(p)
 	}
+	GloBool = a // Use of benchmark "result" to prevent total dead code elimination.
 }
-- 
GitLab