Skip to content

Commit 77d643d

Browse files
Dead code elimination for if (typeof(T).IsValueType) (#97080)
@stephentoub found out that for following code: ```csharp using System.Buffers; Foo<Bar>(); static T[] Foo<T>() { if (typeof(T).IsValueType) { return ArrayPool<T>.Shared.Rent(42); } return null!; } class Bar {} ``` We end up generating `ArrayPool`s of `Bar` even though it's obviously never reachable. The problem is architectural: * We run a whole program analysis phase that tries to figure out things like generic dictionary layouts so that later, in code generation phase, we can inline offsets into generic dictionaries into codegen. * For the above code, whole program analysis decides that the dictionary layout of `Foo<__Canon>` needs a slot for `ArrayPool<!0>`. * Codegen then optimizes out the `IsValueType` branch because `__Canon` is never a valuetype. But we already allocated the dictionary slot and will fill it out, even though it ends up unused due to the optimization. We're going to run into issues like this until #83021 is addressed. Whole program analysis cannot currently assume a certain optimization happens because we don't know whether RyuJIT will do it. The only way we can "optimize" during whole program analysis is if we rewrite IL and give RyuJIT no saying in whether to do an optimization or not. Rewriting the IL is not great because it e.g. causes PGO data to not match. I don't like doing it, but there's nothing else we can do. This change extends dead block elimination to understand `typeof(X).IsValueType`. If we recognize a branch is reachable under this condition, we evaluate whether this is true or false and replace the basic block with nops.
1 parent 957ab2f commit 77d643d

File tree

2 files changed

+89
-22
lines changed

2 files changed

+89
-22
lines changed

src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSwitchManager.cs

+63-22
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,13 @@ private bool TryGetConstantArgument(MethodIL methodIL, byte[] body, OpcodeFlags[
591591
{
592592
return true;
593593
}
594+
else if (method.IsIntrinsic && method.Name is "get_IsValueType"
595+
&& method.OwningType is MetadataType mdt
596+
&& mdt.Name == "Type" && mdt.Namespace == "System" && mdt.Module == mdt.Context.SystemModule
597+
&& TryExpandTypeIsValueType(methodIL, body, flags, currentOffset, out constant))
598+
{
599+
return true;
600+
}
594601
else
595602
{
596603
constant = 0;
@@ -745,6 +752,40 @@ private string GetResourceStringForAccessor(EcmaMethod method)
745752
return null;
746753
}
747754

755+
private static bool TryExpandTypeIsValueType(MethodIL methodIL, byte[] body, OpcodeFlags[] flags, int offset, out int constant)
756+
{
757+
// We expect to see a sequence:
758+
// ldtoken Foo
759+
// call GetTypeFromHandle
760+
// -> offset points here
761+
constant = 0;
762+
const int SequenceLength = 10;
763+
if (offset < SequenceLength)
764+
return false;
765+
766+
if ((flags[offset - SequenceLength] & OpcodeFlags.InstructionStart) == 0)
767+
return false;
768+
769+
ILReader reader = new ILReader(body, offset - SequenceLength);
770+
771+
TypeDesc type = ReadLdToken(ref reader, methodIL, flags);
772+
if (type == null)
773+
return false;
774+
775+
if (!ReadGetTypeFromHandle(ref reader, methodIL, flags))
776+
return false;
777+
778+
// Dataflow runs on top of uninstantiated IL and we can't answer some questions there.
779+
// Unfortunately this means dataflow will still see code that the rest of the system
780+
// might have optimized away. It should not be a problem in practice.
781+
if (type.IsSignatureVariable)
782+
return false;
783+
784+
constant = type.IsValueType ? 1 : 0;
785+
786+
return true;
787+
}
788+
748789
private static bool TryExpandTypeEquality(MethodIL methodIL, byte[] body, OpcodeFlags[] flags, int offset, string op, out int constant)
749790
{
750791
// We expect to see a sequence:
@@ -793,37 +834,37 @@ private static bool TryExpandTypeEquality(MethodIL methodIL, byte[] body, Opcode
793834
constant ^= 1;
794835

795836
return true;
837+
}
796838

797-
static TypeDesc ReadLdToken(ref ILReader reader, MethodIL methodIL, OpcodeFlags[] flags)
798-
{
799-
ILOpcode opcode = reader.ReadILOpcode();
800-
if (opcode != ILOpcode.ldtoken)
801-
return null;
839+
private static TypeDesc ReadLdToken(ref ILReader reader, MethodIL methodIL, OpcodeFlags[] flags)
840+
{
841+
ILOpcode opcode = reader.ReadILOpcode();
842+
if (opcode != ILOpcode.ldtoken)
843+
return null;
802844

803-
TypeDesc t = (TypeDesc)methodIL.GetObject(reader.ReadILToken());
845+
TypeDesc t = (TypeDesc)methodIL.GetObject(reader.ReadILToken());
804846

805-
if ((flags[reader.Offset] & OpcodeFlags.BasicBlockStart) != 0)
806-
return null;
847+
if ((flags[reader.Offset] & OpcodeFlags.BasicBlockStart) != 0)
848+
return null;
807849

808-
return t;
809-
}
850+
return t;
851+
}
810852

811-
static bool ReadGetTypeFromHandle(ref ILReader reader, MethodIL methodIL, OpcodeFlags[] flags)
812-
{
813-
ILOpcode opcode = reader.ReadILOpcode();
814-
if (opcode != ILOpcode.call)
815-
return false;
853+
private static bool ReadGetTypeFromHandle(ref ILReader reader, MethodIL methodIL, OpcodeFlags[] flags)
854+
{
855+
ILOpcode opcode = reader.ReadILOpcode();
856+
if (opcode != ILOpcode.call)
857+
return false;
816858

817-
MethodDesc method = (MethodDesc)methodIL.GetObject(reader.ReadILToken());
859+
MethodDesc method = (MethodDesc)methodIL.GetObject(reader.ReadILToken());
818860

819-
if (!method.IsIntrinsic || method.Name != "GetTypeFromHandle")
820-
return false;
861+
if (!method.IsIntrinsic || method.Name != "GetTypeFromHandle")
862+
return false;
821863

822-
if ((flags[reader.Offset] & OpcodeFlags.BasicBlockStart) != 0)
823-
return false;
864+
if ((flags[reader.Offset] & OpcodeFlags.BasicBlockStart) != 0)
865+
return false;
824866

825-
return true;
826-
}
867+
return true;
827868
}
828869

829870
private sealed class SubstitutedMethodIL : MethodIL

src/tests/nativeaot/SmokeTests/TrimmingBehaviors/DeadCodeElimination.cs

+26
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ public static int Run()
2121
TestArrayElementTypeOperations.Run();
2222
TestStaticVirtualMethodOptimizations.Run();
2323
TestTypeEquals.Run();
24+
TestTypeIsValueType.Run();
2425
TestBranchesInGenericCodeRemoval.Run();
2526
TestUnmodifiableStaticFieldOptimization.Run();
2627
TestUnmodifiableInstanceFieldOptimization.Run();
@@ -355,6 +356,31 @@ public static void Run()
355356
}
356357
}
357358

359+
class TestTypeIsValueType
360+
{
361+
class Never { }
362+
363+
class Ever { }
364+
365+
static void Generic<T>()
366+
{
367+
if (typeof(T).IsValueType)
368+
{
369+
Activator.CreateInstance(typeof(Never));
370+
}
371+
372+
Activator.CreateInstance(typeof(Ever));
373+
}
374+
375+
public static void Run()
376+
{
377+
Generic<object>();
378+
379+
ThrowIfPresent(typeof(TestTypeIsValueType), nameof(Never));
380+
ThrowIfNotPresent(typeof(TestTypeIsValueType), nameof(Ever));
381+
}
382+
}
383+
358384
class TestBranchesInGenericCodeRemoval
359385
{
360386
class ClassWithUnusedVirtual

0 commit comments

Comments
 (0)