[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,90 +2,152 @@
id: wiki-2026-0508-program-dependence-graph
title: Program Dependence Graph
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [PDG, Program Dependence Graph, 프로그램 의존성 그래프]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [compiler, static-analysis, ir, slicing]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: compiler-ir
framework: static-analysis
---
# [[Program Dependence Graph]]
# Program Dependence Graph
## 📌 한 줄 통찰 (The Karpathy Summary)
Program Dependence Graph(프로그램 의존성 그래프, PDG)는 코드 내의 데이터 및 제어 의존성(data and control dependencies)을 명시적으로 표현하는 모델입니다 [1]. 이는 표현식이나 메서드와 같은 두 코드 조각 간의 방향성 있는 관계를 나타내며, 리팩토링 대상이 되는 프로그램의 잠재적 문제를 탐지하기 위한 정적 프로그램 분석(Static program analysis) 등에 활용됩니다 [1, 2]. 개별 PDG들 간의 프로시저 호출을 연결하면 시스템 전체의 의존성을 나타내는 시스템 의존성 그래프(System Dependence Graph)로 확장하여 분석할 수 있습니다 [1].
## 한 줄
> **"매 control + data dependence를 매 한 그래프로"**. Program Dependence Graph (PDG)는 Ferrante, Ottenstein, Warren (1987) 이 매 제안한 매 IR — 매 statement node 사이에 매 control dependence edge와 매 data dependence edge를 매 함께 표현. Program slicing, parallelization, change impact analysis의 매 backbone.
## 📖 구조화된 지식 (Synthesized Content)
* **의존성의 정의와 종류:** 소프트웨어에서 의존성이란 코드의 두 부분 사이의 방향성 있는 관계를 의미합니다 [2]. 여기에는 값의 정의와 사용 사이에서 발생하는 '데이터 의존성(data dependencies)'과 함수의 선언부와 실제 호출되는 위치 사이의 '호출 의존성(call dependencies)' 등이 포함됩니다 [2].
* **정적 분석 도구로서의 역할:** PDG는 유효하지만 표준 이하(substandard)인 프로그램의 구조적 문제를 탐지하기 위한 정적 분석 기법의 핵심적인 표현 도구로 사용됩니다 [1].
* **시스템 의존성 그래프(System Dependence Graph)로의 확장:** PDG들 사이의 프로시저 호출 관계를 표현하기 위해 시스템 의존성 그래프가 사용됩니다 [1]. 마이크로소프트(Microsoft)의 MaX와 같은 자동화 도구는 함수 수준(호출, 임포트, 익스포트 등)에서 이러한 의존성 정보를 추적하여 시스템 전반의 의존성 그래프를 생성하며, 이를 변경 영향 분석(change impact analysis) 및 통합 테스트에 활용합니다 [2].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
소스에 관련 정보가 부족합니다.
### 매 두 종류 edge
- **매 Data dependence**: 매 statement A가 매 정의한 var를 매 B가 매 사용 → A → B (def-use).
- **매 Control dependence**: 매 A의 매 결과가 매 B의 매 실행 여부를 매 결정 → A → B.
- **매 Region node**: 매 unconditional block 매 그룹화 (선택적).
---
*Last updated: 2026-05-03*
### 매 CDG vs DDG vs PDG
- **CDG**: control dependence만 (post-dominator frontier 기반).
- **DDG**: data dependence만 (def-use chain).
- **PDG**: 매 둘 모두를 매 single graph로.
- **SDG (System DG)**: PDG + interprocedural call/parameter edge.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Program slicing (Weiser 1981 + Horwitz et al. 1990).
2. Change impact analysis.
3. Loop parallelization (data dep 없으면 매 parallel-safe).
4. Code clone detection (subgraph isomorphism).
5. Differential testing / fuzzing.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### PDG 구축 sketch (Python AST)
```python
import ast
from collections import defaultdict
## 🧪 검증 상태 (Validation)
class PDGBuilder(ast.NodeVisitor):
def __init__(self):
self.defs = defaultdict(list) # var -> [stmt_id]
self.data_edges = []
self.ctrl_edges = []
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
def visit_Assign(self, node):
sid = id(node)
for n in ast.walk(node.value):
if isinstance(n, ast.Name):
for prev in self.defs[n.id]:
self.data_edges.append((prev, sid))
for tgt in node.targets:
if isinstance(tgt, ast.Name):
self.defs[tgt.id].append(sid)
self.generic_visit(node)
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def visit_If(self, node):
sid = id(node)
for s in node.body + node.orelse:
self.ctrl_edges.append((sid, id(s)))
self.generic_visit(node)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Backward slicing
```python
def backward_slice(pdg, criterion: int) -> set[int]:
# criterion = stmt_id; 매 reachable predecessors via data + ctrl edges
reverse = defaultdict(list)
for u, v in pdg.data_edges + pdg.ctrl_edges:
reverse[v].append(u)
seen, stack = set(), [criterion]
while stack:
n = stack.pop()
if n in seen: continue
seen.add(n)
stack.extend(reverse[n])
return seen
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Loop parallelization check
```python
def is_parallelizable(loop_pdg) -> bool:
# 매 No loop-carried data dependence
for u, v in loop_pdg.data_edges:
if loop_pdg.iter_distance(u, v) > 0:
return False
return True
```
**선택 B를 써야 할 때:**
- *(TODO)*
### LLVM via opt pass
```bash
# LLVM 18+ — print PDG of a function
opt -passes='print<dependence-analysis>' -disable-output input.ll
opt -passes='print<scalar-evolution>' -disable-output input.ll
```
**기본값:**
> *(TODO)*
### Tree-sitter + custom analyzer (modern stack)
```python
import tree_sitter_python as tsp
from tree_sitter import Language, Parser
LANG = Language(tsp.language())
parser = Parser(LANG)
tree = parser.parse(b"x = 1\ny = x + 2")
# 매 walk tree, 매 build PDG with same edges as above
```
## ❌ 안티패턴 (Anti-Patterns)
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Slicing / debugging aid | PDG (data + control) |
| Loop opt only | DDG (loop-carried 매 충분) |
| Cross-function impact | SDG (PDG + summary edges) |
| Code clone detection | PDG subgraph isomorphism |
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
**기본값**: 매 PDG 시작, 매 cross-function 필요 시 매 SDG로 확장.
## 🔗 Graph
- 부모: [[Compiler-IR]] · [[Static-Analysis]]
- 변형: [[Control-Dependence-Graph]] · [[Data-Dependence-Graph]] · [[System-Dependence-Graph]]
- 응용: [[Program-Slicing]] · [[Change-Impact-Analysis]] · [[Auto-Parallelization]]
- Adjacent: [[SSA-Form]] · [[Control-Flow-Graph]] · [[Def-Use-Chain]]
## 🤖 LLM 활용
**언제**: 매 code understanding tool, 매 refactoring impact, 매 LLM-assisted slicing.
**언제 X**: 매 trivial single-function script.
## ❌ 안티패턴
- **매 Pointer aliasing 무시**: 매 may-alias 매 conservative 처리 안 하면 매 unsound.
- **매 Interprocedural skip**: 매 cross-function dep 매 결측 → 매 false negative.
- **매 매 edge 폭주**: 매 every var 매 every stmt → 매 PDG 매 dense 매 unreadable.
## 🧪 검증 / 중복
- Verified (Ferrante/Ottenstein/Warren TOPLAS 1987, Horwitz et al. TOPLAS 1990).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — PDG/CDG/DDG/SDG taxonomy + slicing impl |