analyze-xiangshan-kunminghu · git:20260716.0b00efb · 2026-07-16 · sha256 bc99175445ac981e

analyze-xiangshan-kunminghu git:20260716.0b00efbA

Immutable. This exact content is served forever at /api/v1/blob/bc99175445ac981e.

---
name: analyze-xiangshan-kunminghu
description: Analyze OpenXiangShan XiangShan Kunminghu microarchitecture source, design docs, XiangShanLab course concepts, XSCache, chiselAIA, chiselIOPMP, AXI/AXI4, and difftest signals. Use for module walkthroughs, theory-to-code mapping, branch comparison, difftest architectural/cache/queue-state tracing, signal tracing with Chisel line evidence, algorithm/FSM/control/data-path/storage analysis, replay/redirect/conflict/contention/empty/full scenarios, queue/buffer capacity, exception/interrupt/debug/privilege, AIA/APLIC/IMSIC, IOPMP permission, AXI channel analysis, instruction latency and throughput analysis, per-instruction or per-instruction-class timing/resource analysis, and pipeline/instruction-flow analysis across frontend, backend, mem, cache, and XSCache, including decode/rename/dispatch/issue/execute/writeback/commit and load/store/AMO/LR/SC/prefetch/fence/CBO flows.
---

# Analyze XiangShan Kunminghu

## Objective

Use this skill to produce code-grounded explanations of XiangShan Kunminghu modules, including branch-to-branch module comparisons when requested. Always obtain XiangShan source code directly from `https://github.com/OpenXiangShan/XiangShan.git` unless the user explicitly provides a local path. Default single-branch analysis to branch `kunminghu-v2` unless the user explicitly asks for another branch or commit. For comparison analysis, require two branch/commit names and one or more modules/paths from the user; if any of these are missing, ask for the missing branch/module fields before analyzing. If the prompt contains a conflicting branch/path, state the source URL and branch/commit being analyzed before explaining.

Primary source roots:
- Weekly sync helper: `scripts/weekly_sync.py` and `references/weekly-sync.md`
- Analysis output saver: `scripts/save_analysis.py` and `references/analysis-output.md`
- Predictor paper search: `paper-search-agent-mcp` via `mcp__paper_search_agent`, plus `references/predictor-papers.md`
- AIA/IOPMP/AXI analysis: `references/aia-iopmp-axi.md`
- Difftest signal and architectural-state analysis: `references/difftest.md`
- XiangShan source: `https://github.com/OpenXiangShan/XiangShan.git`, source root `src/main/scala/xiangshan`
- XiangShan Design Doc: `https://github.com/OpenXiangShan/XiangShan-Design-Doc.git`
- XiangShanLab course repo: `https://github.com/OpenXiangShan/XiangShanLab.git`
- XSCache repo: `https://github.com/OpenXiangShan/XSCache.git`
- Course background: XiangShanLab course system 4 implementation docs, especially superscalar/out-of-order basics and XiangShan high-performance out-of-order pipeline docs, plus course system 5 dynamic instruction execution docs
- Required analysis style: answer every module through `who`, `why`, `how`, `from what`, and `to what`

## Workflow

Before step 1, read `references/weekly-sync.md` and run `scripts/weekly_sync.py` unless the user explicitly asks not to sync. This performs a 7-day guarded sync check for local Design Doc, XiangShanLab, and course analysis directories; XiangShan source itself must be fetched or inspected directly from `https://github.com/OpenXiangShan/XiangShan.git`. The sync helper must never reset, clean, or overwrite dirty worktrees.
1. Locate the requested module by fetching or inspecting `https://github.com/OpenXiangShan/XiangShan.git` at the requested branch/commit. Use local XiangShan source only when the user explicitly provides a local path or when GitHub/network access is unavailable and the fallback is clearly stated.
2. Locate matching foundational theory material before code analysis. Read `references/xiangshanlab-course-map.md` and `references/theory-code-mapping.md`, then inspect relevant XiangShanLab superscalar/out-of-order course markdown when available.
3. Locate matching design documentation before explaining broad intent. Read `references/design-doc-map.md` for Design Doc navigation and then inspect the relevant markdown files when available.
4. For predictor analysis, read `references/predictor-papers.md` and use `paper-search-agent-mcp` (`mcp__paper_search_agent.search_papers`) to find the relevant branch-prediction paper(s) before explaining algorithm principles.
5. Read the real Scala/Chisel files from `https://github.com/OpenXiangShan/XiangShan.git` before explaining implementation. Do not infer behavior from names or documentation alone. Record the analyzed source commit (`git rev-parse HEAD` for local checkouts, or the GitHub commit/branch SHA when browsing remote source). Use line-numbered reads such as `nl -ba` or editor line references so every algorithm, port, connection, and datapath claim can cite exact Chisel lines.
6. Identify the enclosing subsystem and load the matching reference:
   - Theory-to-code mapping: read `references/theory-code-mapping.md`
   - XiangShanLab course navigation: read `references/xiangshanlab-course-map.md`
   - Backend pipeline: read `references/backend.md`
   - Frontend fetch and prediction: read `references/frontend.md`
   - Predictor paper search and algorithm principles: read `references/predictor-papers.md` for branch/target/indirect/RAS/statistical-corrector predictor analysis
   - chiselAIA/chiselIOPMP/AXI bus behavior: read `references/aia-iopmp-axi.md` for APLIC/IMSIC, IOPMP, AXI master/slave, and AXI protocol control-signal analysis
   - Memory/cache instruction behavior: read `references/mem-cache.md`
   - XSCache cache subsystem: read `references/xscache.md`
   - Load/store instruction taxonomy: read `references/load-store-instruction-taxonomy.md`
   - Instruction latency and throughput: read `references/instruction-latency-throughput.md`
   - Algorithms, FSMs, control path, and data path: read `references/algorithm-control-dataflow.md`
   - Exceptions, interrupts, debug, and privilege: read `references/exception-debug-privilege.md`
   - Difftest architectural-state, cache-state, queue-state, exception, interrupt, and memory-address signals: read `references/difftest.md`
   - Queue and buffer capacity logic: read `references/queue-buffer-capacity.md`
   - Mermaid and waveform-draw timing diagrams: read `references/diagrams.md`
   - Output structure and question checklist: read `references/analysis-template.md`
   - Weekly repository sync: read `references/weekly-sync.md` before source inspection; this syncs local docs/course inputs, not the authoritative XiangShan source
   - Analysis output saving: read `references/analysis-output.md` before writing generated Markdown
7. Separate theory, design intent from effective code:
   - Use XiangShanLab course docs to define architecture concepts such as superscalar issue, hazards, register renaming, Tomasulo/scoreboard ideas, issue queues, bypass, physical registers, ROB, and dynamic instruction execution.
   - Use Design Doc/course implementation docs to describe motivation and intended XiangShan architecture.
   - Use active source files, instantiated modules, actual IO connections, and parameter values to describe what the implementation really does.
   - If theory/docs and code disagree or a concept is implemented differently, state the difference and prefer code for behavior.
8. Trace interfaces first: `IO(...)`, bundle classes, Decoupled/Valid handshakes, difftest bundles/events, AXI/TL/APB channels, redirect/flush signals, wakeup/writeback channels, interrupt lines, MMU/cache request-response channels, and ROB/FTQ/LSQ pointers. For AXI, explicitly identify master/slave role and AW/W/B/AR/R channel direction before explaining behavior.
9. For memory/cache/XSCache targets, build a per-stage pipeline map before summarizing behavior. For every visible stage (`s0/s1/s2`, request, TLB, tag/meta, data, miss, refill, writeback, replay, commit, or named FSM stage), state what work the stage performs, which payload/control registers it owns, what index/address/allocation decision is computed there, what can stall/flush/replay/cancel it, and what leaves the stage.
10. Trace index and address calculations before summarizing any table, array, queue, cache, bank, entry, pointer, allocation slot, free-list slot, MSHR entry, replay entry, PTW entry, victim way, or selector access. For every index, explain exactly how it is computed from fields/signals/parameters, which bits are used, how bank/set/way/entry slices are formed, how wraparound or pointer arithmetic works, how the allocation/free algorithm chooses the index, and where the computed index is consumed. Include first-cycle or reset-time index behavior when registers or counters are involved.
11. Trace state updates: `RegInit`, `RegEnable`, `RegNext`, `SyncDataModule`, SRAM/data arrays, queues, tables, valid bits, pointers, snapshots, replay queues, FSM state registers, refill/writeback buffers, and replacement metadata. For every explicit FSM or implicit valid/status lifecycle, document reset state, state meaning, why the state exists, a concrete scenario that enters or uses the state, entry condition, transition condition, stage action, output action, blocking condition, and exit/clear condition. For every valid/status bit, explicitly state reset/initial value, set condition, clear condition, hold condition, flush/cancel condition, why the bit exists, an example transaction scenario, and all consumers that observe it. For every storage structure, analyze it through `update`, `release`, `replace`, and `search/read/probe`: the exact timing, enable/fire condition, index calculation, payload fields updated/read/released/replaced, valid-bit effect, conflict priority when multiple operations happen together, and downstream effect. For every read/write port on a storage structure, analyze conflict scenarios: same-cycle read/write same index, multiple writes same index, multiple reads contending for a limited port, read-after-write/write-after-read/write-after-write behavior, bypass/forwarding or assert behavior, and which request wins or stalls. For every queue/buffer, inspect empty/full/almost-full/allow-enqueue/allow-dequeue/backpressure logic.
12. Trace algorithms and paths: replacement, allocation/free index selection, arbitration, selection, prediction, replay, redirect, dependency, forwarding, merge/split, miss handling, permission checking, AIA interrupt delivery/priority, IOPMP permission match/deny, AXI address routing/outstanding/burst/response handling, exception/interrupt/debug/privilege checks, and exception priority algorithms. For every algorithm, port/interface, inter-module connection, and datapath segment, cite exact Chisel source line numbers and include a short core code snippet from the analyzed commit. For every key control signal or state transition that changes behavior, explain why it exists and give at least one concrete scenario, such as a stall, replay, redirect, miss, exception, full queue, conflicting request, probe, refill, or commit release. For each algorithm, describe how it works from initialization/reset, how the first real transaction/request is handled, all major cases/branches, tie or priority behavior, invalid/empty/full behavior, and how state evolves after each case. For every arbiter or priority selector, explicitly analyze the simultaneous-request scenario: all requesters that can assert together, request qualification, priority/age/round-robin rule, grant generation, ready/backpressure, losing request behavior, and same-cycle update effects.
13. Build a scenario mapping for every replay, redirect, conflict, contention, and resource empty/full path that exists in the requested module or changed diff. For each scenario, identify the trigger, competing requesters or blocked resource, exact signal condition, winner/loser behavior, state updates, pipeline/queue/cache effect, and downstream consumer. If a requested category is absent, state that it was searched and not found.
14. Generate diagrams after the trace is understood: one Mermaid data-path diagram, one Mermaid module-interface diagram, and one waveform-draw handshake timing diagram for every requested module that has Decoupled, Valid, pipeline-valid, request/response, enqueue/dequeue, grant/accept, or stall/backpressure behavior. Keep diagrams faithful to effective code; include only real modules, ports, queues, arrays, FSM states, and pipeline stages.
15. For instruction, backend, memory, cache, or FU analysis, read `references/instruction-latency-throughput.md` and add a latency/throughput section. Derive latency from decode-to-commit path stages, FU/wrapper valid timing, memory/cache response timing, replay/exception paths, and writeback/commit timing. Derive throughput from issue width, FU counts, port counts, pipelining or busy/ready behavior, writeback arbitration, cache/MSHR/bank/queue resources, and backpressure. State whether each number is a code-proven fixed cycle count, a best-case bound, a steady-state initiation interval, a variable/miss-dependent bound, or unclear without elaboration/waveforms.
16. Save generated module analysis Markdown to the code-deep-dive course directory. Read `references/analysis-output.md` and use `scripts/save_analysis.py`; default destination is `xiangshan-course/docs/课程体系4:实现篇-香山高性能处理器微架构优化/中级-高性能香山处理器代码深入解析/` relative to `xiangshanlab_home`.
17. Explain only claims supported by code or cited design docs. If a signal source or sink is unclear, say what was found and what file should be inspected next.


## Branch Comparison Workflow

Use this mode when the user asks to compare two branches, versions, commits, or implementations of a module.

Required user inputs:
- Base branch/commit: the older, baseline, or left-side version.
- Target branch/commit: the newer, experiment, or right-side version.
- Module/path: one or more module names, Scala/Chisel files, or subsystem paths to compare.

If the user gives only one branch, only one side of the comparison, or no module, ask a concise clarification for the missing fields before fetching source. If the user does not define base/target direction but provides two branch names, preserve the user-provided order and label them explicitly.

Comparison procedure:
1. Resolve both branches/commits from `https://github.com/OpenXiangShan/XiangShan.git` or the user-provided local path. Record both exact commit SHAs.
2. Locate the requested module in both versions. If a file or module was renamed, moved, added, or deleted, identify the old and new paths and cite the evidence from `git diff --name-status`, `git log --follow`, or direct tree inspection.
3. Build a file set for comparison: primary module file, instantiated child modules whose interfaces changed, parameter definitions, bundle definitions, decode/CSR/config files when they affect the module, and test or elaboration hooks when relevant.
4. Generate a source diff for the selected file set only. Prefer `git diff <base>..<target> -- <paths>` for one checkout or `git diff --no-index` for two worktrees. Do not summarize repository-wide churn.
5. Treat each meaningful diff hunk as a code-analysis target, not a standalone text patch. For every changed hunk, recover the enclosing module/class/function, IO bundle, parameter owner, pipeline stage, storage structure, FSM, arbitration network, or algorithm context before explaining it.
6. Read line-numbered source from both versions for every behavior-changing difference. Cite both sides as `base file:line` and `target file:line`; include short core snippets from both sides when a behavior claim depends on changed code.
7. Classify every meaningful difference by impact area: public interface/IO, parameters, instantiation path, control path, data path, FSM/state lifecycle, storage structure, index/address calculation, arbitration/priority, exception/interrupt/debug/privilege, AXI/TL/APB protocol, memory/cache pipeline stage, predictor algorithm, or documentation-only/no effective behavior.
8. For every semantic change, apply the normal module-analysis principles from this skill: answer who owns/updates it, why it exists, how it works, from what signal/source it is derived, and to what consumer/effect it flows. Also analyze affected valid/ready/fire behavior, state set/clear/hold behavior, index/address calculation, storage update/release/replace/search behavior, and simultaneous-request arbitration when relevant.
9. Explain behavioral impact, not only text diff: what input scenario changes, which downstream module observes it, whether timing/backpressure/replay/flush/exception behavior changes, and whether compatibility or verification risk increases.
10. Separate mechanical changes from semantic changes. Treat formatting, rename-only, comment-only, and dead-code changes as low impact unless they change effective instantiation, generated hardware, or public contracts. For mechanical changes, still state why they do or do not affect effective code.
11. For each changed interface, state compatibility effects for callers and callees: ports added/removed/renamed, bundle field changes, width/parameter changes, ready/valid semantics, AXI channel role or payload changes, and required downstream updates.
12. For each changed algorithm or state machine, compare initial/reset behavior, first transaction behavior, all changed branches/cases, simultaneous-request behavior, priority/tie behavior, and state update effects.
13. For memory/cache/XSCache modules, compare stage-by-stage behavior and identify which stage changed, including set/bank/way/entry index calculation, MSHR/replay/refill/writeback behavior, and empty/full/backpressure logic.
14. End with a migration/risk summary: required code changes, verification focus, likely regressions, and open questions that need waveform, elaboration, or test evidence.

Diff analysis rules:
- Do not output only a patch summary. Convert changed code into microarchitecture analysis using the same evidence, algorithm, control-path, data-path, storage, FSM, and signal-provenance requirements as single-branch analysis.
- For every changed signal or expression, trace producer, consumers, parameter dependence, timing stage, reset/first-use behavior when applicable, and a concrete scenario where the base and target branches differ.
- For every changed table, queue, buffer, array, register group, valid bit, pointer, or replacement state, compare `update`, `release`, `replace`, and `search/read/probe` behavior across both branches, including conflict priority and empty/full/backpressure effects.
- For every changed selector, arbiter, mux priority, grant vector, or ready fanout, compare request qualification, simultaneous-request behavior, priority/fairness rule, losing request behavior, and state update effects.
- For every changed pipeline, Decoupled/Valid, AXI/TL/APB, replay, flush, redirect, exception, interrupt, debug, privilege, cache miss/refill/writeback, or predictor update path, show the base behavior, target behavior, and the exact scenario that changes.

## Answer Contract

For each requested module, produce:

- Module role and boundary: what the module owns and what it delegates.
- Theory context: relevant XiangShanLab superscalar/out-of-order concepts and the exact code structures that implement, specialize, or replace those concepts.
- Predictor paper context: for predictor modules, paper-search-agent MCP results, paper algorithm principle, citation/identifier, and explicit distinction from XiangShan implementation.
- Documentation context: relevant Design Doc/course pages and which claims are theory, design intent, or verified code behavior.
- Effective code path: instantiated modules and live connections that determine actual behavior; mention dead/unused code only as non-effective. Include analyzed source commit and line-numbered Chisel evidence for each effective path.
- Microarchitecture parameters: where relevant parameters are defined, how they enter the module, and how they change port counts, entry counts, widths, algorithms, or optional features.
- Instruction latency and throughput: per instruction or instruction class, report source-proven latency path, best-case and variable contributors, steady-state initiation interval/throughput, bottleneck resource, and uncertainty. Include FU config/wrapper, pipeline stages, issue/select, writeback, commit, memory/cache, replay, and resource-contention evidence as applicable.
- Interaction interface: key inputs, outputs, ports, inter-module connections, handshakes, AXI/TL/APB channels, redirects, flushes, exceptions, interrupts, debug-mode signals, privilege metadata, and performance/debug outputs. Every important port and connection must include Chisel file:line evidence and a short core code snippet.
- Difftest architectural-state coverage: when difftest is relevant, map every emitted difftest signal/event to its producer, timing condition, valid/enable condition, commit or trap association, and downstream reference-model meaning. Cover RISC-V specification-visible int/fp/vector registers, CSR state, exception/trap state, interrupt state, memory virtual/physical address state, cache state, and every queue/buffer state exposed or needed to explain the signal.
- Theory-to-code mapping: map concepts such as structural/data/control hazards, multi-issue, rename, dependency tracking, wakeup/select, bypass, physical registers, ROB, speculation, precise exception, and memory ordering to concrete modules/signals.
- Why it exists: the pipeline, speculation, ordering, bandwidth, latency, or correctness problem it solves.
- Index and address calculation: for every table/array/queue/cache/bank access, explain how the index is calculated, what parameters determine its width/range, which bits select bank/set/way/entry, how pointer arithmetic or wraparound works, and where the index is consumed.
- Memory pipeline stage analysis: for every `mem`, `cache`, or XSCache target, include a stage-by-stage table covering each stage's work, payload/control registers, index/allocation calculation, FSM/valid state, stall/flush/replay behavior, and output.
- Algorithm analysis: selection/replacement/allocation/free-index/arbitration/update rules, priority order, exception/interrupt/debug/privilege priority, AIA interrupt priority/delivery, IOPMP permission matching, AXI address routing/outstanding/burst/response algorithms, predictor lookup/update/recovery principle, pseudocode-level behavior, initialization/reset behavior, first-transaction behavior, all major cases/branches, invalid/empty/full behavior, tie handling, simultaneous-request arbitration behavior, and corner cases. Every algorithm explanation must cite exact Chisel source lines and include the core code snippet from the analyzed commit.
- Scenario mapping: include a table for replay, redirect, conflict, contention, and resource empty/full cases. For each case, state trigger condition, involved resources/requesters, code evidence, arbitration or priority rule, loser/blocking behavior, state update, recovery or retry path, and user-visible or downstream effect.
- Predictor algorithm principle: for every predictor, explain the paper-backed principle, lookup path, update/training path, recovery path, storage state, scenario examples, and code mapping.
- Control-signal rationale: for every behavior-changing control signal, explain who produces it, why it exists, what bug/hazard/resource conflict it prevents or enables, and give a concrete scenario where it matters.
- FSM-state rationale: for every explicit FSM state or implicit valid/status state, explain why the state exists, what transaction phase it represents, what would be wrong without it, and give an example scenario that enters or exits it.
- Diagrams: generate a key Mermaid data-path diagram, a Mermaid module-interface diagram, and waveform-draw timing diagrams for handshake/control timing when the analysis involves multiple modules, stages, queues, arrays, or handshakes.
- State-machine analysis: states, why each state exists, example scenarios, transition conditions, outputs by state, entry/exit conditions, and relation to ready/valid backpressure.
- Control path: focus on mux selects, valid/ready/fire, AXI AW/W/B/AR/R channel controls, arbiters, FSM transitions, stalls, redirects, cancels, replays, exceptions, interrupts, wakeup, commit, and pipeline stage control signals; for each key signal, include why it exists and a scenario example.
- Data path: payload movement, pipeline registers, data transforms, muxes, arrays, bypass/forwarding, queue movement, and writeback/refill paths. Every datapath segment must include Chisel source line numbers and a short core code snippet.
- Storage structures: every important queue/table/array/register group, its owner, reset/initial value, full `update` / `release` / `replace` / `search` behavior, and all read/write port conflict behavior. For each operation, include the exact timing, fire/enable condition, calculated index/address/pointer, payload contents, valid-bit set/clear/hold effect, conflict priority, flush/cancel/replay interaction, empty/full/almost-full condition, and backpressure behavior. For port conflicts, cover same-cycle read/write same index, multiple writes same index, multiple reads with limited ports, RAW/WAR/WAW behavior, bypass/forwarding/assert behavior, and which request wins, stalls, retries, or is dropped.
- Signal provenance: for key signals, list `from what` and `to what`, explain why the signal exists, and give a concrete scenario where the signal changes behavior.
- Dynamic flow: describe normal path, speculative path, and at least one exceptional/replay/redirect/miss path when relevant.
- chiselAIA / chiselIOPMP / AXI Bus: when relevant, identify APLIC/IMSIC or IOPMP boundary, AXI master/slave roles, AW/W/B/AR/R channels, protocol control signals, permission/interrupt behavior, backpressure, error responses, and exact source evidence.
- Difftest signals: when relevant, identify difftest module/bundle/event names, enable gating, payload fields, architectural visibility, speculative-versus-committed timing, cache-state meaning, per-queue state meaning, exception/interrupt/memory-address provenance, and exact source evidence.
- Source evidence: include the analyzed source commit, file paths, class/module names, exact line references for algorithms/ports/connections/datapaths, and concise Chisel core code snippets. Line references are mandatory, not optional, for all behavior-changing claims.
- Branch comparison evidence: when comparing two branches, include base and target branch names, exact commit SHAs, selected file set, diff command or method, per-change classification, base and target line references, changed code snippets from both sides, and a current-skill-style code analysis of each semantic diff: who/why/how/from what/to what, affected algorithm/control path/data path/storage/FSM/index/handshake behavior, concrete scenario difference, behavioral impact, compatibility risk, and verification focus.
- Saved Markdown path: when producing a module analysis file, save it under the code-deep-dive course directory and report the absolute path.

Use English for the generated analysis unless the user explicitly asks for another language.

## Module Navigation

Use these starting points for Kunminghu v2/v3 style trees:

- Top level: `XSCore.scala`, `XSTile.scala`, `Backend.scala`, `Frontend.scala`, `MemBlock.scala`, `L1Cache.scala`
- Backend: `backend/decode`, `backend/rename`, `backend/dispatch`, `backend/issue`, `backend/exu`, `backend/fu`, `backend/datapath`, `backend/regcache`, `backend/rob`, `backend/ctrlblock`
- Frontend: `frontend/IFU.scala`, `frontend/Frontend.scala`, `frontend/NewFtq.scala`, `frontend/IBuffer.scala`, `frontend/BPU.scala`, `frontend/FTB.scala`, `frontend/Tage.scala`, `frontend/ITTAGE.scala`, `frontend/SC.scala`, `frontend/Bim.scala`, `frontend/RAS.scala`, `frontend/icache`
- Memory/cache: `mem/MemBlock.scala`, `mem/pipeline`, `mem/lsqueue`, `mem/sbuffer`, `mem/mdp`, `mem/prefetch`, `mem/vector`, `cache/L1Cache.scala`, `cache/CacheInstruction.scala`, `cache/dcache`, `cache/mmu`, `cache/wpu`
- XSCache: `coupledL2`, `openLLC`, `xscache/chi`, `xscache/common`, `coupledL2/prefetch`, `coupledL2/utils`, `openLLC/chi`, `openLLC/utils`
- AIA/IOPMP/AXI: `chiselAIA`, `ChiselAIA`, `APLIC`, `IMSIC`, `AXIRegIMSIC`, `chiselIOPMP`, `ChiselIOPMP`, `IOPMP`, `AXI4MasterNode`, `AXI4SlaveNode`, `AXI4Bundle`, `AXI4Xbar`, `AXI4Buffer`, `AXI4ToTL`, `TLToAXI4`, `AXI4Memory`
- Difftest: search for `difftest`, `DiffTest`, `Difftest`, `DifftestModule`, `DifftestArch`, `DifftestCSR`, `DifftestTrap`, `DifftestInterrupt`, `DifftestLoad`, `DifftestStore`, `DifftestL1`, `DifftestCache`, and difftest package imports across backend, ROB/commit, CSR, mem, cache, and top-level files.

## Guardrails

- At the start of analysis, perform the weekly sync check described in `references/weekly-sync.md` for local docs/course inputs; if sync is skipped, dirty, missing, or fetch-only, state that in the analysis scope. XiangShan source code must still be obtained directly from `https://github.com/OpenXiangShan/XiangShan.git` unless the user explicitly supplies a local path.
- When generating module code-analysis Markdown, save it under the code-deep-dive course directory using `references/analysis-output.md`; do not overwrite existing files unless explicitly requested.
- Treat XiangShanLab theory docs as concept definitions, and Design Doc as design intent; neither proves implementation. Verify with effective source code.
- Always connect theory terms to exact code artifacts: module/class, IO bundle, parameter, storage structure, control signal, data path, algorithm, or FSM. Include analyzed commit and exact Chisel line numbers for these artifacts.
- Distinguish `backend` execution pipelines from `mem` pipeline units and `cache/dcache` data arrays/mainpipe.
- Treat `cache/mmu/TLB.scala` and related files as the likely ITLB/DTLB implementation area; frontend may instantiate or connect instruction-side TLB signals through fetch/icache bundles.
- When explaining load/store-class memory instructions, always expand both `mem` modules and `cache` modules on the effective path; when the request reaches XSCache/L2/L3/CHI, also expand XSCache modules. For all memory-related analysis, explicitly describe each pipeline stage, what work it performs, how its FSM/valid state advances, and which index/allocation algorithm it uses.
- When explaining instruction timing, distinguish latency from throughput. Latency is the cycles from the chosen start event to the chosen end event; throughput is the steady-state accept/issue/complete rate or initiation interval. Always name the start/end events, best-case assumptions, variable contributors, and bottleneck resource.
- When explaining CBO or fence behavior, search both decode/FU files and cache/memory files; the behavior may be split across decode classification, FU control, memory ordering, and cache request handling.
- For branch prediction, use `references/predictor-papers.md` and `paper-search-agent-mcp` to search relevant papers before explaining algorithm principles. Separate paper algorithm, design intent, and effective XiangShan code. Separate predictor storage lookup from prediction response generation, update/allocation, redirect recovery, and commit training.
- For every `who` answer, include the parameter owner when parameters determine the updater count, width, entries, or optional behavior.
- Whenever code computes an index, address, pointer, bank selector, set selector, way selector, queue entry selector, allocation slot, free-list slot, MSHR slot, replay entry, PTW entry, victim way, `OHToUInt`, `UIntToOH`, `PriorityMux` index, `PopCount` rank, `wrap`, `head`, `tail`, or `ptr`, explain the full calculation, allocation/free policy, and the consumer. Do not only name the signal.
- Whenever code implements an algorithm, explain the algorithm.s operating principle, initialization/reset state, first valid/request behavior, all major cases, priority/tie behavior, simultaneous-request arbitration behavior, index/allocation choice, why the control decisions exist, example scenarios for important decisions, and how state changes for each case. Cite exact Chisel source lines and show the short core code snippet from the analyzed commit.
- Whenever code can replay, redirect, conflict, contend for a resource, or block because a resource is empty/full/almost-full, map the concrete scenario from trigger to effect. Do not only say "it stalls" or "it replays"; identify the exact resource, requesters, priority, blocked path, held or cleared state, retry/redirect target, and downstream observer.
- For every `valid`, `ready-valid` payload valid, table valid bit, queue entry valid bit, FSM-valid state, or status-valid bit, explicitly document when it is set, when it is cleared, when it holds, why it exists, one realistic scenario where it matters, what flush/cancel/replay redirects affect it, and which downstream logic observes it.
- For every storage structure, organize behavior around `update`, `release`, `replace`, and `search/read/probe` even if the code names them enqueue/dequeue/read/write/allocate/free/lookup/match. For each operation, state when it happens, which index is used and how that index is calculated, what content is updated/released/replaced/searched, how valid/status bits change, and which operation wins if update/release/replace/search collide in the same cycle. Also analyze read/write port conflicts: same-cycle read and write to the same index, two writes to the same index, more requesters than physical ports, bypass/forwarding/assert behavior, and whether the losing request stalls, retries, replays, is masked, or is illegal.
- For every arbiter, selector, mux-priority network, grant vector, ready fanout, or request scheduler, enumerate all requesters and analyze what happens when different requesters arrive simultaneously. Explain why each key grant/ready/select signal exists and give a conflict scenario that demonstrates its role. State request qualification, priority or fairness rule, grant encoding, data selected, ready/backpressure returned to each requester, losing request behavior, and state updates caused by the grant.
- For every nontrivial module, include Mermaid diagrams and waveform-draw handshake timing diagrams unless the user asks for prose only. Use `flowchart LR` for data/interface paths, `stateDiagram-v2` for explicit FSMs when useful, and fenced `waveform-draw` blocks with WaveDrom-compatible signal JSON for timing diagrams.
- For exception, interrupt, debug, and privilege behavior, identify the exact priority and propagation path; do not collapse them into a generic flush explanation. For chiselAIA, expand APLIC/IMSIC delivery, CSR interaction, interrupt priority, privilege/virtualization legality, and MSI/MMIO access paths. For chiselIOPMP, expand protected masters/slaves, permission match algorithm, deny/error response, config path, and bypass behavior. For AXI, expand master/slave roles, AW/W/B/AR/R channels, valid/ready fire, payload stability, `last`, `resp`, `id`, burst, outstanding tracking, and backpressure.
- For difftest behavior, read `references/difftest.md` and separate architectural state from microarchitectural debug state. Do not treat speculative queue/cache/internal state as RISC-V architectural state unless the code shows it is commit-visible or reference-model-visible.
- For every queue or buffer, explicitly explain empty/full checks and what upstream/downstream logic observes them.
- In Dynamic Operation, always include speculative path when the module participates in prediction, out-of-order execution, replayable memory operations, cache prefetch, coherence speculation, or permission checks before commit.
- Avoid generic CPU textbook summaries unless they are tied to a concrete XiangShan/XSCache signal, queue, table, state machine, algorithm, port, connection, datapath segment, or module with exact Chisel line evidence.