Function References Crashes Program

Summary

While trying to investigate related issue #39762 with more details I encountered a program breaking bug that results in a crash with "Runtime error 216".

System Information

Operating system: Linux Mint Processor architecture: x86-64 Compiler version: trunk Device: Computer

Steps to reproduce

When I run the following code attached below in the example project I get no output and "Runtime error 216" as soon as the first assignment to a "reference to" is attempted.

Example Project

program ReferenceTo;

{$mode delphi}
{$modeswitch functionreferences}

type
  TMultiply = reference to function(Value: Integer): Integer;

  { TTestObject }

  TTestObject = class
  private
    FA, FB: Integer;
    function GetB: Integer;
    procedure SetB(const Value: Integer);
  public
    function MultiplyA(Value: Integer): Integer;
    function MultiplyB(Value: Integer): Integer;
    property A: Integer read FA write FA;
    property B: Integer read GetB write SetB;
  end;

function TTestObject.GetB: Integer;
begin
  Result := FB;
end;

procedure TTestObject.SetB(const Value: Integer);
begin
  FB := Value;
end;

function TTestObject.MultiplyA(Value: Integer): Integer;
begin
  Result := Value * A;
end;

function TTestObject.MultiplyB(Value: Integer): Integer;
begin
  Result := Value * B;
end;

procedure Test;
const
  Factor = 4;
var
  T: TTestObject;
  M: TMultiply;
  I: Integer;
begin
  T := TTestObject.Create;
  M := T.MultiplyA;
  WriteLn('MultiplyA reference to');
  for I := 0 to 4 do
  begin
    T.A := I;
    WriteLn(M(Factor));
  end;
  WriteLn('MultiplyA direct');
  for I := 0 to 4 do
  begin
    T.A := I;
    WriteLn(T.MultiplyA(Factor));
  end;
  M := T.MultiplyB;
  WriteLn('MultiplyB reference to');
  for I := 0 to 4 do
  begin
    T.B := I;
    WriteLn(M(Factor));
  end;
  WriteLn('MultiplyB direct');
  for I := 0 to 4 do
  begin
    T.B := I;
    WriteLn(T.MultiplyB(Factor));
  end;
  T.Free;
end;

begin
  Test;
end.

What is the current bug behavior?

When running the project I get the following output:

Runtime error 216 at $00000000004128C2
  $00000000004128C2
  $00000000004015AE  $main,  line 82 of referenceto.lpr
  $0000000000423431

No heap dump by heaptrc unit
Exitcode = 216

What is the expected (correct) behavior?

I expect to see numbers printed from MultiplyA and MultiplyB.

To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information