자막
음성

Lec 11 · branch prediction 마무리 (trace cache·predication), exception 과 interrupt

정밀 정리 · 검증 2026-09-24 18:17

1개요

1.1앞부분(~34분)은 Lecture 10 branch prediction 마무리: predictor state 갱신 시점, trace cache, x86 decoding, predication, SW hint.
1.234분부터 Lecture 11: 예기치 않은 event 처리 — polling vs interrupt, interrupt 종류(synchronous/asynchronous/system call)와 source.
1.3OS 의 virtualization·protection 을 위한 privilege level 과, pipeline 에서의 precise interrupt·flush.
1.4RISC-V CSR(SSTATUS/SEPC/SCAUSE), direct/vectored handler, ERET 복귀, MIPS handler 예까지 진행하고 nesting interrupt 도입에서 끝남 (slide 25~28 미진행).

2섹션별 정리 상황·문제 → 원인 → 해결

2.14:33–11:37pipeline 안의 branch predictor 상태 갱신 시점
상황·문제pipeline 안에 branch 가 여러 개 있으면 앞 branch 의 결과가 나오기 전에 뒤 branch 를 예측해야 한다.
원인PHT(pattern history table) 는 바로 갱신해도 뒤 예측이 같은 방향이라 이득이 없다. branch history(최근 5개 결과 등)는 바로 반영해야 뒤 예측이 달라진다.
해결PHT 는 실제 outcome 이 나온 뒤 갱신. history 는 예측 직후 추측 갱신하고, 틀리면 이전 state 로 복구(추가 storage·복구 mechanism 필요).
  • 예측 대상은 target PC 와 branch direction 두 가지
  • history 에 taken 을 LSB 로 shift-in (예: 1,0,0,1,1)
  • 강의자: 고급 주제, 완전히 이해 못해도 괜찮다
p.27
2.1.1 · p.27 · 4:50 · BEQ 2개와 BHT 값을 손필기로 설명
2.1.r.1Branch predictor (Wikipedia) ↗ · global history, return stack buffer, neural(perceptron) predictor 개요
2.211:37–13:18speculative execution 요약
상황·문제fetch 하는 모든 instruction 에 대해 예측한 next PC 를 pipeline 따라 들고 가야 한다.
원인실제 outcome(branch resolution) 은 나중 stage 에서야 알 수 있다.
해결맞으면 BHT 등 갱신. 틀리면 BHT·BTB 갱신 + wrong path 의 younger instruction flush + 올바른 target 에서 재시작.
  • 5-stage in-order RISC-V 에서는 비교적 쉽다
  • deeply pipelined superscalar out-of-order CPU 에서는 훨씬 복잡
  • return address stack 은 지난 시간에 다룸 (791s 에 잠깐 넘김)
p.29
2.2.1 · p.29 · 11:37
p.28
2.2.2 · p.28 · 13:11 · 이미 다뤘다며 넘김
2.2.r.1Branch predictor (Wikipedia) ↗ · global history, return stack buffer, neural(perceptron) predictor 개요
2.313:18–19:33trace caching
상황·문제static instruction count 가 큰 basic block(E) 보다 실제로 많이 실행되는 경로(D→F→G)가 더 중요하다.
원인일반 I-cache 는 static 배치대로 저장해 안 쓰는 경로 instruction 까지 fetch·보관한다.
해결자주 실행되는 basic block 연속(trace)을 하나의 단위로 저장. PC 와 branch 예측 결과로 trace 를 찾는다. 단 여러 경로를 담으면 중복으로 공간 낭비.
  • static count = 실행 파일 속 instruction 수, dynamic count = 실제 실행된 수
  • 10 instruction loop 을 10번 돌면 dynamic count 100
  • trace cache 는 pros/cons 가 있다
p.30
2.3.1 · p.30 · 13:18
2.3.r.1Trace cache (Wikipedia) ↗ · dynamic instruction stream(trace) 저장, Pentium 4 사례
2.419:33–25:20x86 front-end: Pentium 4 trace cache 와 decoding
상황·문제x86 은 CISC 라 instruction 이 가변 길이(1 byte~10여 byte)이고 decode 가 어렵다.
원인현재 instruction 을 decode 해야 다음 instruction 시작 위치를 알 수 있다.
해결(1) ILD 로 길이를 판정해 경계를 찾고 (2) dynamic translation 으로 micro-op 변환. Pentium 4 는 micro-op 을 trace cache 에 보관.
  • ILD 는 보통 1 instruction/cycle, 복잡한 경우 여러 cycle
  • 대부분 1 x86 instruction → 1 uop, 복잡하면 4 uop 이상
  • trace cache 에서 못 찾으면 memory 에서 fetch → decoder → uop (BTB 2개)
p.31
2.4.1 · p.31 · 19:33
p.32
2.4.2 · p.32 · 22:16
2.4.r.1Trace cache (Wikipedia) ↗ · dynamic instruction stream(trace) 저장, Pentium 4 사례
2.4.r.2Micro-operation (Wikipedia) ↗ · x86 instruction 을 micro-op 으로 decode/translate 하는 과정
2.525:20–30:39predicated execution (if-conversion)
상황·문제branch 예측이 틀리면 wrong path instruction 을 flush 해야 한다.
원인control flow 가 branch outcome 에 의존하기 때문.
해결양쪽 basic block 을 모두 pipeline 에 넣고 predicate 가 false 인 instruction 은 no-op 처리. 대신 필요 없는 instruction 도 자원을 소모한다.
  • Itanium: 64개 1-bit predicate register, instruction 마다 predicate field
  • branch predictor 가 부정확할 때 유리
  • 단점: 모두 pipeline 을 통과하므로 resource 낭비 (학생 질문으로 확인)
p.33
2.5.1 · p.33 · 25:20
2.5.r.1Predication (computer architecture) (Wikipedia) ↗ · predicated execution·if-conversion, IA-64 의 64개 predicate register
2.630:39–34:06software 의 branch prediction 참여, 정리
상황·문제hardware 만으로 예측하지 않고 software 가 도울 수 있다.
원인program 을 아는 쪽(프로그래머·compiler)이 branch 경향을 알려줄 수 있다.
해결branch 마다 taken/not-taken hint 를 인코딩(C 에서 GCC 로 unlikely 표시). Itanium 의 brp instruction 으로 BTB 상태를 미리 설정, TAR hit 는 다른 예측을 override.
  • hardware 는 hint 를 사용하거나 무시할 수 있다
  • 추천 논문: Dynamic Branch Prediction with Perceptrons
p.34
2.6.1 · p.34 · 30:39
p.35
2.6.2 · p.35 · 33:08
p.36
2.6.3 · p.36 · 33:14
2.6.r.1GCC Other Builtins: __builtin_expect ↗ · 강의에서 말한 C 코드의 branch 'likely/unlikely' hint 의 실제 GCC 문법
2.6.r.2Jiménez & Lin, Dynamic Branch Prediction with Perceptrons (HPCA'01, PDF) ↗ · 강의가 추천한 perceptron branch predictor 원 논문
2.734:06–40:23예기치 않은 event 와 interrupt control transfer
상황·문제instruction 실패(invalid instruction), I/O 입력(keyboard), time-shared 시스템의 quantum 만료 같은 event 를 처리해야 한다.
원인polling 은 toaster 같은 단순 embedded 시스템엔 괜찮지만, I/O device 가 수백 개면 대부분 event 가 없는데도 확인하느라 overhead 가 크다.
해결interrupt: 평소엔 정상 실행, event 가 나면 알림을 받아 exception handler 로 제어 이동 후 중단된 instruction 에서 재시작. 원래 program 에 투명해야 한다.
  • interrupt = 예측·준비할 수 없는 handler 호출
  • control 은 interrupted instruction 으로 복귀
  • transparent = main thread 에 보이는 영향 없음
p.2
2.7.1 · p.2 · 34:12
p.3
2.7.2 · p.3 · 38:46
2.7.r.1Polling (computer science) (Wikipedia) ↗ · polling 정의와 interrupt 대비 비효율
2.840:23–45:17interrupt 종류와 source
상황·문제interrupt 는 원인에 따라 처리 긴급도가 다르다.
원인특정 instruction 에 묶인 것(synchronous)과 외부 event(asynchronous), 의도적 trap 이 있다.
해결synchronous(exception): illegal opcode/operand, page fault 등, forward progress 불가라 즉시 처리. asynchronous(interrupt): I/O·timer, 약간 지연 가능하나 무한정 미룰 수 없음. system call: printf 안의 trap 처럼 OS 경유 I/O 요청.
  • 교과서 정의의 exception 은 interrupt 를 포함 (용어 혼용 주의)
  • exception 은 datapath(failed/system call instruction)에서, interrupt 는 interrupt control logic 의 IRQ line 으로 들어온다
p.4
2.8.1 · p.4 · 40:23
p.5
2.8.2 · p.5 · 44:23
2.8.r.1System call (Wikipedia) ↗ · user program 이 trap/software interrupt 로 OS 서비스를 요청하는 방식
2.945:17–51:42virtualization·protection 과 privilege level
상황·문제browser, PowerPoint, Zoom 등 여러 process 가 time-share 하지만 각자 전용 machine 처럼 동작한다.
원인process 가 다른 process 의 state·device 를 직접 조작하면 서로를 망칠 수 있다.
해결OS 가 device handler·thread scheduler 를 관리하고 별도 privileged(protected, kernel) mode 를 둔다. interrupt 때만 user → privileged 로 전환, 처리 후 user 로 복귀.
  • user-level process 는 private architectural state 만 본다
  • privilege 동심원: hypervisor > OS > user
  • user code 는 privileged mode 에서 절대 실행되지 않는다
p.6
2.9.1 · p.6 · 45:17
p.7
2.9.2 · p.7 · 48:32
p.8
2.9.3 · p.8 · 50:01
2.9.r.1Protection ring (Wikipedia) ↗ · kernel/user privilege level 계층 (slide 7 동심원 그림)
2.9.r.2Hypervisor (Wikipedia) ↗ · 여러 OS 를 가상화하는 hypervisor level
2.1051:42–57:32precise vs imprecise interrupt
상황·문제code 의미론은 instruction 을 하나씩 원자적으로 실행하지만 pipeline 에선 실행이 겹친다.
원인exception 시점에 앞뒤 instruction 이 부분적으로 실행된 상태로 pipeline 에 있다.
해결precise: older 는 완료, younger 는 실행 안 된 것처럼 보이게 → OS 쉬움, HW 복잡. imprecise: HW 단순, OS 가 younger 의 부분 효과를 고려해야 함.
  • precise 면 handler 후 faulting instruction 부터 재실행하면 된다
  • RISC-V 와 대부분 현대 architecture 가 precise 지원 (슬라이드)
p.9
2.10.1 · p.9 · 51:23
p.10
2.10.2 · p.10 · 51:44
2.10.r.1Smith & Pleszkun, Implementing Precise Interrupts in Pipelined Processors (1988, PDF) ↗ · precise interrupt 정의와 pipeline 에서의 구현법 5가지 (slide 28 선택 논문)
2.1157:32–1:00:53pipeline 정지와 재시작
상황·문제t5 에 I3 가 EX 에서 exception 을 낸다.
원인I3 는 계속 실행될 수 없고 뒤 instruction 도 이어갈 수 없다.
해결I3·I4·I5 를 bubble 로 flush 하고 t6 부터 handler(Ih) 를 fetch. asynchronous interrupt 는 이미 pipeline 에 있는 instruction 을 마치고 handler 를 시작해도 된다.
  • slide 11 의 bub/Ih 칸은 애니메이션으로 채워짐
  • slide 12 질문: I2~I5 가 모두 t5 에 exception 이면?
  • 3628s 출석 체크 (chat)
p.11
2.11.1 · p.11 · 57:32
p.12
2.11.2 · p.12 · 59:03
2.11.r.1Instruction pipelining (Wikipedia) ↗ · pipeline bubble·flush 기본 개념
2.11.r.2Smith & Pleszkun, Implementing Precise Interrupts in Pipelined Processors (1988, PDF) ↗ · precise interrupt 정의와 pipeline 에서의 구현법 5가지 (slide 28 선택 논문)
2.121:00:53–1:03:32stage 별 exception 원인
상황·문제pipeline stage 마다 생길 수 있는 exception 이 다르다.
원인각 stage 가 접근하는 자원(I-mem, decoder, ALU, D-mem)이 다르다.
해결IF: instruction memory address/protection fault. ID: illegal opcode, 미구현 instruction SW emulation, system call. EX: divide-by-zero, overflow(MIPS 만). MEM: data memory protection fault. WB: 멈출 수 없음.
  • overflow exception 은 MIPS 에는 있고 RISC-V 에는 없다
  • asynchronous interrupt 는 원하는 instruction/stage 에 연결할 수 있다
p.13
2.12.1 · p.13 · 1:00:53
2.131:03:32–1:08:23RISC-V interrupt architecture: CSR
상황·문제interrupt 처리에 필요한 state 를 user 가 건드리지 못하게 보관해야 한다.
원인PC 는 handler 가 곧 덮어쓰고, x1 은 user 의 return address 라 쓸 수 없다.
해결privileged CSR(CSRRW 로 접근): SSTATUS(interrupt enable, privilege mode), SEPC(중단된 instruction 주소), SCAUSE(MSB=interrupt bit, 나머지=exception code). HW 는 SW 가 저장 못 하는 것만 자동 저장.
  • SCAUSE 예: interrupt 1/code 5 = supervisor timer interrupt
  • HW 가 자동 저장해야 하는 것은 아주 적다
p.15
2.13.1 · p.15 · 1:03:43
p.16
2.13.2 · p.16 · 1:05:47
p.17
2.13.3 · p.17 · 1:06:32
2.13.r.1The RISC-V Instruction Set Manual Vol. II: Privileged Architecture (PDF) ↗ · sepc·scause·stvec(Direct/Vectored)·SRET 원문 정의
2.141:08:23–1:11:52handler 선택: direct vs vectored
상황·문제원인(I/O, invalid instruction, data memory 접근 등)에 따라 다른 처리를 해야 한다.
원인어느 handler 로 갈지 결정하는 방식이 필요하다.
해결option 1(direct): 항상 STVEC 주소로 가서 초기 handler 가 cause 를 보고 분기 (RISC-V, MIPS). option 2(vectored): cause 별 주소로 바로 점프, 공간 제한 때문에 길면 real handler 로 점프 (x86, Arm, RISC-V).
  • handler 주소는 user process 가 jump 할 수 없게 보호
  • vectored 는 cause 별 slot 크기 제한이 있다
p.18
2.14.1 · p.18 · 1:08:23
p.19
2.14.2 · p.19 · 1:10:20
2.14.r.1The RISC-V Instruction Set Manual Vol. II: Privileged Architecture (PDF) ↗ · sepc·scause·stvec(Direct/Vectored)·SRET 원문 정의
2.14.r.2Interrupt vector table (Wikipedia) ↗ · 원인별 handler 주소 table (vectored interrupt)
2.151:11:52–1:14:06handler 예와 interrupt 복귀
상황·문제interrupt 종류별로 handler 가 하는 일이 다르고, 끝나면 원래 위치로 돌아가야 한다.
원인external interrupt 는 device 서비스, exception 은 수정·signal·kill 중 선택, system call 은 OS 기능 수행.
해결ERET 로 CPU state 복원(PC←SEPC), privilege 를 user 로 복원, 중단 주소로 jump 를 원자적으로 수행.
  • mouse, keyboard, display, network card 마다 device-specific handler
  • 강의·슬라이드는 ERET, RISC-V spec 의 S-mode 복귀 명령은 SRET
p.20
2.15.1 · p.20 · 1:11:52
p.21
2.15.2 · p.21 · 1:13:12
2.15.r.1The RISC-V Instruction Set Manual Vol. II: Privileged Architecture (PDF) ↗ · sepc·scause·stvec(Direct/Vectored)·SRET 원문 정의
2.161:14:06–1:18:33MIPS handler 예와 nesting interrupt 도입
상황·문제handler 실행 중 새 interrupt 가 오면 어떻게 할지 정해야 한다.
원인interrupt 를 재활성화하지 않으면 그동안의 interrupt 는 무시된다.
해결아주 짧은 handler 는 r26·r27 만 쓰고 재활성화 안 함. 조금 길면 stack 에 r8·r9 저장 후 사용. 중요한 interrupt 를 놓치지 않으려면 재활성화(nested) — 다음 강의로 이어짐.
  • MIPS 복귀: mfc0 r26,epc / jr r26 / rfe (RISC-V 는 ERET 하나)
  • slide 25~28 은 이번 강의에서 다루지 않음
p.22
2.16.1 · p.22 · 1:14:06
p.23
2.16.2 · p.23 · 1:16:09
p.24
2.16.3 · p.24 · 1:17:13
2.16.r.1Interrupt handler (Wikipedia) ↗ · interrupt masking, nested interrupt, priority

3핵심 개념

3.1static vs dynamic instruction count(정적/동적 명령어 수)
static 은 실행 파일 속 instruction 수, dynamic 은 실제 실행된 수. 10개짜리 loop 을 10번 돌면 dynamic 100.
3.2trace cache(트레이스 캐시)
자주 실행되는 basic block 연속을 한 line 으로 저장. PC + branch 예측으로 접근.
3.2.r.1Trace cache (Wikipedia) ↗ · dynamic instruction stream(trace) 저장, Pentium 4 사례
3.3micro-op(마이크로 연산)
x86 instruction 을 RISC 형태로 바꾼 내부 연산. 대부분 1:1, 복잡하면 4개 이상.
3.3.r.1Micro-operation (Wikipedia) ↗ · x86 instruction 을 micro-op 으로 decode/translate 하는 과정
3.4predicated execution(프레디케이션 실행)
양쪽 경로를 모두 실행하되 predicate false 인 instruction 은 no-op. flush 가 없지만 resource 낭비.
3.4.r.1Predication (computer architecture) (Wikipedia) ↗ · predicated execution·if-conversion, IA-64 의 64개 predicate register
3.5polling vs interrupt(폴링 vs 인터럽트)
polling 은 주기적 확인(단순 embedded 에 적합), interrupt 는 event 시 알림(device 많을 때 효율적).
3.5.r.1Polling (computer science) (Wikipedia) ↗ · polling 정의와 interrupt 대비 비효율
3.6synchronous / asynchronous interrupt(동기/비동기 인터럽트)
synchronous(exception)는 특정 instruction 에 묶여 즉시 처리. asynchronous(interrupt)는 외부 event, 약간 지연 가능.
3.7system call / trap(시스템 호출)
exception 발생만이 목적인 instruction. I/O 는 OS 만 접근 가능해 printf 도 이를 거친다.
3.7.r.1System call (Wikipedia) ↗ · user program 이 trap/software interrupt 로 OS 서비스를 요청하는 방식
3.8privileged mode(특권 모드)
kernel/protected mode. interrupt 때만 진입하며 user code 는 여기서 실행되지 않는다.
3.8.r.1Protection ring (Wikipedia) ↗ · kernel/user privilege level 계층 (slide 7 동심원 그림)
3.9precise interrupt(정확한 인터럽트)
older 는 완료, younger 는 미실행처럼 보이게 함. HW 복잡·SW 단순 (imprecise 는 반대).
3.9.r.1Smith & Pleszkun, Implementing Precise Interrupts in Pipelined Processors (1988, PDF) ↗ · precise interrupt 정의와 pipeline 에서의 구현법 5가지 (slide 28 선택 논문)
3.10CSR: SSTATUS·SEPC·SCAUSE
interrupt enable/privilege, 중단 instruction 주소, 원인(MSB interrupt bit + exception code). CSRRW 로 접근.
3.10.r.1The RISC-V Instruction Set Manual Vol. II: Privileged Architecture (PDF) ↗ · sepc·scause·stvec(Direct/Vectored)·SRET 원문 정의
3.11STVEC direct / vectored mode
direct: 모든 trap 이 STVEC 한 주소로. vectored: cause 별 주소로 바로 이동.
3.11.r.1The RISC-V Instruction Set Manual Vol. II: Privileged Architecture (PDF) ↗ · sepc·scause·stvec(Direct/Vectored)·SRET 원문 정의
3.11.r.2Interrupt vector table (Wikipedia) ↗ · 원인별 handler 주소 table (vectored interrupt)
3.12ERET / SRET(예외 복귀 명령)
state·privilege 복원과 SEPC 로의 jump 를 원자적으로. 강의는 ERET, RISC-V spec 의 S-mode 명령은 SRET.
3.12.r.1The RISC-V Instruction Set Manual Vol. II: Privileged Architecture (PDF) ↗ · sepc·scause·stvec(Direct/Vectored)·SRET 원문 정의

4스스로 확인

4.1branch history 는 예측 직후 갱신하고 PHT 는 outcome 후에 갱신해도 되는 이유는?
답
PHT 를 바로 갱신해도 뒤 branch 의 예측 방향이 같다. history 는 반영 여부에 따라 뒤 예측이 달라져 바로 반영, 틀리면 복구.
4.2loop 안 10 instruction 을 10번 반복하면 static/dynamic count 는?
답
static 10, dynamic 100.
4.3predicated execution 의 단점은?
답
필요 없는 쪽 instruction 도 모두 pipeline 을 통과해 resource 를 낭비한다.
4.4synchronous 와 asynchronous interrupt 의 처리 시점 차이는?
답
synchronous 는 진행이 막히므로 즉시, asynchronous 는 현재 instruction 을 마친 뒤 등 약간 지연 가능.
4.5interrupt 주소를 PC 나 x1 에 둘 수 없는 이유는?
답
PC 는 handler 가 즉시 덮어쓰고, x1 은 user 의 return address 를 보존해야 해서. 그래서 SEPC 사용.
4.6precise interrupt 를 지원하면 HW 와 SW 중 누가 복잡해지나?
답
HW 가 복잡해지고 OS(SW)는 단순해진다. imprecise 는 반대.

5참고 자료

5.1Branch predictor (Wikipedia) ↗ · global history, return stack buffer, neural(perceptron) predictor 개요
5.2Trace cache (Wikipedia) ↗ · dynamic instruction stream(trace) 저장, Pentium 4 사례
5.3Predication (computer architecture) (Wikipedia) ↗ · predicated execution·if-conversion, IA-64 의 64개 predicate register
5.4Jiménez & Lin, Dynamic Branch Prediction with Perceptrons (HPCA'01, PDF) ↗ · 강의가 추천한 perceptron branch predictor 원 논문
5.5Smith & Pleszkun, Implementing Precise Interrupts in Pipelined Processors (1988, PDF) ↗ · precise interrupt 정의와 pipeline 에서의 구현법 5가지 (slide 28 선택 논문)
5.6The RISC-V Instruction Set Manual Vol. II: Privileged Architecture (PDF) ↗ · sepc·scause·stvec(Direct/Vectored)·SRET 원문 정의
5.7RISC-V Ratified Specifications ↗ · privileged spec 최신판 목록
5.8Interrupt handler (Wikipedia) ↗ · interrupt masking, nested interrupt, priority

7한국어판 강의자료

단축키
Ctrl K · s자료 검색
[ ]이전·다음 강의
Space영상 재생·정지
j k다음·이전 section
n p다음·이전 slide
b강의 목록 접기·펴기
t맨 위
/강의 검색
Esc닫기