Don't perform constant propagation when relocatable handles are involved.
authorEugene Rozenfeld <erozen@microsoft.com>
Mon, 18 Apr 2016 23:04:05 +0000 (16:04 -0700)
committerEugene Rozenfeld <erozen@microsoft.com>
Thu, 21 Apr 2016 00:05:48 +0000 (17:05 -0700)
This change ensures that value-number-based constant propagation won't
attempt to propagate constants whose value calculations involve handles
when those handles are relocatable and have to be recorded with the VM.

DDR is clean.

4 methods are affected in SuperPMI:

33.09:         Code Size improvements (code sizes in bytes):
33.09:         <filename>                                            baseline        diff improvement  %improvement    #funcs
33.09:         CLR_SH_1_Clean_Thin_Unique_all.dasm                         41          49          -8        -19.51         1
33.09:            1 functions regressed (8 total bytes regression)
33.09:               Regression # 1 goes from    41 to    49, diff of     8 (16.33%) :: <Module>:main():int
33.09:         JIT_SH_Clean_Thin_Unique_all.dasm                         3952        3973         -21         -0.53         9
33.09:            1 aggregated functions improved (4 total bytes improvement)
33.09:               Improvement # 1 goes from  3056 to  3052, diff of     4 ( 0.13%) ::  7 x Exploit:ExploitTarget()
33.09:            2 functions regressed (25 total bytes regression)
33.09:               Regression # 1 goes from    54 to    62, diff of     8 (12.90%) :: <Module>:main():int
33.09:               Regression # 2 goes from   842 to   859, diff of    17 ( 1.98%) :: <Module>:BadFunc(long)
33.09:         TOTAL                                                     3993        4022         -29         -0.73        10

src/jit/assertionprop.cpp
src/jit/gentree.cpp
src/jit/gentree.h
src/jit/valuenum.cpp
tests/src/JIT/Regression/JitBlue/DevDiv_206786/app.config [new file with mode: 0644]
tests/src/JIT/Regression/JitBlue/DevDiv_206786/handleMath.il [new file with mode: 0644]
tests/src/JIT/Regression/JitBlue/DevDiv_206786/handleMath.ilproj [new file with mode: 0644]

index c21e5ed..cb6f12b 100644 (file)
@@ -2212,12 +2212,19 @@ GenTreePtr Compiler::optVNConstantPropOnTree(BasicBlock* block, GenTreePtr stmt,
     case TYP_LONG:
         {
             INT64 value = vnStore->ConstantValue<INT64>(vnCns);
-#ifdef _TARGET_64BIT_           
+#ifdef _TARGET_64BIT_
             if (vnStore->IsVNHandle(vnCns))
             {
-                newTree = gtNewIconHandleNode(value, vnStore->GetHandleFlags(vnCns));
-                newTree->gtVNPair = ValueNumPair(vnLib, vnCns);
-                newTree = optPrepareTreeForReplacement(tree, newTree);
+                // Don't perform constant folding that involves a handle that needs
+                // to be recorded as a relocation with the VM.
+#ifdef RELOC_SUPPORT
+                if (!opts.compReloc)
+#endif
+                {
+                    newTree = gtNewIconHandleNode(value, vnStore->GetHandleFlags(vnCns));
+                    newTree->gtVNPair = ValueNumPair(vnLib, vnCns);
+                    newTree = optPrepareTreeForReplacement(tree, newTree);
+                }
             }
             else
 #endif
@@ -2277,9 +2284,16 @@ GenTreePtr Compiler::optVNConstantPropOnTree(BasicBlock* block, GenTreePtr stmt,
 #ifndef _TARGET_64BIT_
             if (vnStore->IsVNHandle(vnCns))
             {
-                newTree = gtNewIconHandleNode(value, vnStore->GetHandleFlags(vnCns));
-                newTree->gtVNPair = ValueNumPair(vnLib, vnCns);
-                newTree = optPrepareTreeForReplacement(tree, newTree);
+                // Don't perform constant folding that involves a handle that needs
+                // to be recorded as a relocation with the VM.
+#ifdef RELOC_SUPPORT
+                if (!opts.compReloc)
+#endif
+                {
+                    newTree = gtNewIconHandleNode(value, vnStore->GetHandleFlags(vnCns));
+                    newTree->gtVNPair = ValueNumPair(vnLib, vnCns);
+                    newTree = optPrepareTreeForReplacement(tree, newTree);
+                }
             }
             else
 #endif
index 33ca7fe..a669568 100644 (file)
@@ -9760,6 +9760,11 @@ GenTreePtr                  Compiler::gtFoldExprConst(GenTreePtr tree)
         return tree;
     }
 
+    if (tree->OperGet() == GT_NOP)
+    {
+        return tree;
+    }
+
 #ifdef FEATURE_SIMD
     if (tree->OperGet() == GT_SIMD)
     {
@@ -9776,6 +9781,7 @@ GenTreePtr                  Compiler::gtFoldExprConst(GenTreePtr tree)
         case TYP_INT:
 
             /* Fold constant INT unary operator */
+            assert(op1->gtIntCon.ImmedValCanBeFolded(this, tree->OperGet()));
             i1 = (int) op1->gtIntCon.gtIconVal;
 
             // If we fold a unary oper, then the folded constant 
@@ -9890,6 +9896,7 @@ CHK_OVF:
 
             /* Fold constant LONG unary operator */
 
+            assert(op1->gtIntConCommon.ImmedValCanBeFolded(this, tree->OperGet()));
             lval1 = op1->gtIntConCommon.LngValue();
 
             switch (tree->gtOper)
@@ -10214,6 +10221,9 @@ CHK_OVF:
         //
         assert(!varTypeIsGC(op1->gtType) && !varTypeIsGC(op2->gtType));
 
+        assert(op1->gtIntConCommon.ImmedValCanBeFolded(this, tree->OperGet()));
+        assert(op2->gtIntConCommon.ImmedValCanBeFolded(this, tree->OperGet()));
+
         i1 = op1->gtIntConCommon.IconValue();
         i2 = op2->gtIntConCommon.IconValue();
 
@@ -10536,6 +10546,9 @@ OVF:
         //
         assert((op2->gtType == TYP_LONG) || (op2->gtType == TYP_INT));
 
+        assert(op1->gtIntConCommon.ImmedValCanBeFolded(this, tree->OperGet()));
+        assert(op2->gtIntConCommon.ImmedValCanBeFolded(this, tree->OperGet()));
+
         lval1 = op1->gtIntConCommon.LngValue();
         
         // For the shift operators we can have a op2 that is a TYP_INT and thus will be GT_CNS_INT 
@@ -12571,6 +12584,42 @@ size_t GenTreeIndir::Offset()
         return 0;
 }
 
+//------------------------------------------------------------------------
+// GenTreeIntConCommon::ImmedValNeedsReloc: does this immediate value needs recording a relocation with the VM?
+//
+// Arguments:
+//    comp - Compiler instance
+//
+// Return Value:
+//    True if this immediate value needs recording a relocation with the VM; false otherwise.
+
+bool GenTreeIntConCommon::ImmedValNeedsReloc(Compiler* comp)
+{
+#ifdef RELOC_SUPPORT
+    return comp->opts.compReloc && (gtOper == GT_CNS_INT) && IsIconHandle();
+#else
+    return false;
+#endif
+}
+
+//------------------------------------------------------------------------
+// ImmedValCanBeFolded: can this immediate value be folded for op?
+//
+// Arguments:
+//    comp - Compiler instance
+//    op - Tree operator
+//
+// Return Value:
+//    True if this immediate value can be folded for op; false otherwise.
+
+bool GenTreeIntConCommon::ImmedValCanBeFolded(Compiler* comp, genTreeOps op)
+{
+    // In general, immediate values that need relocations can't be folded.
+    // There are cases where we do want to allow folding of handle comparisons
+    // (e.g., typeof(T) == typeof(int)).
+    return !ImmedValNeedsReloc(comp) || (op == GT_EQ) || (op == GT_NE);
+}
+
 #ifdef _TARGET_AMD64_
 // Returns true if this absolute address fits within the base of an addr mode.
 // On Amd64 this effectively means, whether an absolute indirect address can
@@ -12616,12 +12665,6 @@ bool GenTreeIntConCommon::FitsInAddrBase(Compiler* comp)
     }    
 }
 
-// Returns true if this icon value is encoded as immediate value needs recording a relocation with VM
-bool GenTreeIntConCommon::ImmedValNeedsReloc(Compiler* comp)
-{
-    return comp->opts.compReloc && IsIconHandle();
-}
-
 // Returns true if this icon value is encoded as addr needs recording a relocation with VM
 bool GenTreeIntConCommon::AddrNeedsReloc(Compiler* comp)
 {
@@ -12657,12 +12700,6 @@ bool GenTreeIntConCommon::FitsInAddrBase(Compiler* comp)
     return IsCnsIntOrI() && !IsIconHandle(GTF_ICON_TLS_HDL);
 }
 
-// Returns true if this icon value is encoded as immediate value needs recording a relocation with VM
-bool GenTreeIntConCommon::ImmedValNeedsReloc(Compiler* comp)
-{
-    return comp->opts.compReloc && IsIconHandle();
-}
-
 // Returns true if this icon value is encoded as addr needs recording a relocation with VM
 bool GenTreeIntConCommon::AddrNeedsReloc(Compiler* comp)
 {
index 23371a7..91a4e69 100644 (file)
@@ -1799,9 +1799,11 @@ struct GenTreeIntConCommon: public GenTree
 #endif
         }
 
+        bool ImmedValNeedsReloc(Compiler* comp);
+        bool GenTreeIntConCommon::ImmedValCanBeFolded(Compiler* comp, genTreeOps op);
+
 #ifdef _TARGET_XARCH_
         bool FitsInAddrBase(Compiler* comp);
-        bool ImmedValNeedsReloc(Compiler* comp);
         bool AddrNeedsReloc(Compiler* comp);
 #endif
 
index d8e0f50..220d96a 100644 (file)
@@ -1440,9 +1440,17 @@ ValueNum ValueNumStore::EvalFuncForConstantArgs(var_types typ, VNFunc func, Valu
     switch (TypeOfVN(arg0VN))
     {
     case TYP_INT:
-        return VNForIntCon(EvalOp(func, ConstantValue<int>(arg0VN)));
+        {
+            int resVal = EvalOp(func, ConstantValue<int>(arg0VN));
+            // Unary op on a handle results in a handle.
+            return IsVNHandle(arg0VN) ? VNForHandle(ssize_t(resVal), GetHandleFlags(arg0VN)) : VNForIntCon(resVal);
+        }
     case TYP_LONG:
-        return VNForLongCon(EvalOp(func, ConstantValue<INT64>(arg0VN)));
+        {
+            INT64 resVal = EvalOp(func, ConstantValue<INT64>(arg0VN));
+            // Unary op on a handle results in a handle.
+            return IsVNHandle(arg0VN) ? VNForHandle(ssize_t(resVal), GetHandleFlags(arg0VN)) : VNForLongCon(resVal);
+        }
     case TYP_FLOAT:
         return VNForFloatCon(EvalOp(func, ConstantValue<float>(arg0VN)));
     case TYP_DOUBLE:
diff --git a/tests/src/JIT/Regression/JitBlue/DevDiv_206786/app.config b/tests/src/JIT/Regression/JitBlue/DevDiv_206786/app.config
new file mode 100644 (file)
index 0000000..6f7bbd9
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+  <runtime>
+    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+      <dependentAssembly>
+        <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.20.0" newVersion="4.0.20.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Text.Encoding" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.10.0" newVersion="4.0.10.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.10.0" newVersion="4.0.10.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.IO" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.10.0" newVersion="4.0.10.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Reflection" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.10.0" newVersion="4.0.10.0" />
+      </dependentAssembly>
+    </assemblyBinding>
+  </runtime>
+</configuration>
diff --git a/tests/src/JIT/Regression/JitBlue/DevDiv_206786/handleMath.il b/tests/src/JIT/Regression/JitBlue/DevDiv_206786/handleMath.il
new file mode 100644 (file)
index 0000000..18c76af
--- /dev/null
@@ -0,0 +1,93 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+// Need to be careful about constant folding and handles
+// during prejitting.
+
+.assembly extern mscorlib {}
+.assembly handleMath {}
+.module handleMath.exe
+
+.class public F
+{
+
+.method public instance void .ctor(int32 a)
+{
+   ldarg.0
+   call       instance void [mscorlib]System.Object::.ctor()
+   ldarg.0
+   ldarg.1
+   ldc.i4 75
+   add
+   stfld int32 F::A
+   ret
+}
+
+.field public int32 A
+
+.method public int32 Fix() cil
+{
+   ldarg.0
+   ldfld int32 F::A
+   ldc.i4 125
+   add
+   ret
+}
+
+.method public static native int Add(native int x) cil managed
+{
+   ldarg.0
+   ldc.i4 5
+   add
+   ret
+}
+
+.method public static native int Sub(native int x) cil managed noinlining
+{
+   ldarg.0
+   ldc.i4 5
+   sub
+   ret
+}
+
+.method public hidebysig static int32 Main(string[] args) cil managed
+{
+   .entrypoint
+   ldc.i4 -100
+   newobj instance void F::.ctor(int32)
+   ldftn instance int32 F::Fix()
+   call native int F::Add(native int)
+   call native int F::Sub(native int)
+   calli int32(class F)
+   ldc.i4 100
+   bne.un failure
+
+   ldc.i4 -100
+   newobj instance void F::.ctor(int32)
+   ldftn instance int32 F::Fix()
+   neg
+   neg
+   calli int32(class F)
+   ldc.i4 100
+   bne.un failure
+   
+   ldc.i4 -100
+   newobj instance void F::.ctor(int32)
+   ldftn instance int32 F::Fix()
+   not
+   not
+   calli int32(class F)
+   ldc.i4 100
+   bne.un failure
+
+success:
+   ldc.i4 100
+   ret
+failure:
+   ldc.i4.0
+   ret
+}
+
+
+}
diff --git a/tests/src/JIT/Regression/JitBlue/DevDiv_206786/handleMath.ilproj b/tests/src/JIT/Regression/JitBlue/DevDiv_206786/handleMath.ilproj
new file mode 100644 (file)
index 0000000..23d94cb
--- /dev/null
@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <AssemblyName>$(MSBuildProjectName)</AssemblyName>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{95DFC527-4DC1-495E-97D7-E94EE1F7140D}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <FileAlignment>512</FileAlignment>
+    <ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+    <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\11.0\UITestExtensionPackages</ReferencePath>
+    <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
+    <RestorePackages>true</RestorePackages>
+    <NuGetPackageImportStamp>7a9bfb7d</NuGetPackageImportStamp>
+  </PropertyGroup>
+  <!-- Default configurations to help VS understand the configurations -->
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+  </PropertyGroup>
+  <ItemGroup>
+    <CodeAnalysisDependentAssemblyPaths Condition=" '$(VS100COMNTOOLS)' != '' " Include="$(VS100COMNTOOLS)..\IDE\PrivateAssemblies">
+      <Visible>False</Visible>
+    </CodeAnalysisDependentAssemblyPaths>
+  </ItemGroup>
+  <PropertyGroup>
+    <DebugType>PdbOnly</DebugType> 
+  </PropertyGroup>
+  <ItemGroup>
+    <Compile Include="handleMath.il" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="$(JitPackagesConfigFileDirectory)minimal\project.json" />
+    <None Include="app.config" />
+  </ItemGroup>
+  <ItemGroup>
+    <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
+  </ItemGroup>
+  <PropertyGroup>
+    <ProjectJson>$(JitPackagesConfigFileDirectory)minimal\project.json</ProjectJson>
+    <ProjectLockJson>$(JitPackagesConfigFileDirectory)minimal\project.lock.json</ProjectLockJson>
+  </PropertyGroup>
+  <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+  <PropertyGroup Condition=" '$(MsBuildProjectDirOverride)' != '' ">
+  </PropertyGroup> 
+</Project>