Wrong code generated with -O3 option by current trunk compiler

Summary

Current trunk compiler compiled with -O3 option currently fails to run. The simple test below, adapted from tests/test/cg/tbytetypecast.pp displays a bug in optimization, which seems to be CPU independent (at least present both for ì386and x86_64`).

System Information

  • Operating system: Any
  • Processor architecture: Any
  • Compiler version: trunk

Steps to reproduce

Copy example below and compile as explained after.

Example Project

muller@cfarm137:~/pas/check$ cat ./tbytetypecast-shortest.pp
type
  TRecord = record
    w1,w2,w3,w4 : word;
  end;

var
  w1 : word;
  b1 : byte;
  rec : TRecord;
  ErrorCount : longint;

begin
  ErrorCount:=0;
  b1:=$57;
  w1:=$2D57;
  rec.w1:=w1;
  if (byte(rec.w1)<>b1) then
    inc(ErrorCount,3);
  if (rec.w1=b1) then
    inc(ErrorCount,4);
  halt(ErrorCount);
end.

What is the current bug behavior?

muller@cfarm137:~/pas/check$ fpc -O3  tbytetypecast-shortest.pp
Free Pascal Compiler version 3.3.1-20105-gd93b8b83c3-unpushed [2026/04/25] for x86_64
Copyright (c) 1993-2026 by Florian Klaempfl and others
muller@cfarm137:~/pas/check$ ./tbytetypecast-shortest ; echo "res=$?"
res=4

What is the expected (correct) behavior?

The test should exit with zero exitcode.

Relevant logs and/or screenshots

Using gdb shows that the executable is jumping from line if (byte(rec.w1)<>b1) thendirectly to line inc(ErrorCount,4); when it sholud jump to previous line if (rec.w1=b1) then.

Possible fixes