Fix memory leak in rr::Optimizer

Leak was introduced in 5ba2a5b9a43cc07f1d3042d649907ace92e4cb58.
There are calls to setUses(operand, nullptr) in the algorithm, that,
with the latest changes, would simply replace the existing allocated
Uses object with a new one. Fix it so that setUses(operand, nullptr)
deletes an existing Uses object on the Operand before allocating and
assigning a new one.

Bug: b/145754674
Change-Id: Ie1438378595401619831a2da81d4d0d54a606f80
Reviewed-on: https://swiftshader-review.googlesource.com/c/SwiftShader/+/40628
Reviewed-by: Ben Clayton <bclayton@google.com>
Reviewed-by: Nicolas Capens <nicolascapens@google.com>
Tested-by: Antonio Maiorano <amaiorano@google.com>
Kokoro-Presubmit: kokoro <noreply+kokoro@google.com>
diff --git a/src/Reactor/Optimizer.cpp b/src/Reactor/Optimizer.cpp
index 6a0acc4..f97b81b 100644
--- a/src/Reactor/Optimizer.cpp
+++ b/src/Reactor/Optimizer.cpp
@@ -106,9 +106,8 @@
 
 	for(auto operand : operandsWithUses)
 	{
-		auto uses = reinterpret_cast<Uses *>(operand->getExternalData());
-		delete uses;
-		operand->setExternalData(nullptr);
+		// Deletes the Uses instance on the operand
+		setUses(operand, nullptr);
 	}
 	operandsWithUses.clear();
 }
@@ -722,6 +721,11 @@
 
 void Optimizer::setUses(Ice::Operand *operand, Optimizer::Uses *uses)
 {
+	if(auto *oldUses = reinterpret_cast<Optimizer::Uses *>(operand->Ice::Operand::getExternalData()))
+	{
+		delete oldUses;
+	}
+
 	operand->Ice::Operand::setExternalData(uses);
 }
 
@@ -837,4 +841,4 @@
 	optimizer.run(function);
 }
 
-}  // namespace rr
\ No newline at end of file
+}  // namespace rr