TAOCP 1.4.4 Exercise 6
To initialize the `WORDIN` subroutine (4) correctly, we must ensure that the first call to `WORDIN` will access the first word of the initial buffer and that the subsequent calls will correctly advanc...
Section 1.4.4: Input and Output
Exercise 6. [12] What instructions should be placed at the beginning of a program so that the WORDIN subroutine (4) gets off to the right start? (For example, index register 6 must be set to something.)
Verified: no
Solve time: -
Solution
To initialize the WORDIN subroutine (4) correctly, we must ensure that the first call to WORDIN will access the first word of the initial buffer and that the subsequent calls will correctly advance through the buffer and swap to the other buffer when necessary. Index register 6 is used in the subroutine to point to the current word within the buffer, and each buffer contains a sentinel at the end to detect the buffer boundary. Lines 02–05 of the subroutine increment r6, load the word at that position, and compare it to the sentinel; if the sentinel is reached, the subroutine refills the buffer and switches to the other buffer.
Let the first buffer INBUF1 begin at address $B_1$, and let the second buffer INBUF2 begin at address $B_2$. By lines 09–14, each buffer contains two words after the main block of 100 data words: the sentinel and the address of the other buffer. Therefore, the first usable word in INBUF1 is at address $B_1$, the second at $B_1 + 1$, ..., up to $B_1 + 99$, with the sentinel at $B_1 + 100$.
To start the subroutine correctly, index register 6 must be set to point to the word immediately preceding the first word to be read, so that the initial increment INC6 1 in line 02 moves it to the first word of the buffer. Therefore, we should set
$$ r6 \leftarrow B_1 - 1. $$
Next, we must initiate reading of the first buffer. The subroutine expects the current buffer to have already been filled. Let U denote the tape unit from which input is to be read. We begin reading into the first buffer with the instruction
$$ \texttt{IN } B_1(U), $$
which starts reading 100 words (the length of the buffer) into memory cells $B_1$ through $B_1 + 99$. The WORDIN subroutine will not access these memory cells until the first increment of r6 occurs, so this procedure is safe.
Finally, if any initial swap logic or buffer linking is required, it is already present in lines 11 and 14, which contain the addresses of the opposite buffers. No additional action is necessary to initialize the linking.
In summary, the program should begin with the following instructions:
$$ \begin{aligned} & r6 \leftarrow B_1 - 1, \ & \texttt{IN } B_1(U). \end{aligned} $$
This ensures that the first call to WORDIN increments r6 to $B_1$, reads the first word of input, and correctly handles buffer swapping when the end of the buffer is reached. Subsequent calls to WORDIN will alternate between INBUF1 and INBUF2 as intended.
This completes the proof.
∎