--- id: wiki-2026-0508-speculative-execution title: Speculative Execution category: 10_Wiki/Topics status: verified canonical_id: self aliases: [P-Reinforce-AUTO-CCED4D, Branch Speculation, Out-of-order Execution] duplicate_of: none source_trust_level: A confidence_score: 0.95 verification_status: applied tags: [cpu, microarchitecture, security, performance, spectre] raw_sources: [] last_reinforced: 2026-05-10 github_commit: pending tech_stack: language: C / asm framework: x86-64 / ARMv9 --- # Speculative Execution ## 매 한 줄 > **"매 CPU 의 매 branch 의 outcome 의 wait 의 X — 매 predicted path 의 의 ahead 의 execute, 매 wrong → rollback"**. 1990s Pentium Pro 매 first commercial impl → 2018 Spectre/Meltdown 매 the dark side 의 reveal → 2026 매 hardware mitigation (Intel CET, ARM BTI/MTE) + compiler hardening 매 standard. ## 매 핵심 ### 매 mechanism - **Branch predictor** 매 매 branch 의 taken/not-taken 의 history 의 학습 (TAGE, Perceptron). - **Reorder buffer (ROB)** 매 매 speculative instruction 의 in-flight 의 hold. - **Retire stage** 매 매 branch 의 resolved 의 후 의 commit (correct) or flush (mispredict). - **Misprediction penalty**: 매 modern CPU 매 ~15-25 cycles. ### 매 dark side - **Spectre v1 (Bounds Check Bypass)**: 매 attacker 의 branch predictor 의 train → 매 sensitive memory 의 cache 의 leak. - **Spectre v2 (Branch Target Injection)**: 매 indirect branch 의 mispredict 의 force. - **Meltdown**: 매 user 의 kernel memory 의 speculative read. - **L1TF, MDS, Retbleed, GhostRace** (2018-2024): 매 variant 의 endless. ### 매 응용 1. CPU performance (1.5-3x IPC vs in-order). 2. Branch prediction research. 3. Compiler 매 PGO + autovectorization 의 enabler. ## 💻 패턴 ### Pattern 1: 매 Spectre v1 매 PoC (educational) ```c // 매 educational only uint8_t array1[16] = {0}; uint8_t array2[256 * 512]; char* secret = "key"; unsigned int array1_size = 16; void victim(size_t x) { if (x < array1_size) { // <-- 매 trained branch uint8_t v = array2[array1[x] * 512]; // 매 cache 의 leak via timing } } // Attacker 매 array1_size 의 cache 의 evict → speculative path 매 OOB read ``` ### Pattern 2: 매 LFENCE / 매 retpoline 의 mitigation ```c // gcc -mindirect-branch=thunk-extern -mfunction-return=thunk-extern static inline void speculation_barrier(void) { __asm__ volatile ("lfence" ::: "memory"); } bool safe_lookup(size_t i, size_t n, uint8_t* arr) { if (i < n) { speculation_barrier(); // 매 stops speculative path return arr[i]; } return 0; } ``` ### Pattern 3: 매 bench 의 branch misprediction ```c // perf stat -e branches,branch-misses ./a.out #include int main(int argc, char** argv) { int sum = 0; for (int i = 0; i < 1000000; i++) { if (i % 2 == 0) sum += i; // 매 100% predictable // if ((rand() & 1)) sum += i; // 매 50% miss → much slower } printf("%d\n", sum); } ``` ### Pattern 4: 매 V8 / JIT 의 speculative optimization ```js // V8 매 hidden class 의 speculatively assume → 매 type 의 change → 매 deopt function add(o) { return o.x + o.y; } add({ x: 1, y: 2 }); // 매 monomorphic, JIT 의 specialize add({ x: 1, y: 2, z: 3 }); // 매 hidden class 의 change → 매 deopt ``` ## 매 결정 기준 | 상황 | Approach | |---|---| | 매 user code 매 typical app | 매 default — speculation 매 win, 매 mitigation OS-level | | 매 cryptography (constant-time req) | `LFENCE`, branchless code, 매 secret-dep 의 branch X | | 매 multi-tenant cloud | site-isolation, hardware mitigation enable, microcode update | | 매 perf-critical hot loop | Profile-guided opt + branchless when miss > 5% | | 매 indirect call hot path | retpoline (Spectre v2) + IBRS off if isolated | **기본값**: 매 OS + microcode 의 latest, 매 crypto code 매 constant-time, 매 hot-loop 매 PGO. ## 🔗 Graph - 부모: [[CPU Bottleneck]] · [[Branch Prediction]] - 변형: [[Out-of-order Execution]] - 응용: [[V8 Engine]] · [[Spectre]] ## 🤖 LLM 활용 **언제**: 매 perf 분석 (branch-miss rate), 매 microbenchmark 의 design, 매 mitigation flag 의 trade-off 분석. **언제 X**: 매 actual exploit 의 development — out of scope. ## ❌ 안티패턴 - **매 secret-dependent branch** 매 crypto code — 매 timing leak. - **매 mitigation 의 disable** ("for performance") 매 multi-tenant host. - **매 indirect call 의 hot loop** without retpoline 매 Spectre v2-vulnerable CPU. - **매 unpredictable branch** 매 inner loop — 매 branchless (cmov, mask) 의 prefer. ## 🧪 검증 / 중복 - Verified (Hennessy & Patterson 6e Ch.3, Spectre paper Kocher 2018, Intel SDM Vol.3 Ch.2). - 신뢰도 A. - 중복 risk: [[Branch Prediction]] (related), [[Out-of-order Execution]] (parent mechanism). ## 🕓 Changelog | 날짜 | 변경 | |---|---| | 2026-05-08 | Phase 1 | | 2026-05-10 | Manual cleanup — mechanism, Spectre family, mitigations 정리 |