MIPS 32비트 명령어 포맷(R/I/J) 및 5단계 파이프라인 해저드(Hazard) 해결MIPS 32-Bit Instruction Formats (R/I/J) and 5-Stage Pipeline Hazard Resolution
MIPS 아키텍처의 3대 명령어 포맷(R, I, J-Type) 비트 필드 구조와 5단계 파이프라인(IF-ID-EX-MEM-WB)의 데이터 해저드 포워딩 및 분기 지연 슬롯(Branch Delay Slot) 동작 원리를 다룹니다.Covers the bit-field layout of the three MIPS instruction formats (R, I, J-Type) along with data hazard forwarding and branch delay slots in the 5-stage pipeline (IF-ID-EX-MEM-WB).
1. MIPS 3대 명령어 포맷 구조1. Structure of the Three MIPS Instruction Formats
모든 MIPS 명령어는 32비트(4바이트) 고정 길이로 인코딩되며 메모리 워드 경계(4바이트 단위)에 정렬됩니다.
Every MIPS instruction is encoded as a fixed 32-bit (4-byte) word and aligned on 4-byte memory boundaries.
| 포맷 유형 | 비트 필드 구성 (총 32비트) | 용도 및 대표 명령어 |
|---|---|---|
| R-Type (Register) | opcode (6) | rs (5) | rt (5) | rd (5) | shamt (5) | funct (6) | 레지스터 간 산술/논리/시프트 연산 (add, sub, and, sll) |
| I-Type (Immediate) | opcode (6) | rs (5) | rt (5) | immediate (16) | 상수 연산, 메모리 로드/스토어, 조건 분기 (addi, lw, sw, beq) |
| J-Type (Jump) | opcode (6) | target address (26) | 무조건 장거리 점프 및 서브루틴 호출 (j, jal) |
| Format Type | Bit Field Layout (32 Bits Total) | Purpose and Representative Instructions |
|---|---|---|
| R-Type (Register) | opcode (6) | rs (5) | rt (5) | rd (5) | shamt (5) | funct (6) | Register-to-register arithmetic, logic, and shift operations (add, sub, and, sll) |
| I-Type (Immediate) | opcode (6) | rs (5) | rt (5) | immediate (16) | Immediate arithmetic, memory load/store, and conditional branches (addi, lw, sw, beq) |
| J-Type (Jump) | opcode (6) | target address (26) | Unconditional long-range jumps and subroutine calls (j, jal) |
2. 5단계 파이프라인 구조와 해저드(Hazard)2. 5-Stage Pipeline Structure and Hazards
- IF (Instruction Fetch): PC가 가리키는 메모리 주소에서 명령어를 인출하고 PC를 4 증가시킵니다.
- ID (Instruction Decode / Register Read): 명령어를 디코드하고 소스 레지스터(
rs,rt)의 값을 읽습니다. - EX (Execute / Address Calculation): ALU에서 산술 연산을 수행하거나 메모리 참조 주소(
base + offset)를 계산합니다. - MEM (Memory Access): 데이터 메모리 읽기(
lw) 또는 쓰기(sw)를 수행합니다. - WB (Write Back): 연산 결과나 로드된 데이터를 목적지 레지스터(
rd또는rt)에 기록합니다.
- IF (Instruction Fetch): Fetches the instruction at the memory address pointed to by PC and increments PC by 4.
- ID (Instruction Decode / Register Read): Decodes the instruction and reads the source register (
rs,rt) values. - EX (Execute / Address Calculation): Performs arithmetic in the ALU or computes the effective memory address (
base + offset). - MEM (Memory Access): Reads from (
lw) or writes to (sw) data memory. - WB (Write Back): Writes the ALU result or loaded memory word back into the destination register (
rdorrt).
3. 데이터 해저드 해결: 포워딩(Forwarding)3. Resolving Data Hazards: Forwarding (Bypassing)
선행 명령어의 연산 결과는 EX 단계가 끝나는 시점에 이미 산출되지만, 정규 파이프라인 절차대로라면 WB 단계(5단계)가 끝날 때까지 레지스터 파일에 기록되지 않습니다. 이때 EX/MEM 또는 MEM/WB 파이프라인 레지스터에서 결과값을 가져와 다음 명령어의 ALU 입력으로 직접 전달하는 기법을 포워딩(Forwarding / Bypassing)이라고 합니다.
Although the result of an arithmetic instruction is available at the end of the EX stage, normal pipeline flow does not write it to the register file until the WB stage (stage 5). Forwarding (Bypassing) routes the intermediate result directly from the EX/MEM or MEM/WB pipeline register into the ALU input of the following instruction.
# 1. 포워딩으로 해결 가능한 데이터 해저드 (Stall 불필요)
add $s0, $t0, $t1 # $s0 = $t0 + $t1 (EX 단계에서 결과 산출)
sub $t2, $s0, $t3 # EX/MEM 레지스터의 $s0 값을 ALU 입력으로 직접 바이패스(Forwarding)
# 2. 포워딩만으로 불가능한 Load-Use 해저드 (1-Cycle Stall 필수)
lw $s0, 0($sp) # 메모리에서 $s0 값은 MEM 단계가 끝나야 확보됨
nop # 1-사이클 버블(Stall) 삽입 필요 (인터락 하드웨어가 삽입)
add $t1, $s0, $t2 # MEM/WB 파이프라인 레지스터에서 EX 단계로 포워딩
# 3. 분기 지연 슬롯 (Branch Delay Slot)
beq $t0, $t1, target # 분기 여부와 무관하게 바로 다음 1개 명령어가 실행됨
add $v0, $zero, $zero # <- 지연 슬롯에 독립 명령어 배치 (없으면 nop)
# 1. Data hazard resolved via Forwarding (no stall required)
add $s0, $t0, $t1 # $s0 = $t0 + $t1 (result produced in EX stage)
sub $t2, $s0, $t3 # Bypass $s0 from EX/MEM pipeline register directly into ALU input
# 2. Load-Use hazard that cannot be resolved by forwarding alone (1-cycle stall required)
lw $s0, 0($sp) # $s0 value from memory is only available after the MEM stage
nop # 1-cycle bubble (stall) required (inserted by hardware interlock)
add $t1, $s0, $t2 # Forwarded from MEM/WB pipeline register to EX stage
# 3. Branch Delay Slot
beq $t0, $t1, target # The immediately following instruction executes regardless of branch outcome
add $v0, $zero, $zero # <- Place independent work in the delay slot (or nop if none)
4. 실무 적용 및 주의사항4. Practical Considerations and Caveats
- Load-Use 해저드 회피 스케줄링:
lw명령어 직후에 로드된 레지스터를 바로 연산에 사용하면 포워딩을 쓰더라도 1사이클 스톨(Stall)이 불가피하므로, 컴파일러나 어셈블리 작성자는lw와 사용처 사이에 연관 없는 다른 명령어를 배치해 파이프라인 정지를 줄여야 합니다. - 지연 슬롯(Delay Slot)의 설계 한계: 초기 단일 이슈 파이프라인에서 분기 페널티를 숨기기 위해 분기 직후 명령어를 무조건 실행하도록 설계되었으나, 슈퍼스칼라 구조와 예외 복귀 처리를 복잡하게 만들어 RISC-V 등 최신 아키텍처에서는 제거되었습니다.
$zero레지스터 활용:$0($zero)는 항상 0으로 고정되어 있어 별도의 명령어 추가 없이 레지스터 초기화나 복사(add $t0, $s0, $zero)를 단일 R-Type 명령어로 처리할 수 있습니다.
- Instruction Scheduling for Load-Use Hazards: Consuming a register immediately after
lwincurs a 1-cycle stall even with forwarding hardware; compilers and assembly authors should schedule an independent instruction betweenlwand the dependent operation. - Architectural Trade-offs of Delay Slots: Branch delay slots hid branch penalties in early single-issue pipelines, but they complicated superscalar execution and precise exception recovery, leading modern ISAs like RISC-V to omit them.
- Leveraging the
$zeroRegister: Because$0($zero) is hardwired to zero, register clearing and register-to-register moves (add $t0, $s0, $zero) can be synthesized from standard R-Type instructions without dedicated opcodes.
고정 폭 명령어 포맷과 파이프라인 포워딩 경로를 이해하면 어셈블리 수준에서 스톨을 유발하는 명령어 배치를 피하고 프로세서 처리량을 높일 수 있습니다.
Understanding fixed-width instruction encoding and pipeline forwarding paths helps developers schedule instructions to avoid stalls and maximize execution throughput.