Unconditional Jump: The instruction j label sets the program counter (PC) to the specified label.
Example:
L1:
j L2
L2:
j L1
Branching
Conditional Branch: The instruction beq r, s, L branches to label L if register r equals register s.
Example:
L1:
beq $t0, $t1, L2
L2:
blez $s7, L1
If the condition holds, the flow of control takes the branch; otherwise, it moves to the next instruction.
Loops
For Loop - Sum of Squares
Sum of Squares Calculation:
C Code: c
sumSq = 0;
for (i = 1; i <= n; i++)
sumSq += i * i;
MIPS Assembly:
li $v0, 0 # Initialize sumSq
li $t0, 1 # Initialize i
forLoop:
bgt $t0, $a0, endLoop # Check if i > n
mul $t1, $t0, $t0 # t1 = i * i
add $v0, $v0, $t1 # sumSq += i * i
addi $t0, $t0, 1 # Increment i
j forLoop # Loop back
endLoop:
While Loop - Number of 1-Bits
Counting 1 Bits:
C Code: c
oneBits = 0;
while (a != 0) {
oneBits += (a & 1);
a >>= 1;
}
MIPS Assembly:
li $v0, 0 # Initialize oneBits
whileLoop:
beqz $a0, endLoop # Check if a is 0
andi $t0, $a0, 1 # t0 = a & 1
add $v0, $v0, $t0 # oneBits += (a & 1)
srl $a0, $a0, 1 # a >>= 1
j whileLoop # Loop back
endLoop:
Do-While Loop - Factorial
Factorial Calculation:
C Code: c
fac = 1;
do {
fac *= n;
n--;
} while (n > 0);
MIPS Assembly:
li $v0, 1 # Initialize fac
doLoop:
mul $v0, $v0, $a0 # fac *= n
addi $a0, $a0, -1 # n--
bgtz $a0, doLoop # Loop while n > 0
Basic Blocks
Definition: A basic block is a sequence of instructions that:
Has one entry point (beginning).
Contains no jumps or branches (except possibly at the end).
If any part is executed, all of it will be executed.