beq
Branch if Equal - 41 82 00 00
beq
Instruction Syntax
Mnemonic | Format | Flags |
beq | target | LK = 0 |
beql | target | LK = 1 |
Instruction Encoding
0
1
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
LK
Field | Bits | Description |
Primary Opcode | 0-5 | 010010 (0x12) |
BO | 6-10 | 01010 (Branch Option) |
BI | 11-15 | 00000 (Branch Input - CR0[EQ]) |
BD | 16-29 | Branch displacement (14-bit signed) |
AA | 30 | Absolute Address |
LK | 31 | Link bit |
Operation
if CR0[EQ] = 1 then if AA = 0 then NIA ← CIA + EXTS(BD || 0b00) else NIA ← EXTS(BD || 0b00) if LK = 1 then LR ← CIA + 4
BEQ branches to the target address if the Equal (EQ) bit in Condition Register field 0 is set.
- Checks if the Equal bit (EQ) in CR0 is set
- If equal, calculates the target address
- Branches to the target address
- Optionally saves the return address in LR if LK=1
Note: BEQ is a derived form of the BC (Branch Conditional) instruction with BO=01010 and BI=00000.
Affected Registers
Link Register (LR)
(if LK = 1)
- LR - Set to CIA + 4 (return address)
Next Instruction Address (NIA)
- NIA - Set to target address if condition is met
Examples
Basic Conditional Branch
# Compare two values and branch if equal cmpw r3, r4 # Compare r3 with r4 beq equal_values # Branch if r3 == r4 # Continue here if not equal b continue_code equal_values: # Code executed when r3 == r4 continue_code:
Loop Control
# Loop until counter reaches zero loop_start: # ... loop body ... subi r3, r3, 1 # Decrement counter cmpwi r3, 0 # Compare with zero beq loop_end # Branch if counter == 0 b loop_start # Continue loop loop_end:
Function Call with Return
# Call function and return if successful cmpwi r3, 0 # Check return value beql function_success # Branch and link if equal # Handle error case b error_handler function_success: # Handle success case blr # Return from function
Array Processing
# Process array until end marker found process_array: lwz r4, 0(r3) # Load array element cmpwi r4, -1 # Check for end marker beq array_end # Branch if end marker found # Process element addi r3, r3, 4 # Move to next element b process_array array_end:
String Comparison
# Compare strings character by character string_compare: lbz r4, 0(r3) # Load character from string1 lbz r5, 0(r6) # Load character from string2 cmpw r4, r5 # Compare characters beq continue_compare # Branch if characters equal b strings_different # Strings are different continue_compare: cmpwi r4, 0 # Check for null terminator beq strings_equal # Branch if end of string reached addi r3, r3, 1 # Move to next character addi r6, r6, 1 b string_compare
Error Handling
# Check for error conditions cmpwi r3, 0 # Check error code beq no_error # Branch if no error (error code == 0) # Handle error case b error_handler no_error: # Continue normal execution
Related Instructions
bc (Branch Conditional), bne (Branch if Not Equal), bge (Branch if Greater or Equal), blt (Branch if Less Than)