Architecture / ISA
Intermediate
RISC-V RVC / GCC (-march=rv32imc)
코드 크기를 30% 줄이는 RISC-V 16비트 압축 명령어(RVC / C 확장) 원리Principles of RISC-V 16-Bit Compressed Instructions (RVC / C Extension)
임베디드 플래시 메모리 제약을 완화하기 위해 빈번히 사용되는 명령어를 16비트로 인코딩하여 명령어 캐시 히트율과 코드 밀도를 높이는 RVC 확장 기술입니다.How the RISC-V C Extension (RVC) encodes frequent instructions into 16 bits to reduce binary size by 25–30% and improve instruction cache hit rates on embedded targets.
#RISC-V #RVC #Optimization #Embedded #Compression
핵심 개념ARM Thumb-2와 유사하게, RISC-V는 C 확장(Compressed Instructions)을 통해 자주 사용되는 명령어를 16비트 포맷(
c.li, c.mv, c.add, c.lw, c.swsp 등)으로 압축 제공합니다. 모든 16비트 압축 명령어는 정규 32비트 명령어와 1:1로 대응되므로, 파이프라인 IF/ID 앞단의 경량 디코더에서 32비트 명령어로 즉시 확장할 수 있는 효율적인 하드웨어 구조가 특징입니다.Key ConceptSimilar to ARM Thumb-2, RISC-V provides the C Extension (Compressed Instructions) to encode common operations in a 16-bit format (
c.li, c.mv, c.add, c.lw, c.swsp). Because every 16-bit RVC instruction maps 1:1 to a standard 32-bit RV32I instruction, a lightweight pre-decoder in the IF/ID pipeline stage can expand compressed instructions into 32-bit equivalents with minimal gate overhead.1. 압축 명령어 1:1 매핑 예시1. 1:1 Compressed Instruction Mapping Examples
좌우로 밀어서 표 전체 내용을 확인하세요
| 압축 명령어 (16-bit) | 정규 RV32I 동등 명령어 (32-bit) | 적용 조건 및 바이트 절감 |
|---|---|---|
| c.li rd, imm | addi rd, zero, imm | 6비트 부호 상수 범위 내 50% 절감 (2 bytes) |
| c.mv rd, rs2 | add rd, zero, rs2 | 레지스터 간 복사 시 50% 절감 (2 bytes) |
| c.j offset | jal zero, offset | 11비트 오프셋 점프 시 50% 절감 (2 bytes) |
| c.lw rd', offset(rs1') | lw rd', offset(rs1') | x8~x15 (s0~s1, a0~a5) 사용 시 50% 절감 |
| c.lwsp rd, offset(sp) | lw rd, offset(sp) | 스택 포인터(sp) 기준 로드 시 50% 절감 |
Swipe horizontally to view the full table
| Compressed Instruction (16-bit) | Standard RV32I Equivalent (32-bit) | Constraint and Byte Savings |
|---|---|---|
| c.li rd, imm | addi rd, zero, imm | 50% reduction (2 bytes) for 6-bit signed immediates |
| c.mv rd, rs2 | add rd, zero, rs2 | 50% reduction (2 bytes) for register-to-register moves |
| c.j offset | jal zero, offset | 50% reduction (2 bytes) for 11-bit jump offsets |
| c.lw rd', offset(rs1') | lw rd', offset(rs1') | 50% reduction when using x8–x15 (s0–s1, a0–a5) |
| c.lwsp rd, offset(sp) | lw rd, offset(sp) | 50% reduction for stack-pointer-relative word loads |
2. 어셈블러 자동 압축 및 레지스터 선택 코드 예제2. Automatic Assembler Compression and Register Selection Example
# GCC/AS 옵션: -march=rv32imc
# 어셈블러는 정규 문법으로 작성해도 조건이 맞으면 자동으로 16비트 RVC 명령어로 인코딩합니다.
.option rvc # 압축 명령어 자동 변환 활성화
.globl sum_array
sum_array:
# a0(x10): 배열 포인터, a1(x11): 원소 개수 (모두 x8~x15 압축 대상 레지스터)
li a2, 0 # -> c.li a2, 0 (2 바이트)
loop:
beqz a1, done # -> c.beqz a1, done (2 바이트, a1이 x8~x15 범위에 속함)
lw a3, 0(a0) # -> c.lw a3, 0(a0) (2 바이트)
add a2, a2, a3 # -> c.add a2, a3 (2 바이트, 목적지와 소스가 동일한 누적 덧셈)
addi a0, a0, 4 # -> c.addi a0, 4 (2 바이트)
addi a1, a1, -1 # -> c.addi a1, -1 (2 바이트)
j loop # -> c.j loop (2 바이트)
done:
mv a0, a2 # -> c.mv a0, a2 (2 바이트)
ret # -> c.jr ra (2 바이트)
# GCC/AS flag: -march=rv32imc
# The assembler automatically emits 16-bit RVC encodings from standard mnemonics when constraints are met.
.option rvc # Enable automatic compressed instruction selection
.globl sum_array
sum_array:
# a0(x10): array pointer, a1(x11): element count (both within x8~x15 prime register range)
li a2, 0 # -> c.li a2, 0 (2 bytes)
loop:
beqz a1, done # -> c.beqz a1, done (2 bytes; a1 is within x8~x15)
lw a3, 0(a0) # -> c.lw a3, 0(a0) (2 bytes)
add a2, a2, a3 # -> c.add a2, a3 (2 bytes; destructive 2-operand addition)
addi a0, a0, 4 # -> c.addi a0, 4 (2 bytes)
addi a1, a1, -1 # -> c.addi a1, -1 (2 bytes)
j loop # -> c.j loop (2 bytes)
done:
mv a0, a2 # -> c.mv a0, a2 (2 bytes)
ret # -> c.jr ra (2 bytes)
3. 실무 적용 및 주의사항3. Practical Considerations and Caveats
- 프라임 레지스터(
x8~x15) 우선 활용: 16비트 공간 안에 레지스터 번호를 담기 위해 많은 RVC 명령어(c.lw,c.sw,c.beqz,c.sub)는 3비트 레지스터 필드(x8~x15, 즉s0~s1및a0~a5)만 지정할 수 있습니다. 자주 쓰는 변수를 이 레지스터들에 배치하면 압축률이 높아집니다. - 2바이트 명령어 경계와 PC 증가폭 변화: RVC가 활성화된 환경에서는 명령어가 2바이트(16비트) 단위로 정렬되며, 32비트 명령어가 4바이트 비정렬 주소(2바이트 경계)에 걸칠 수 있습니다. 따라서 예외 핸들러에서
mepc를 증가시킬 때 해당 명령어의 하위 2비트가11인지(32비트 명령어) 아니면00/01/10인지(16비트 압축 명령어) 확인해야 합니다. - 모드 전환 오버헤드 없음: ARM의 구형 Thumb 모드처럼 상태 비트를 바꾸며 분기(
bx)할 필요 없이, 동일한 코드 섹션 안에서 16비트와 32비트 명령어를 자유롭게 섞어 쓸 수 있습니다.
- Prefer Prime Registers (
x8–x15) in Hot Loops: To fit within 16 bits, many RVC instructions (c.lw,c.sw,c.beqz,c.sub) use 3-bit register specifiers restricted tox8–x15(s0–s1anda0–a5). Allocating hot variables to these eight registers increases compression density. - 2-Byte Instruction Alignment and Variable PC Stride: With RVC enabled, instructions align on 2-byte boundaries and 32-bit instructions may straddle 4-byte boundaries. Trap handlers advancing
mepcmust inspect the lowest two bits of the instruction parcel (11for 32-bit, anything else for 16-bit) to determine whether to add 4 or 2. - Zero Mode-Switching Overhead: Unlike legacy ARM/Thumb interworking, RISC-V mixes 16-bit and 32-bit instructions freely in the same instruction stream without mode bits.
RVC 확장은 별도의 소스 코드 수정 없이 컴파일러 플래그(-march=rv32imc)와 어셈블러의 자동 변환만으로도 전체 바이너리 크기를 평균 25~30% 절감하여 임베디드 MCU의 명령어 캐시 효율을 높여줍니다.
Enabling RVC via -march=rv32imc shrinks compiled code size by 25–30% without source changes, directly reducing instruction cache misses on memory-constrained microcontrollers.