Program Loops In Assembly Language
A program loop is a sequence of instructions that are executed multiple times, each time with a different set of data. In high-level languages like Fortran, loops are specified using constructs such as the DO
statement. The following example demonstrates a Fortran program that computes the sum of 100 integer numbers:
DIMENSION A(100)
INTEGER SUM, A
SUM = 0
DO 3 J = 1, 100
3 SUM = SUM + A(J)
In this example, statement number 3 is executed 100 times, each time with a different operand A(J) for J = 1, 2, ..., 100.
A compiler translates high-level language programs like the one above into machine language. This involves more complexity compared to an assembler because it requires understanding of system programming. To illustrate this, we will demonstrate the translation of the Fortran program to an assembly language program.
Memory Allocation and Initialization
The DIMENSION statement instructs the compiler to reserve memory for 100 operands. Assuming the compiler reserves memory locations from 0x150 to 0x1B3 for these operands, it will generate the following initialization in the assembly language:
ORG 100
LDA ADS
STA PTR
LDA NBR
STA CTR
CLA
ADD PTR I
ISZ PTR
ISZ CTR
BUN LOP
STA SUM
HLT
Assembly Program Breakdown
Memory Origin
ORG 100
Specifies that the origin of the program is at address 0x100.
Load First Operand Address
LDA ADS
STA PTR
Loads the first address of the operands into a pointer register.
Initialize Counter
LDA NBR
STA CTR
Loads -100 (number of iterations) into the counter register.
Clear Accumulator
CLA
Clears the accumulator to prepare for summing the values.
Loop Body
LOP, ADD PTR I
ISZ PTR
ISZ CTR
BUN LOP
- ADD PTR I: Adds the current operand to the accumulator.
- ISZ PTR: Increments the pointer to the next operand.
- ISZ CTR: Increments the counter. If the counter is not zero, the next instruction is skipped.
- BUN LOP: Branches back to the loop start if the counter has not reached zero.
Store Result and Halt
STA SUM
HLT
Data and Pointers
ADS, HEX 150 ; Address of first operand
PTR, HEX 0 ; Pointer initialization
NBR, DEC -100 ; Loop counter initialization
CTR, HEX 0 ; Counter
SUM, HEX 0 ; Sum storage
ORG 150
Here, ADS is initialized to 0x150, the first operand's address, and NBR to -100, representing the number of iterations. The pointer and counter (PTR and CTR) and the final sum (SUM) are also initialized.
Indirect Addressing and Pointer Logic
In the loop body, the ADD PTR I instruction uses indirect addressing to fetch the operand from memory. The pointer is incremented using ISZ PTR to move to the next operand. This ensures that each operand is accessed sequentially.
This example illustrates how high-level loop constructs are translated into low-level assembly instructions. The assembly program leverages pointers and counters to replicate the functionality of the Fortran DO loop, iterating over a set of data and accumulating the results in the accumulator.