Skip to content

[ILLink] trimming null constant propagation #114730

@pavelsavara

Description

@pavelsavara

Problem

if (null != null) is not trimmed.

IL after trimming

namespace System.BloatCodeExample
{
  public class Foo
  {
    private static void Main(string[] args)
    {
      object obj = (object) null;
      if (true)
        ;
      if (obj != null)
      {
        Console.WriteLine("This is bloated code");
        Foo.Bloat();
      }
      Console.WriteLine("hello world");
    }

    private static void Bloat() => Console.WriteLine("And there could be lot of it");
  }
}

Repro

<Project Sdk="Microsoft.NET.Sdk">

	<PropertyGroup>
		<OutputType>Exe</OutputType>
		<TargetFramework>net10.0</TargetFramework>
		<RootNamespace>trim_constant_propagation</RootNamespace>
		<ImplicitUsings>enable</ImplicitUsings>
		<Nullable>enable</Nullable>

		<IsTrimmable>true</IsTrimmable>
		<PublishTrimmed>true</PublishTrimmed>
		<TrimMode>full</TrimMode>
		<_ExtraTrimmerArgs> $(_ExtraTrimmerArgs) --dump-dependencies</_ExtraTrimmerArgs>
	
	</PropertyGroup>
	
	<ItemGroup>
		<RuntimeHostConfigurationOption Include="Bloat.IsSupported" Value="false" Trim="true" />
	</ItemGroup>

</Project>
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

[assembly: AssemblyMetadata("IsTrimmable", "True")]

namespace System.BloatCodeExample;

public class Foo
{

    [FeatureSwitchDefinition("Bloat.IsSupported")]
    private static bool IsBloatSupported { get; } = InitializeIsBloatSupported();
    private static bool InitializeIsBloatSupported() => AppContext.TryGetSwitch("Bloat.IsSupported", out bool isSupported) ? isSupported : true;

    static void Main(string[] args)
    {
        var bar = BarFactory();
        if (IsBloatSupported)
        {
            Console.WriteLine("Bloat is supported"  + (bar!=null));
        }

        if (bar != null)
        {
            Console.WriteLine("This is bloated code");
            Bloat();
        }

        //MethodInfo? bloat = typeof(Foo).GetMethod("Bloat", BindingFlags.NonPublic | BindingFlags.Static);
        //Console.WriteLine("Was bloat trimmed ? : " + (bloat == null));
        Console.WriteLine("hello world");
    }

    static void Bloat()
    {
        Console.WriteLine("And there could be lot of it");
    }

    static object BarFactory()
    {
        if (!IsBloatSupported)
        {
            return null;
        }
        return new object();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Tools-ILLink.NET linker development as well as trimming analyzers

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions