jvm-tail-recursion icon indicating copy to clipboard operation
jvm-tail-recursion copied to clipboard

Optimize recursive calls when unoptimizable branches are present in the return path

Open Sipkab opened this issue 4 years ago • 0 comments

There may be cases when a tail recursive call has multiple execution paths after the call itself. The optimization should be performed in cases where it is possible.

One example is such:

public static int count(int n) {
	if (n == 0) {
		return 0;
	}
	int v = count(n - 1);
	if (n == 2) {
		callSomeOtherMethod();
	}
	return v;
}

Should be optimized to:

public static int count(int n) {
start:
	if (n == 0) {
		return 0;
	}
	
	if (n == 2) {
		int v = count(n - 1);
		callSomeOtherMethod();
		return v;
	}
	// this below is the same as 
	//     return count(n - 1);
	n = n - 1;
	goto start;
}

Current state

Currently we allow branches to be present in the return path, but they all need to be side-effect free. This issue requires individual modifications and analysis to the subsequent execution paths.

Sipkab avatar Apr 14 '20 17:04 Sipkab