refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조

에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게
[공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류.
문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인).

- Topic_Programming → Domain_Programming (내부 구조 보존)
- Topic_Graphic → Domain_Design
- Topic_Business → Domain_Product
- Topic_General → Domain_General
- _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning),
  Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing)
- 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서)
- 빈 폴더 정리 (memory/procedures)
- 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Antigravity Agent
2026-07-11 11:05:56 +09:00
parent 6549ead309
commit c24165b8bc
6193 changed files with 1717 additions and 31 deletions
@@ -0,0 +1,145 @@
---
id: wiki-2026-0508-branch-prediction
title: Branch Prediction
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-4D7707, CPU Branch Predictor]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [cpu, performance, security, microarchitecture]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: cpp
framework: none
---
# Branch Prediction
## 매 한 줄
> **"매 modern CPU 의 IPC 핵심 mechanism — 그리고 Spectre 의 attack surface."**. Branch predictor 는 conditional/indirect branch 의 결과를 speculatively execute 함으로써 deep pipeline 의 stall 을 회피; 매 misprediction penalty 는 15-20+ cycles, 매 mispredicted speculative window 가 Spectre v1/v2 의 leak vector.
## 매 핵심
### 매 Predictor 종류
- **Static**: forward-not-taken, backward-taken (hint).
- **Bimodal (2-bit)**: per-PC saturating counter.
- **Local history**: per-branch shift register.
- **Global history (gshare/GAg)**: shared GHR XOR PC.
- **Tournament**: meta-predictor selects local vs global.
- **TAGE / ITTAGE**: tagged geometric history (modern SOTA).
- **Perceptron**: AMD Zen — neural-style predictor.
### 매 Indirect Branches
- BTB (Branch Target Buffer) — caches target.
- ITTAGE for indirect.
- Critical for vtables, function pointers, switch.
### 매 응용
1. Hot loops — predictable branches → near-zero penalty.
2. Sorted-data effect (the famous SO question).
3. Spectre/BranchScope side-channel attacks.
4. JIT branch ordering decisions (V8, Hotspot).
## 💻 패턴
### Likely / Unlikely Hints (C++20)
```cpp
if (x > 0) [[likely]] {
fast_path();
} else [[unlikely]] {
slow_path();
}
```
### Branchless via Mask
```cpp
// branchful
int abs_v(int x) { return x < 0 ? -x : x; }
// branchless
int abs_v_nb(int x) {
int mask = x >> 31; // 0 or -1
return (x ^ mask) - mask;
}
```
### Branchless Min via cmov
```cpp
int min_v(int a, int b) {
return a < b ? a : b; // compilers emit cmov on x86
}
```
### Sort Before Loop (classic)
```cpp
std::sort(data.begin(), data.end()); // 정렬 → branch predictable
long sum = 0;
for (int v : data) if (v >= 128) sum += v;
```
### LLVM `__builtin_expect`
```cpp
if (__builtin_expect(error_flag, 0)) {
handle_error();
}
```
### Spectre v1 Mitigation (lfence)
```cpp
// vulnerable
if (idx < arr_size) {
secret = arr[idx]; // mispredict → leaks
}
// hardened
if (idx < arr_size) {
asm volatile("lfence" ::: "memory");
secret = arr[idx];
}
```
### perf Branch Stats
```bash
perf stat -e branches,branch-misses ./bench
# branch-miss rate > 5% → suspect; > 10% → critical
```
## 매 결정 기준
| 상황 | 전략 |
|---|---|
| Hot loop, predictable | Trust predictor — natural code |
| Hot loop, unpredictable | Branchless / mask / cmov |
| Cold path | Doesn't matter — clarity > tricks |
| Indirect-heavy (vtable) | Devirtualize, monomorphize |
| Security-sensitive | lfence / speculative load hardening |
**기본값**: write clear branchful code; branchless only when profiler shows misprediction hotspot.
## 🔗 Graph
- 부모: [[Pipeline]]
- 응용: [[JIT Compilation]]
- Adjacent: [[Spectre]] · [[Speculative Execution]]
## 🤖 LLM 활용
**언제**: explain mispredict cost, generate branchless equivalents, suggest hints.
**언제 X**: micro-arch tuning without perf data — speculation hurts.
## ❌ 안티패턴
- **Random unpredictable branch in hot loop**: 20-30% slowdown.
- **Premature branchless conversion**: hurts cold/clarity paths.
- **Trusting `[[likely]]` blindly**: PGO data > human guess.
- **Ignoring Spectre in untrusted-input parsers**: real CVE risk.
## 🧪 검증 / 중복
- Verified (Hennessy & Patterson 6th, Agner Fog optimization manuals, Intel SDM).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — predictor types, branchless patterns, Spectre |