Why is the “start small” algorithm for branch displacement not optimal?

Here’s a proof that, in the absence of the anomalous jumps mentioned by harold in the comments, the “start small” algorithm is optimal:

First, let’s establish that “start small” always produces a feasible solution — that is, one that doesn’t contain any short encoding of a too-long jump. The algorithm essentially amounts to repeatedly asking the question “Is it feasible yet?” and lengthening some jump encoding if not, so clearly if it terminates, then the solution it produces must be feasible. Since each iteration lengthens some jump, and no jump is ever lengthened more than once, this algorithm must eventually terminate after at most nJumps iterations, so the solution must be feasible.

Now suppose to the contrary that the algorithm can produce a suboptimal solution X. Let Y be some optimal solution. We can represent a solution as the subset of jump instructions that are lengthened. We know that |X \ Y| >= 1 — that is, that there is at least 1 instruction lengthening in X that is not also in Y — because otherwise X would be a subset of Y, and since Y is optimal by assumption and X is known to be feasible, it would follow that X = Y, meaning that X would itself be an optimal solution, which would contradict our original assumption about X.

From among the instructions in X \ Y, choose i to be the one that was lengthened first by the “start small” algorithm, and let Z be the subset of Y (and of X) consisting of all instructions already lengthened by the algorithm prior to this time. Since the “start small” algorithm decided to lengthen i’s encoding, it must have been the case that by that point in time (i.e., after lengthening all the instructions in Z), i’s jump displacement was too big for a short encoding. (Note that while some of the lengthenings in Z may have pushed i’s jump displacement past the critical point, this is by no means necessary — maybe i’s displacement was above the threshold from the beginning. All we can know, and all we need to know, is that i’s jump displacement was above the threshold by the time Z had finished being processed.) But now look back at the optimal solution Y, and note that none of the other lengthenings in Y — i.e., in Y \ Z — are able to reduce i’s jump displacement back down, so, since i’s displacement is above the threshold but its encoding is not lengthened by Y, Y is not even feasible! An infeasible solution cannot be optimal, so the existence of such a non-lengthened instruction i in Y would contradict the assumption that Y is optimal — meaning that no such i can exist.

Leave a Comment