Skip to content

Draft: [Feature] Online CFG Analysis

Frederic Kehrein requested to merge Warfley/fpcsource:branchanalysis into main

With this MR I introduce online CFG analysis capabilities to the FPC. Online here means that the analysis is live during parsing, such that at any point information about the CFG parsed to this point, as well as information about the current place in it, can be accessed.

Why this Feature

Basically this allows extended reasoning capabilities for the FPC, which are mainly useful for error detection. While the CFG is linked to the node graph, and could thereby also be used for optimization purposes during code generation, as this is neither my area of expertise, nor am I sure if at this high code level is actually useful to do so, or if a more low level assembly CFG would be better suited.

So for this MR I mainly focused on usage for error detection, with two major features:

  1. Unreachable code detection
  2. Uninitialized Variable checks

Mainly the following things will now be detected:

procedure Test(A: Boolean);
var
  x: Integer;
begin
  if A then
    x:=1
  else
    WriteLn(x); // Warning uninitialized variable x
end;
procedure Test(A: Boolean);
var
  x: Integer;
begin
  if A then
    x:=1;
  WriteLn(x); // Warning uninitialized variable x, as else branch did not set x
end;
procedure Test(A: Boolean);
var
  x: Integer;
begin
  if A then
    x:=1
  else
    exit;
  WriteLn(x); // No warning, as else branch never reaches this point
end;

As for unreachable code detection, the following would be cought:

procedure fail;noreturn;

procedure Test(A: Boolean);
begin
  if A then
    exit
  else
    Fail;
  WriteLn('Hello World!'); // Unreachable because exit on one branch, noreturn on other
end;

See the test cases for some more things that are cought.

Merge request reports