Skip to content

[mono] box+callvirt optimization incorrect when instructions are in different basic blocks #95347

Closed

Description

@iXyles

The box+callvirt optimization from #73456 is firing incorrectly when the box and the callvirt are consecutive IL instructions but in different basic blocks and there is another basic block that jumps to the callvirt.

See #95347 (comment) and the next 3 comments for repro and diagnosis

Original issue description below:


Description

Runtime behaviour changes in net8.0.
In net8.0 when running the code under/linked repo in Release mode on Mono (Android, ios, wasm) vs Debug it behaves different.
It also behaves different to release mode of a windows console app.

In net7.0 - both of them worked the same, in both debug and release mode

(nullableObject ?? false).ToString()

Reproduction Steps

  1. Checkout code - https://github.com/iXyles/net8-regression-bug (or copy the code part from it)
  2. Run console app in Release mode Should print 'False': False
  3. Run Andrioid app in Release mode Should print same, but instead it prints 'False': true

Optional:
4. Uninstall app from device
5. Run app in Debug mode - now it shows 'False': False (as expected)

Expected behavior

Should work the same as in previous versions.
Debug & Release mode should behave the same with the given code.
Output should be the same in Android, iOS & Windows console app

Actual behavior

Returns different values in Debug vs Release mode & works different on different platforms and previous net versions
Output value on Android & iOS: true
Output value on Windows console app: FALSE

Regression?

This works with previous net7.0 version (latest)

Known Workarounds

nullableObject != null ? nullableObject.ToString() : false.ToString() (in this sample)
or
Downgrade back to net7.0

Configuration

Android - Unsure
iOS - ARM64

Other information

No response

Activity

  1. ghost added
    needs-area-label
    on Nov 28, 2023
  2. ghost added
    untriaged
    on Nov 28, 2023
  3. iXyles commented on Nov 28, 2023

    @iXyles
    Author

    Noticed that this also impacts Blazor webassembly

  4. changed the title [-][Android][iOS] Null check then tostring works differently[/-] [+][mono] Release mode - Null check then tostring works differently[/+] on Nov 28, 2023
  5. lambdageek commented on Nov 29, 2023

    @lambdageek
    Member

    I think this is a dup of #94773

  6. removed
    untriaged
    needs-area-label
    on Nov 29, 2023
  7. added this to the 8.0.x milestone on Nov 29, 2023
  8. lambdageek commented on Nov 29, 2023

    @lambdageek
    Member

    Hmm... actually in that case the interpreter was giving the wrong answers. but in this case Debug mode (with interp) is fine, but Release is wrong.

  9. added
    needs-further-triage
    and removed on Nov 29, 2023
  10. lambdageek commented on Nov 29, 2023

    @lambdageek
    Member

    Confirmed. run this console app:

    object? n = "abcd";
    var s = (n ?? false).ToString();
    Console.WriteLine(s);

    CoreCLR:

    $ dotnet run
    abcd

    Then set these in the .csproj:

      <PropertyGroup>
        <UseMonoRuntime>true</UseMonoRuntime>
        <SelfContained>true</SelfContained>
      </PropertyGroup>
    </Project>

    Mono Interp:

    $ MONO_ENV_OPTIONS=--interp dotnet run 
    abcd

    Mono JIT:

    $ dotnet  run
    True

    @vargaz It's kind of similar IL like in #94923

      .method private hidebysig static void  '<Main>$'(string[] args) cil managed
      {
        .entrypoint
        // Code size       31 (0x1f)
        .maxstack  2
        .locals init (object V_0,
                 string V_1)
        IL_0000:  ldstr      "abcd"
        IL_0005:  stloc.0
        IL_0006:  ldloc.0
        IL_0007:  dup
        IL_0008:  brtrue.s   IL_0011
    
        IL_000a:  pop
        IL_000b:  ldc.i4.0
        IL_000c:  box        [System.Runtime]System.Boolean
        IL_0011:  callvirt   instance string [System.Runtime]System.Object::ToString()
        IL_0016:  stloc.1
        IL_0017:  ldloc.1
        IL_0018:  call       void [System.Console]System.Console::WriteLine(string)
        IL_001d:  nop
        IL_001e:  ret
      } // end of method Program::'<Main>$'
    

    So there's a jump from IL_0008 to IL_0011 with a String value on the stack, but the fallthru from IL_000c to IL_0011 has a Nullable<Boolean> on the stack so if ToString is getting devirtualized based on the fallthru info, it makes sense we'd see True instead of abcd

  11. lambdageek commented on Nov 29, 2023

    @lambdageek
    Member

    It's probably related to #73456

    Although I would expect the optimization not to fire:

    // ASSUME
    // interface ISomeIface { void Method(); }
    // struct SomeStruct : ISomeIface {...}
    // OPTIMIZE
    // box SomeStruct
    // callvirt instance ISomeIface::Method()
    // TO
    // call SomeStruct::Method()
    guchar* callvirt_ip;
    guint32 callvirt_proc_token;
    if (!((cfg->compile_aot || cfg->compile_llvm) && !mono_class_is_def(klass)) && // we cannot devirtualize in AOT when using generics
    next_ip < end &&
    (callvirt_ip = il_read_callvirt (next_ip, end, &callvirt_proc_token)) &&
    ip_in_bb (cfg, cfg->cbb, callvirt_ip) ) {

    here I would expect cfg->cbb to be the basic block of the box instruction and next_ip and callvirt_ip are IL_0011 and I would expect that ip_in_bb will be false.

  12. removed
    needs-further-triage
    on Nov 29, 2023
  13. lambdageek commented on Nov 30, 2023

    @lambdageek
    Member
  14. lambdageek commented on Nov 30, 2023

    @lambdageek
    Member

    Yea running with MONO_VERBOSE_METHOD='<Main>$' I see

    converting (in B4: stack: 1) IL_0011: callvirt  0x0a00000d
    cmethod = string bool:ToString ()
    

    Which looks like we used the cmethod_override from here

    // The method to be called may have already been resolved when handling a previous opcode. In that
    // case, we ignore the operand and act as CALL, instead of CALLVIRT.
    // E.g. https://github.com/dotnet/runtime/issues/32166 (box+callvirt optimization)
    if (cmethod_override) {
    cmethod = cmethod_override;
    cmethod_override = NULL;
    virtual_ = FALSE;
    //il_op = MONO_CEE_CALL;
    } else {
    cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
    }
    CHECK_CFG_ERROR;
    if (cfg->verbose_level > 3)
    printf ("cmethod = %s\n", mono_method_get_full_name (cmethod));

    So the optimization fired

  15. changed the title [-][mono] Release mode - Null check then tostring works differently[/-] [+][mono] box+callvirt optimization incorrect when instructions are in different basic blocks[/+] on Nov 30, 2023
  16. ghost added
    in-pr
    on Nov 30, 2023
  17. ghost removed
    in-pr
    on Dec 1, 2023
  18. locked and limited conversation to collaborators on Dec 31, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions