bdnz
Branch if Decrement Not Zero - 42 00 00 00
bdnz
Instruction Syntax
Mnemonic | Format | Flags |
bdnz | target | LK = 0 |
bdnzl | target | LK = 1 |
Note: BDNZ is a derived form of BC with BO=16 and BI=0, meaning it decrements CTR and branches if CTR is not zero.
Instruction Encoding
0
1
0
0
0
0
1
0
0
0
0
0
0
0
0
0
B
D
I
A
A
A
A
A
A
A
A
A
A
A
A
A
0
Field | Bits | Description |
Primary Opcode | 0-5 | 010000 (0x10) |
BO | 6-10 | Branch Option (16 = decrement CTR, branch if CTR≠0) |
BI | 11-15 | Branch Input (0 = not used) |
BD | 16-29 | Branch Displacement (signed, 14-bit) |
AA | 30 | Absolute Address (0 = relative, 1 = absolute) |
LK | 31 | Link (0 = no link, 1 = link) |
Operation
CTR ← CTR - 1 if (CTR ≠ 0) then if (AA = 0) then NIA ← CIA + EXTS(BD || '00') else NIA ← EXTS(BD || '00') if (LK = 1) then LR ← CIA + 4
The Count Register (CTR) is decremented by 1. If the result is not zero, a branch is taken to the target address. If LK=1, the address of the instruction following BDNZ is placed into LR.
Affected Registers
Count Register (CTR)
(always)
- Decremented by 1
Link Register (LR)
(if LK = 1)
- Updated with the address of the instruction following BDNZ
Next Instruction Address (NIA)
(if CTR ≠ 0 after decrement)
- Set to the branch target address
Examples
Basic Loop
# Simple loop with BDNZ li r3, 10 # Load loop count mtctr r3 # Set CTR to loop count loop: # ... loop body ... bdnz loop # Decrement CTR, branch if not zero
Array Processing
# Process array elements lis r3, array@ha addi r3, r3, array@l li r4, 100 # Array size mtctr r4 # Set CTR to array size process_loop: lwz r5, 0(r3) # Load array element # ... process element ... addi r3, r3, 4 # Move to next element bdnz process_loop # Continue until CTR = 0
String Copy
# Copy string using BDNZ lis r3, source@ha addi r3, r3, source@l lis r4, dest@ha addi r4, r4, dest@l li r5, 50 # String length mtctr r5 # Set CTR to length copy_loop: lbz r6, 0(r3) # Load byte from source stb r6, 0(r4) # Store byte to destination addi r3, r3, 1 # Increment source pointer addi r4, r4, 1 # Increment destination pointer bdnz copy_loop # Continue until CTR = 0
Nested Loops
# Nested loop structure li r3, 5 # Outer loop count mtctr r3 # Set CTR for outer loop outer_loop: li r4, 10 # Inner loop count mfctr r5 # Save outer loop counter mtctr r4 # Set CTR for inner loop inner_loop: # ... inner loop body ... bdnz inner_loop # Inner loop mtctr r5 # Restore outer loop counter bdnz outer_loop # Outer loop