Bug 20040

Summary: Issue with variable reuse in generated IL
Product: [Mono] Compilers Reporter: jameswilddev <facelol11>
Component: C#Assignee: Marek Safar <masafa>
Severity: normal CC: mono-bugs+mono
Priority: ---    
Version: 3.2.x   
Target Milestone: ---   
Hardware: PC   
OS: Windows   
Tags: Is this bug a regression?: ---
Last known good build:

Description jameswilddev 2014-05-26 07:04:34 UTC

I've been writing a vector mathematics library as a project and noticed that a test that passes on Visual Studio fails on Xamarin Studio.  Indeed, it appears that the result of a calculation is completely out.  On review of the generated code, it would appear the Mono compiler is overwriting a variable with intent to use it later on:

Code entered:
var closest = ray.Start.Add( ray.Normal.Multiply( along ) );

Generated code according to DotPeek:
TVector vector1 = ray.Start; 
// ISSUE: explicit reference operation 
// ISSUE: variable of a reference type 
TVector& local1 = @vector1; 
vector1 = ray.Normal; 
TVector to = vector1.Multiply(multiply1); 
// ISSUE: explicit reference operation 
float num1 = VectorExtensions.Magnitude((^local1).Add(to));

If my understanding is correct here, it is storing ray.Start in vector1, taking a reference to vector1, overwriting vector1 with ray.Normal, then expecting the referenced value to still equal ray.Start later on.

On the other hand, if I split this out into two statements which should be functionally identical:
var offset = ray.Normal.Multiply( along ); 
var closest = ray.Start.Add( offset );

The generated code according to DotPeek is much simpler:
float multiply1 = VectorExtensions.Dot(new TVector().Subtract(ray.Start), ray.Difference) / ray.Length; 
TVector to1 = ray.Normal.Multiply(multiply1); 
float num1 = VectorExtensions.Magnitude(ray.Start.Add(to1));

And the result matches that in Visual Studio.

I can't reproduce this issue outside of this method, but I've branched specifically for it, and have noticed it happening elsewhere in the same method.

The test which fails as a result of this bug is SUNRUSE.Geometry.RoundTests.EntryButStopsBeforeOrigin.

Thanks for reading.
Comment 1 Marek Safar 2014-05-26 12:51:28 UTC
Fixed in master
Comment 2 jameswilddev 2014-05-26 13:05:54 UTC
Thank you!  (https://github.com/mono/mono/commit/122a67e4c88064d4a67434e59fd9191260bfcd91)  I'm on the beta channel for Xamarin Studio, which seems to get updates fairly often.  I'll be sure to retest this the next time an update comes through for it.

Thanks for all the great work you guys are doing on this platform.