ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Architecture / ISA > RISC-V (RV32I) 레지스터 아키텍처 및 ABI 함수 호출 규약(Calling Convention)RISC-V (RV32I) Register Architecture and ABI Calling Convention
Architecture / ISA Intermediate RISC-V RV32I / RARS Simulator / GCC

RISC-V (RV32I) 레지스터 아키텍처 및 ABI 함수 호출 규약(Calling Convention)RISC-V (RV32I) Register Architecture and ABI Calling Convention

오픈 표준 아키텍처인 RISC-V 32비트 기본 정수(RV32I) 레지스터 32개의 ABI 명칭과 역할, Caller-Saved vs Callee-Saved 보존 규칙, 스택 프레임 프롤로그·에필로그 구현을 다룹니다.Covers the 32 general-purpose registers in RISC-V RV32I, their ABI names and roles, Caller-Saved vs. Callee-Saved preservation rules, and stack frame prologue/epilogue assembly.

#RISC-V #RV32I #Assembly #ABI #Computer Architecture
핵심 개념RISC-V는 UC 버클리에서 설계된 오픈 표준 ISA입니다. RV32I는 32개의 32비트 범용 레지스터(x0~x31)를 가지며, 표준 ABI(Application Binary Interface)에 따라 함수 인자 전달(a0~a7), 반환 주소(ra), 스택 포인터(sp), 임시 변수(t0~t6), 보존 레지스터(s0~s11)로 역할이 구분됩니다.
Key ConceptRISC-V is an open-standard ISA originated at UC Berkeley. RV32I provides thirty-two 32-bit general-purpose registers (x0–x31) partitioned by the standard ABI (Application Binary Interface) into function arguments (a0–a7), return address (ra), stack pointer (sp), temporaries (t0–t6), and saved registers (s0–s11).

1. RV32I 레지스터 매핑 및 ABI 명칭1. RV32I Register Mapping and ABI Names

좌우로 밀어서 표 전체 내용을 확인하세요
레지스터ABI 이름보존자 (Saver)용도 및 설명
x0zero-하드웨어 0 (항상 0이며 쓰기 무시)
x1raCallerReturn Address (함수 복귀 주소)
x2spCalleeStack Pointer (스택 최상단 포인터)
x3gp-Global Pointer (전역 데이터 접근 기준)
x4tp-Thread Pointer (스레드별 로컬 데이터)
x5 - x7t0 - t2Caller임시 레지스터 (호출 후 값 보존 안 됨)
x8 / x9s0 / s1 (fp)Callee보존 레지스터 / 프레임 포인터
x10 - x11a0 - a1Caller함수 인자 1~2 / 반환값 1~2
x12 - x17a2 - a7Caller함수 인자 3~8
x18 - x27s2 - s11Callee보존 레지스터 (함수 종료 시 복원 필수)
x28 - x31t3 - t6Caller추가 임시 레지스터
Swipe horizontally to view the full table
RegisterABI NameSaverRole and Description
x0zero-Hardwired zero (always reads 0, writes ignored)
x1raCallerReturn Address
x2spCalleeStack Pointer
x3gp-Global Pointer (base for static data access)
x4tp-Thread Pointer (thread-local storage)
x5 - x7t0 - t2CallerTemporary registers (not preserved across calls)
x8 / x9s0 / s1 (fp)CalleeSaved registers / Frame Pointer
x10 - x11a0 - a1CallerFunction arguments 1–2 / Return values 1–2
x12 - x17a2 - a7CallerFunction arguments 3–8
x18 - x27s2 - s11CalleeSaved registers (must be restored before return)
x28 - x31t3 - t6CallerAdditional temporary registers

2. Caller-Saved vs Callee-Saved 보존 규칙2. Caller-Saved vs. Callee-Saved Preservation Rules

  • Caller-Saved (호출자 보존 - t0~t6, a0~a7, ra): 함수를 호출하는 쪽(Caller)에서 이 레지스터의 값이 유지되어야 한다면, 함수 호출(jal) 전에 자신의 스택에 저장해야 합니다. 피호출자는 이 레지스터를 별도 백업 없이 덮어쓸 수 있습니다.
  • Callee-Saved (피호출자 보존 - s0~s11, sp): 호출을 받은 함수(Callee)는 이 레지스터를 사용하려면 진입 시 스택에 백업하고, 반환 직전에 원래 값으로 복원해 두어야 합니다.
  • Caller-Saved (t0–t6, a0–a7, ra): If the calling function (Caller) needs values in these registers to survive a subroutine call (jal), it must spill them to its own stack frame before the call. The callee may overwrite them freely.
  • Callee-Saved (s0–s11, sp): Any subroutine (Callee) that modifies these registers must back them up on the stack upon entry and restore their original values before returning.

3. 표준 함수 프롤로그 및 에필로그 어셈블리3. Standard Function Prologue and Epilogue Assembly

riscv_function_convention.s
# C 함수: int compute(int a, int b) {
#     return helper(a + 5) + (b * 2);
# }

.globl compute
compute:
    # --- [프롤로그 (Prologue)] ---
    # 표준 ABI에서 스택 포인터는 16바이트 단위 정렬(16-byte aligned) 유지
    addi sp, sp, -16      # 스택 프레임 16바이트 할당
    sw   ra, 12(sp)       # 다른 함수(helper)를 호출하므로 ra 저장
    sw   s0, 8(sp)        # Callee-saved 레지스터 s0 백업
    sw   s1, 4(sp)        # Callee-saved 레지스터 s1 백업

    # --- [본문 (Body)] ---
    mv   s0, a0           # 인자 a 저장
    slli s1, a1, 1        # s1 = b * 2 (좌측 시프트 1비트)

    addi a0, s0, 5        # helper의 첫 번째 인자 (a + 5)
    jal  ra, helper       # helper(a + 5) 호출 (반환값은 a0에 담김)

    add  a0, a0, s1       # 결과 = helper결과(a0) + (b * 2)(s1)

    # --- [에필로그 (Epilogue)] ---
    lw   ra, 12(sp)       # ra 복원
    lw   s0, 8(sp)        # s0 복원
    lw   s1, 4(sp)        # s1 복원
    addi sp, sp, 16       # 스택 프레임 반환
    ret                   # 복귀 (jalr zero, ra, 0)
riscv_function_convention.s
# C function: int compute(int a, int b) {
#     return helper(a + 5) + (b * 2);
# }

.globl compute
compute:
    # --- [Prologue] ---
    # The standard ABI requires 16-byte stack pointer alignment
    addi sp, sp, -16      # Allocate 16-byte stack frame
    sw   ra, 12(sp)       # Save ra because we call another function (helper)
    sw   s0, 8(sp)        # Save callee-saved register s0
    sw   s1, 4(sp)        # Save callee-saved register s1

    # --- [Body] ---
    mv   s0, a0           # Preserve argument a in s0
    slli s1, a1, 1        # s1 = b * 2 (logical left shift by 1 bit)

    addi a0, s0, 5        # First argument for helper: (a + 5)
    jal  ra, helper       # Call helper(a + 5); return value placed in a0

    add  a0, a0, s1       # Result = helper_return(a0) + (b * 2)(s1)

    # --- [Epilogue] ---
    lw   ra, 12(sp)       # Restore ra
    lw   s0, 8(sp)        # Restore s0
    lw   s1, 4(sp)        # Restore s1
    addi sp, sp, 16       # Deallocate stack frame
    ret                   # Return (jalr zero, ra, 0)

4. 실무 적용 및 주의사항4. Practical Considerations and Caveats

  • 스택 포인터(sp) 16바이트 정렬 규격: RISC-V 표준 psABI 규약에서는 32비트(RV32I) 환경에서도 64비트/128비트 확장 호환성 및 캐시 정렬을 위해 함수 호출 시점의 sp를 16바이트 배수로 맞추도록 규정하고 있습니다.
  • 리프 함수(Leaf Function) 최적화: 내부에서 다른 함수를 전혀 호출하지 않는 말단 함수(Leaf Function)는 ra를 덮어쓸 일이 없고 t0~t6, a0~a7만으로도 연산이 가능하므로 스택 프레임 할당 없이 즉시 실행 후 ret로 복귀할 수 있습니다.
  • 넉넉한 인자 및 보존 레지스터 활용: MIPS는 인자 레지스터가 4개($a0~$a3)뿐이었으나, RISC-V는 8개(a0~a7)의 인자 레지스터와 12개(s0~s11)의 보존 레지스터를 제공하여 불필요한 스택 메모리 접근을 줄여줍니다.
  • 16-Byte Stack Alignment (sp): The RISC-V psABI mandates keeping sp aligned to 16-byte boundaries at function call boundaries even on 32-bit RV32I targets to ensure compatibility with 64/128-bit data types.
  • Leaf Function Optimization: A leaf function that makes no nested calls does not need to save ra and can operate entirely within t0–t6 and a0–a7, avoiding stack allocation altogether.
  • Expanded Argument Register Set: Providing 8 argument registers (a0–a7) and 12 saved registers (s0–s11) compared to MIPS's 4 argument registers ($a0–$a3) reduces stack traffic during function calls.

C 컴파일러(GCC/Clang)가 생성한 목적 파일과 수동 작성한 어셈블리 루틴을 링크할 때는 Caller-Saved와 Callee-Saved 레지스터 보존 계약 및 16바이트 스택 정렬 규칙을 정확히 준수해야 합니다.

When linking handwritten RISC-V assembly routines with C object files compiled by GCC or Clang, strictly following Caller/Callee register preservation rules and 16-byte stack alignment prevents stack corruption.