
amd-ross-agentic-ai-assistant
Agent Skills for Developing Products with AMD Embedded Technologies
- version
- 2026.10.1
- GitHub stars
- 269
Install
/plugin install amd-ross-agentic-ai-assistant@amd-ross-agentic-ai-assistantRun it inside Claude Code after adding the marketplace with /plugin marketplace add Xilinx/ross-ai-assistant.
Contents
Discovered from sourceSkills 81
Consume an existing SDT and run gen-machine-conf. Do not create or source a Yocto
environment in this skill.
Instructions
- Resolve the SDT source from the user. It may be an unpacked SDT directory, a local
archive (
.tar.gz,.tar.xz,.zip, ...), or a URL. If absent, ask for it; do not search broadly. Pass archives and URLs to--hw-descriptionverbatim. Never download or extract them first.gen-machine-confroutes any input containing://, and any local archive, through the BitBake fetcher, unpacks it under${BUILDDIR}/.hw-description, and records the original URI plus its checksum asSDT_URI/SDT_URI[sha256sum]in the generated machine conf. Hand-extracting produces afile://SDT_URIpointing at a local scratch path, which is not reproducible for anyone else building the machine. Append;S=<subdir>to the archive/URL when it holds more than one SDT directory. - Validate the input for its form:
- Directory: confirm
system-top.dtsis nonempty. Require nonemptypcw.dtsiandpl.dtsiwhen referenced by its#includedirectives. PL-only SDTs normally omitpcw.dtsi; its absence is informational when it is not referenced. - Archive or URL: do not pre-extract. At most confirm a URL is reachable with a HEAD request; the tool reports fetch failures clearly on its own.
.xsain any form: the tool rejects it. Route to$esw-xsa-to-sdtto produce an SDT first.
- Directory: confirm
- Confirm the current shell is initialized:
If either check fails, stop and invoke or recommendtest -n "$BUILDDIR" command -v gen-machine-conf$esw-yocto-source-setup. The setup and parse commands must run in the same shell/session. The shell must be a clean Yocto environment —XILINX_VITIS/XILINX_VIVADOmust not be set and the Vitis/Vivadosettings64.shmust not have been sourced here. Those settings clash with the Yocto/OEPATH,LD_LIBRARY_PATH, and Python and breakgen-machine-conf. IfXILINX_VITISis set, stop and ask the user to re-run in a fresh shell that only sources the Yocto build environment. Before metadata queries or native-tool preparation, query the effectiveTMPDIRwithbitbake-getvar --value TMPDIR(or the release's equivalent), then checkfindmnt -T <path>on it or its nearest existing parent. Do not infer it from the shell'sTMPDIR. Preserve valid local storage and keep sanity checks enabled. On query failure ornfs/nfs4, stop and follow this skill's recovery steps in${CLAUDE_SKILL_DIR}/references/troubleshooting.md#tmpdir-on-nfs. - Discover both levels of the installed interface. Tool releases differ; do not rely on a
remembered option list:
The first command shows global options and the second shows subcommand options. If the command's shebang interpreter lacks PyYAML, perform step 7 first and invoke both help commands with the selected interpreter.gen-machine-conf --help gen-machine-conf parse-sdt --help - Resolve a machine YAML template from the active layers when the user did not supply
--template:- Defer this question until the SDT exists. When the SDT is still being produced
upstream (
$esw-xsa-to-sdt), do not ask about the template in the same message as that skill's board-DTS question. The two are separate gates: the board DTS changes the SDT, the template consumes it, and the SDT's actual domains and PL content are what make a template relevant or pointless. Bundling them also makes the reply ambiguous — an answer like "no template" resolves this question while leaving the board DTS unanswered. - Get the configured layer paths from
bitbake-layers show-layers; search only theirconf/machineyaml/*.yamlfiles for names matching the target board/device. - Inspect each matching YAML's
args,inherit,domain-file, andmachine.descriptionto explain its software-domain scope. Do not classify*-multidomain.yamlas non-segmented: both*-sdt-seg.yamland*-multidomain.yamlmay be Segmented Configuration templates; the usual distinction is Linux-only versus multiple domains. - If exactly one compatible machine YAML is found, do not apply it automatically. Present it with its concrete deltas and ask the user whether to use it or build without a template. Proceed only after the user confirms.
- If multiple compatible machine YAML files are found and the user did not identify one, stop before generation, list their exact paths and concise descriptions, and ask which machine YAML to use. Never choose among multiple matches from the filename, XSA, board DTS, or apparent domain count.
- If no compatible machine YAML is found, continue without
--templateunless the user explicitly required a template. - Present the concrete deltas a template introduces - its
--domain-filelist,-gvalue, Kconfig entries, andpostsettings - not just its name, so the user can evaluate the choice. Offer "no template" as a real option: it yields a machine built purely from the SDT. - Know the merge semantics before recommending one. Values under the YAML
argskey become argparse defaults, so any option passed on the command line overrides the template.inheritmerges the parent YAML with the inherited file taking priority. - AMD BSP machine YAMLs commonly hard-code
--hw-description <url-to-released-sdt.tar.gz>. Using such a template without an explicit--hw-descriptionsilently builds the machine from AMD's released SDT instead of the user's hardware. Always pass the local SDT directory with--template, then confirm the generated conf'sSDT_URIandPDI_PATHreference the user's artifacts. - A template usually supplies
--machine-nametoo. When that name matches a machine already shipped by a layer, the tool warns about the conflict; the copy in${BUILDDIR}/conf/machinewins because the build conf directory precedes layers inBBPATH. Report the shadowing and offer a distinct name rather than leaving it ambiguous. - A distinct
--machine-namesilently drops the BSP's machine-gated appends. AMD BSP recipes enable board targets through override-keyed compatibility, for exampleCOMPATIBLE_MACHINE:versal-vrk160-revb-multidomain = "${MACHINE}"in anedf-ospi,edf-qspi,image-selector,imgrcvry, oruefi-capsulebbappend. A machine named anything else matches none of them, and the failure surfaces only at build time asERROR: Nothing PROVIDES '<target>'— not during generation. Keep both properties by adding the BSP machine as an override instead of renaming to it:
Verifygen-machine-conf ... --machine-name <custom-name> \ --machine-overrides <bsp-machine-name> --force ...MACHINEOVERRIDESin the generated conf lists the BSP name, then prove the target resolves withMACHINE=<custom-name> bitbake -n <target>before starting a real build. Present the trade-off explicitly: reuse the BSP name and shadow its conf, or keep a distinct name plus the override and leave the layer's machine untouched.
- Defer this question until the SDT exists. When the SDT is still being produced
upstream (
- Select only user-relevant options that the installed help reports:
- Resolve segmented PL overlay mode before generation when no template is selected.
Inspect the supplied SDT directory for
*_pld.pdifiles, alongside its other PDI, BIF, and PL device-tree artifacts. If a*_pld.pdiis present and the user has not already explicitly selectedfullordfx, stop and ask which PL overlay mode to use. This check is required even when the prompt says "leave optional PL overlay settings unset", "use defaults", or "skip questions"; those phrases do not resolve the segmented PL loading requirement. Show the discovered PDI paths and explain that this workflow must resolve how separately loaded PL devices are described instead of silently leaving them in the base DTS. Offerfullfor full PL configuration anddfxfor a design with dynamic function exchange; allow the user to clarify the loading workflow if neither applies. Do not select a mode automatically or infer DFX from multiple PDIs. Wait for the answer before runninggen-machine-conf, then pass the confirmed--gen-pl-overlay fullor--gen-pl-overlay dfx. Resolve the intended PL payload separately if--plis needed; never substitute the boot PDI for the PLD PDI. This directory inspection does not authorize downloading or extracting archive/URL inputs; retain the input-handling rules in steps 1–2 for those inputs. - Global controls commonly include
--template,--machine-name,--config-dir,--require-machine,--machine-overrides,--output,--native-sysroot,--menuconfig,--add-config,--debug, and--force. parse-sdtcontrols commonly include--gen-pl-overlay,--domain-file,--psu-init-path,--pl,--localconf,--multiconfigfull, and--dts-path.- Never default
--gen-pl-overlay/-g(e.g.-g full). Only pass it when the user explicitly asks for or selects a PL device-tree overlay. If the segmented PL check above applies, obtain that selection first; otherwise omit it when unspecified. The same applies to--pl/--multiconfigfull— do not add them on the user's behalf. - Never default
--outputor--config-dir. Only pass either when the user explicitly specifies the corresponding directory; otherwise omit them and let the tool auto-set up its own output and config locations. - Let the tool auto-detect SoC family and variant. Do not ask about or pass
--soc-familyor--soc-variantunless the user explicitly requests an override to correct failed detection. - Validate supplied template, domain, PL/PDI, init, config, and sysroot paths before use. Do not infer a domain file, custom template, required base machine, machine overrides, or Kconfig settings.
- Treat
--localconfas a write to that file,--menuconfigas interactive, and--forceas replacement of cached/generated output. Obtain approval when the user's request did not already authorize the corresponding mutation. - Apply Kconfig overrides non-interactively with
--add-config CONFIG_<macro>=y; they take priority over the template'skconfigblock. Read the generatedconfigs/Kconfig.*to confirm the exact symbol before using it, and note that symbols in achoicedeselect their siblings automatically, so one macro is enough. Always regenerate after any Kconfig selection or generatedconf/configchange. Pass the intended symbol through--add-configand pair it with--force; change detection hashes the hardware description, so an unchanged SDT otherwise makes the tool skip regeneration and silently leave previous output in place. Never directly editconf/config, generated machine.conffiles, generated domain DTS files, or other generated output and report the change as complete. If direct edits were made while diagnosing, treat them as temporary only: rerungen-machine-conf --forcewith the corresponding--add-configoverride so the generator replaces them, then validate the regenerated values.
- Resolve segmented PL overlay mode before generation when no template is selected.
Inspect the supplied SDT directory for
- Choose the Python interpreter —
gen-machine-confneeds thePyYAML(yaml) module. Probe the environment interpreter and fall back only if it is missing it:python3 -c 'import yaml' # environment python3 /usr/bin/python3 -c 'import yaml' # fallback, only if the above fails- If the environment
python3importsyaml, use it (leaveGEN_MACHINE_CONF_PYTHONunset). - If it fails but
/usr/bin/python3importsyaml, exportGEN_MACHINE_CONF_PYTHON=/usr/bin/python3before running the wrapper. - If neither imports
yaml, stop and report the missing dependency. Never install packages or create a virtual environment to satisfy it.
- If the environment
- Run the tool. The checked wrapper accepts only an SDT directory; put global options
before
--andparse-sdtoptions after it, and it places them on the correct sides of the subcommand:
Example (the${CLAUDE_SKILL_DIR}/scripts/run_gen_machine_conf.sh <sdt-dir> [global options...] -- [parse-sdt options...]parse-sdtoverlay options below are illustrative — include them only when the user asks for a PL overlay):
For backward compatibility, arguments supplied without${CLAUDE_SKILL_DIR}/scripts/run_gen_machine_conf.sh ./sdt \ --machine-name my-machine --force -- \ --gen-pl-overlay full --pl ./sdt/design.pdi --multiconfigfull--are treated asparse-sdtoptions. Do not use that form for global options. The wrapper honorsGEN_MACHINE_CONF_PYTHONwhen set; otherwise it runsgen-machine-confwith its own interpreter. For an archive or URL the wrapper's directory check rejects the input, so bypass it and invoke the tool directly with the same argument order, using the interpreter chosen in step 7:
Report that the wrapper was bypassed and why.gen-machine-conf --hw-description <archive-or-url> [global options...] parse-sdt [options...] - Capture the command, tool path/version output, and generated paths. Do not overwrite an existing machine configuration unless the user approves or the installed command offers a clearly safe update mode selected by the user.
- Validate that the output reported by the tool exists and inspect generated
.conf,.inc, and device-tree artifacts for empty files and unresolved template markers. For a Kconfig/config customization, verify both the selected symbol inconf/configand every affected emitted value in the machine.confand final domain DTS. The successful generator exit and regenerated artifacts—not a manual edit—are the completion criterion. With--template, additionally prove the template applied to the intended hardware: checkSDT_URIandPDI_PATH(must point at the user's SDT/PDI),DEFAULT_HW_BOOT_MODE(reflects the template's Kconfig boot mode), and thepostsettings the YAML declared. When the input was a URL, confirmSDT_URIis that exact URL and thatSDT_URI[sha256sum]matches the server's checksum - that proves the template's own hard-coded--hw-descriptionwas overridden rather than silently used. Aconf/dts/<machine>/*-linux.dtsthat differs from an untemplated run confirms the domain files took effect. After any peripheral or console Kconfig override, verify the target node in the finalconf/dts/<machine>/*-linux.dts, not just inconfigand the machine conf. A template'sCONFIG_YOCTO_BBMC_*_DTSIcustom DTSI is applied last and can/delete-property/an alias or setstatus = "disabled"on the very node just selected, because BSPs reserve peripherals for other domains. Confirm the node isstatus = "okay"and its alias still exists. Achosennode that loststdout-pathwhile keepingbootargsis the signature of this conflict:bootargsis a plain string and survives, whereasstdout-pathresolves throughaliasesand is pruned once the alias is deleted. Report the conflict instead of treating matchingSERIAL_CONSOLES/configvalues as proof the change works.
Read ${CLAUDE_SKILL_DIR}/references/troubleshooting.md when parsing fails.
Handoff
After success, report the exact MACHINE value and the configuration/layer path that must
be present in BBLAYERS. Do not start a BitBake build unless the user separately requests it;
when they do, hand off to $esw-yocto-build in the same initialized shell rather than invoking
bitbake here. Note that the generated MACHINE is a board machine, so it builds boot
artifacts; an EDF rootfs image is a separate build against a common machine.
EDF JTAG image loading
Load a board-matched boot image over JTAG with XSDB and hw_server. Completion means the
family helper reported success (IMAGE_DOWNLOADED for Versal, IMAGES_LOADED for
Zynq/ZynqMP); it does not prove U-Boot or Linux came up. The board can be attached to a
remote hw_server; it need not be connected to the agent host.
Assume the user may not know these tools. Find the tools, server, board and files yourself, explain choices in plain words, and ask only for what cannot be determined.
Where this fits: build the image ($esw-yocto-build), try it on the board over JTAG (this
skill: fast, and the board's flash is left untouched), then write it to flash with
$esw-program-flash when the user wants the board to boot on its own.
For evidence-only requests, review the supplied logs without running the hardware steps below or connecting to the board. A download or execution-start marker supports only image loading and execution start. Claim a U-Boot prompt or Linux boot only when captured console output establishes that milestone; otherwise report it as unverified.
Instructions
-
Check the setup. Use a separate hardware shell: source Vitis/Vivado settings only there, never mixed with the EDF setup, gen-machine-conf or BitBake environment. Existing images do not require sourcing Yocto or starting a build.
- XSDB: use the install the user names. Otherwise look for
xsdbonPATH, under$XILINX_VITIS/bin, then in standard install locations such as/tools/Xilinx/<version>/Vitis. Ask only if none is found. Record its path and release. - hw_server: use the server the user names and normalize
host:porttotcp:host:port. If none is named, the board is on this machine: uselocal; XSDB then starts a local hw_server itself when none is running. - Cable: loading works only over JTAG through hw_server. On AMD evaluation boards this is a normal USB cable from the PC to the board's JTAG/UART port; custom boards use a JTAG pod such as Platform Cable USB II or SmartLynq. If no cable or device is found, see troubleshooting.
- XSDB: use the install the user names. Otherwise look for
-
Resolve the board and files. Establish the board, family (
versal,versal-net,versal-2ve-2vm,zynqmporzynq) and silicon revision when relevant. Take the image path from the user or the board-machine deploy directory of an EDF build. Find the files the family needs (see Family details) from file names and known package conventions. Resolve aliases and movinglatestpaths once and use the canonical paths everywhere. Check each file is readable, nonempty and has the expected format and architecture; reuse earlier evidence for unchanged files. Do not routinely read BIF files, manifests, ESW source or partition tables; consult them only to resolve ambiguous candidates or a concrete compatibility problem. Missing metadata alone does not block loading.- Unsupported application processors: classic PL MicroBlaze and MicroBlaze V
(RISC-V), including SCU200 designs, are not supported by this skill. If the supplied
hardware or artifacts identify either processor, report that limitation and stop
before programming, resetting, downloading or starting execution. Read-only target
discovery is allowed when needed to identify the hardware. A
.pdifile alone does not identify a Versal platform; do not route a MicroBlaze design to the Versal helper. This restriction does not apply to the PMU firmware stage of the supported ZynqMP flow.
- Unsupported application processors: classic PL MicroBlaze and MicroBlaze V
(RISC-V), including SCU200 designs, are not supported by this skill. If the supplied
hardware or artifacts identify either processor, report that limitation and stop
before programming, resetting, downloading or starting execution. Read-only target
discovery is allowed when needed to identify the hardware. A
-
Choose one target. Connect to the server and enumerate target properties. Use a filter or cable identity that matches exactly one intended device. When several boards are present and the request does not identify one, list them to the user by product and serial from the cable name and ask. Never select numeric target 1 by default or reset all devices.
-
Load with the family helper. Run the helper for the family from Family details, resolving
<skill-dir>to this skill's installed directory, and capture XSDB output to a run-specific log. The Versal and Zynq helpers check that the board's active boot mode is JTAG before their single system reset and again after it, and stop on a failed read or another mode. The helpers never change boot-mode registers; do not change them yourself to get past the check. The scripts check argument syntax only; file checks belong to step 2. Helpers print the Tcl commands as they run them. -
Report. Lead with a plain result, for example "Your image was loaded on the VEK280 over JTAG; the board is now starting from it." Then tell the user how to see it boot: the same USB cable usually provides the serial console as one of its new serial ports (
/dev/ttyUSB*on Linux, COM ports on Windows), at 115200 baud, showing U-Boot and then Linux. Always show the actual shell invocation in a copyable code block, with resolved XSDB, script and firmware paths, server and target filter or cable identity, correctly quoted, plus thedevice programordow/conTcl commands and the log path. ReportIMAGE_DOWNLOADEDorIMAGES_LOADEDonly when the helper printed it. Do not claim U-Boot reached its prompt based on a successful download. -
Handle failures from the log. Report the failed command and XSDB/PLM error, then use troubleshooting to explain the likely cause and fix in plain words. Diagnose before retrying; do not loop resets or power cycles. Keep the exact attempted command and log available.
Family details
For discovering component files from a build directory, see firmware discovery.
Versal, Versal Net and Versal Gen 2 (versal, versal-net, versal-2ve-2vm)
- Files: one complete board-matched PDI/
boot.bin. Its DTB placement is packaged, so do not load a separate DTB. Do not load R5 applications separately; if the PDI contains R5 partitions,device programstarts them, so use an APU-only image when R5 firmware must be excluded. A hardware-only init PDI is not enough. - Command:
xsdb <skill-dir>/scripts/versal_jtag_boot.tcl <versal|versal-net|versal-2ve-2vm> <image> <server> '<target-filter>' - What it does: connects, selects one device, checks boot mode, resets, reselects,
checks boot mode again, runs
device program, and disconnects. - Details: Versal reference.
ZynqMP (zynqmp)
- Files: PMU firmware, A53 FSBL, U-Boot and TF-A (
bl31.elf), plus the separate Linux DTB when available:devicetree/cortexa53-linux.dtbif present, otherwise a unique appropriate DTB in the directory. A ZynqMPboot.binis a discovery input for these files, not something the helper loads. R5 applications and PL are outside this APU load, even in a multidomain package. - Command:
The DTB loads atxsdb <skill-dir>/scripts/zynqmp_jtag_boot.tcl <server> '<cable-context>' <pmufw.elf> <fsbl.elf> <u-boot.elf> <bl31.elf> [--dtb <dtb> [<address>]]0x100000unless the user gives another address. - What it does: polls for target discovery, checks boot mode and enables the PMU debug gate before and after its one system reset, starts PMU firmware, runs FSBL for four seconds, stops A53 #0, loads the DTB, U-Boot and TF-A, then resumes TF-A. The four-second delay assumes a compatible FSBL; do not derive an FSBL checkpoint.
- Details: ZynqMP reference.
Zynq-7000 (zynq)
- Files: ARM32 FSBL (with its symbol table) and U-Boot, plus an optional separate DTB.
A Zynq
boot.binis a discovery input for these files. - Command:
The DTB loads atxsdb <skill-dir>/scripts/zynq_jtag_boot.tcl <server> '<cable-context>' <fsbl.elf> <u-boot.elf> [<dtb> [<dtb-address>]]0x100000unless the user gives another address. This is a flow convention; it does not prove compatibility with every custom memory layout. - What it does: runs FSBL to a hardware breakpoint on its
FsblHandoffJtagExitsymbol (60-second timeout), loads the DTB when supplied, then downloads and resumes U-Boot. No PMU firmware or TF-A. - Details: Zynq-7000 reference.
Square brackets in commands mark optional arguments; they are not literal shell syntax.
Guardrails
- Keep hardware-tool settings separate from the Yocto build environment.
- Do not change build configuration, deploy artifacts or files beneath
tmp/workto make a load succeed. Use persistent inputs through the appropriate EDF workflow. - Do not program flash, save firmware environment, issue Linux boot commands, change boot-mode registers, bypass device security, or kill shared debug servers as part of loading the image.
Handoff
Report the board/family, machine and build identity when known, canonical image path, server/device selection, exact executed commands, programming result and XSDB log. Mark missing metadata as unknown.
| Need | EDF handoff |
|---|---|
| Write the image to flash so the board boots on its own | $esw-program-flash |
| Generate SDT from an XSA | $esw-xsa-to-sdt, in its own tool shell |
| Prepare a Yocto checkout/build environment | $esw-yocto-source-setup |
| Generate or change board-machine configuration | $esw-gen-machine-conf, in the Yocto shell |
| Produce missing or corrected boot artifacts | $esw-yocto-build, with the exact board machine and release target list |
| Boot in emulation | $esw-runqemu |
Perform additional stages only when covered by the user's request. Do not start a build merely to validate a hardware loading command.
EDF flash programming with program_flash
Write a flash image to the board's QSPI or OSPI flash with Vitis program_flash. The tool
initializes the board over JTAG, loads a small flashing U-Boot shipped with Vitis, then
erases, writes and optionally verifies the flash. Completion means program_flash reported
Flash Operation Successful; it does not mean the board has booted from flash.
Assume the user may not know these tools. Find the tools, server, board and files yourself, explain choices in plain words, and ask only for what cannot be determined.
Where this fits: build the image ($esw-yocto-build), optionally try it once over JTAG
($esw-jtag-boot, fast and leaves flash untouched), write it to flash (this skill), then
boot from flash and check the serial console (step 9).
For evidence-only requests, review the supplied logs without running the hardware steps below or connecting to the board. Programming success and verification establish the flash operation, not a subsequent boot. Claim Linux booted from flash only when captured console output and boot-source evidence establish it; otherwise report it as unverified.
Instructions
-
Check the setup.
- Vitis: use the install the user names. Otherwise look for
program_flashandxsdbonPATH, under$XILINX_VITIS/bin, then in standard install locations such as/tools/Xilinx/<version>/Vitis. Ask only if none is found. Resolve moving paths such as..._latest/...once withreadlink -eand use the canonical path everywhere. - hw_server: use the server the user names and normalize
host:porttotcp:host:port. If none is named, the board is on this machine: usetcp:localhost:3121and, if nothing is listening on port 3121, start<vitis>/bin/hw_server -d. - Cable:
program_flashonly works over JTAG through hw_server. On AMD evaluation boards this is a normal USB cable from the PC to the board's JTAG/UART port; custom boards use a JTAG pod such as Platform Cable USB II or SmartLynq. If no cable is found later, see troubleshooting.
- Vitis: use the install the user names. Otherwise look for
-
Resolve the image. Use the file the user gives. If they give a build deploy directory, pick the flash image: EDF typically names it
edf-<qspi|ospi>-<family>-<board>-...bin, which also tells you the flash kind, family and board. If the name does not make this clear, or several files match, ask. Check the file is readable and nonempty; record its size. -
Find the board setup file.
program_flashmust initialize the board before it can reach the flash. This file is design specific: never substitute one from another board or build.- Zynq-7000 / ZynqMP: the FSBL ELF (
-fsbl). Take the uniquefsbl*.elfin the same directory as the image, from the same build. Check withfile -L: ARM 32-bit for Zynq-7000, AArch64 for ZynqMP. It is required even thoughprogram_flash -helplists it as optional; without it the tool stops withERROR: Please specify a valid FSBL file for flash type: .... The flash image itself holds an FSBL, butprogram_flashneeds the ELF file. - Versal / Versal Gen 2: an initialization PDI for the board design (
-pdi). Use the one the user supplies or one from the matching build, such as a board init PDI next to the image. If none is identified, ask for it and explain it is the board setup file from the same hardware design.
- Zynq-7000 / ZynqMP: the FSBL ELF (
-
Find the board. Run the read-only helper against the server:
xsdb <skill-dir>/scripts/flash_targets.tcl tcp:<host>:<port>Use the
target_nameof thearm_dapdevice on the intended board's cable for-target_name. The helper also prints each cable's supported JTAG rates. Check the board matches the image (for example a VEK280 cable for a...-vek280-...image). If the server has more than one board and the request does not identify one, ask, listing boards by product and serial from the cable name (for example<board>, serial <serial>); never rely on the tool's default of the first device on the first cable. -
Choose the flash type. Use the user's value, or the known board settings in flash configuration. Otherwise ask for the board's flash layout (QSPI/OSPI, single/dual, bus width), pointing the user to the board's user guide.
program_flashdetects the actual flash part, but it needs-flash_typeto choose its flashing U-Boot. Add-flash_densityfor dual stacked/parallel layouts and-erase_sectorfor flashes whose erase sector is not 64 KB. -
Confirm in plain words before starting. Say which board, which file and size, that the board's current flash contents will be erased, and that large images take tens of minutes to over an hour. Example: "This will erase the flash on the VEK280 (serial ...) and write
edf-ospi-...bin(256 MB), then verify it. It can take about an hour. Continue?" Skip the question only when the user already asked for exactly this write. -
Run
program_flash. Use the Vitis install'sbin/program_flash:program_flash -f <image> -offset 0 \ -fsbl <fsbl.elf> | -pdi <init.pdi> \ -flash_type <type> [-flash_density <MB>] [-erase_sector <bytes>] \ -frequency <max supported hz> -verify \ -target_name '<arm_dap target_name>' -url tcp:<host>:<port> \ 2>&1 | tee /tmp/<board>-program-flash-<date>.log(
-fsblor-pdiby family.) Omit-blank_check: the erase already leaves the flash blank, and the check adds about as much time as the write. Keep-verifyunless the user asks to skip it. Use-offset 0for a complete flash image; use another offset only when the user specifies one. Set-frequencyto the highest supported rate from step 4. Judge the result from the log: with| teethe shell exit status is that oftee, so success means the log ends withFlash Operation Successful.Run it in a session that stays alive for the whole job, such as a persistent terminal session that you poll. Do not start it with
nohup ... &from a tool shell that exits right away: the process can be killed when the shell returns, leaving an empty log. Within the first minute, confirm the log showsConnected to hw_serverand the process is still running. Poll the log, give progress updates from its percentage output, and do not interrupt or restart a running write. -
Report. Lead with a plain result ("The flash on your VEK280 now holds
<image>and was verified."), then the exact command, log path, theDetected Flashline, each step'sElapsed timeand the final result. AFlash Mismatchedwarning is expected when the selected type is generic; say it is harmless unless the operation failed. Say that booting from flash was not tested unless it was. -
Explain how to boot from flash. Tell the user the next step:
- Board at the user's desk: power off, set the board's boot-mode switches to the flash
that was written (QSPI or OSPI; positions are in the board's user guide), power on, and
watch the serial console. The same USB cable usually provides the console as one of its
new serial ports (
/dev/ttyUSB*on Linux, COM ports on Windows), at 115200 baud. A good boot shows the boot loader messages, U-Boot, then a Linux login prompt. - Remote board, or the user asks you to switch it: for Versal, follow the boot-mode section in flash configuration, confirm the register readback, and tell the user how to return the board to JTAG mode.
- Board at the user's desk: power off, set the board's boot-mode switches to the flash
that was written (QSPI or OSPI; positions are in the board's user guide), power on, and
watch the serial console. The same USB cable usually provides the console as one of its
new serial ports (
-
On failure, report the tool's error line and the last completed step, then use troubleshooting to explain the likely cause and fix in plain words. Diagnose before retrying. Do not loop retries. If a write stopped part way, tell the user the board will not boot from flash until a write completes.
Guardrails
- The operation erases and rewrites flash. Program only the board the user named, and only after the target is uniquely identified.
- The board must be in JTAG boot mode for programming. Do not change boot-mode registers or switch the board to flash boot unless the user asks.
- Use only the image, setup file and settings resolved above. Do not modify build artifacts.
- Do not kill or restart shared hw_server instances. Starting a local one when none is running is fine.
Scope
The Vitis 2026.2 install ships flashing U-Boot images for QSPI on Zynq-7000, ZynqMP, Versal,
Versal Net and Versal Gen 2, and for OSPI on the Versal families. NAND, NOR (Zynq-7000) and
eMMC are also listed by program_flash -help. UFS is not supported. Writing flash without
JTAG (USB boot/DFU modes, or from a running U-Boot or Linux) is outside this skill.
Hardware-tested so far: ZynqMP QSPI and Versal OSPI over the onboard USB-JTAG, including
Versal boot-mode switching to OSPI; see flash configuration.
Use QEMU to validate firmware handoff, kernel startup, rootfs, networking, and userspace. Do
not claim this validates physical board peripherals, electrical behavior, or on-board boot ROM
handling. Versal SD-boot QEMU loads partition 1's boot.bin from the WIC and requires it to
be byte-for-byte equal to the BOOT-<machine>.bin selected through qemuboot.conf.
For this boot mode, a common-machine WIC is usable only when this condition holds; see the
SD boot repair procedure.
Instructions
-
Source either the checkout's EDF initializer or the EDF SDK environment shipped with Vitis. Confirm
runqemuis onPATH; an SDK shell need not setBUILDDIR, andXILINX_VITIS/XILINX_VIVADOalone do not disqualify it. Versal SD boot needswicandmdir(mtools) to inspect partition 1 and compareboot.binwith the kernel file. Use SDK-provided tools when available. If native tools need building, switch to a clean Yocto build shell, without Vitis/Vivado settings, and obtain approval for that build. Before native-tool preparation, querybitbake-getvar --value TMPDIR(or the release's equivalent) and checkfindmnt -T <path>or its nearest existing parent. Do not infer it from the shell'sTMPDIR; preserve valid local storage and keep sanity checks enabled. On query failure ornfs/nfs4, stop and read${CLAUDE_SKILL_DIR}/references/troubleshooting.md#tmpdir-on-nfs. Existing SDK/QEMU artifacts do not require BitBake, relocation, or rebuilding tools. -
Obtain both artifacts explicitly:
- a board-machine
*.qemuboot.confbeside itsBOOT-<machine>.bin, QEMU hardware DTBs, and QSPI/OSPI image when referenced; - an uncompressed common-machine
.wicrootfs satisfying the SDboot.binrequirement when using SD boot. Decompress.wic.xzto a working copy;runqemudoes not boot the compressed file directly.
- a board-machine
-
Read the qemuboot configuration. Record
machine,qb_system_name,qb_dtb,qb_default_kernel,qb_rootfs_opt, serial settings, memory, boot mode, and flash-image references. Resolve relative paths against the qemuboot file's directory. -
The wrapper dry run checks paths, transport suffix, and SD size; it does not compare the embedded
boot.bin. Verify that file using the SD boot repair procedure above before launching in SD mode. Validate the pair with${CLAUDE_SKILL_DIR}/scripts/run_edf_qemu.sh --dry-run. A common rootfs machine name differing from the board machine is normal in EDF. Require compatible architecture/SoC family and release; report differing build IDs or timestamps. Whenqb_default_fstypeiswic.qemu-sd, present an existing raw WIC through a*.wic.qemu-sdsymlink sorunqemuattaches it as SD rather than inferring generic SCSI from.wic. Preserve this suffix during path normalization. Xilinx QEMU requires a positive power-of-two SD image size up to and including 2 GiB; above 2 GiB, a multiple of 512 KiB is required. If necessary, preserve the original, make a real copy of the WIC, and extend only that copy to the next valid size withqemu-img resize -f raw. A symlink is not a copy. -
Default to safe local execution:
${CLAUDE_SKILL_DIR}/scripts/run_edf_qemu.sh \ --qemuboot <board.qemuboot.conf> \ --rootfs <common-machine.rootfs.wic.qemu-sd>The wrapper defaults to
nographic slirp snapshot: terminal console, unprivileged user networking, and no persistent writes to the WIC. Pass--writableonly when the user wants guest changes persisted. Pass--taponly when tap networking is already configured or the user authorizes privileged network setup. -
Always launch QEMU inside a detached
tmuxsession, and always print the connection instructions afterwards. An agent's own PTY cannot be attached to by the user, so a console started there is readable but not typeable — the user cannot log in, and the session dies with the caller.tmuxgives the user a real TTY over their existing SSH connection, with no X display, VNC server, or extra port involved. Do not attempt to open a terminal window (xterm,gnome-terminal) instead: an inheritedDISPLAYoften has no usable auth cookie, and QEMU here runs-nographicwith a serial-only console, so an X session would host nothing but a terminal emulator.The example below uses a Yocto build initializer. For an SDK run, replace its
sourcecommand with the EDF SDK environment setup used in step 1; no build directory argument is needed by the wrapper.tmux new-session -d -s edfqemu -x 200 -y 50 "bash -lc '\ cd <workdir> && source <setup_yocto_env.sh> <init-build-env> <build-dir> && \ ${CLAUDE_SKILL_DIR}/scripts/run_edf_qemu.sh --qemuboot <board.qemuboot.conf> --rootfs <common-machine.rootfs.wic.qemu-sd>; \ exec bash'" tmux capture-pane -p -t edfqemu | tail # poll boot progress without attaching tmux capture-pane -p -S -2000 -t edfqemu | grep -i "port forward:"Report to the user, every time an instance is started:
- Outside tmux:
tmux attach -t <session>(add-dto detach other clients). Inside tmux:tmux switch-client -t <session>. Usessh <user>@<host>first if they are on another machine — the tmux socket under/tmp/tmux-<uid>/is local to that host and UID. Ctrl-b dto detach with QEMU still running,Ctrl-b [to scroll the boot log,Ctrl-a xto quit QEMU.Ctrl-cmay be delivered to the guest in nographic mode; it is not a reliable QEMU shutdown fallback. If QEMU remains, identify and terminate the exact host QEMU process, then inspect its helpers.- the host-forward ports read from the run's own
runqemuoutput, and the login policy from step 7.
Use
tmux list-clients -t <session>to see whether the user is already attached, and do not type into the console while they are driving it. - Outside tmux:
-
Capture the exact command and console log. A successful validation should reach a login or requested service, not merely start the QEMU process. Report boot time, kernel identity, mounted root device, and network address when available. Some EDF images mark the initial account password expired. Complete the mandatory password change on the serial console before testing SSH; SSH authentication may reject the account until that first console login succeeds. Never guess credentials. In snapshot mode the password change disappears on shutdown, so repeat it after each boot or explicitly use writable mode when persistence is required. Read the account policy instead of guessing it:
EXTRA_USERS_PARAMSin the EDF distro conf (meta-amd-edf/.../conf/distro/amd-edf.conf) declares the user, and auseradd -p ''pluspasswd-expirepair means the login takes an empty password and then forces a change immediately. Confirm whetherlocal.confenablesempty-root-password/allow-root-loginbefore suggesting a root login. -
On failure, rerun with
--debug, preserve the console output, and read${CLAUDE_SKILL_DIR}/references/troubleshooting.md.
Serial and networking
nographicuses the serial configuration emitted intoqemuboot.conf; do not add arbitrary-serialarguments because Xilinx multiarch machines define several serial endpoints.- Use
qemu-serial-port-tool <qemuboot.conf> --stdoutwhen the expected console is unclear. - Prefer
slirpfor non-root testing. It supplies outbound guest networking;runqemualso creates host forwards to guest SSH (22) and Telnet (23). Other guest services need additional forwarding. A forwarded port does not guarantee that its guest service runs. - Read the actual host-forward ports from
runqemuoutput. If its preferred lock files are unavailable, it automatically selects different ports; do not assume SSH always uses 2222. - Tap networking can use pre-created tap devices or have
runqemucreate them through its privileged helper. Device creation may require administrator privileges; obtain approval before allowing the helper or changing host networking.
Artifact ownership
Keep the source WIC immutable unless writable mode is explicitly requested. Snapshot mode is
the default. Do not rebuild missing QEMU artifacts implicitly; identify the missing target
(qemu-helper-native, qemu-devicetrees-native, qemu-<flash-type>, or the board boot target)
and obtain approval before starting a build.
For a writable run, prefer a real copy of the image over the deployed artifact. The copy
may live outside DEPLOY_DIR_IMAGE: runqemu recognizes the basename, not directory
membership. Use a basename containing -image- or .rootfs. and preserve the transport
suffix, for example
<image>-<machine>.rootfs.writable.wic.qemu-sd. An arbitrary renamed file may produce
Unknown path arg even when it exists. Keep the board configuration and its companion
artifacts together; do not relocate those just to place a WIC copy elsewhere.
Handoff
Report the initializer, board machine, qemuboot file, rootfs path, network mode, disk mode, console command, and outcome. State clearly that QEMU validation does not replace a physical board boot test.
Guide the user through generating a System Device Tree (SDT) from an XSA exported by Vivado, using the sdtgen tool. The generated SDT directory is the input to the downstream gen-machine-conf step.
Instructions
-
Resolve the XSA path. Use an existing
.xsapath supplied by the user. Otherwise ask one short free-text question: "What is the XSA path? You can also include a board DTS name or custom DTSI path." If a supplied path does not exist, name that path and ask for a valid one. Do not search the filesystem for XSAs. Distinguish.xsafrom custom.dtsi/.dtsopaths by extension. -
Offer a board DTS choice.
- Use an already supplied
--board-dts <name>or--custom-dts <path>without asking again. If the user passes--no-board-dts, says "no board DTS", or requests defaults/non-interactive execution/"skip questions", generate without one unless they supplied a DTS choice. Treat--no-board-dtsas a skill-level opt-out; omit it from the wrapper command because the wrapper does not accept that flag. A downstream answer such as "no template" does not resolve the board choice. - Otherwise read
SYSTEMINFO/@BOARDandSYSTEMINFO/@ARCHfrom the XSA'ssysdef.xmlusingunzipandawkas shown below. If either tool is unavailable or extraction fails, briefly report that and offer the full board list for manual selection. Then run${CLAUDE_SKILL_DIR}/scripts/gen_sdt.sh --list-boards. - Use the board component of a colon-delimited
BOARDvalue to shortlist listed names case-insensitively:xilinx.com:vpk360:1.2→vpk360,xilinx.com:vek385_1:1.1→vek385_1. Prefer exact identifier matches. If none exist, show recognizable board-family matches such asvek385and label them as broader candidates. UseARCHto organize architecture-related candidates when board matches are unavailable. If metadata is missing or unreadable, state that briefly and offer the available candidates or full list; do not guess from archive filenames or image entries. - Ask one short question: "Which board DTSI should I use?" Show the shortlist with the detected board and architecture as brief context. Use actual shortlisted names as choices, plus "Show all boards" and "Without board DTS". Say "You can also enter a custom DTSI path." Avoid long explanations in the prompt; if needed, add only "This supplies board-specific device nodes."
- Keep this question separate from downstream machine/template choices. Wait for the answer and use the selected name or custom path. For an unknown name, explain that it is not listed and ask again. If the user declines or has no preference, generate without a board DTS and mention that in the result.
- Shortlisting is for display only. Never auto-select a DTSI, interpret
_1or1.1as a hardware revision, or exclude Rev A/Rev B entries using an unverified mapping.
- Use an already supplied
-
Prerequisites:
XILINX_VITISorXILINX_VIVADOset (or exportable) sosdtgenis reachable — see${CLAUDE_SKILL_DIR}/references/troubleshooting.md.dtcandcpponPATHfor full output validation (optional — the compile check is skipped if either is unavailable).
-
Run the pipeline with the main wrapper. Pick the mode that matches the target:
# SDT without a board DTS ${CLAUDE_SKILL_DIR}/scripts/gen_sdt.sh <path_to_xsa> --outdir ./sdt_output # Known eval board — user-supplied board DTS name ${CLAUDE_SKILL_DIR}/scripts/gen_sdt.sh <path_to_xsa> --board-dts <name> --outdir ./sdt_output # Custom / non-eval board — user-supplied board DTSI ${CLAUDE_SKILL_DIR}/scripts/gen_sdt.sh <path_to_xsa> --custom-dts <board.dtsi> --outdir ./sdt_output--custom-dtsaccepts.dtsi/.dtso, not.dts.--zephyr-dtsaccepts a local.dtsior a repository board filename; SDTGen can also copy a Zephyr board DTSI automatically from XSA metadata, even without a Linux board DTS.--domain pmcis the only supported domain restriction.SDTGEN_OUTDIRsets the default output directory;--outdiroverrides it.Add
--debugfor trace output,--cleanto wipe a previous output dir first,--env-checkto only validate the environment,--list-boardsto enumerate available board DTS names, or--validate-onlyto re-check an existing output. -
What the wrapper does (three phases, all in
scripts/gen_sdt.sh):- Environment check — resolve
sdtgenviaXILINX_VITIS→XILINX_VIVADO→PATH. - Generate —
sdtgen -xsa <xsa> -dir <outdir> [-user_dts <board.dtsi> [overlay.dtsi ...]] [-debug enable -trace enable]. (The board DTS is passed via-user_dts; the legacy-board_dtsis deprecated from 2026.2 and removed in future releases.) - Validate — require
system-top.dtsand anypcw.dtsiorpl.dtsiit includes; report separate clock files and node/CPU counts as information, and compile withcppanddtcwhen both are available.
- Environment check — resolve
-
On failure, read
${CLAUDE_SKILL_DIR}/references/troubleshooting.mdand pattern-match the log against the known error signatures (XSA load failures, missing board files, permission errors, and Tcl argument errors). -
Available scripts:
Script Purpose scripts/gen_sdt.shMain wrapper — generate → validate pipeline scripts/validate_sdt.shStandalone output validator using generated includes scripts/gen_sdt.tclTcl template: generation via -user_dts <board.dtsi> [overlay.dtsi ...](plus-zoclto create a Zocl node); omit-user_dtsto generate without a board DTSgen_sdt.shis the default entry point; the.tclfile is a standalone alternative that drivessdtgenvia itsset_dt_param/generate_sdtAPI. -
Output and handoff — a successful run produces
system-top.dtsand its included files, withinclude/and hardware artifacts where applicable. MicroBlaze platforms normally put processor, peripheral, and clock nodes inpl.dtsi, withoutpcw.dtsi. PS output varies by family; separate SoC/clock DTSIs are not universal. A Linux flow requires downstream device-tree processing; SDT generation and DTC compilation do not establish Linux boot support: confirm the target processor and downstream tool support before promising a Linux image. Theesw-gen-machine-confwrapper accepts PL-only output and requires nonemptypcw.dtsiorpl.dtsionly when included bysystem-top.dts. The next step is$esw-gen-machine-conf, which requires a sourced Yocto build environment first — so hand off to$esw-yocto-source-setupbefore generating, in the same shell:# Full chain: $esw-xsa-to-sdt (XSA → SDT, here; needs XILINX_VITIS) # → $esw-yocto-source-setup (fetch sources + source the Yocto env in THIS shell) # → $esw-gen-machine-conf (SDT → machine config) # → $esw-yocto-build (bitbake targets → images/boot artifacts) # The Yocto stages share one clean shell; $esw-xsa-to-sdt must use a separate shell # because Vitis/Vivado settings corrupt the OE environment. gen-machine-conf parse-sdt --hw-description ./sdt_output ... # only after the env is sourced
Gotchas
board_dtsis offered but never auto-selected — read the XSA board/architecture metadata to shortlist names after--list-boards, then let the user choose. This is not hardware-revision validation. A wrong name may surface as acould neither be locatederror (seetroubleshooting.md).- Generating without a board DTS fails silently, not loudly —
sdtgenstill succeeds and validation still passes, but board-level nodes are simply absent. The signature is a PS peripheral leftstatus = "okay"with nothing to attach to: e.g.gem*enabled while the DTS contains zerophy-handle/ethernet-phynodes, so Ethernet never comes up. After a no-board-DTS run, grep the generated DTS for that pattern and report it, rather than reporting only that validation passed. -board_dtsis deprecated (2026.2+) — the wrapper emits-user_dtswith.dtsifilenames instead (e.g.-user_dts zcu102-rev1.0.dtsi ./overlay.dtsi); the--board-dts <name>flag still works and is translated to-user_dts <name>.dtsi.grep -c PATTERN file || echo 0double-counts on a zero match —grep -cprints0and still exits 1, so the fallback fires anyway and corrupts the value. Use|| trueor${var:-0}.- Required files follow the generated
#includedirectives. Missingpcw.dtsiis normal when it is not included; a referenced file must exist. Clocks may be inlined, and small trees or domain-specific output are not necessarily incomplete. - Read board and architecture from
sysdef.xml— the standard XSASYSTEMINFOattributes can be extracted withunzipandawk; Python and third-party modules are unnecessary. For the already resolved XSA path:
This handles multiline tags and single- or double-quoted attributes. Missing attributes produce empty values; an unavailable tool, missing XML, or missingset -o pipefail unzip -p "$XSA_PATH" sysdef.xml | awk ' BEGIN { RS = ">" } /<([[:alnum:]_.-]+:)?SYSTEMINFO[[:space:]]/ && !found { for (i = 1; i <= 2; i++) { key = (i == 1 ? "BOARD" : "ARCH") value = "" pattern = "[[:space:]]" key "[[:space:]]*=[[:space:]]*[\"\047][^\"\047]*[\"\047]" if (match($0, pattern)) { value = substr($0, RSTART, RLENGTH) sub(/^[^=]*=[[:space:]]*[\"\047]/, "", value) sub(/[\"\047]$/, "", value) } print key "=" value } found = 1 } END { if (!found) exit 1 } 'SYSTEMINFOmeans metadata is unavailable, so offer the full board list.BOARD="xilinx.com:vek385_1:1.1"andARCH="versal"identify listing hints; neither_1nor1.1establishes Rev B without a verified mapping.
When NOT to Use
- Parsing an existing SDT into a machine config → that's the downstream
$esw-gen-machine-confstep (after$esw-yocto-source-setup). - Running a BitBake build → that's
$esw-yocto-build, after a machine config exists. - Generating a device tree overlay (
.dtbo) for runtime PL reload → use/segcfg-petalinux-build,/segcfg-yocto-build, or/segcfg-linux-runtime.
References
${CLAUDE_SKILL_DIR}/references/troubleshooting.md— failure signatures, environment setup, recovery.
Run BitBake against an initialized EDF build directory. Do not fetch sources, source the environment, or generate machine configuration here.
Instructions
-
Confirm the shell is initialized and clean:
${CLAUDE_SKILL_DIR}/scripts/run_edf_build.sh --env-checkThis checks
BUILDDIR,bitbakeonPATH, free disk, that the MACHINE resolves, and thatXILINX_VITIS/XILINX_VIVADOare unset. A Vitis/Vivado environment in the build shell is a hard failure, not a warning — it injects a hostPATH,LD_LIBRARY_PATHand Python that corrupt an OE build. Setup and build must happen in the same shell; hand off to$esw-yocto-source-setupifBUILDDIRis unset.Before building, query effective
TMPDIR,HOSTTOOLS_DIRandDEPLOY_DIR_IMAGEwithbitbake-getvar(or the release's equivalent), for the selected machine and enabled multiconfigs. Checkfindmnt -T <TMPDIR>or its nearest existing parent; the shell'sTMPDIRis not proof. Preserve valid local storage and keep sanity checks enabled. On query failure ornfs/nfs4, stop and follow${CLAUDE_SKILL_DIR}/references/troubleshooting.md#tmpdir-on-nfs.On every build, let the wrapper probe the compiler on
PATHand its existing main or multiconfig host-tools trees. It currently scans$BUILDDIR/tmp*/hosttools; when the evaluatedHOSTTOOLS_DIRpaths are elsewhere, probe those explicitly as described in the troubleshooting reference. The probe compiles aDBL_MAXexpression with-O2and fails fast on the incompatible-host-compiler signature before BitBake starts. Also inspect the links on an unfamiliar host:ls -l "<evaluated HOSTTOOLS_DIR>"/{gcc,g++,cpp,gcc-ar} # repeat per configuration command -v gcc # what PATH says — often differentOE resolves host tools through separate persistent
tmp*/hosttoolssymlink trees, and creates entries only when missing, so an entry from the first build survives every laterPATHchange. A broken host compiler then fails hours later inside a-nativerecipe. Check all multiconfig trees, not just the maintmp/hosttools. See${CLAUDE_SKILL_DIR}/references/troubleshooting.md#host-toolchain-faultsfor the probe and the fix. -
Read the checkout's own target list before proposing anything:
${CLAUDE_SKILL_DIR}/scripts/run_edf_build.sh --list-targets # cats $BUILDDIR/conf/conf-notes.txtconf-notes.txtis authoritative per release and lists the valid machines and targets. Do not rely on remembered target names. Forpackagegroup-boot-artifacts, inspect the active layers' recipe and appends and the evaluated metadata for the selected machine; see${CLAUDE_SKILL_DIR}/references/targets.md#boot-artifact-targets. The group's contents can vary by machine and release, including the active 2026.2 checkout. -
Obtain the machine from the user before starting any build. Do not infer or select a machine from the board family, an earlier build,
local.conf, or the target name. If the user did not explicitly name a machine, show the relevant choices fromconf-notes.txtand ask which exactMACHINEto use. A recommendation is fine, but do not start until the user chooses. If the target/machine combination is unsupported, warn before starting and ask for confirmation rather than relying on BitBake's warning during the build. -
Establish which half of the build the user wants. EDF splits a bootable system across two builds with two different
MACHINEvalues:- a common machine (
amd-cortexa78-common, ...) builds the portable rootfs (edf-linux-disk-image,edf-platform-disk-image); - a board SDT machine (
versal-2ve-2vm-vek385-revb-sdt-seg, ...) builds boot artifacts (packagegroup-boot-artifacts, or individual targets such asxilinx-bootbin,edf-ospi,edf-qspi,kria-qspi, where supported).
Every common machine is marked "Not bootable on its own" and clears
HW_BOOT_MODE,SOC_ON_DISK_BOOT_BINandIMAGE_BOOT_FILES, so it will never emit aboot.bin. A request like "build an image for VEK385" is therefore ambiguous. State the split, say which half you are building and which target/machine pair that implies, and ask before assuming the user wants both. Read${CLAUDE_SKILL_DIR}/references/targets.mdfor the machine/target matrix and the common-machine-to-SoC-family mapping.A request for
packagegroup-boot-artifactsselects the boot-artifact group. Preserve that target rather than substituting a fixed list of recipes or adding a rootfs build. Explain its resolved contents and check compatibility with the user's selected machine using the wrapper's--dry-runbefore the real build. For individual boot.bin or SPI image requests, select the corresponding supported individual recipe. - a common machine (
-
Resolve
MACHINEexplicitly. Pass it in the environment of every BitBake invocation, for exampleMACHINE=<machine> bitbake <target>, rather than relying onlocal.conf, whose default is often stillqemuarm64. Never editlocal.confto setMACHINE. The-moption of${CLAUDE_SKILL_DIR}/scripts/run_edf_build.shimplements this same per-invocation environment override and leaves the checkout usable for other machines. If the machine does not exist, stop and route to$esw-gen-machine-conf; do not substitute a similarly named BSP machine. -
Take
DISTROfromconf-notes.txtwhen the target needs one (e.g.DISTRO=amd-edf-smallfor AMR platforms) and pass it in the BitBake command environment. The wrapper's-Doption implements this environment override. Otherwise leave the checkout default alone. -
Build. Builds run for hours. Prefer a detached
tmuxsession so they survive the caller and the user can attach to the live BitBake UI. The wrapper does this by default whentmuxis installed (--detachremains a compatibility alias):${CLAUDE_SKILL_DIR}/scripts/run_edf_build.sh -m <machine> <target> tmux attach -t <printed-session> tmux capture-pane -p -S -2000 -t <printed-session>Pass
--tmux-session <name>for a stable custom name. Reporttmux attach -t <session>(ortmux attach -d -t <session>when already attached elsewhere),Ctrl-b dto detach, and the printed capture/log commands. The session remains open after BitBake exits so the result can be inspected. Do not start a second BitBake against the same$BUILDDIR.If
tmuxis unavailable, the wrapper falls back automatically to detachedsetsid/nohup, prints the PID and log path, and remains usable without installing anything. Report that the live attach capability is unavailable in fallback mode.Run
--dry-run, environment checks, and small queries in the foreground.For a multiconfig target generated alongside the machine, use BitBake's
mc:prefix, e.g.mc:<machine>-microblaze-pmc:<target>; the machine conf'sBBMULTICONFIGline lists the available multiconfigs. -
On success, report the evaluated
DEPLOY_DIR_IMAGEand list the artifacts actually produced. Check the wrapper's printed deploy path against the evaluated value whenTMPDIRis relocated. When both halves were built, report both directories — they differ by machine. Forpackagegroup-boot-artifacts, report the resolved group members and their actual deploy outputs. Check requested firmware/image files are nonempty and resolve symlinks to canonical paths. Identify missing outputs; the packagegroup itself is not a boot image, and its success does not prove that every possible boot or SPI format was produced. If the user requests hardware loading, hand off the matching board artifacts to$esw-jtag-boot; for writing QSPI/OSPI flash, use$esw-program-flash. Run these in a separate Vitis hardware shell. A completed build alone does not authorize programming a board or writing flash. -
On failure, read the
log.do_<task>file BitBake names, not just the console summary, then consult${CLAUDE_SKILL_DIR}/references/troubleshooting.md.
Inspect or modify WIC images
Use Yocto's wic utility for partition tables and filesystem contents instead of mounting
the image. In this checkout scripts/wic may be absent or the scripts/esdk-tools/wic
symlink may be dangling. Use the wic installed in the image recipe's native sysroot and
put that sysroot's usr/bin first on PATH so its nativepython3 launcher resolves:
ns="<evaluated RECIPE_SYSROOT_NATIVE for the image recipe>"
wic="$ns/usr/bin/wic"
PATH="$ns/usr/bin:$PATH" "$wic" ls image.wic --native-sysroot "$ns"
PATH="$ns/usr/bin:$PATH" "$wic" ls image.wic:1/ --native-sysroot "$ns"
PATH="$ns/usr/bin:$PATH" "$wic" cp boot.bin image.wic:1/ --native-sysroot "$ns"
wic ls image.wic needs only partition tools, but FAT directory and copy operations also
need mdir/mcopy from mtools-native. A sysroot may contain wic without those programs.
If wic reports Can't find executable 'mdir', build the native tool in the clean Yocto
shell and prepend its component directory:
bitbake mtools-native
mtools="<evaluated COMPONENTS_DIR>/x86_64/mtools-native/usr/bin"
PATH="$mtools:$ns/usr/bin:$PATH" "$wic" ls image.wic:1/ --native-sysroot "$ns"
Do not install host mtools when the matching Yocto-native tool is available.
Query RECIPE_SYSROOT_NATIVE for the selected image recipe and COMPONENTS_DIR for the
native tools in the initialized shell. Verify those directories rather than guessing work
paths or assuming $BUILDDIR/tmp. Partition numbers are one-based. Run wic ls image.wic first, identify each filesystem
and label, and confirm the requested destination partition when the wording is ambiguous.
For standard EDF disk images, confirm the release's .wks: partition 1 (esp, /efi) holds
boot.bin, partition 2 (storage) is user storage, and partition 3 (root) is the rootfs.
Do not choose the empty storage partition just because it has more space.
Before combining independently produced rootfs and boot artifacts, extract and compare the
WIC's edf-version.txt with bootbin-version.txt and boot.bin.manifest.json from the boot
deploy directory when available. Check the EDF/Xilinx release, target architecture or SoC
family, board machine, hardware boot mode, and build IDs/timestamps. A common-machine rootfs
and matching-family board-machine boot binary are expected to have different machine names;
that alone is not a mismatch. Report differing release builds or timestamps explicitly and do
not claim hardware compatibility unless the combination has actually booted on the board.
After insertion, list the destination, copy the file back out, and verify it byte-for-byte
with cmp and sha256sum; a successful wic cp alone is not sufficient verification.
For .wic.ufs images the sector size is 4096 bytes, so every wic command must pass
--sector-size 4096; without it wic assumes 512-byte sectors and misreads the partition
table. Add it to each invocation, for example:
PATH="$ns/usr/bin:$PATH" "$wic" ls image.wic.ufs --sector-size 4096 --native-sysroot "$ns"
PATH="$ns/usr/bin:$PATH" "$wic" cp boot.bin image.wic.ufs:1/ --sector-size 4096 --native-sysroot "$ns"
Treat .wic.xz as a compressed derivative: do not attempt to edit it directly. Modify the
uncompressed timestamped .wic, then regenerate its matching .wic.xz with xz -T0 -k -f,
run xz -t, and use xz --robot -l to verify that its recorded uncompressed size equals the
modified WIC. Be aware that recompressing can change the compressed size while preserving the
same uncompressed image. Read the original uncompressed size with xz --robot -l and check
free space before extraction. Conservatively allow about twice that size when preserving the
working WIC while writing a new compressed file; report and retain the uncompressed copy unless
the user asks to remove it.
AMD Account form URLs (account.amd.com/.../xef.html?filename=...) may require an authenticated
browser/export-control session and can stall while returning zero bytes to command-line clients.
Use bounded connection and overall timeouts, then validate the payload with file and xz -t;
never treat HTML, a login response, or an empty partial file as the requested image. If login is
required, ask for a local downloaded path and check only shared artifact locations the user puts
in scope.
Guardrails
- Never source Vitis/Vivado settings in the build shell; use a separate shell for
sdtgen. - Always use the wrapper for real BitBake builds. It prefers
tmuxand safely falls back tosetsid/nohupwhentmuxis absent. Do not use plain background jobs or terminal-emulator windows.tmuximproves observability but does not replace the host-compiler checks. - Never modify
local.confto selectMACHINE,DISTRO, parallelism, or other per-build settings. Pass those values in the BitBake command environment. - Never modify files beneath
tmp/work. They are generated build state, and changes there are non-reproducible and may be overwritten. On a recipe or compiler failure, stop and report the failing task and log. If a source fix is required, propose a persistent layer patch or.bbappendand obtain explicit approval before changing it. - Do not modify
bblayers.confor any machine conf to make a build succeed without the user's approval. Report the needed change and its effect instead. - Do not disable
own-mirrors,SSTATE_MIRRORS, or theBB_DISKMON_DIRSguards to work around a failure; those mask a real environment problem. - Do not start a build merely to validate configuration — use
--dry-run. - When a
-nativerecipe fails to compile, check the host compiler before suspecting the recipe, and checktmp/hosttoolsbefore trustingPATH. - Do not run
cleansstate,cleanall, or deletetmp/without approval; these discard hours of cached work. - Report the resolved
machine confpath the wrapper prints. A machine generated into$BUILDDIR/conf/machineshadows a same-named BSP machine, which is easy to miss. - Treat shared mirror paths as external state: report when they are missing rather than silently building everything from source.
Handoff
Report the exact MACHINE, DISTRO, target list, log path, and deploy directory for each
build. For flashing or booting the result, hand off to the relevant segcfg-* runtime skill.
Prepare a Yocto checkout for subsequent commands. Do not run
gen-machine-conf parse-sdt in this skill.
Instructions
-
Obtain the sources when no Yocto checkout exists. Use the AMD/Xilinx
repomanifest, with these stable defaults:- URL:
https://github.com/Xilinx/yocto-manifests - Branch: use the user's release when supplied via natural language,
-b, orYOCTO_MANIFEST_BRANCH(CLI overrides the environment). Otherwise resolve the manifest repository's current default branch by passing-b HEADtorepo init. Do not pin a release or invent a fallback. If initialization fails, report the error and suggest an explicit-b <branch>. - Manifest:
default-edf.xml
Map user-supplied repository, branch/release, and manifest overrides to
-u,-b, and-m. Echo the resolved values before syncing. With no branch supplied, let the fetch script pass-b HEADand report the resolved branch after initialization.Confirm the destination directory with the user, then fetch:
"${CLAUDE_SKILL_DIR}/scripts/fetch_yocto_sources.sh" <dest-dir> # override defaults when the user asks for a different source/branch/manifest: "${CLAUDE_SKILL_DIR}/scripts/fetch_yocto_sources.sh" -u <url> -b <branch> -m <manifest> <dest-dir>Skip the confirmation prompt when the user opts out. If the user says "skip questions", "don't ask", "non-interactive", "just fetch", "use defaults", or supplies an explicit destination with an instruction to proceed, fetch immediately with the resolved values — still echo them first, but do not wait for approval. Only fall back to prompting when the destination is missing and cannot be derived.
Skip this whole step when the user already has a checkout containing
edf-init-build-env. - URL:
-
Resolve the checkout root and initializer before changing directories.
- After fetching, use the absolute destination from Step 0 as the checkout root;
the fetch script's
cddoes not change the caller's directory. For an existing checkout, use the user's supplied root. Resolve explicit relative paths from the caller's current directory. - Accept the user's selected initializer name or file path. With a known checkout,
resolve an initializer name beneath that root; resolve an explicit relative file
path from the caller's directory. Default to the checkout's
edf-init-build-envonly when no initializer is named. List available initializers when the checkout uses an internal manifest; do not substitute the public initializer for a named internal one. - With only an initializer file supplied, identify the checkout root from that file and the checkout layout. If the root cannot be established, ask for it before choosing a default build directory. With no checkout or initializer supplied, check the current directory, then ask for the path if missing. Do not scan broad shared filesystems or select a moving release symlink without authorization.
- Pass an absolute initializer file path to the helper, not a checkout directory. Verify it exists and report the selected checkout and initializer.
- After fetching, use the absolute destination from Step 0 as the checkout root;
the fetch script's
-
Resolve the build directory before sourcing. Preserve an absolute supplied path; resolve an explicit relative path from the caller's current directory. Otherwise use
<absolute-checkout-root>/build. Report the resolved absolute build directory. -
Initialize in the same shell that will run later Yocto commands:
source "${CLAUDE_SKILL_DIR}/scripts/setup_yocto_env.sh" "<absolute-initializer-path>" "<absolute-build-dir>"The helper sources the initializer itself; do not source it separately first. Executing the helper in a child shell does not update the caller. The fetch script's completion command uses the default initializer and build directory; adjust it when the user selects different paths. Do not export
XILINX_VITIS/XILINX_VIVADOor source Vitis/Vivadosettings64.shin this shell. Their host-tool environment can conflict with Yocto/OE. Run Vitis-dependent work, such assdtgenvia$esw-xsa-to-sdt, in a separate shell. -
Check the helper's exit status and its reported
BUILDDIR,bitbake, andgen-machine-confpaths before continuing. On failure, followreferences/troubleshooting.md. A missing command is a checkout or environment problem; verify the selected initializer and command location before proposing changes to layers. -
Check the effective Yocto
TMPDIRafter initialization and before layer queries, machine generation or builds. Query it withbitbake-getvar --value TMPDIRwhen available; use the installed release's equivalent configuration query otherwise. Do not assume it is$BUILDDIR/tmpor use the shell'sTMPDIRas proof of the BitBake value. Check the resolved path's filesystem withfindmnt -T <path>; if the directory does not exist, check its nearest existing parent. An NFS source/build workspace is usable when the effectiveTMPDIRis on suitable local storage. Preserve an existing valid setting. IfTMPDIRis onnfs/nfs4, resolve a writable local location before proceeding; check available space and obtain the user's path/configuration choice unless already authorized. Do not automatically choose/tmpor disable the Yocto sanity checker. Read${CLAUDE_SKILL_DIR}/references/troubleshooting.md#tmpdir-on-nfsfor configuration and recovery details. If the query itself fails, report that failure and inspect the active configuration rather than claiming the default path is the evaluated value. -
Check host OS compatibility against the initialized Yocto release. Read
/etc/os-releaseto report the host distribution and version. QueryNATIVELSBSTRINGandSANITY_TESTED_DISTROSwithbitbake-getvar --value <variable>when available, or the release's equivalent configuration query. Runbitbake -pin the initialized shell to parse metadata and invoke the release's sanity checks without executing build tasks. Preserve and inspect its output and exit status. Report any host-distribution validation warning; do not treat an unlisted host as a fatal error unless the release's checks require stopping. A fatal sanity or parse error means setup validation is incomplete: report the first error and resolve it before handing off. Do not hardcode supported Ubuntu versions, suppress sanity checks, or claim compatibility when the checks could not complete. Yocto validation is separate from AMD EDF's official host support; consult the selected EDF release's documentation when official support is required. Read${CLAUDE_SKILL_DIR}/references/troubleshooting.md#host-os-compatibilityfor details. -
Inspect
BBLAYERSviabitbake-layers show-layerswhen available. Report whethermeta-xilinx-core,meta-xilinx-standalone, andmeta-xilinx-standalone-sdtare present by checking the layer paths (displayed names can bexilinx,xilinx-standalone, andxilinx-standalone-sdt). These are sublayers ofsources/meta-xilinx; the repository itself is not a layer. Do not mutatebblayers.confunless explicitly requested. -
Record the resolved initializer, build directory, Yocto release (when discoverable), path to
gen-machine-conf, the evaluatedTMPDIRwith its filesystem, host OS, and the host compatibility check result (including any warning or incomplete check). -
Hand off SDT parsing to
$esw-gen-machine-confin the same initialized shell. -
Hand off BitBake builds to
$esw-yocto-buildin that same shell. The environment does not survive into a new shell or a later tool call, so the build must run where the initializer was sourced. This applies whether the user asked to build immediately after setup or after generating a machine.
Read ${CLAUDE_SKILL_DIR}/references/troubleshooting.md when setup or command
discovery fails.
Guardrails
- Never combine the Vitis/Vivado environment with the Yocto build environment in one
shell or command — do not export
XILINX_VITIS/XILINX_VIVADOor sourcesettings64.shin the shell whereedf-init-build-envis sourced. Use separate shells. - Default source fetches to
https://github.com/Xilinx/yocto-manifestsand manifestdefault-edf.xml; use the explicit branch or discover the remote default, and fail clearly with guidance to pass-bif discovery fails. Confirm the destination directory before syncing unless the user opts out ("skip questions", "non-interactive", "just fetch"). - Do not download layers or alter an existing build configuration without approval.
- Do not claim environment persistence across separate tool calls or terminal sessions.
- Use configuration queries for the TMPDIR preflight and parse-only BitBake for host sanity checks; do not execute build tasks merely to validate shell setup.
- Treat shared
daily_latestpaths as non-reproducible and report their canonical target.
HLS Design Architecture
Sources: "Parallel Programming for FPGAs" (Kastner et al.) + AMD UG1399 (Vitis HLS User Guide)
Preamble — Parse Arguments and Print Summary
Vitis environment
The Step 2e g++ verification depends on $XILINX_VITIS to locate ap_fixed.h.
- When called by
/hls-matlab-to-cpp(the normal flow): the environment was sourced in that skill's preamble — do NOT source it again, just verify it is set. - When called standalone: source Vitis first via
./reference/setup.mdStep 1 or ensure$XILINX_VITISis set
Verify before proceeding:
echo "XILINX_VITIS=$XILINX_VITIS" && ls $XILINX_VITIS/include/ap_fixed.h
Parse arguments
Parse $ARGUMENTS at the very start:
- Everything before
part=is theTHROUGHPUT_TARGET(may be empty) part=<value>→XPARTclock=<value>→CLOCK_NS
If XPART or CLOCK_NS are missing from $ARGUMENTS, ask the user for the missing values before proceeding.
Input Discovery — Find or Create Workspace
The architect looks for an existing workspace, or creates one if needed. Detection is based solely on filesystem state (not context variables).
Step 1: Check for existing frame_based/ workspace
# Search for existing frame_based/kernel.cpp (from hls-matlab-to-cpp or previous run)
EXISTING_KERNEL=$(find . -maxdepth 3 -path "*/frame_based/kernel.cpp" -type f | head -1)
if [ -n "$EXISTING_KERNEL" ]; then
# Found existing workspace - extract design_name from path
design_name=$(echo "$EXISTING_KERNEL" | cut -d'/' -f2)
MODE=existing
else
# No workspace found - need to create one
MODE=new
fi
Step 2a: If MODE=existing (workspace found)
# Verify testbench also exists
if [ ! -f "$design_name/frame_based/testbench.cpp" ]; then
ERROR: "Found frame_based/kernel.cpp but testbench.cpp is missing"
fi
# Print confirmation
echo "Found existing workspace: $design_name/frame_based/"
echo " ✓ kernel.cpp"
echo " ✓ testbench.cpp"
Proceed to Interface Selection.
Step 2b: If MODE=new (no workspace found)
-
Ask user for input file paths:
- "Where is your C++ kernel source file?" →
USER_KERNEL_PATH - "Where is your testbench file?" →
USER_TESTBENCH_PATH
- "Where is your C++ kernel source file?" →
-
Ask user for design name (or derive from kernel filename):
- "What should the design workspace be named?" →
design_name - Default suggestion: extract basename without extension from kernel path
- "What should the design workspace be named?" →
-
Create workspace and copy files:
# Create frame_based/ directory mkdir -p "$design_name/frame_based" # Copy user files into canonical locations cp "$USER_KERNEL_PATH" "$design_name/frame_based/kernel.cpp" cp "$USER_TESTBENCH_PATH" "$design_name/frame_based/testbench.cpp" -
Print confirmation:
───────────────────────────────────────────────────── [architect] New Workspace Created Design name : <design_name> Kernel copied : <USER_KERNEL_PATH> → <design_name>/frame_based/kernel.cpp TB copied : <USER_TESTBENCH_PATH> → <design_name>/frame_based/testbench.cpp ─────────────────────────────────────────────────────
After Input Discovery completes (both modes):
design_name/frame_based/kernel.cppexists ← INPUT to architectdesign_name/frame_based/testbench.cppexists
Proceed to Interface Selection.
Interface Selection
In interactive mode: ask the user which top-level interface the kernel should use. Present the options clearly:
[architect] Interface Selection — choose one:
1. m_axi Data in/out via AXI4 burst master (arrays in DDR/HBM).
Best for: frame buffers, large lookup tables, batch processing.
load_input() reads a full frame from memory before compute starts.
Example: peakPicker reading xcorr[] and threshold[] arrays.
2. axis Data in/out via AXI4-Stream (pixel/sample streaming, no buffering).
Best for: real-time pipelines, video, DSP chains.
load_input() forwards stream samples directly into compute.
Example: demosaic receiving a pixel stream from a camera sensor.
3. m_axi + axis Mixed — one port streams in, another bursts from memory (or vice versa).
Best for: kernels that stream output but need a lookup table from DDR.
4. m_axi + s_axilite Data arrays via m_axi; scalar parameters (thresholds, sizes) via
AXI-Lite control register. Most common for standalone Vitis kernels.
Which interface fits your design?
If autoconfirm=true is in $ARGUMENTS: do NOT ask — infer IFACE_TYPE
automatically from the top-level function signature:
- Pointer/array arguments (
float*,int[]) with nohls::streamargs →m_axi hls::streamarguments only →axis- Mix of pointer and
hls::stream→m_axi + axis - Pointer args alongside scalar-only control args →
m_axi + s_axilite
Print the inferred choice:
[architect] Interface inferred: m_axi (autoconfirm; pointer args detected)
Store the answer as IFACE_TYPE. Use it when writing #pragma HLS INTERFACE pragmas and when deciding whether load_input / store_output use hls::stream ports or m_axi pointer arguments.
Print confirmation:
─────────────────────────────────────────────────────
[architect] Starting — <design_name>
Throughput target : <THROUGHPUT_TARGET or "none — will derive from II=1 floor">
FPGA part : <XPART>
Clock : <CLOCK_NS> ns
Interface : <IFACE_TYPE>
─────────────────────────────────────────────────────
Directory Layout
After Input Discovery, the canonical workspace structure is:
design_name/
├── frame_based/ ← INPUT (always exists after Input Discovery)
│ ├── kernel.cpp ← Plain C++ kernel (created by hls-matlab-to-cpp OR copied in standalone mode)
│ └── testbench.cpp ← Testbench (created by hls-matlab-to-cpp OR copied in standalone mode)
└── rearchitect/
└── v1/ ← OUTPUT (created by architect via design-layout.md)
├── src/
│ └── kernel_hls.cpp ← HLS dataflow architecture
├── tb/
│ └── testbench.cpp ← Copied from frame_based/ unchanged
└── hls_config.cfg ← Generated config file
└── vitis-comp.json ← Generated hls component file
Optional directories (only present if called from /hls-matlab-to-cpp):
design_name/
├── golden/ ← MATLAB source files + golden bins
├── sample_based/ ← Refactor 1 (line-by-line MATLAB → C++)
All directories under rearchitect/ are created via ./reference/design-layout.md — never create directories manually.
Handoff Protocol
Every step ends with a → HANDOFF block. No step may begin until the previous step's Condition is satisfied.
→ HANDOFF to Step X
Produces : <artifact>
Condition: <what must be true>
Blocked if: <what causes a loop-back or stop>
Flow Overview
Print this immediately after the confirmation banner so the user can track progress:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
[architect] Pipeline — <design_name>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Step 1 Study domain patterns (./reference/vitis-libraries.md)
Step 2a Draw activity timeline + choose paradigm
Step 2b Generate fixed top-level (load → compute → store)
Step 2c Decompose compute() — hierarchical or monolithic
Step 2d Write to rearchitect/ + pragma audit
Step 2e G++ functional verification
Step 3a Validate with hls* skills
Step 3b Architecture review (user approval)
Step 3c Write to perf_outcomes.md
Step 3d-1 Apply performance pragmas (if throughput)
Step 3d-2 Save baseline snapshot
Step 3e Hand off to /hls-optimize
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Re-print this after each step with ✓ on completed steps and ← NEXT on the upcoming one.
Workflow
Step 1 / 3 — Study Domain Patterns
─────────────────────────────────────────────────────
[architect] Step 1 / 3 — Study Domain Patterns (./reference/vitis-libraries.md)
─────────────────────────────────────────────────────
Invoke ./reference/vitis-libraries.md to study coding patterns from production HLS implementations before writing any code. Do NOT include or link Vitis Library headers in user designs — study, then write your own.
Print before proceeding:
─────────────────────────────────────────────────────
[architect] Step 1 done — Domain Patterns
Patterns found : <list patterns identified from ./reference/vitis-libraries.md>
Applies to : <how each pattern maps to this algorithm>
Gap : <any applicable pattern NOT found — or "none">
─────────────────────────────────────────────────────
✓ Step 1 Study domain patterns (./reference/vitis-libraries.md)
Step 2a Draw activity timeline + choose paradigm ← NEXT
Step 2b Generate fixed top-level (load → compute → store)
Step 2c Decompose compute() — hierarchical or monolithic
Step 2d Write to rearchitect/ + pragma audit
Step 2e G++ functional verification
Step 3a Validate with hls* skills
Step 3b Architecture review (user approval)
Step 3c Write to perf_outcomes.md
Step 3d-1 Apply performance pragmas (if throughput)
Step 3d-2 Save baseline snapshot
Step 3e Hand off to /hls-optimize
→ HANDOFF to Step 2
Produces : Domain pattern notes (in-context — coding patterns from ./reference/vitis-libraries.md)
Condition: At least one relevant HLS pattern identified for the input algorithm
Blocked if: No applicable pattern found → document why, proceed to Step 2 anyway
Step 2 / 3 — Generate Architecture
─────────────────────────────────────────────────────
[architect] Step 2 / 3 — Generate Architecture
─────────────────────────────────────────────────────
Apply the two paradigms when converting input code to HLS:
| Paradigm | What it means | HLS mapping |
|---|---|---|
| Producer-Consumer | N tasks, each with one responsibility, communicating through channels | One static function per stage; top-level with #pragma HLS DATAFLOW |
| Streaming Data | Tasks exchange data via FIFOs (in-order, max overlap) or PIPOs (random-order, safer) | hls::stream for sequential access; PIPO for random access; avoid wide channels |
Draw the activity timeline before coding — shows when each stage executes across multiple invocations; reveals expected parallelism and bottlenecks.
Note: Loop-level pipelining (
#pragma HLS PIPELINE) is NOT applied by the architect — see Pragma Rules below. The performance pragma handles throughput targets.
→ HANDOFF to Fixed Top-Level Structure
Produces : Activity timeline drawn; paradigm (producer-consumer / streaming) identified
Condition: At least one activity timeline sketched showing stage overlap across invocations
Blocked if: Timeline cannot be drawn → ask user for clarification on algorithm boundaries
Fixed Top-Level Structure
The top level always has exactly three functions connected by one #pragma HLS DATAFLOW:
load_input() → compute() → store_output()
load_input()— reads from AXI master port(s), writes to stream(s) or PIPO(s)compute()— all algorithmic work; see decomposition rules belowstore_output()— reads from stream(s) or PIPO(s), writes to AXI master port(s)- Channels:
hls::streamfor sequential access, local arrays (PIPO) for random access - All
#pragma HLS INTERFACEpragmas on top-level function args only
Validate the structure. Use the hls-dataflow skill to confirm the {load_input, compute, store_output} region is canonical before proceeding. The skill checks that the top-level matches the required three-function pattern with proper DATAFLOW pragma.
Print before proceeding:
─────────────────────────────────────────────────────
[architect] Fixed Top-Level — done
Structure : load_input() → compute() → store_output()
Interface : <IFACE_TYPE — pragmas applied>
Channels : <stream or PIPO — and why>
/hls-dataflow: PASS
─────────────────────────────────────────────────────
✓ Step 1 Study domain patterns (./reference/vitis-libraries.md)
✓ Step 2a Draw activity timeline + choose paradigm
✓ Step 2b Generate fixed top-level (load → compute → store)
Step 2c Decompose compute() — hierarchical or monolithic ← NEXT
Step 2d Write to rearchitect/ + pragma audit
Step 2e G++ functional verification
Step 3a Validate with hls* skills
Step 3b Architecture review (user approval)
Step 3c Write to perf_outcomes.md
Step 3d-1 Apply performance pragmas (if throughput)
Step 3d-2 Save baseline snapshot
Step 3e Hand off to /hls-optimize
→ HANDOFF to compute() Decomposition
Produces : Top-level code (load_input + compute + store_output) with one #pragma HLS DATAFLOW
Condition: /hls-dataflow passes on the top-level region
Blocked if: /hls-dataflow fails → fix top-level structure; do NOT proceed to compute() Decomposition
compute() Decomposition
Analyze whether compute() can be internally divided into sequential sub-stages by invoking /hls-dataflow on the proposed decomposition.
If /hls-dataflow passes → Hierarchical compute:
compute():
#pragma HLS DATAFLOW
compute_stage1() → compute_stage2() → … → compute_stageN()
- Decompose into N
static void compute_stageX(...)functions, split at natural algorithmic boundaries - Add
#pragma HLS DATAFLOWinsidecompute()over {compute_stage1, …, compute_stageN} - N=1 requires no internal DATAFLOW — treat as monolithic
If /hls-dataflow fails → Monolithic compute:
compute()contains sequential loops only — no internal#pragma HLS DATAFLOW- Report the specific rule(s) flagged by
/hls-dataflow
Print before proceeding:
─────────────────────────────────────────────────────
[architect] compute() Decomposition — done
Structure : Hierarchical (<N> stages: <names>) / Monolithic (<reason>)
Bottleneck : <estimated stage> (~<N> cycles)
/hls-dataflow: PASS / FAIL (<reason if fail>)
─────────────────────────────────────────────────────
✓ Step 1 Study domain patterns (./reference/vitis-libraries.md)
✓ Step 2a Draw activity timeline + choose paradigm
✓ Step 2b Generate fixed top-level (load → compute → store)
✓ Step 2c Decompose compute() — hierarchical or monolithic
Step 2d Write to rearchitect/ + pragma audit ← NEXT
Step 2e G++ functional verification
Step 3a Validate with hls* skills
Step 3b Architecture review (user approval)
Step 3c Write to perf_outcomes.md
Step 3d-1 Apply performance pragmas (if throughput)
Step 3d-2 Save baseline snapshot
Step 3e Hand off to /hls-optimize
→ HANDOFF to Write to rearchitect/
Produces : compute() implementation — hierarchical (with internal DATAFLOW) or monolithic (reason documented);
compute() code presented to user
Condition: /hls-dataflow result recorded; compute() code is complete
Blocked if: /hls-dataflow fails on decomposition and no valid monolithic fallback → ask user before proceeding
Write to rearchitect/
Call ./reference/design-layout.md design_name=<name> stage=rearchitect_v1
This creates design_name/rearchitect/v1/src/, design_name/rearchitect/v1/tb/, a template hls_config.cfg and a template vitis-comp.json.
Write into design_name/rearchitect/v1/:
src/kernel_hls.cpp— kernel source (load_input + compute + store_output)tb/testbench.cpp— copied fromdesign_name/frame_based/testbench.cppunchanged (Input Discovery ensures this file exists)hls_config.cfg— use this exact template (substitutingXPART,CLOCK_NS,TOP_FUNCTION):
# ⚠ part= MUST be at the TOP LEVEL — never write syn.part= or put part inside [hls]
# ⚠ clock= uses ns period — never write syn.clkPeriod=
part=<XPART>
[hls]
syn.top=<TOP_FUNCTION>
clock=<CLOCK_NS>
syn.file=src/kernel_hls.cpp
tb.file=tb/testbench.cpp
For testbenches that use OpenCV, add these keys — use the exact key names:
tb.cflags=-I<OPENCV_INCLUDE>
csim.ldflags=-L<OPENCV_LIB> -lopencv_core -lopencv_imgcodecs -lopencv_imgproc -Wl,-rpath,<OPENCV_LIB>
FORBIDDEN cfg patterns — never generate these:
[hls]
syn.part=xczu9eg-... ← not a valid field; v++ ignores or rejects it
syn.clkPeriod=3.5 ← wrong field name; use clock=
vitis-comp.json— use this exact template (substitutingTOP_FUNCTIONdesign_name):
{
"name": <design_name>,
"type": "HLS",
"configuration": {
"componentType": "HLS",
"configFiles": ["./hls_config.cfg"],
"work_dir": <TOP_FUNCTION>
}
}
Present the generated code to the user.
→ HANDOFF to Pragma Rules
Produces : kernel_hls.cpp written to design_name/rearchitect/v1/src/; directories confirmed by ./reference/design-layout.md
Condition: top-level has exactly one #pragma HLS DATAFLOW over {load_input, compute, store_output};
compute() is either hierarchical (with internal DATAFLOW) or monolithic (documented reason)
Blocked if: code cannot be written (unresolvable dependency) → document reason, ask user before proceeding
Pragma Rules — Self-Audit Gate
After the code is written, scan every pragma before proceeding to validation.
Allowed in architect-generated code:
#pragma HLS performance target_ti=N
#pragma HLS INTERFACE // m_axi, axis, s_axilite
#pragma HLS DATAFLOW
#pragma HLS STREAM variable=<stream_var> depth=<N> // set FIFO depth on hls::stream channels
FORBIDDEN — must not appear:
#pragma HLS PIPELINE
#pragma HLS UNROLL
#pragma HLS ARRAY_PARTITION
#pragma HLS ARRAY_RESHAPE
#pragma HLS INLINE
#pragma HLS FLATTEN
If any forbidden pragma is found → remove it immediately before proceeding.
Print this confirmation before moving on:
Pragma audit passed — code contains only: DATAFLOW, INTERFACE, performance.
Rationale:
#pragma HLS performancegives HLS the throughput target and lets it infer micro-optimizations automatically. The architect controls macro-architecture only. Fine-grained pragmas are the responsibility of/hls-optimize.
Print before proceeding:
─────────────────────────────────────────────────────
[architect] Pragma audit — done
Pragmas present : <list all #pragma HLS lines in the file>
Forbidden found : none
─────────────────────────────────────────────────────
✓ Step 1 Study domain patterns (./reference/vitis-libraries.md)
✓ Step 2a Draw activity timeline + choose paradigm
✓ Step 2b Generate fixed top-level (load → compute → store)
✓ Step 2c Decompose compute() — hierarchical or monolithic
✓ Step 2d Write to rearchitect/ + pragma audit
Step 2e G++ functional verification ← NEXT
Step 3a Validate with hls* skills
Step 3b Architecture review (user approval)
Step 3c Write to perf_outcomes.md
Step 3d-1 Apply performance pragmas (if throughput)
Step 3d-2 Save baseline snapshot
Step 3e Hand off to /hls-optimize
→ HANDOFF to Step 2e
Produces : Pragma-clean source file; audit confirmation line printed
Condition: Zero forbidden pragmas
Blocked if: Forbidden pragma cannot be cleanly removed → ask user before deleting
Step 2e — G++ Functional Verification
─────────────────────────────────────────────────────
[architect] Step 2e — G++ Functional Verification
─────────────────────────────────────────────────────
Before invoking the hls* validation battery, prove the rearchitected code is functionally correct by compiling with g++ and running against the MATLAB golden. This catches regressions introduced by the architecture transformation (load_input/ compute/store_output split, channel insertion, hierarchical decomposition) BEFORE the expensive hls* validation cycle.
Compile
cd <design_name>/rearchitect/v1/
# ap_fixed/ap_int/ap_uint headers ship with Vitis at $XILINX_VITIS/include
g++ -std=c++14 \
-I$XILINX_VITIS/include \
-o verify_arch src/kernel_hls.cpp tb/testbench.cpp \
&& ./verify_arch
For OpenCV designs (when the testbench uses cv::imread):
g++ -std=c++14 \
-I$XILINX_VITIS/include \
-I${OPENCV_INCLUDE} \
-o verify_arch src/kernel_hls.cpp tb/testbench.cpp \
-L${OPENCV_LIB} -lopencv_core -lopencv_imgcodecs -lopencv_imgproc \
-Wl,-rpath,${OPENCV_LIB} \
&& ./verify_arch
Pass criteria
The executable must print PASS on both calls (the testbench runs the kernel
twice for II measurement). If FAIL:
- Compare against the
frame_based/verification — it passed there - Common regressions:
- channel/stream byte order swap in
load_input→store_output compute_stagedecomposition split a dependency- pragmas were stripped that the algorithm needs (e.g.,
DATAFLOW)
- channel/stream byte order swap in
- Fix
rearchitect/src/kernel_hls.cpp; do NOT proceed to Step 3a
Print before proceeding:
─────────────────────────────────────────────────────
[architect] Step 2e done — G++ functional verification
Compile : OK / FAIL (<error if any>)
Run result : PASS / FAIL (<mismatch count if FAIL>)
Status : <ok to proceed to hls* validation / blocked>
─────────────────────────────────────────────────────
✓ Step 1 Study domain patterns (./reference/vitis-libraries.md)
✓ Step 2a Draw activity timeline + choose paradigm
✓ Step 2b Generate fixed top-level (load → compute → store)
✓ Step 2c Decompose compute() — hierarchical or monolithic
✓ Step 2d Write to rearchitect/ + pragma audit
✓ Step 2e G++ functional verification
Step 3a Validate with hls* skills ← NEXT
Step 3b Architecture review (user approval)
Step 3c Write to perf_outcomes.md
Step 3d-1 Apply performance pragmas (if throughput)
Step 3d-2 Save baseline snapshot
Step 3e Hand off to /hls-optimize
→ HANDOFF to Step 3a (hls* validation)
Produces : verify_arch executable, both calls PASS
Condition: g++ compiles cleanly AND ./verify_arch prints PASS twice
Blocked if: compile error or mismatch → fix kernel_hls.cpp before Step 3a
Step 3 / 3 — Validate, Record, and Optimize
─────────────────────────────────────────────────────
[architect] Step 3 / 3 — Validate → Record → Optimize
─────────────────────────────────────────────────────
3a — Validate with hls* Skills
Use all available HLS validation tools. Run the following skills to check the rearchitected design:
hls-synthesizableskill: verify the code is synthesizablehls-dataflow-infosskill: analyze process/channel topologyhls-array-to-streamskill: identify array→stream optimization opportunitieshls-burst-inferenceskill: check AXI burst inference eligibilityhls-flattenableskill: verify loop nest can be flattenedhls-stencil-patternskill: identify stencil pattern optimization opportunitieshls-line-bufferskill: check if line buffer pattern applies
Run all of the above. Fix any violations before proceeding.
╔════════════════════════════════════════════════════════════════╗
║ HLS Validation Report — <design name> ║
╠═════════════════════╦══════════════════════════╦═══════════════╣
║ Skill ║ What it checks ║ Result ║
╠═════════════════════╬══════════════════════════╬═══════════════╣
║ hls-synthesizable ║ Synthesizable code ║ ✅ PASS ║
║ hls-dataflow-infos ║ Process/channel topology ║ ✅ PASS ║
║ hls-array-to-stream ║ Array→stream opportunity ║ ⚠️ N/A ║
║ hls-burst-inference ║ AXI burst inference ║ ❌ FAIL ║
║ hls-flattenable ║ Loop nest flattenable ║ ✅ PASS ║
║ hls-stencil-pattern ║ Stencil optimization ║ ⚠️ N/A ║
║ hls-line-buffer ║ Line buffer II=1 recipe ║ ⚠️ N/A ║
╠═════════════════════╩══════════════════════════╩═══════════════╣
║ Overall: X/7 passed Violations: <list skills that failed> ║
╚════════════════════════════════════════════════════════════════╝
Result key: ✅ PASS — ok | ❌ FAIL — fix before proceeding | ⚠️ N/A — not applicable
Reference skills for fixes:
| Violation in | Fix with |
|---|---|
hls-synthesizable | /hls-synthesizable |
hls-dataflow | /hls-dataflow |
hls-burst-inference | /hls-burst-inference |
hls-flattenable | /hls-flattenable |
hls-line-buffer | /hls-line-buffer → re-check all 8 steps |
If any ❌ FAIL → fix violation, re-run that specific skill, reprint the table; repeat until clean.
3b — Architecture Review Gate
Check $ARGUMENTS for autoconfirm=true. If present, skip the approval wait and auto-proceed.
Present the architecture summary:
─────────────────────────────────────────────────────
[architect] Architecture Review — <design_name>
─────────────────────────────────────────────────────
Top-level : load_input() → compute() → store_output()
Interface : <IFACE_TYPE>
compute() : <Hierarchical — N stages> OR <Monolithic — reason>
Bottleneck : <stage_name> (~N cycles)
Est. rate : ~X FPS @ Y MHz
hls* checks: all ✅ PASS
─────────────────────────────────────────────────────
✓ Step 1 Study domain patterns (./reference/vitis-libraries.md)
✓ Step 2a Draw activity timeline + choose paradigm
✓ Step 2b Generate fixed top-level (load → compute → store)
✓ Step 2c Decompose compute() — hierarchical or monolithic
✓ Step 2d Write to rearchitect/ + pragma audit
✓ Step 2e G++ functional verification
✓ Step 3a Validate with hls* skills
Step 3b Architecture review ← HERE
Step 3c Write to perf_outcomes.md
Step 3d-1 Apply performance pragmas (if throughput)
Step 3d-2 Save baseline snapshot
Step 3e Hand off to /hls-optimize
If autoconfirm=true is in $ARGUMENTS: print [architect] autoconfirm=true — auto-proceeding and continue immediately. Do NOT wait for input.
Otherwise: ask the user:
Does this architecture match your expectations?
- Reply yes to proceed to perf_outcomes.md and /hls-optimize
- Reply with feedback to revise the architecture
Wait for an explicit "yes" before continuing. If the user gives feedback:
- Acknowledge — summarise what will change
- Return to Step 2 (Fixed Top-Level Structure or compute() Decomposition as appropriate)
- Re-run Step 3a validation on the revised code
- Re-present this review gate
- Repeat until the user says yes
If the user gives feedback:
- Acknowledge — summarise what will change
- Return to Step 2 (Fixed Top-Level Structure or compute() Decomposition as appropriate)
- Re-run Step 3a validation on the revised code
- Re-present this review gate
- Repeat until the user says yes
→ HANDOFF to Write Architecture to perf_outcomes.md
Produces : Explicit "yes" approval from user
Condition: User has confirmed the architecture matches expectations
Blocked if: User gives revision feedback → loop back to Step 2 → Step 3a → re-present review
3c — Write Architecture to perf_outcomes.md
Write the design configuration to a repo-local memory file. Resolve the repo root first so the path works regardless of where the skill was invoked:
REPO_ROOT="$(git -C . rev-parse --show-toplevel 2>/dev/null || pwd)"
PERF_LOG="$REPO_ROOT/.claude/memory/perf_outcomes.md"
mkdir -p "$REPO_ROOT/.claude/memory"
Then:
If $PERF_LOG does not exist — create it with the full template (header, All Designs Summary table, Design section).
If $PERF_LOG exists — append a new Design section; add one row to the All Designs Summary table. Never overwrite existing content.
## Design: <name>
### Configuration
| Field | Value |
|---|---|
| Description | <one-line description of what the kernel does> |
| Part | <XPART from hls_config.cfg> |
| Clock | <CLOCK_NS> ns = <MHz> MHz |
| Target | <throughput target if given by user, else "TBD"> |
| Architecture | Hierarchical (compute internally staged) OR Monolithic (compute atomic) |
| Working dir | <path to design directory> |
| Source file | <path to kernel source file> |
| Build command | `make csynth` or `python run.py csynth` |
### Architecture
#### Stage Breakdown
| Stage | Function | Input | Output | Loop trip count | Est. cycles |
|---|---|---|---|---|---|
| 1 | load_input() | <m_axi port> | stream / PIPO | <N> | <N> |
| 2 | compute() | stream / PIPO | stream / PIPO | <N> | <N> |
| N | store_output() | stream / PIPO | <m_axi port> | <N> | <N> |
#### compute() Internal Stages (if hierarchical)
| Sub-stage | Function | Input | Output | Loop trip count | Est. cycles |
|---|---|---|---|---|---|
| 1 | compute_stage1() | stream / PIPO | stream / PIPO | <N> | <N> |
| … | compute_stage2() | … | … | … | … |
#### Bottleneck
| Bottleneck stage | Est. cycles | Est. throughput @ <MHz> MHz |
|---|---|---|
| <stage_name> | <N> cycles | ~<X> FPS / ~<Y> Msps |
### Target TI Calculation
(To be filled in by /hls-optimize Step 1b after throughput target is confirmed)
### Attempt History
| # | target_ti | Achieved TI | Achieved Rate | Outcome |
|---|---|---|---|---|
| — | — | — | — | Architecture written by /hls-architect — optimization not started |
3d-1 — Apply Performance Pragmas (if throughput target)
IF THROUGHPUT_TARGET is EMPTY: Skip to Step 3d-2
IF THROUGHPUT_TARGET is NON-EMPTY:
Call /hls-perf-pragma to:
- Calculate target_ti from throughput
- Cascade through architecture/loops
- Apply pragmas to source (Position 1: top-level, Position 2: all loops)
- Record cascade table in perf_outcomes.md
cd <design_name>/rearchitect/v1/
/hls-perf-pragma $THROUGHPUT_TARGET
hls-perf-pragma will:
- Modify src/*.cpp (add pragmas)
- Write cascade table to perf_outcomes.md
DO NOT git commit yet — commit happens after baseline snapshot.
Print:
─────────────────────────────────────────────────────
[architect] Step 3d-1 ✓ Pragmas Applied
Throughput : $THROUGHPUT_TARGET
Target TI : <value> cycles
Applied to : Top-level function + <N> loops
Recorded in : perf_outcomes.md
─────────────────────────────────────────────────────
3d-2 — Save Baseline Snapshot
Before handing off to /hls-optimize, save a clean copy of the architect-generated code:
cd <design_name>
cp -r rearchitect/v1 architect_baseline
echo "Baseline saved to architect_baseline/"
This preserves the architecture-stage output before /hls-optimize begins iterating, allowing you to:
- Compare optimize iterations against the architect baseline
- Revert to the clean architecture if optimization goes off-track
- Archive the macro-architecture separately from micro-optimizations
Print confirmation:
─────────────────────────────────────────────────────
[architect] Baseline snapshot saved
Source : <design_name>/rearchitect/v1/
Snapshot : <design_name>/architect_baseline/
Contents : src/*.cpp, tb/*.cpp, hls_config.cfg, vitis-comp.json
─────────────────────────────────────────────────────
3e — Hand Off to Optimize
─────────────────────────────────────────────────────
[architect] Handing off to /hls-optimize
─────────────────────────────────────────────────────
✓ Step 1 Study domain patterns
✓ Step 2a Draw activity timeline + choose paradigm
✓ Step 2b Generate fixed top-level (load → compute → store)
✓ Step 2c Decompose compute() — hierarchical or monolithic
✓ Step 2d Write to rearchitect/ + pragma audit
✓ Step 2e G++ functional verification
✓ Step 3a Validate with hls* skills
✓ Step 3b Architecture review (user approval)
✓ Step 3c Write to perf_outcomes.md
✓ Step 3d-1 Apply performance pragmas (if throughput)
✓ Step 3d-2 Save baseline snapshot
Step 3e Hand off to /hls-optimize ← NOW
Invoke /hls-optimize passing THROUGHPUT_TARGET parsed from $ARGUMENTS:
If THROUGHPUT_TARGET is non-empty:
/hls-optimize <THROUGHPUT_TARGET>
If THROUGHPUT_TARGET is empty — ask the user:
"What is your throughput target? (e.g. 140 FPS, 500 Msps, 1 GFLOPS)"
Wait for the response, then invoke:
/hls-optimize <user-provided target>
Note on pragma scope:
/hls-optimizemay internally use#pragma HLS PIPELINE,UNROLL,ARRAY_PARTITION, etc. — the Pragma Rules restriction above applies only to architect-generated code, not to the optimize skill.
The optimize skill runs: hls-perf-pragma → csim → csynth → iterate → cosim.
Reference
§1 — AMD UG1399 Prescription (Checklist)
"Software written for CPUs and software written for FPGAs is fundamentally different. Embrace this."
- Establish verification first — testbench with golden reference before any optimization
- Focus on macro-architecture first — model with producer-consumer paradigm
- Draw the activity timeline — identify parallelism and bottlenecks across multiple invocations
- Only code after macro-architecture is set — no premature micro-optimization
- HLS infers task-level parallelism only from function calls — concurrent blocks must be separate functions
- Decompose into small modular components — smaller components can be replicated for parallelism
- Aim for a single loop nest per function — simplifies throughput measurement
- Avoid wide channels — decompose into narrower ones
- Avoid large inlined functions — complex control paths harm tool QoR
- Size streams correctly — FIFO depth must prevent deadlock
- Use HLS reports to guide optimization — never optimize blind
You are focused on analyzing whether code follows the recommended coding style for array-to-stream conversion.
Concepts:
- Array-to-stream conversion: Converting arrays to streaming interfaces for efficient data transfer
- Stream pragma:
#pragma HLS stream variable=A type=T depth=D - Interface pragma:
#pragma HLS interface [mode=ap_fifo|axis] port=A(modeis optional; for example,mode=ap_fifoor justap_fifo) - Top function: the top-level HLS function, get it via argument
<TOP_FUNCTION>, if not provided, call/hls-component-basic-infoskill to get top_function which is the top-level function name - dataflow region: dataflow region is a function or for-loop that contains a #pragma HLS dataflow.
- Top function arguments: Parameters of the top-level function
Scope:
- Strictly follow rules 1–6; do not extend
- Must get
<TOP_FUNCTION>value which is the top-level function name (e.g.Kernel)
Analysis Steps:
1. Pragma Presence Validate that the code contains at least one of the following two array-to-stream pragmas:
- Stream pragma:
#pragma HLS stream variable=A type=T depth=D - Interface pragma:
#pragma HLS interface [mode=ap_fifo|axis] port=A(modeis optional; for example,mode=ap_fifoor justap_fifo)
2. Stream Pragma Rules (check if #pragma HLS stream variable=<VAR> [type=<T>] [depth=<D>] is used)
- 2.1 It must be a legal HLS stream pragma with the form
#pragma HLS stream variable=<VAR> [type=<T>] [depth=<D>] - 2.2
<VAR>can be:- An array (single or multi-dimensional)
- A scalar variable
- 2.3
<VAR>must be a local variable or a global variable - 2.4
<VAR>must be passed within the dataflow region - 2.5
<VAR>cannot be a top-level function argument - 2.6
type=<T>is optional:- If omitted, defaults to "fifo"
- If provided,
<T>must be "fifo"
- 2.7
depth=<D>is optional:- If omitted, uses default depth
- If provided,
<D>must be a positive integer literal or const expression that evaluates to a positive integer
3. Interface Pragma Rules (check if #pragma HLS interface [mode=ap_fifo|axis] port=A is used; mode is optional; for example, mode=ap_fifo or just ap_fifo)
- 3.1
Amust be an array (possibly multi-dimensional) or a scalar - 3.2
Amust be passed within the dataflow region - 3.3
Amust be a top function argument - 3.4
modemust be eitherap_fifooraxis
4. Struct Element Type Rules (skip if array element type is not a struct type) If the array element type is a struct type, ensure that the whole struct is prepared in a separate struct variable and then stored at once in the array.
5. Struct Copy Assignment Rules (skip if array element type is not a struct type)
If the array element type is a struct type, ensure that no custom copy assignment operator is defined (such as A& operator=(const A& a)) except mark it as default (such as A& operator=(const A& a) = default) for that struct type.
6. Stream Pragma Access Pattern Rules (check only if stream pragma #pragma HLS stream variable=A type=T depth=D is used)
Ensure that each accessed array element is read exactly once, written exactly once, and that the read/write order is consistent:
- 6.1 Ensure that each element is accessed exactly once and not more than once (no repeated access to any element)
- 6.2 Ensure that the array is accessed in the same order and range on both reading and writing sides
- 6.3 Ensure the iteration order must be the same (e.g., both ascending or both descending)
- 6.4 Each side must access the same number of elements (e.g., if write accesses N-1 elements, read must also access N-1 elements, not N)
Verdict:
If all applicable criteria are met, the code follows the recommended coding style for array-to-stream conversion. Otherwise, it does not follow the recommended coding style.
When Asked to Fix Code to Follow Array-to-Stream Style
If the user asks you to fix code so it follows the recommended array-to-stream style:
- Identify the failing rule(s)
- Apply the minimal fix while preserving behavior
- Output the complete fixed code in a fenced code block:
```cpp // fixed code here ```
You are focused on analyzing whether burst inference optimization can be applied. You only answer questions related to Burst Inference.
Concepts:
- Burst inference: Automatic optimization that combines multiple sequential memory accesses into a single burst transaction
- M-AXI interface: Memory-mapped AXI interface for accessing external memory
- Burst inference region: Each non-inlined function, the top function, or a top loop is an independent region. Code before the first top-level loop and code after any top-level loop within a function are also independent regions
- Top function: the top-level HLS function, get it via argument
<TOP_FUNCTION>, if not provided, call/hls-component-basic-infoskill to get top_function which is the top-level function name - Vivado flow: Default flow where top arguments without interface pragma are NOT M-AXI
- Vitis flow: Flow where top arguments without interface pragma ARE M-AXI by default
Scope:
- Global rules (Preconditions 1–4 and Limitations 1–2) must be checked globally, NOT per region
- Region-local rules (Preconditions 5–9 and Limitations 3–5) MUST be checked independently within each burst inference region
- Strictly follow rules 1–9 for preconditions and 1–5 for limitations; do not extend. Do NOT apply burst rules from general Vitis HLS knowledge (e.g. UG1399 "Conditional Access to Memory") that are not listed in this skill.
Analysis Steps:
1. M-AXI Interface Check (Global) Validate that the variable must be an M-AXI top argument:
- 1.1 Check if there is an interface pragma
#pragma HLS interface m_axion the variable - 1.2 If no interface pragma:
- Under Vivado flow: top arguments are NOT M-AXI (burst inference not applicable)
- Under Vitis flow: top arguments ARE M-AXI by default (burst inference may apply)
2. DATAFLOW Pragma Check (Global)
- 2.1 Only judge burst inference as disallowed if the DATAFLOW pragma appears as a direct statement within the loop block itself
- 2.2 If the DATAFLOW pragma is located within any nested block (such as an inner loop or other nested scope inside the loop), burst inference is allowed for the outer loop
- 2.3 If the DATAFLOW pragma is outside the loop, burst inference is allowed for the loop
3. Data Type Width Check (Global)
- 3.1 The width of the accessed data type must be a power of 2
- 3.2 If the accessed data type has an
alignedattribute, always use the aligned size instead of the natural size for this check - 3.3 Arbitrary precision types (
ap_int,ap_uint,ap_fixed,ap_float) are padded to the next power-of-2 width under default settings. Use the padded width (e.g.ap_int<24>→ 32 bits) for this check, so these types always PASS this check by default, regardless of their declared bit width
4. Volatile Qualifier Check (Global)
Validate that the variable must NOT have the volatile qualifier. The volatile qualifier prevents burst access.
5. Burst Length Check (Region-Local)
- 5.1 The burst length must be greater than 1 (at least 2 accesses)
- 5.2 Do NOT reject burst inference only because the burst size is small—as long as burst length is 2 or more, it is allowed
6. Memory Access Pattern Check (Region-Local) Validate that accesses must be consecutive in memory and in monotonically increasing order:
- 6.1 Accesses must be one next to another with no gaps or overlap, in forward order
- 6.2 It is allowed to access only a contiguous subset (e.g.,
out[0]toout[var-1]) as long as that subset has no skipped elements - 6.3 The start or end of the access region does not have to cover the entire array—only the accesses in a burst must be strictly contiguous
- 6.4 When checking the consecutive/non-overlapping rule, analyze the combined index ranges of ALL memory accesses to the SAME variable within the loop
- 6.5 If there is any overlap between accesses (e.g., both
a[i]anda[i+offset]might touch the same address during different iterations), burst inference CANNOT be applied, even if each individual expression is strictly increasing and contiguous
7. Burst Length/Step Determinability Check (Region-Local)
- 7.1 The number of read/write accesses (burst length) must be determinable before the request is sent out
- 7.2 Burst length/step can be computed at runtime (expression), but must be computed before the read/write request is issued
- 7.3 Do NOT require burst length/step to be a compile-time constant—dynamically provided values via function arguments or runtime variables are allowed
- 7.4 A guard inside the loop body that compares ONLY the loop induction variable against a loop-invariant value (e.g.
for (i = 0; i < N; i++) if (i < var) out[i] = in[i];) does NOT violate this check: the guarded accesses form a contiguous prefix whose lengthmin(N, var)is known before the request is issued. Burst inference CAN be applied. - 7.5 Do NOT reject burst inference merely because an access is wrapped in an
if. Only reject when the guard makes the accessed indices non-contiguous (e.g. data-dependentif (in[i] > 0), orif (i % 2 == 0)), and in that case cite Precondition 6, not 7.
8. Same Direction Access Check (Region-Local)
- 8.1 If there are same-direction accesses (all reads or all writes) on the same channel of the same bundle in the same region, burst inference will NOT apply to any of these accesses
- 8.2 If there are multiple m_axi interfaces on the same channel and same bundle, and they are all reads or all writes, burst will not happen for any of them
9. Dependency Check (Region-Local)
- 9.1 There must be no dependency issues from the time a burst request is initiated until finished
- 9.2 If there are load/store operations on the same address under the same region (e.g.,
a[i] += 5orb[i] = a[i], a[i] = c[i]), burst will NOT happen
Burst Limitations (MAY FAIL):
These conditions may cause burst inference to fail even if preconditions are met:
Limitation 1. ap_int/ap_uint Loop Induction Variables (Global)
Usage of ap_int/ap_uint types as loop induction variables may fail burst inference.
Limitation 2. Shared M-AXI Port in Dataflow (Global) If multiple tasks or functions inside a dataflow region access the same M-AXI port (same port and bundle), burst inference may FAIL—even if there is no address range overlap—because tasks might initiate parallel transactions. Burst is generally not supported on shared ports unless static analysis can prove safe sequencing.
Limitation 3. Loop Dependencies (Region-Local) Inter and intra loop dependencies on the variables may fail burst inference.
Limitation 4. Cross-Function Access (Region-Local) If memory accesses occur across function boundaries and the index is passed in as a parameter, and the subfunction containing the access is inline off, burst inference may fail; If memory accesses occur across function boundaries and the index is passed in as a parameter, and the subfunction containing the access is inline, burst inference can be applied;
Limitation 5. Potential Address Overlap (Region-Local)
If there are load/store operations on potentially the same address under the same region, burst may not happen (e.g., if reading a[i] and writing a[j], burst may fail unless i != j can be proven).
Verdict:
If all preconditions (1–9) are met and no limitations (1–5) apply, burst inference optimization can be applied. Otherwise, it cannot be applied.
When Asked to Fix Code for Burst Inference
If the user asks you to fix code so that burst inference can be applied:
- Identify the failing precondition(s)
- Apply the minimal fix to satisfy all preconditions while preserving behavior
- Output the complete fixed function(s) in a fenced code block:
```cpp // fixed code here ```
hls-component-basic-info
This skill collects Vitis HLS component basic information from an HLS component directory.
It is implemented by calling the script:
That script:
- takes exactly one argument:
<component_location> - prints a JSON object describing the content of component basic info
Inputs
component_location(string, required) — absolute path to the Vitis HLS component directory (the folder containingvitis-comp.json).- If the user specifies a component_location: use the user-specified component_location.
- If the user does not specify component_location:
- If inside Vitis Unified IDE: Call the
getActiveComponentLocationtool to get the component_location. - If outside Vitis Unified IDE: Request the user to provide component_location.
- If inside Vitis Unified IDE: Call the
Output
stdout: JSON (pretty-printed)- Top-level: a JSON object.
- The JSON object includes:
component_name(str of component name)source_files(list of source file path)testbench_files(list of testbench file path)include_paths(list of include path)top_function(str of top function)
How to invoke
Must cd into ./hls-scripts/ first.
cd ./hls-scripts
./run.sh <component_location>
hls-cosim-report
Collect Vitis HLS cosimulation artifacts from an HLS component directory and emit a single JSON object.
When to use
After cosimulation has completed, use this skill to inspect performance/resource estimates, dataflow process and channel infos for a component.
Prerequisite: the component must contain hls/.autopilot/db/process_info.csv.
Inputs
component_location(string, required) — absolute path to the Vitis HLS component directory (the folder containingvitis-comp.json).- If the user specifies a component_location: use the user-specified component_location.
- If the user does not specify component_location:
- If inside Vitis Unified IDE: Call the
getActiveComponentLocationtool to get the component_location. - If outside Vitis Unified IDE: Request the user to provide component_location.
- If inside Vitis Unified IDE: Call the
Output
stdout: JSON (pretty-printed)- Top-level: a JSON object.
- The JSON object includes:
coSimulationReportContentdataflowProcessAndChannelContent
How to invoke
Two equivalent methods — same JSON shape.
1. Inside the Vitis Unified IDE (preferred)
Call the getHLSCoSimulationInfo tool if available. It uses the currently selected project.
2. Outside Vitis Unified IDE (fallback)
Must cd into ./hls-scripts/ first.
cd ./hls-scripts
./run.sh <component_location>
Script source: run.sh
hls-dataflow-infos
This skill collects Vitis HLS dataflow information (processes + channels) from an HLS component directory.
It is implemented by calling the script:
That script:
- takes exactly one argument:
<component_location> - prints a JSON array describing all detected dataflow modules, including per-process and per-channel fields
Inputs
component_location(string, required) — absolute path to the Vitis HLS component directory (the folder containingvitis-comp.json).- If the user specifies a component_location: use the user-specified component_location.
- If the user does not specify component_location:
- If inside Vitis Unified IDE: Call the
getActiveComponentLocationtool to get the component_location. - If outside Vitis Unified IDE: Request the user to provide component_location.
- If inside Vitis Unified IDE: Call the
Output
stdout: JSON (pretty-printed)- Top-level: a JSON array; each element corresponds to one dataflow module.
How to invoke
Must cd into ./hls-scripts/ first.
cd ./hls-scripts
./run.sh <component_location>
You are focused on analyzing whether a dataflow region follows the canonical dataflow coding style. A dataflow region defines a network of processes communicating through channels. The canonical coding style results in a dataflow network that directly matches the function calls given in the source code. It is thus more predictable for the user, in terms of both performance and structure. Unlike canonical regions, non-canonical dataflow regions are transformed by Vitis HLS by grouping instructions and control so that they become canonical regions. In particular, a loop in a dataflow region is extracted as a function call.
Concepts:
- Dataflow pragma:
#pragma HLS dataflowor#pragma HLS dataflow disable_start_propagation - Dataflow region: A region that contains directly a dataflow pragma
- Function dataflow region: A function whose body is a dataflow region
- Loop dataflow region: A loop whose body is a dataflow region
- Dataflow function: A function that is either a function dataflow region or that contains only a loop dataflow region
- Dataflow function arguments: Arguments of a dataflow function
- Global variable: A variable defined outside of all functions
- Static variable: A variable declared as
staticwithin a function - Flow target:
vivado(the default) orvitis, given in the prompt or byflow_target=in the HLS configuration file. If it is not specified, assumevivado - m_axi type: An array or pointer argument of the top function (possibly passed as an argument to subfunctions) that accesses external memory through the m_axi protocol. This is the case when the argument is marked by
#pragma HLS interface m_axior, by default, whensyn.interface.default_axiis true (which is the case if the flow target isvitis), unless a#pragma HLS interfaceselects another protocol (e.g.,ap_memory,bram) - Top function: The top-level HLS function, get it via argument
<TOP_FUNCTION>, if not provided, call/hls-component-basic-infoskill to get top_function which is the top-level function name - Top dataflow function: The top function if it is a dataflow function
- Overlapping dataflow region: A dataflow region that is a top dataflow function, or the body of a loop dataflow region, or a function dataflow region called directly as a process of an overlapping dataflow region. An intermediate non-dataflow region is a sequential region and thus prevents overlapping
- Read process: A process (function/task/block) that reads a variable's value
- Write process: A process (function/task/block) that writes a variable's value
- Read/write process: A process that both reads and writes the same variable
- Class instance rule: If the dataflow region is defined within a non-static class method, treat
this(and its member variables) as dataflow function arguments
Scope:
- Strictly follow rules 1–10; each rule should only be checked within that specific rule—do not extend
- Follow the literal text of each rule strictly; do not extend rules based on general design principles
- For loop dataflow regions, analyze only a single iteration
Analysis Steps:
1. Pragma Presence
Validate that the code must contain #pragma HLS dataflow or #pragma HLS dataflow disable_start_propagation.
2. Pragma Location Validate that the dataflow pragma is in a loop body or function body.
3. Loop Dataflow Region Rules (skip if pragma is not inside a loop body)
- 3.1 The loop must be a
for-loop. - 3.2 The parent function of the for-loop contains only this for-loop and no other code except local variable declarations and pragma statements.
- 3.3 The loop counter is declared in the loop header and is of
inttype. - 3.4 The iterator must be initialized to a non-negative integer constant in the loop header.
- 3.5 The loop bounds must be a non-negative integer constant or a scalar argument of the function.
- 3.6 The step of the iterator must be a positive integer constant.
- 3.7 The loop must have no early exit such as return, continue, break.
4. Dataflow Region Content Rules (check line-by-line)
- 4.1 The dataflow region must not contain any statements other than:
- Pragma statements
- Local variable declarations (of any kind, including class objects instantiations), which become dataflow channels
- Function call statements (including
hls::taskinstantiations and class method calls), which become dataflow processes - Assignment of a local scalar variable from the return of a function is allowed.
- 4.2 If
hls::taskis present, it must be declared ashls_thread_local:hls_thread_local hls::task t1(proc, arg1, arg2, arg3); - 4.3 If
hls::taskis present,hls::streamandhls::stream_of_blockswithin it must be declared ashls_thread_local. - 4.4 All local variables within the dataflow region must be declared as non-static.
- 4.5 Local variables with initializing default constructors (e.g.,
std::complex) lead to implicit write processes. To avoid this, use theno_ctorattribute:std::complex<float> arr[SIZE] __attribute__((no_ctor)); - 4.6 Function calls must not pass array element values (e.g.,
arg_mem[offset_var],mem[i],array[index]) as arguments. Only pass the entire array/pointer variable itself. - 4.7 Function calls must not perform arithmetic or logical operations on arguments at the call site (e.g., use
i, noti + 1; useptr, notptr + offset). - 4.8 List all function parameters and explicitly verify type compatibility between function parameters and arguments. No type conversion is allowed during function calls, except value-to-reference conversions.
5. Multiple Invocation Rules If a function is invoked multiple times within a dataflow region, ensure static variables follow these rules:
- 5.1 If the function is invoked by a loop within the dataflow region:
- 5.1.a If the same function is called in each iteration (repeatedly across all iterations), skip rules 5, 5.1, 5.2.
- 5.1.b If the function is called multiple times within a single iteration, ensure no static variables within that function are accessed.
- 5.2 If the function is invoked multiple times by a non-loop within the dataflow region, ensure no static variables within that function are accessed.
6. Dataflow Function Argument Rules List dataflow function arguments before checking. If arguments are accessed within a loop, analyze only a single iteration.
- 6.1 If the argument is of type
hls::stream, ensure it is accessed (read or written) by only one dataflow process. - 6.2 If the argument is an array of m_axi type, it may be read by at most one process and written by at most one process (a process that both reads and writes it counts as both a reader and a writer). The access pattern must be one of:
- a single process accesses it (reading, writing, or both)
- one process only reads it and a different process only writes it, and the writing process appears textually after the reading process
- 6.3 If the argument is an array and not of m_axi type, ensure:
- If written, it is accessed (read or written) by only one process
- If read-only, it is read by at most two processes
- 6.4 Scalar carried over successive invocations of an overlapping region between two different processes: if a scalar argument (passed by address or reference) of an OVERLAPPING dataflow region is read in a process P that appears textually before a different process Q that writes it, ensure that this scalar is always written in the region before it is read. When applying this rule, consider that a conditional write corresponds to a read followed by a write (in the same process). This rule is thus not triggered when no such pair (P, Q) exists, or if the same single process performs both the read and the write of the scalar, or if the dataflow region is not an overlapping dataflow region. The reason for this rule is that a flow "loop-carried" dependence within dataflow is supported only within a single process. 6.5 A dataflow function must not have a return value: outputs must be passed as arguments. The rule does not apply for a top dataflow function.
7. Dataflow Function Global/Static Scalar Rule Ensure all scalar-type global/static variables accessed within an overlapping dataflow region follow the rule 6.4 (substituting scalar argument by global/static scalar variable).
8. Top Dataflow Function Scalar Argument Rules
If <TOP_FUNCTION> function is a top dataflow function, and a scalar argument of the top function is used in a dataflow region, recursively included in dataflow regions up to the top, ensure that if written, it is accessed (read or written) by only one process.
9. Global/Static Array Rule If an array-type global/static variable is accessed within the dataflow region, validate that no more than one dataflow process reads or writes the global/static array in the dataflow region.
10. Local Variable Rules Validate local variables within the dataflow region. For loop dataflow regions, analyze a single iteration only. Ignore local variables that are unused (pragmas are not considered uses either).
- 10.1 Any local variable within a dataflow region must be a scalar, an array,
hls::stream,hls::stream_of_blocks, or a class containing any of these types. A class object is not checked as a whole: each of its members is checked according to its own type. A reference member is checked as the variable it refers to. - 10.2 If a local array is marked with
#pragma HLS bind_storage variable=... type=ram_1wnr, validate exactly one writer process and one or more reader processes, with the writer appearing lexically before all readers. - 10.3 If a local array is not marked with
#pragma HLS bind_storage variable=... type=ram_1wnr, validate exactly one writer process and one reader process (a process that both reads and writes it only counts as a writer), with the writer appearing lexically before the reader. - 10.4 If a local variable is of
hls::streamtype, validate exactly one writer process and one reader process. - 10.5 If a local variable is of
hls::stream_of_blockstype, validate:- a. It is declared as:
#include "hls_streamofblocks.h" ... hls::stream_of_blocks<block_type, depth> block; // or hls::stream_of_blocks<block_type> block; - b. Exactly one write process, and it is using
hls::write_lock lock(block)in the region that writes - c. Exactly one read process, and it is using
hls::read_lock lock(block)in the region that reads
- a. It is declared as:
- 10.6 If a local variable is a scalar, there are no writer/reader limits.
Verdict:
If all criteria are met, the code forms a canonical dataflow region. Otherwise, it is not canonical.
Agent Skill: HLS Flattenable Loop Nest Analysis
Modes
- Analyze (default): the user asks whether a loop nest is flattenable, or HLS reports it was not flattened (
HLS 200-957,200-1991,200-1992). Apply the rules and report in the Output Format. - Make flattenable: the user wants a non-flattenable nest rewritten so it flattens. Do the analysis, then follow Making a Nest Flattenable.
Strictly follow the rules below. Do not infer, assume, or add criteria beyond these rules.
Definitions
- Remaining loop: a
for,while, ordo-whileloop that is still a loop after HLS unrolling. A loop is not a remaining loop (it becomes straight-line code) if either:- (a) it has
#pragma HLS UNROLLwith nofactor=and nooff=true, and its trip count is a compile-time constant; or - (b) it is reached from inside the innermost loop body of the nest (Rule 7 only), its trip count is a compile-time constant, and it has no
#pragma HLS UNROLL factor=.../off=trueand no#pragma HLS PIPELINE off. HLS auto-pipelines the innermost loop, and pipelining implies full unroll of loops inside it (HLS 214-291 ... complete unroll implied by the pipeline pragma). This assumes default settings: if automatic loop pipelining is disabled for the design (syn.compile.pipeline_loops=0), apply (a) only.
- (a) it has
- Any loop whose trip count is not a compile-time constant (it depends on a function argument, a runtime variable, or data) is always a remaining loop.
- Loop counter (also called induction variable): the variable declared or initialized in the
forheader and updated in its increment expression, e.g.kinfor (int k = 0; k < N; k++). It is not any other variable that happens to change on every iteration, such as an accumulator or a pointer advanced in the body. - Compile-time constant: a literal,
#define,const/constexprvalue, template parameter, or an expression built only from these.
Rules
Rule 1 — Identify All Nested Loops
- Scan the code for all nested loop constructs.
- 1.1 Reject if any loop is a
do-whileloop. → Not flattenable. - 1.2 Every loop must be a
forloop. → If any loop iswhile, not flattenable. - 1.3 The loop step (increment/decrement expression) must not be a runtime variable. Constants and compile-time expressions are allowed. → If the step is a variable, not flattenable.
- 1.4 No loop's loop counter (the variable in its
forheader, e.g.kinfor (int k = 0; k < N; k++)) may be written inside the loop body. Theforheader's own increment does not count. Writes includek--,k++,k += n,k = ..., and passingkby non-const reference or pointer. Writing the counter in the body makes the trip count data-dependent, even if theforheader looks constant. Writes to other variables, such as accumulators, are allowed. → If any loop counter is written in a body, not flattenable.- Typical trap, the "retry on empty" idiom:
if (s.empty()) { k--; } else { ... s.read() ... }
- Typical trap, the "retry on empty" idiom:
Rule 2 — No control flow between outer and inner loops
- If there is intervening control-flow structure (another block, conditional, etc.) between the outer loop body and the inner loops, → Not flattenable.
Rule 3 — No Control Flow Before Inner Loop
- In the region after the outer loop's opening brace and before the inner loop, the following statements are prohibited:
if,switch,break,continue,goto
- If any of these appear, → Not flattenable.
Rule 4 — Inner Loop Bounds Independence
- The inner loop's start, end, and step expressions must not depend on the outer loop's loop counter.
- If any bound references the outer loop variable, → Not flattenable.
Rule 5 — Function Calls Before Inner Loop Are Allowed (With Constraint)
- Function calls are permitted in the region before the inner loop.
- 5.1 If the function's definition is visible, inspect it, including functions it calls: it must not contain any remaining loop. Only definition (a) applies here, because this region is not pipelined. If it does, → Not flattenable.
- If the definition is not available, assume it is acceptable (do not reject).
Rule 6 — Innermost Loop Body: Conditionals Allowed (With Exceptions)
- Inside the innermost loop body, conditional statements (
if,switch, ternary) are allowed. - However,
breakandgotoinside the innermost loop are prohibited. → If found, Not flattenable.
Rule 7 — Innermost Loop Body: Function Calls Allowed (With Constraint)
- Function calls inside the innermost loop body are allowed.
- If the function's definition is visible, inspect it, including functions it calls: it must not contain any remaining loop. Definitions (a) and (b) both apply. If it does, → Not flattenable.
- Loops written directly in the innermost body are judged the same way. A non-remaining loop there is fine; a remaining loop there means the "innermost" loop is not really innermost.
- If the definition is not available, assume it is acceptable.
Rule 8 — No Control Flow After Inner Loop
- In the region after the inner loop and before the outer loop's closing brace, the following statements are prohibited:
if,switch,break,continue,goto
- If any of these appear, → Not flattenable.
Rule 9 — Function Calls After Inner Loop Are Allowed (With Constraint)
- Function calls are permitted in the region after the inner loop.
- 9.1 If the function's definition is visible, inspect it, including functions it calls: it must not contain any remaining loop. Only definition (a) applies here. If it does, → Not flattenable.
- If the definition is not available, assume it is acceptable.
Output Format
Respond with a structured analysis in this exact format:
### Flattenable Loop Nest Analysis
**Loop Structure Identified:**
- <list each loop with its line number, type, and nesting level>
**Rule-by-Rule Evaluation:**
| Rule | Description | Result |
| ---- | -------------------------------------------------------- | -------------------- |
| 1 | All `for`, constant step, no counter writes in body | PASS / FAIL (reason) |
| 2 | Direct nesting | PASS / FAIL (reason) |
| 3 | No control flow before inner loop | PASS / FAIL (reason) |
| 4 | Inner bounds independent of outer var | PASS / FAIL (reason) |
| 5 | Calls before inner loop (no remaining loops inside) | PASS / FAIL / N/A |
| 6 | Innermost body: conditionals OK, no break/goto | PASS / FAIL (reason) |
| 7 | Innermost body: calls/loops (no remaining loops) | PASS / FAIL / N/A |
| 8 | No control flow after inner loop | PASS / FAIL (reason) |
| 9 | Calls after inner loop (no remaining loops inside) | PASS / FAIL / N/A |
**Verdict:** ✅ Flattenable / ❌ Not Flattenable
**Reason (if not flattenable):** <first failing rule and explanation>
Making a Nest Flattenable
Use this section when the user asks to fix, make flattenable, convert, restructure, or rewrite a loop nest so that HLS can flatten it:
-
Run the analysis above and list every failing rule, not just the first.
-
Apply the minimal fix for each failing rule while preserving behavior. After each fix, re-check all rules, because a fix can introduce a new violation (e.g. code moved into the innermost body must not add a
break). Recommended fixes:Failing rule Fix 1.4 retry-on-empty ( if (s.empty()) k--; else { x = s.read(); ... })Preferred: drop the empty()test and use a blockings.read(). Inside a pipelined loop a blocking read stalls the pipeline until data arrives, which is the same behavior. Keep the non-blocking form only if the loop must do other work while the stream is empty; in that case use the manual flatten below.1.4 (other counter writes), or any rule where the outer loop must stay data-driven Manual flatten: replace the nest with one for (int it = 0; it < OUTER*INNER; it++)loop and derive the old indices (i = it / INNER; j = it % INNER, or shift/mask whenINNERis a power of two). A single loop needs no flattening, so a counter write such asit--is then acceptable. Note that the result is a single loop, not a "flattenable nest".5 / 7 / 9: callee loop with a constant trip count Add #pragma HLS UNROLL(no factor) to that loop, if the area of full unrolling is acceptable.5 / 7 / 9: callee loop with a variable trip count Rewrite with a constant maximum bound and a guard ( for (t = 0; t < MAX; t++) { if (t < n) ... }) and fully unroll it, or hoist the loop out of the nest.3 / 8: control flow in the outer body Move it into the innermost body as a condition on the inner index (e.g. if (j == 0) .../if (j == INNER-1) ...).4: inner bound depends on outer index Use the constant maximum bound and guard the body with if (j < bound(i)).1.1 / 1.2: while/do-whileloopRewrite as for (int t = 0; t < MAX; t++)with a compile-timeMAXequal to the worst-case trip count, and guard the body with the original condition.1.3: variable step Iterate with step 1 over the constant maximum range and guard the body, e.g. if (j % step == 0), or precompute the index asj * stepwith a guarded bound.2: block or conditional wrapping the inner loop Remove the wrapper. Move a condition into the innermost body as a guard (see 3 / 8). 6: break/gotoin the innermost bodyReplace with a doneflag set instead ofbreak, and guard the rest of the body withif (!done). Reset the flag where the inner loop used to start (if (j == 0) done = false;). -
Re-run the full rule table on the rewritten code; every rule must PASS (or N/A) before you report success.
-
Output a short list of changes, one per failing rule (rule number → what you changed and why it preserves behavior), then the complete fixed function (not just the changed lines) in a fenced code block:
```cpp // fixed code here ``` -
Then output the machine-readable verdict marker:
FLATTENABLE_VERDICT: FIXED_FLATTENABLEor if you cannot fix it:
FLATTENABLE_VERDICT: COULD_NOT_FIX
Confirm with synthesis when possible. A successful flatten logs
INFO: [HLS 200-2259] Flattening a loop nest with inner loop '<inner>' and outer loop '<outer>' ... successfully.
and the csynth loop table shows one merged loop named <outer>_<inner>. If neither appears, the nest was not flattened.
Behavioral Constraints
- Do not add extra rules or heuristics beyond the rules and definitions above.
- Do not speculate about optimization intent or suggest code changes unless the user asked to fix, convert, or make the nest flattenable (see Making a Nest Flattenable).
- Evaluate rules in order (1 → 9) and stop at the first failure for the verdict reason, but still report all rules in the table.
- When multiple loop nests exist, analyze each nest independently.
- For loop nests deeper than 2 levels, apply Rules 2–9 to every adjacent pair of outer/inner loops in the nest hierarchy, and apply Rule 1 to every loop.
hls-ii-diagnose
Diagnose why a pipelined loop or function did not reach its target II, classify the bottleneck into a known category, and cite the evidence. This skill produces a diagnosis only — the calling agent (e.g. hls-optimize) decides whether and how to fix it.
Why this skill exists
An II violation can stem from several distinct root causes that need completely different fixes, and the csynth summary table does not distinguish them — its violation labels are coarse (e.g. "Memory Dependency" is reported for recurrences that have nothing to do with memory ports), so agents reading only the summary often misdiagnose. Sweeping #pragma HLS PIPELINE II=<N> is also not a substitute for diagnosis: it works only when the fix happens to be an II target, can hurt timing, and never finds a structural fix (inline a callee, disable a shared mux). This skill forces a real diagnosis first.
When to use
Use after C synthesis (csynth) has completed, when a pipelined loop or function has an achieved II greater than 1 — either II achieved > II target when a target is set, or II achieved > 1 with no target set.
Out of scope: choosing/applying the fix (that is the caller's decision), running any flow, and designs whose II already meets target.
Inputs
component_location(string, required) — absolute path to the Vitis HLS component directory (the folder containingvitis-comp.json).- If the user does not specify it and you are inside the Vitis Unified IDE, call
getActiveComponentLocation. Otherwise ask the user.
- If the user does not specify it and you are inside the Vitis Unified IDE, call
target_label(string, optional) — a specific loop or function to focus on. If omitted, diagnose the loop/function with the worstII achieved / II targetratio.
Prerequisite
The component must already be synthesized. This skill does not run flows. If the synthesis reports/log are missing or stale, ask the caller to run hls-run-flow first.
Workflow
Step 1 — Get the synthesis report and log
Invoke the hls-synth-report skill on component_location to obtain synthesisReportContent, synthesisPragmaReportContent, and synthesisLogContent. Use the report to find the loop/function with the worst II ratio if no target_label was given.
Step 2 — Extract the pipelining block(s)
Do not rely on the summary tables. The real evidence is in the per-loop/function block delimited by Pipelining loop ... / Pipelining function ... and Pipelining result ... in the synthesis log. These blocks contain the carried-dependence warning (HLS 200-880), scheduler notes, and resource-limit messages.
Use the raw logs/hls_compile.log, not the filtered log. The Pipelining loop ... / Pipelining result ... markers are INFO: lines, and the hls-synth-report skill filters INFO: lines out of synthesisLogContent — so they are missing from the filtered content. Read the component's raw log at <component_location>/logs/hls_compile.log.
Pull the block for each loop/function with awk over the markers:
LOG=<component_location>/logs/hls_compile.log
# all pipelining blocks (each ends with its "Pipelining result" line showing Target/Final II):
awk '/Pipelining (loop|function)/{f=1} f; /Pipelining result/{f=0}' "$LOG"
# jump straight to the result lines to spot violations (Final II > Target II, or > 1 with no target):
grep -E "Pipelining result" "$LOG"
# then read the full block for the violating target by name:
awk "/Pipelining (loop|function) '<target_label>'/{f=1} f; /Pipelining result/{f=0}" "$LOG"
Read the full block — not just the result line. Note the carried variable name and type (scalar vs array element), the distance/offset, the producer/consumer line numbers (HLS 200-880), and any timing (HLS 200-887) or resource-limit messages.
Step 2b — Confirm the long-latency element in the schedule report
When the violation is a carried dependence (a recurrence across iterations), the log's HLS 200-880 line names the carried variable and the producer/consumer ops, but it does not always reveal which operation on the path carries the latency (e.g. it may name only a store/load of the carried scalar, while the real cost is a non-inlined call between them). Do not infer this from source alone — confirm it in the authoritative schedule report:
<component_location>/hls/.autopilot/db/<module>.verbose.sched.rpt
where <module> is the violating loop/function's module name from the HLS 200-880 message (e.g. test_Pipeline_encryption_cfb8_loop). Each line shows an operation, the schedule stages it spans ([20/20]…[1/20] = a 20-stage operation), and its delay, e.g.:
ST_3 : Operation 72 [20/20] (1.18ns) ---> "%output_block = call i8 @process, ..." [cfb.hpp:442] ---> 'call' ...
Trace the recurrence on the carried variable through the stages: the operation that spans the most stages (or whose delay dominates) between the carried store and its next-iteration load is the long-latency element — and tells you directly whether it is a call (→ inline), a memory load/store (→ lower memory latency), or a long arithmetic chain (→ restructure). Cite the specific ST_n … Operation … (delay) lines as evidence.
Step 3 — Classify the bottleneck
First decide whether the limiter is a carried dependence (a recurrence across iterations) or a resource shortage (a single-iteration access that exceeds available resources). Then pick the specific category:
Pre-check
- (a) No II target — no
II=<N>was specified. Without a target, timing constraints take priority over most II-related constraints, so HLS may relax II to whatever satisfies timing. You are encouraged to verify this is actually the cause — e.g. some operations on the recurrence path were given longer latency to satisfy timing — before classifying as (a). The natural check is whether re-synthesizing with an explicit II target would close the gap (but that is the caller's action, not this skill's).
Carried-dependence bottlenecks
-
(b) Long latency on the recurrence path — the recurrence carries a dependence whose round-trip latency the scheduler cannot fit into the target II, so II grows to cover it. The general task is to find which element on the path is long and why the scheduler cannot shorten it. Common sources (not exhaustive):
- a non-inlined function call, treated as a black-box latency the scheduler cannot retime across;
- a memory load/store whose access latency sits on the path;
- a registered shared-resource mux inserted by resource sharing;
- a long combinational chain that the scheduler lengthened to satisfy timing (overlaps with (a) when no II target was set).
Identify the specific source using the schedule report (Step 2b) — the carried variable, the operations on the path (
load/store/call/add/…), and their per-operation latencies — because the fix direction depends on it (inline the callee, lower the memory latency, disable sharing, or restructure to shorten the chain).
Resource-shortage bottlenecks
- (c) Memory port shortage — within a single iteration, the unrolled accesses to a memory exceed its available ports. This is not a cross-iteration dependence; it surfaces as a different class of violation in the log.
Categories are not mutually exclusive — report every cause the evidence supports. Two situations call for reporting more than one:
- Co-occurring causes. A single violation can have more than one real cause at once. The most common pair is (a) + (b): no II target was set and the recurrence carries a long-latency element. Here both are true and both matter — without a target the scheduler never tries to shorten the path, and even with a target the path latency still caps the achievable II. Report both, and make the relationship explicit (e.g. "(b) is the physical limiter; (a) is why the scheduler accepted the relaxed II"). The
next_stepshould then cover both levers (set an II target and shorten the path). - Genuine ambiguity. If the evidence cannot distinguish between two plausible categories, report both with their supporting evidence rather than guessing.
Step 4 — Locate the source
Identify the source location of the bottleneck: the carried variable, the callee, or the memory access, depending on the category. Use the line numbers from the HLS 200-880 message and the source files reported by hls-component-basic-info if needed.
Step 5 — Cite the evidence
For every claim in the diagnosis, point at the supporting artifact: synthesis-log line(s) (the HLS 200-880/HLS 200-887 text and the Pipelining result line), the verbose.sched.rpt ST_n … Operation … (delay) line(s) that identify the long-latency element (Step 2b), and source line(s). The caller must be able to verify the diagnosis independently. For a category (b) classification, the schedule-report citation is what distinguishes a grounded diagnosis from a guess — prefer it over inferring the long-latency element from source.
Output
Emit a structured diagnosis:
target_label— the loop or function being diagnosedachieved_ii/target_iicategory— one or more of (a)–(c) above (report all that the evidence supports; see Step 3); for (b), name the specific long-latency source on the pathevidence— log line numbers, source line numbers, schedule excerptsnext_step— high-level recommendation (e.g. "specify II target", "inline callee", "lower memory latency", "increase memory ports", "restructure to break recurrence"). Pragma or directive names (e.g.inline,bind_storage) may appear only when paired with the mechanism they address. The caller makes the final decision on whether and how to apply them.
Constraints
This skill MUST NOT:
- Modify source files.
- Run csim / csynth / cosim / impl flows. (Use
hls-run-flowfor that.) - Recommend a fix without naming the underlying mechanism.
hls-impl-report
Collect Vitis HLS C implementation artifacts from an HLS component directory and emit a single JSON object.
When to use
After run impl (impl) has completed, use this skill to inspect post-route timing, resource utilization, and implementation logs
Prerequisite: the component must contain hls/impl/report/verilog|vhdl/export_impl.rpt
Inputs
component_location(string, required) — absolute path to the Vitis HLS component directory (the folder containingvitis-comp.json).- If the user specifies a component_location: use the user-specified component_location.
- If the user does not specify component_location:
- If inside Vitis Unified IDE: Call the
getActiveComponentLocationtool to get the component_location. - If outside Vitis Unified IDE: Request the user to provide component_location.
- If inside Vitis Unified IDE: Call the
Output
JSON object printed to stdout with three string fields:
{
"postRoute": "...", // export_impl.rpt, Place & Route Timing Summary->Post-Route value
"placeRouteResourceSummary": "...", // Place & Route Resource Summary-> LUT,FF,DSP,BRAM,URAM,SRL
"placeRouteFailFast": "..." // Place & Route Fail Fast LUT FD DSP percentage
}
How to invoke
Two equivalent methods — same JSON shape.
1. Inside the Vitis Unified IDE (preferred)
Call the getHLSImplementationInfo tool if available. It uses the currently selected project.
2. Outside Vitis Unified IDE (fallback)
Must cd into ./hls-scripts/ first.
cd ./hls-scripts
./run.sh <component_location>
Script source: run.sh
HLS Line Buffer
The LLM can generate a line buffer and window buffer structure on its own. This guide fills the gap on what it consistently gets wrong.
Before generating code, understand the flow below, then produce code that matches it.
Constants (derive before writing code):
KRAD = KSIZE / 2— kernel radius (e.g. KSIZE=15 -> KRAD=7)NLB = KSIZE - 1— number of line buffer rowsWARMUP = KRAD * COLS + KRAD— iterations before first valid output pixelTOTAL_ITER = ROWS * COLS + WARMUP— total loop iterations
1 — Run for TOTAL_ITER, not ROWS x COLS
After the last image pixel, the line buffer still holds KRAD rows of real data that have never been centered in the window. Without extra iterations those rows are never output.
Fix: run the compute loop for TOTAL_ITER iterations. Read the actual pixel from the stream when n < ROWS * COLS, otherwise use zero — all in one loop:
U8 pixel = (n < num_pixels) ? pixel_stream.read() : 0;
The zeros flush the last rows through so every pixel gets centered and output. Use one loop — not two separate loops (two loops add an FSM transition and cost ~16 cycles).
2 — Verify the LLM applied step 1 correctly
Check these before running csim/cosim:
TOTAL_ITER = ROWS * COLS + WARMUP— not justROWS * COLSWARMUP = KRAD * COLS + KRAD— uses the same COLS as col_ptr wrapping (if col_ptr wraps at COLS_POW2, WARMUP must also use COLS_POW2)- Zero tail is inline in the loop (
n < num_pixelsternary), not a second loop - Output is gated on
n >= WARMUP— no output written during warmup
MATLAB to C++ Conversion
Convert MATLAB sample-based algorithms into frame-based plain C++ that compiles with g++, then hand off to /hls-architect for multi-stage HLS dataflow architecture.
Preamble — Verify Tooling + Capture Required Parameters
Step 0 — Run ./reference/setup.md in tooling-only mode
All required tooling (Vitis HLS, MATLAB, OpenCV) is verified by the ./reference/setup.md skill.
At this point in the flow there is no design directory yet, so call ./reference/setup.md with
mode=tooling-only — design discovery and build commands (Steps 2 & 3 of ./reference/setup.md)
are skipped.
./reference/setup.md mode=tooling-only
The ./reference/setup.md skill will:
- Source Vitis (and export
$XILINX_VITIS) — Step 1 - Detect & verify OpenCV install if the testbench will use
cv::imread— Step 4 - Locate MATLAB and export
$MATLAB_BIN— Step 5
If ./reference/setup.md cannot resolve a tool (e.g. MATLAB not on PATH, OpenCV lib path missing),
it prompts the user with AskUserQuestion. Do not proceed until ./reference/setup.md reports
all three checks passed (or marked N/A).
After ./reference/setup.md returns, the following env vars are guaranteed to be set:
| Env var | Set by | Used by |
|---|---|---|
$XILINX_VITIS | ./reference/setup.md Step 1 | g++ compile commands in Step 2 & Step 4 |
$OPENCV_INCLUDE | ./reference/setup.md Step 4 | g++ -I flag for testbench compile |
$OPENCV_LIB | ./reference/setup.md Step 4 | g++ -L flag for testbench compile |
$MATLAB_BIN | ./reference/setup.md Step 5 | Step 0 — running the user's .m files |
Downstream skills (/hls-architect, /hls-optimize, /csim, /csynth, /cosim) inherit
this environment — never re-verify or re-source.
Capture pipeline parameters
Parse parameters from $ARGUMENTS:
Expected format:
/matlab-to-cpp <file.m> [part=<fpga-part>] [clock=<ns>] [throughput=<target>]
Examples:
/matlab-to-cpp rgbEdgeDetector.m part=xczu9eg-ffvb1156-2-e clock=3.3 throughput=4400fps
/matlab-to-cpp demosaic.m part=xczu9eg-ffvb1156-2-e clock=3.5
/matlab-to-cpp filter.m
Parse logic:
- Extract MATLAB file path (first non-key=value argument)
- Extract
part=...→ store asXPART - Extract
clock=...→ store asCLOCK_NS - Extract
throughput=...→ store asTHROUGHPUT_TARGET
No silent defaults. If any of <matlab-file>, part=, clock=, or throughput= is missing from $ARGUMENTS, prompt the user with AskUserQuestion:
| Missing arg | Question header | Question text |
|---|---|---|
| matlab file | "MATLAB script" | "Which MATLAB script should I convert? (path to .m file)" |
part= | "FPGA part" | "FPGA part to target? (e.g. xczu9eg-ffvb1156-2-e)" |
clock= | "Clock period" | "Clock period in ns? (e.g. 3.3 for ~303 MHz)" |
throughput= | "Throughput" | "Throughput target? (e.g. 4400 FPS, 500 Msps, 1 GFLOPS)" |
Why no defaults: silent defaults (xczu9eg, 3.5 ns) used to mask user typos and propagate the wrong values into /hls-architect and /hls-optimize. The prompt forces an explicit choice and surfaces parsing failures immediately.
After all four are resolved, print confirmation:
─────────────────────────────────────────────────────
[matlab-to-cpp] Pipeline parameters
Source : <matlab-file>
Part : <XPART>
Clock : <CLOCK_NS> ns (≈ <MHz> MHz)
Throughput : <THROUGHPUT_TARGET>
─────────────────────────────────────────────────────
Flow Overview
Print this at the very start so the user can track progress throughout:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
[matlab-to-cpp] Pipeline — <design_name>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Step 0 Run MATLAB simulation → save golden I/O
Step 0b Range instrumentation → sim-measured types
Step 1 Analyze MATLAB algorithm
Step 2 Generate refactor_1 (plain C++) + verify
Step 3 Generate refactor_2 (frame-based C++)
Step 4 Hand off to /hls-architect → /hls-optimize
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Re-print this overview after each step completes with a ✓ next to the completed step so the user always knows where the flow is.
Design Workspace
Before running Step 0, derive design_name from the MATLAB script filename (snake_case, no .m extension).
Call ./reference/design-layout.md to orient the workspace:
./reference/design-layout.md design_name=<name> stage=show
This prints the full expected directory tree without creating anything. Confirm the tree with the user, then proceed — each step calls ./reference/design-layout.md to create its directory before writing files.
Step 0 / 4 — Run MATLAB Simulation (Golden Reference)
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 0 / 4 — Run MATLAB Simulation (Golden Reference)
─────────────────────────────────────────────────────
Before converting anything, run the MATLAB simulation to capture golden inputs and outputs. These are used in Step 2 to verify the generated C++.
Launch MATLAB CLI
Use $MATLAB_BIN — exported by ./reference/setup.md Step 5. Do NOT hardcode a path here; that breaks for any user other than the one whose path was baked in.
"$MATLAB_BIN" -nodisplay -nodesktop
If $MATLAB_BIN is empty at this point, ./reference/setup.md mode=tooling-only was not run (or it failed) — go back and re-run it before continuing.
Run the Simulation
Once the MATLAB CLI is open, run the *_runme.m script in the design directory:
>> run('path/to/design_runme.m')
Important:
- Run only the simulation section — do not run any MtoHDL Coder or code generation sections
- If the runme script contains both, stop before the HDL/HLS coder calls
Save Inputs and Outputs
Save both the input data (stimulus) and output data (golden reference) so the C++ testbench can use the same files:
% Save input
fid = fopen('matlab_input.bin', 'wb');
fwrite(fid, input_array, 'uint8'); % match the actual data type
fclose(fid);
% Save golden output
fid = fopen('matlab_golden.bin', 'wb');
fwrite(fid, output_array, 'uint8');
fclose(fid);
Keep note of: output dimensions, data type, and border pixels that are undefined (e.g., warmup edges for filter kernels).
Write to golden/
Call ./reference/design-layout.md design_name=<name> stage=golden
Then copy into design_name/golden/:
- All MATLAB source files (
*.m) from the input design path matlab_input.bin— saved stimulusmatlab_golden.bin— saved golden reference output
Print before proceeding:
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 0 done — MATLAB Simulation
Input saved : golden/matlab_input.bin (<N> bytes, <dtype>)
Output saved : golden/matlab_golden.bin (<N> bytes, <dtype>)
Dimensions : <ROWS × COLS or signal length>
Border/warmup: <KSIZE/2 rows+cols invalid / N/A>
─────────────────────────────────────────────────────
✓ Step 0 Run MATLAB simulation → save golden I/O
Step 0b Range instrumentation → sim-measured types ← NEXT
Step 1 Analyze MATLAB algorithm
Step 2 Generate refactor_1 (plain C++) + verify
Step 3 Generate refactor_2 (frame-based C++)
Step 4 Hand off to /hls-architect → /hls-optimize
Step 0b — Range Instrumentation
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 0b — Range Instrumentation
0b.0 Detect design type (A: script / B: function-based)
0b.1 Generate instrumented MATLAB files
0b.2 Re-run MATLAB, collect RANGE lines
0b.2b Precision sweep — measure F end-to-end vs golden
0b.3 Build range table (filter constants/masks)
0b.4 Derive W and I for each variable
0b.4b Select Q and O modes (closest to MATLAB double)
0b.4c Report quantization error (from the 0b.2b measurement)
0b.4d Size fixed-point multiply intermediates
0b.5 Present table → user accept / refine loop
─────────────────────────────────────────────────────
Capture min/max of every intermediate variable from the MATLAB simulation. This drives exact-bitwidth type selection in Step 2 — tight widths reduce area and improve achievable II. Without this, type selection falls back to conservative static analysis.
0. Detect design type
Examine the design directory:
- Type A — script-based: the top-level runme calls no sub-function
.mfiles; all computation is inline. The MATLABwhocommand can see all variables after the script runs. - Type B — function-based: the design has multiple
.mfiles that start with thefunctionkeyword. Sub-function internals are invisible towho— only the function's return values appear in the caller's workspace. These require per-function instrumentation.
Detection rule: scan the design directory for .m files. If more than one file begins with function (excluding the runme/tb scripts), it is Type B.
1. Generate instrumented MATLAB files
Type A — append snippet to runme
Add this block to the end of the *_runme.m script, after the main algorithm has already executed. Do not modify the algorithm itself.
% --- Range instrumentation — append after main algorithm ---
fprintf('\n=== RANGE INSTRUMENTATION ===\n');
vars = who;
for k = 1:length(vars)
v = eval(vars{k});
if isnumeric(v) && ~isempty(v) && numel(v) > 1
vmin = double(min(v(:)));
vmax = double(max(v(:)));
is_int = all(v(:) == floor(v(:)));
fprintf('RANGE %-30s min=%12.4f max=%12.4f integer=%d\n', ...
vars{k}, vmin, vmax, double(is_int));
end
end
fprintf('=== END RANGE INSTRUMENTATION ===\n');
Type B — auto-generate instrumented sub-functions
Use the two scripts shipped with this repo under ./hls-scripts/:
SCRIPTS_DIR="./hls-scripts"
Both gen_all_instr.py and gen_matlab_instr.py ship with the repo — no external download required.
Step 1: Generate *_instr.m for every sub-function:
python3 $SCRIPTS_DIR/gen_all_instr.py --dir <design_dir>
This scans the design directory, finds all files starting with function, skips *_instr, *_runme, *_tb, *_range, *_init, and generates <name>_instr.m for each. The prefix embedded in every RANGE line equals the filename stem (e.g., hb2_fir_i.m → prefix hb2_fir_i).
Print the summary output from gen_all_instr.py — it lists every generated file and its tracked variable count.
Step 2: Create or update an instrumented runner.
Create <design_name>_full_instr_runme.m in the design directory that:
- Calls
clear functionsat the top to reset all persistent variables - Calls the
*_instrversions of every sub-function (not the originals) - Uses the same stimulus and parameters as the original runme
- Prints any top-level coefficient/LUT ranges directly via
fprintf('RANGE ...')before the pipeline loop
The RANGE lines are emitted by each *_instr.m function automatically at the end of their execution — no additional snippet is needed in the runner.
Note on loop-internal constants:
gen_all_instr.pytracks ALL named assignments inside the outer loop, including constants likebit_start = 21oroffset = fi(1025,...). These will appear in the RANGE output with trivial ranges (e.g.,[21,21]). Ignore them when building the type table — they are not signal-path variables.
Note on output_direct temps: assignments like
cout(i) = expr_with_no_named_intermediateare captured via injected temp variables namedrng_<array>_N. These appear asRANGE prefix_rng_<array>_Nand represent the actual output signal value — keep them in the type table.
2. Re-run the simulation
STOP — do not proceed until MATLAB has actually been re-run.
The only valid source for the range table is the RANGE lines printed to the MATLAB console during this re-run. Any other source is forbidden:
| Forbidden source | Why it fails |
|---|---|
| Prior simulation output | Does not contain loop-internal variables |
| Code inspection / static analysis | Cannot see runtime values or conditional variables |
| Type inference from input ranges | Underestimates multiply/accumulate intermediates |
| Memory of a previous run | Stale — types may have changed |
Run the script:
# Type A
/path/to/matlab -nodisplay -nodesktop -r "run('path/to/design_runme.m'); exit"
# Type B
/path/to/matlab -nodisplay -nodesktop -r "run('path/to/design_full_instr_runme.m'); exit"
How to verify: the output must contain RANGE lines — one per tracked variable per function. For Type B, lines arrive interleaved as each *_instr function finishes its loop; collect all of them.
Collect every line beginning with RANGE from the output.
2b. Precision sweep — measure F
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 0b.2b — Precision sweep
Tolerance : 1% (skill default — see 0b.4c thresholds)
─────────────────────────────────────────────────────
The RANGE lines just collected answer how big each variable gets. They cannot answer
how fine it needs to be. F is measured here, by running the algorithm at a series of
fractional-bit widths and comparing the final output against the golden from Step 0.
Why this is measured and not derived. F is a property of the algorithm and its input,
not of a variable's values. Same tolerance, same peak magnitude, wildly different answers:
| Structure | Input | F for 1% |
|---|---|---|
| 16-tap averaging FIR | white | 10 |
| adjacent-sample difference | white | 6 |
| adjacent-sample difference | oversampled (smooth) | 16 |
single-pole IIR (a=0.995) | white | 8 |
Rows 2 and 3 are the same code on the same amplitude — a 10-bit swing caused only by
how correlated the input samples are. Nothing in a min/max pair can see that. Averaging
attenuates the signal while error stays put; differencing cancels the signal while errors
add; recursion accumulates error across iterations. Only running it measures the result.
Generate the quantized variants
# one file per design function; qF is a runtime argument, so one file serves the whole sweep
python hls-scripts/gen_matlab_instr.py <src>.m <src>_q.m <prefix> --quantize
This emits <func>_q(..., qF) with x = q_(x, qF); after every fractional assignment,
where q_ = @(x,F) round(x .* 2^F) ./ 2^F — round-to-nearest, matching AP_RND_CONV.
Variables detected as integer-valued are left alone (they are already on an exact grid).
Sweep driver
% ── 0b.2b precision sweep ──────────────────────────────────────────────────
TOL = 0.01; % 1% — skill default, same number as the 0b.4c gate
F_LIST = 6:2:24;
ref = <run the design unmodified, doubles>; % or load golden/matlab_golden.bin
ref = double(ref(:));
peak = max(abs(ref));
is_int_golden = all(ref == floor(ref)); % uint8/uint16 golden → bit-exact is reachable
fprintf('\nSWEEP F max_abs_err rel_err mismatch SQNR(dB) status\n');
fprintf('SWEEP ─────────────────────────────────────────────────────────────\n');
F_pick = NaN;
for F = F_LIST
out = double(reshape(<run the design with _q variants, passing qF = F>, [], 1));
e = out - ref;
max_abs_err = max(abs(e));
rel_err = max_abs_err / peak;
mismatch = sum(e ~= 0);
sqnr = 20*log10(norm(ref) / max(norm(e), eps));
ok = rel_err < TOL;
if is_int_golden, ok = ok && (mismatch == 0); end % integer golden ⇒ demand bit-exact
if ok && isnan(F_pick), F_pick = F; end
status = '';
if ok, status = 'PASS'; end
fprintf('SWEEP %3d %12.4e %9.4f%% %9d %9.1f %s\n', ...
F, max_abs_err, 100*rel_err, mismatch, sqnr, status);
end
fprintf('SWEEP smallest F meeting %.0f%% tolerance: %d\n', 100*TOL, F_pick);
Reading the result
SWEEP F max_abs_err rel_err mismatch SQNR(dB) status
SWEEP ─────────────────────────────────────────────────────────────
SWEEP 6 1.9531e-02 4.5139% 4081 26.9
SWEEP 8 4.8828e-03 1.0723% 4079 39.0
SWEEP 10 1.2207e-03 0.2831% 4064 51.0 PASS
SWEEP 12 3.0518e-04 0.0654% 3971 63.0 PASS
SWEEP 14 7.6294e-05 0.0170% 3585 75.1 PASS
SWEEP smallest F meeting 1% tolerance: 10
F_pickis the answer. Carry it into 0b.4 asF, givingW = I + F.- SQNR rises ~6 dB per bit. If it does not, quantization is not what limits accuracy — suspect an algorithmic difference, not a width problem.
rel_errmust fall monotonically. If it plateaus, adding bits will not help; the error is structural (anInf/NaNpath, a saturating clamp, a divide by a small number).- Never report only
F_pick. The whole table goes to the user at 0b.5 so the accuracy vs width trade is theirs to make, not the skill's.
Margin. F_pick is the minimum that met tolerance on this stimulus. Apply the same
reasoning as the Margin rule in 0b.4 and offer F_pick + 2 as the safe default.
If no F in the list passes: do not silently extend the sweep forever. Extend once to
F_LIST = 6:2:40 and re-run. If it still fails, the design is not width-limited — stop and
report that to the user rather than widening blindly.
3. Build the range table
First — print every RANGE line exactly as captured, unfiltered:
RANGE <var1> min=... max=... integer=...
RANGE <var2> min=... max=... integer=...
...
Do not omit any line. This is the raw capture — show it all before making any decisions.
Second — classify each variable:
| Variable | Min | Max | Keep / Filter | Reason if filtered |
|---|---|---|---|---|
prefix_acc | -1.2 | 1.1 | keep | signal-path accumulator |
prefix_rng_cout_1 | -1.0 | 1.0 | keep | output_direct temp — actual output value |
prefix_bit_start | 21 | 21 | filter | loop-internal constant (trivial range) |
prefix_bit_end | 32 | 32 | filter | loop-internal constant (trivial range) |
prefix_offset | 1025 | 1025 | filter | loop-internal constant (trivial range) |
Filter rules:
- Loop-internal constants: min == max (or range is trivially the literal value) — these are assigned inside the loop but never change. Filter them — they have no useful range information for HLS type sizing.
- Type A scalars: loop counters, config constants, boolean scalars — filter.
- Keep everything else: signal-path variables, accumulators, intermediate products, output_direct temps (
rng_*).
Build the type derivation table from the kept rows only:
| Variable | Min | Max | All-integer? | Chosen HLS type |
|---|---|---|---|---|
im1_pre | -219 | 1107 | yes | ap_int<12> |
s_horiz | 0 | 510 | yes | ap_uint<9> |
coeff_acc | -0.125 | 0.5 | no | ap_fixed<4,1> |
4. Derive HLS type for each variable
Types come from the observed range table, not from reading the MATLAB source. MATLAB computes everything in double, so the instrumented ranges are the only evidence of what a variable actually needs.
| Observed range | Type |
|---|---|
| all integers, min ≥ 0 | ap_uint<N> |
| all integers, min < 0 | ap_int<N> |
| any fractional value | ap_fixed<W,I> |
Any fractional value at all means ap_fixed. Using ap_int where MATLAB used a double
breaks bit-exactness — the property this entire flow exists to preserve.
Integer bits I — one formula for all three types
I is fixed entirely by observed magnitude. Compute it the same way regardless of which
of the three types you end up choosing:
A = max(|min|, |max|) peak magnitude, from the range table
if A == 0: degenerate — see guard below
I = 1
else:
I = floor(log2(A)) + 1 + (1 if min < 0 else 0) the +1 for sign only when min < 0
ap_uint<N>/ap_int<N>— no fractional bits, soN = Iap_fixed<W,I>/ap_ufixed<W,I>—Iis this value, andW = I + F
I may be zero or negative — that is legal and frequently correct. A signal whose peak
is below 1.0 needs no integer bits at all; a peak of 4.97e-3 gives I = -7, placing the
binary point outside the word so that all W bits are fractional.
This matters for precision, not area: F = W - I, so every integer bit allocated to
range the signal never reaches is a fractional bit you do not get. Holding W = 34, an
I of 1 leaves F = 33 (LSB 1.16e-10); the correct I of -7 leaves F = 41
(LSB 4.55e-13) — same width, 8 more bits of resolution.
Guard —
A = 0. If the variable is all zeros across the whole simulation — a signal that never activates on this stimulus, a branch that is never taken, a coefficient array that is genuinely zero, or a constant0fed in as input — thenmin = max = 0, soA = 0andlog2(0) = -inf. The formula explodes:Icomes out-inf, and any width derived from it is garbage.Special-case it before evaluating the log:
if A == 0 → I = 1(a lone sign bit, or a single integer bit if unsigned). One bit is enough to represent zero exactly, and the type stays legal so downstream arithmetic andW = I + Fstill work.But treat it as a signal, not just a number.
A = 0almost always means the instrumentation never exercised that variable. Before acceptingI = 1, check which case you are in:
Cause What to do Stimulus never drives this path (dead branch, unused mode) Range is not trustworthy — the variable is unsized, not zero-sized. Re-run 0b.2 with stimulus that exercises it, or carry it forward marked unverified. Variable is genuinely and permanently zero I = 1is correct. Better: fold the constant away — it is not a signal, it is a literal.Assignment executed but the value happened to be 0 every time Same as row 1 — the stimulus is too narrow. Widen it.
Related degenerate case —
min = Inf,max = -Inf. This is notA = 0, and it is important not to confuse the two. The generated tracker seedsmn_x = inf; mx_x = -inf;before the loop, so a variable whose tracking line never executed prints:RANGE prefix_myvar min= Inf max= -Inf integer=0
A = max(|Inf|, |-Inf|) = Inf, which blows up in the opposite direction. Causes: the assignment sits in a branch the stimulus never took, or the injection landed inside a...line continuation and silently broke. Never size a type from anInfrow — it is an instrumentation result, not a range measurement. Fix or re-stimulate, then re-run.The two are distinguishable straight from the RANGE line, so use that:
min=0, max=0→ assignment ran, value was always zero.min=Inf, max=-Inf→ assignment never ran at all.
Report every A = 0 and every Inf variable explicitly in the 0b.5 table with the cause
identified — never let one pass through silently as a normal sized row.
Exactness: the rule is exact except when
minis an exact negative power of two ([-128, 127]→ 9 instead of 8). One bit conservative there, never unsafe — it can over-allocate but never under-allocate, soAP_WRAPstays safe by construction.
ap_fixed<W,I> sizing
Formula:
A = max(|min|, |max|)
I = floor(log2(A)) + 1 + (1 if min < 0 else 0) (integer bits incl. sign; may be <= 0)
F = F_pick measured in 0b.2b — never derived here
W = I + F
Example: range [-0.125, 0.5] → A = 0.5, min < 0
I = floor(log2(0.5)) + 1 + 1 = -1 + 2 = 1
F = 3 (from the 0b.2b sweep) → ap_fixed<4, 1>
Fis never computed from the range table. It isF_pickfrom the 0b.2b sweep. There is no valid formula forFin terms ofmin/max, for three reasons:
- The information is not there. A rule over "the values a variable took" needs every value; the
RANGElines carry exactly two numbers per variable.- The question often has no answer.
0.7and0.1have no finite binary expansion — noFrepresents them exactly, so "bits needed to be exact" is undefined for most data.Fis a property of the algorithm, not the variable. Quantization error propagates: averaging attenuates signal while error stays put, differencing cancels signal while errors add, recursion accumulates. Two designs with identical range tables need differentF. See the measured table in 0b.2b — the same code on the same amplitude ranged fromF = 6toF = 16purely with input correlation.
min/maxanswerIexactly. They cannot answerFat all.W = I + Fjoins the two.
Common ranges:
[0, 1.0] → ap_ufixed<12, 1> A=1.0, unsigned: floor(0)+1 = 1 int, 11 frac
[-4.0, 4.0] → ap_fixed <16, 4> A=4.0, signed: floor(2)+1+1 = 4 int, 12 frac
[0, 6.0] → ap_ufixed<16, 3> A=6.0, unsigned: floor(2.58)+1 = 3 int, 13 frac
Note how the third row is unsigned (min = 0) — spending a sign bit it never uses would
cost a fractional bit. And if the first row is measured at [0.027, 0.992] rather than
declared as [0, 1.0], then A = 0.992 and I = floor(-0.012) + 1 = 0 →
ap_ufixed<12, 0>, range [0, 1), all 12 bits fractional. That is the correct answer, not
a bug — but see the Margin rule below before committing to it.
CRITICAL - Do NOT "optimize" by converting to integers:
Given a MATLAB weighted sum y = 0.25*a + 0.5*b + 0.25*c with observed range
[0.027, 0.992]:
❌ WRONG:
// "I'll convert to uint8 for hardware efficiency"
ap_uint<8> y = (64*a + 128*b + 64*c) >> 8; // [0, 255] range
// ❌ This changes the numeric domain → different values → mismatches
✅ CORRECT:
// Match MATLAB's domain
ap_ufixed<12,1> y = 0.25*a + 0.5*b + 0.25*c; // [0, 1] range
// ✅ Same numeric domain → same values → bit-exact match
Why this matters:
- Rescaling [0,1] to [0,255] changes ALL downstream computations
- Any nonlinear step (
sqrt, compare, saturate) gives different results in a different domain - Constants calibrated for [0,1] won't work in the [0,255] domain
- Result: mismatches in csim, failed verification
Rule: If MATLAB uses floating-point, C++ uses ap_fixed. Period.
Margin rule: Add 1 extra bit beyond strict minimum when observed range comes from a single small test image. Larger production images may push extremes slightly further.
4b. Select Q (quantization) and O (overflow) modes
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 0b.4b — Q/O mode selection
─────────────────────────────────────────────────────
The full fixed-point type is ap_fixed<W, I, Q, O>. Default is AP_TRN, AP_WRAP. Select Q and O to minimise deviation from MATLAB's double-precision result.
Reference — all valid modes (from ap_decl.h):
| Q mode | Behaviour |
|---|---|
AP_TRN | Truncation toward −∞ (default) |
AP_TRN_ZERO | Truncation toward zero |
AP_RND | Round toward +∞ |
AP_RND_ZERO | Round toward zero |
AP_RND_MIN_INF | Round toward −∞ |
AP_RND_INF | Round away from zero (matches MATLAB round()) |
AP_RND_CONV | Convergent / banker's rounding — round half to even (matches IEEE 754, MATLAB's default double arithmetic) |
| O mode | Behaviour |
|---|---|
AP_WRAP | Wrap-around (default) |
AP_SAT | Saturate at ±max |
AP_SAT_ZERO | Saturate to zero on overflow |
AP_SAT_SYM | Symmetrical saturation |
AP_WRAP_SM | Sign-magnitude wrap |
Overflow mode O — always derive from the range table
| Condition | O mode | Reason |
|---|---|---|
| Range table proves I bits cover min/max | AP_WRAP (default) | Overflow never occurs → no saturation hardware, no overhead |
| Intermediate result can temporarily exceed I bits | Widen I instead | AP_SAT masks bugs — fix the width, do not hide the overflow |
| Final output boundary (e.g. clip to [0, 255]) | Explicit if/else in C++ | More readable than AP_SAT and visible in code |
Rule: size I correctly from the range table and use AP_WRAP. Never use AP_SAT to compensate for an undersized I.
Quantization mode Q — derive from how MATLAB computes each variable
MATLAB computes in IEEE 754 double precision. Q determines how the HLS type handles fractional bits that are dropped when assigning to a narrower fixed-point type.
Inspect the MATLAB expression that produces each variable:
| MATLAB operation | Q mode | Reason |
|---|---|---|
General arithmetic (+, -, *, /N) | AP_RND_CONV | IEEE 754 default is round-half-to-even — AP_RND_CONV matches exactly |
Power-of-2 divide then store (/8, /16) | AP_RND_CONV | MATLAB rounds the double result before storing; plain >> N in C++ truncates (AP_TRN) — use AP_RND_CONV to recover 1 LSB accuracy |
Explicit floor(x) | AP_TRN | MATLAB truncates toward −∞; AP_TRN does the same |
Explicit round(x) | AP_RND_INF | MATLAB rounds half away from zero; AP_RND_INF matches |
Explicit fix(x) / int(x) | AP_TRN_ZERO | MATLAB truncates toward zero; AP_TRN_ZERO matches |
Explicit ceil(x) | implement as floor(x) + 1 or negate-floor-negate in C++ | No direct HLS mode |
| Pure integer arithmetic (no fractional bits drop) | AP_TRN (default) | Q is irrelevant when F=0; leave at default |
Default when unsure: AP_RND_CONV — it is the IEEE 754-compatible choice and closest to MATLAB's double-precision arithmetic. It costs one extra adder per assignment versus AP_TRN.
Note:
AP_RND(round toward +∞) is not the same as round-to-nearest. It biases positive results upward. Do not use it as a substitute forAP_RND_CONV.
Full type examples
// xcorr: fractional, general MATLAB arithmetic → AP_RND_CONV, sized from range table
// peak is 4.97e-3, so I = floor(log2(4.97e-3)) + 1 = -8 + 1 = -7 → all 34 bits fractional
ap_ufixed<34, -7, AP_RND_CONV, AP_WRAP> xcorr_val;
// accumulator: fractional intermediate — widen I to avoid overflow
ap_fixed<20, 4, AP_RND_CONV, AP_WRAP> acc;
// result of explicit floor() in MATLAB
ap_fixed<16, 8, AP_TRN, AP_WRAP> floored_val;
// result of explicit round() in MATLAB
ap_fixed<16, 8, AP_RND_INF, AP_WRAP> rounded_val;
// index: unsigned integer — Q/O irrelevant
ap_uint<13> idx;
// final output clamp [0, 255] — done explicitly, not via AP_SAT
ap_uint<8> out_px;
if (result < 0) out_px = 0;
else if (result > 255) out_px = 255;
else out_px = (ap_uint<8>)result;
Update the range table to include the full type with Q and O:
| Variable | Min | Max | All-integer? | HLS type (full) |
|---|---|---|---|---|
xcorr | 3.14e-10 | 4.97e-3 | no | ap_ufixed<34,-7,AP_RND_CONV,AP_WRAP> |
s_horiz | 0 | 510 | yes | ap_uint<9> |
coeff_acc | -0.125 | 0.5 | no | ap_fixed<4,1,AP_RND_CONV,AP_WRAP> |
4c. Report quantization error
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 0b.4c — Quantization error check
Source : measured 0b.2b sweep (not predicted)
─────────────────────────────────────────────────────
For every fractional variable, report the grid the chosen type sits on:
F = W - I (fractional bits, = F_pick from 0b.2b)
LSB = 2^(-F)
max_q_error = 0.5 × LSB (AP_RND_CONV)
= 1.0 × LSB (AP_TRN / AP_TRN_ZERO)
| Variable | HLS type | LSB | Max q-error |
|---|---|---|---|
xcorr | ap_ufixed<34,-7,AP_RND_CONV,AP_WRAP> | 4.55e-13 | 2.27e-13 |
coeff_acc | ap_fixed<4,1,AP_RND_CONV,AP_WRAP> | 0.125 | 0.0625 |
These are descriptive, not a verdict. They say how coarse each variable's grid is. They do not say whether the design is accurate — error propagates, so a coarse grid on a variable whose error cancels downstream is fine, and a fine grid on one that feeds a subtraction is not. The accuracy verdict is the measured 0b.2b sweep, and only that.
The gate
Carry the sweep table forward verbatim. This is what decides:
| F | max_abs_err | rel_err | mismatch | SQNR (dB) | Status |
|---|---|---|---|---|---|
| 6 | 1.9531e-02 | 4.5139% | 4081 | 26.9 | ✗ |
| 8 | 4.8828e-03 | 1.0723% | 4079 | 39.0 | ✗ |
| 10 | 1.2207e-03 | 0.2831% | 4064 | 51.0 | ✓ |
| 12 | 3.0518e-04 | 0.0654% | 3971 | 63.0 | ✓ |
| 14 | 7.6294e-05 | 0.0170% | 3585 | 75.1 | ✓ |
Thresholds — applied to the sweep's measured rel_err, error at the design output
relative to peak output:
| Measured rel_err | Action |
|---|---|
| < 1% | ✓ acceptable |
| 1% – 10% | ⚠ present to the user with the adjacent rows so they can trade width for accuracy |
| > 10% | ✗ do not offer this row as a default |
F_pick is the smallest ✓ row. Recommend F_pick + 2 as the default and let the user choose
— see 0b.5.
Do not compute
rel_errfromLSB / |signal_min|. The obvious-looking metricmax_q_error / |signal_min|— error relative to the smallest observed sample — is wrong and was removed from this step. It grades a fixed-point type on relative precision, which only floating-point provides:
precision model error at a small sample ap_fixeduniform absolute grid — LSBis the same everywheregrows without bound as the sample shrinks float/doubleuniform relative — the exponent rescales constant fraction of the sample A correctly-sized fixed-point type fails that test, and the failure says nothing about whether the design is accurate. Concretely, the generated tracker records every assignment including initialization, so
acc = 0;putsmin = 0in the range table for essentially every accumulator in every design.max_q_error / 0 = Inf→ every accumulator fails unconditionally, and any "addceil(log2(rel_err/0.01))bits" remedy asks for infinitely many. The same happens for any bipolar signal crossing zero and any image with a black pixel. Measure the output; do not predict from the range table.
Width ceiling
| Limit | Value | Nature |
|---|---|---|
ap_[u]int / ap_[u]fixed W | 1024 bits default | hard, but raisable to 4096 via #define AP_INT_MAX_W before including ap_int.h |
| Native/DSP-friendly operators | ~64 bits | QoR advisory, not a limit — beyond this, operators decompose into multiple DSPs and carry chains, costing area and Fmax |
Source: UG1399, Overview of Arbitrary Precision Integer Data Types. If a design genuinely
needs W > 64, that is legal and synthesizes — flag the QoR cost to the user, do not refuse
the width.
4d. Fixed-point multiplication intermediates
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 0b.4d — Multiply intermediate sizing
─────────────────────────────────────────────────────
Fixed-point multiplication changes the value range: a × b produces a result with W_a + W_b total bits and I_a + I_b integer bits. If the result is immediately assigned to a narrower type, fractional bits are silently dropped — MATLAB never loses these bits (it stays in double throughout).
Rule: any intermediate that is the result of a multiply must be declared at the full product width before any narrowing.
For every multiply in the MATLAB algorithm, identify the operands and declare the intermediate:
// MATLAB: result = a * b
// a: ap_fixed<Wa, Ia, Qa, Oa>
// b: ap_fixed<Wb, Ib, Qb, Ob>
ap_fixed<Wa+Wb, Ia+Ib, AP_RND_CONV, AP_WRAP> prod = a * b;
// Only then narrow — after the full-precision product is captured:
ap_fixed<W_out, I_out, AP_RND_CONV, AP_WRAP> result = prod;
For the peakPicker case — comparing xcorr[i] >= threshold[i]:
- This is a comparison, not a multiply — no intermediate needed
- If an accumulation or scale factor is added later (e.g.
xcorr * weight), declareprodat full width first
Include a multiply-intermediate column in the range table where applicable:
| Multiply | Operand types | Intermediate type | Output type |
|---|---|---|---|
a * b | ap_fixed<16,4> × ap_fixed<16,4> | ap_fixed<32,8,AP_RND_CONV,AP_WRAP> | ap_fixed<16,4,AP_RND_CONV,AP_WRAP> |
5. Present to user and validate
Print the completed table. I is derived from the measured range; F comes from the
measured sweep. Show both sources so the user can see which number came from where:
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 0b — Types + Measured Accuracy
Variables instrumented : <N>
F source : 0b.2b sweep @ F=<F_pick> Tolerance : 1%
Variable Sim range HLS type LSB Max q-err
──────────────────────────────────────────────────────────────────────────────────────────────────
xcorr [3.14e-10, 4.97e-3] ap_ufixed<34,-7,AP_RND_CONV,AP_WRAP> 4.55e-13 2.27e-13
threshold [1.53e-5, 4.40e-3] ap_ufixed<34,-7,AP_RND_CONV,AP_WRAP> 4.55e-13 2.27e-13
...
End-to-end accuracy vs golden (measured, 0b.2b):
F max_abs_err rel_err mismatch SQNR(dB)
6 1.9531e-02 4.5139% 4081 26.9
8 4.8828e-03 1.0723% 4079 39.0
10 1.2207e-03 0.2831% 4064 51.0 ← smallest meeting 1%
12 3.0518e-04 0.0654% 3971 63.0
14 7.6294e-05 0.0170% 3585 75.1
Multiply intermediates:
<a> × <b> → ap_fixed<Wa+Wb, Ia+Ib, AP_RND_CONV, AP_WRAP> (full product width)
─────────────────────────────────────────────────────
Then ask the user to pick a row, using AskUserQuestion. Every option must be a real row of the sweep, labelled with its measured consequence — never an abstract accept/refine:
Which precision do you want to build at?
[F=12] +2 bits margin — rel_err 0.065%, SQNR 63 dB (recommended)
[F=10] minimum meeting 1% — rel_err 0.283%, SQNR 51 dB
[F=14] rel_err 0.017%, SQNR 75 dB — costs 2 more bits per variable
[F=8] below tolerance: rel_err 1.07% — only if width is critical
Rules for building the options:
- Recommend
F_pick + 2, notF_pick.F_pickis the minimum that passed on this stimulus; two bits of margin costs little and absorbs a wider input distribution. Same reasoning as the Margin rule forIin 0b.4. - Offer
F_pickitself as the tight option. - Offer one row above so the user can buy accuracy if they want it.
- Offer one row below tolerance only when it is close (1–10%), labelled as such. Never
offer a
> 10%row. - If the golden is integer-valued (uint8/uint16 image), state bit-exactness explicitly —
mismatch = 0is a stronger and more meaningful claim than any percentage:[F=14] bit-exact vs golden — 0 of 262144 pixels differ. - Never present a row the sweep did not actually run. If the user wants a width not in
F_LIST, extendF_LISTand re-run 0b.2b — do not interpolate.
Wait for the user's answer, then set F = <chosen> and W = I + F for every fractional
variable. Refining is cheap now — it is re-reading a row of a table that already exists,
not a Step 0 re-run. Only return to 0b.2b if the user asks for an F outside the swept list.
Once a row is chosen:
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 0b done — Range Instrumentation
✓ Step 0 Run MATLAB simulation → save golden I/O
✓ Step 0b Range instrumentation → sim-measured types
Step 1 Analyze MATLAB algorithm ← NEXT
Step 2 Generate refactor_1 (plain C++) + verify
Step 3 Generate refactor_2 (frame-based C++)
Step 4 Hand off to /hls-architect → /hls-optimize
─────────────────────────────────────────────────────
Save the accepted range table in memory — Step 2 references it for every intermediate type decision.
Step 1 / 4 — Analyze the MATLAB Code
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 1 / 4 — Analyze MATLAB Code
─────────────────────────────────────────────────────
Read the MATLAB code and extract:
- Algorithm intent — what does it compute? (filter, transform, color space, etc.)
- Inputs and outputs — types, dimensions, value ranges
- Sample-based operations — identify every operation that works on a single pixel/sample at a time vs. entire frame
- Neighborhood access — does it use
imfilter,conv2, sliding windows, or index expressions likeA(i-1:i+1, j-1:j+1)? - Filter coefficients — are they fixed at compile time or runtime parameters?
- Control flow — loops, conditionals, switch/case based on pixel position (Bayer phase, color channel, etc.)
Print before proceeding:
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 1 done — MATLAB Analysis
Algorithm : <what it computes>
Input : <type, dimensions>
Output : <type, dimensions>
Operations : <sample-based ops identified>
Neighborhood : <sliding window / none>
Coefficients : <fixed at compile time / runtime>
Assumptions : <any assumptions made>
Any gaps : <MATLAB constructs with no direct HLS equivalent — or "none">
─────────────────────────────────────────────────────
✓ Step 0 Run MATLAB simulation → save golden I/O
✓ Step 0b Range instrumentation → sim-measured types
✓ Step 1 Analyze MATLAB algorithm
Step 2 Generate refactor_1 (plain C++) + verify ← NEXT
Step 3 Generate refactor_2 (frame-based C++)
Step 4 Hand off to /hls-architect → /hls-optimize
Step 2 / 4 — Generate refactor_1 (Plain C++) + Testbench, Verify Against MATLAB
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 2 / 4 — Generate refactor_1 (Plain C++) + Verify
─────────────────────────────────────────────────────
Before writing HLS code, generate refactor_1 — a plain C++ implementation (no HLS pragmas, no ap_int, no streams) — and a testbench that mirrors the MATLAB simulation exactly. Verify correctness first.
refactor_1 — Plain C++ File
- Translate the MATLAB algorithm to HLS C++ using types chosen from the Step 0b simulation range table. For each intermediate variable, the simulation result drives the choice among exactly three candidates:
ap_uint<N>— simulation shows min ≥ 0 and all values are integerap_int<N>— simulation shows min < 0 and all values are integerap_fixed<W,I>— simulation shows fractional values, or the MATLAB path usesdouble/float(which are forbidden in synthesis and must be replaced)- For variables not captured by the range table (scalars, loop counters): apply the same three-way choice using static analysis of the MATLAB code
Generate Typedefs from Range Table
For every variable in the accepted Step 0b range table, generate a typedef:
// Generate one typedef per unique type from range table
typedef ap_ufixed<W1, I1, AP_RND_CONV, AP_WRAP> input_t;
typedef ap_fixed<W2, I2, AP_RND_CONV, AP_WRAP> intermediate_t;
typedef ap_ufixed<W3, I3, AP_RND_CONV, AP_WRAP> output_t;
// ... one typedef for each variable in the range table
Naming convention:
- Use the MATLAB variable name as the suffix:
<var>_t - For shared ranges (variables with identical min/max), use one typedef with a descriptive name
Apply Types to All Variables
Use the generated typedefs for:
- Output arrays: Must match the derived output types from Step 0b
- Intermediate variables: Loop-internal calculations use the range-table types
- Multiply products: Declare at full product width before narrowing
✅ CORRECT: Use derived types from range table:
static intermediate_t buffer[FRAME_PIXELS];
static result_t results[FRAME_PIXELS];
void my_kernel(input_t input_arr[FRAME_PIXELS],
output_t output_arr[FRAME_PIXELS]) // ← use derived output_t, not float
{
for (int i = 0; i < FRAME_PIXELS; i++) {
intermediate_t temp = buffer[i] * buffer[i]; // ← use typed intermediate
output_arr[i] = process(temp);
}
}
❌ WRONG: Don't fall back to float for fixed-point variables:
// ❌ Defeats the purpose of Step 0b range instrumentation
float output_arr[FRAME_PIXELS];
float intermediate = ...;
- Use the same logic, same coefficients, same normalization as the MATLAB code
- No HLS pragma constructs yet — this is a functional translation, but with HLS-compatible types
- Always use row-major scan order (row outer, col inner) — even if the MATLAB code uses column-major. Row-major is the HLS standard for image processing.
- Output dimensions must match input dimensions exactly — read
ROWSandCOLSfrom the input image; do NOT add extra rows or columns for border padding. If the algorithm has a warmup border (e.g., filter kernels), exclude those border pixels from the error comparison — do not change the output array size.
// Row-major flat loop — always use this pattern
for (int k = 0; k < ROWS * COLS; k++) {
int row = k / COLS;
int col = k % COLS;
...
}
Pattern-string indices: a MATLAB expression like
find(str == 'r') - 1must be resolved outside the kernel — pre-encode it as an integer and pass it in as anap_uint<2>parameter. Do not search a character array inside the kernel; it synthesises, but it is wasted logic and the wrong interface.
Testbench
The testbench must mirror the MATLAB *_runme.m structure — same input data, same comparison against the golden output.
Shape mismatch warning: MATLAB stores arrays in column-major order; C++ iterates in row-major order. A direct flat index comparison will fail even on a correct implementation. The comparison must map between the two orderings:
MATLAB flat index (column-major): j = col * ROWS + row
C++ flat index (row-major): i = row * COLS + col
int main() {
// 1. Load input — MATLAB saves in column-major order.
// Reorder to row-major for C++ kernel.
load_bin("matlab_input.bin", matlab_in, FRAME_PIXELS); // column-major
for (int row = 0; row < ROWS; row++)
for (int col = 0; col < COLS; col++)
in_buf[row * COLS + col] = matlab_in[col * ROWS + row];
// 2. Load MATLAB golden output (column-major)
load_bin("matlab_golden.bin", golden, OUT_PIXELS);
// 3. Run the C++ function TWICE. This testbench is carried forward
// unchanged to /hls-architect, where cosim needs back-to-back calls
// to report an Initiation Interval. g++ measures no II here.
int total_mismatches = 0;
for (int call = 1; call <= 2; call++) {
my_kernel(in_buf, out_buf);
// 4. Compare: map C++ row-major index to MATLAB column-major index.
// Compare in double. NEVER cast the kernel output to int — that
// truncates ap_fixed fractional bits and hides sub-LSB error,
// which is exactly the error the 0b.2b sweep was sizing.
int mismatches = 0;
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
int cpp_idx = row * COLS + col; // C++ row-major
int matlab_idx = col * ROWS + row; // MATLAB column-major
double got = out_buf[cpp_idx].to_double(); // ap_uint/ap_int/ap_fixed all define to_double()
double expect = (double)golden[matlab_idx];
if (fabs(got - expect) > TOLERANCE) {
printf("Call %d MISMATCH (%d,%d): got %.6f expected %.6f\n",
call, row, col, got, expect);
mismatches++;
}
}
}
printf("Call %d: %s\n", call, mismatches == 0 ? "PASS" : "FAIL");
total_mismatches += mismatches;
}
// 5. Collapse to 0/1. The shell masks exit codes to 8 bits, so returning
// the raw count makes any multiple of 256 mismatches look like success.
printf("TOTAL mismatches: %d\n", total_mismatches);
return total_mismatches ? 1 : 0;
}
Note: This testbench carries forward unchanged into the HLS design.
/hls-architectuses the same testbench — only the kernel implementation changes, not the stimulus or comparison logic.
Image I/O Detection — PNG/Image Read/Write
MANDATORY CHECK during Step 1: Scan the MATLAB code for image I/O:
% Detection patterns:
imread()
imwrite()
imshow()
Detection result determines testbench I/O:
| MATLAB has | C++ testbench must |
|---|---|
imread() + imwrite() | Read PNG input + write PNG output (OpenCV) |
imread() only | Read PNG input + save .bin golden + write PNG output |
| Neither | Binary .bin I/O only |
Rule: If MATLAB writes visual output (imwrite/imshow), C++ must write PNG for side-by-side comparison.
PNG I/O Implementation (when detected)
When image I/O is detected, the testbench must do BOTH:
- Binary
.bincomparison (numerical verification) - PNG write (visual comparison)
Start from the testbench above and add the four pieces below. The load, the two-call loop, the comparison and the return are unchanged — do not fork a second copy of them.
#include <opencv2/opencv.hpp>
// (a) Before the loads: resolve golden paths up front and build absolute paths.
// Downstream tools run the testbench from their own build directory, so a
// relative "../golden" only works for the local g++ run.
const char *GOLDEN_DIR = getenv("GOLDEN_PATH");
if (!GOLDEN_DIR) GOLDEN_DIR = "../golden";
char input_bin[512], golden_bin[512], input_png_path[512];
snprintf(input_bin, sizeof(input_bin), "%s/matlab_input.bin", GOLDEN_DIR);
snprintf(golden_bin, sizeof(golden_bin), "%s/matlab_golden.bin", GOLDEN_DIR);
snprintf(input_png_path, sizeof(input_png_path), "%s/<input>.png", GOLDEN_DIR);
// then load_bin(input_bin, ...) and load_bin(golden_bin, ...) instead of bare filenames
// (b) Optional: load the input PNG so you can eyeball it next to the output.
cv::Mat input_png = cv::imread(input_png_path, cv::IMREAD_GRAYSCALE);
if (input_png.empty())
printf("Warning: input PNG not found — proceeding with binary-only input\n");
// (c) Inside the two-call loop, after the comparison: write the C++ output as PNG.
cv::Mat out_png(ROWS, COLS, CV_8UC1);
for (int row = 0; row < ROWS; row++)
for (int col = 0; col < COLS; col++)
out_png.at<uint8_t>(row, col) = (uint8_t)out_buf[row * COLS + col];
char filename[256];
snprintf(filename, sizeof(filename), "cpp_output_call%d.png", call);
cv::imwrite(filename, out_png);
printf(" (visual): %s written\n", filename);
// (d) After the loop, before the return: name the three files to compare.
printf("Visual comparison — open side by side:\n");
printf(" Input : %s\n", input_png_path);
printf(" MATLAB gold: %s/<golden>.png\n", GOLDEN_DIR);
printf(" C++ output : cpp_output_call2.png (written to the current directory)\n");
Hybrid testbench rules:
- Binary verification: the
.bincomparison catches precision errors - Visual output: the PNG catches algorithm errors (shifts, channel swaps, wrong Bayer phase)
- Both must pass: binary PASS and visual inspection
- Use
cv::IMREAD_GRAYSCALEorcv::IMREAD_COLORto match MATLAB - For RGB output, use
CV_8UC3and interleave channels correctly - Write PNG for both calls (call1 and call2) to verify consistency
- Resolve every input path absolutely at generation time — the testbench is reused by downstream tools that run it from a different working directory
Verify
# ap_fixed/ap_int/ap_uint headers ship with Vitis at $XILINX_VITIS/include
g++ -std=c++14 -I$XILINX_VITIS/include -o verify testbench.cpp kernel.cpp && ./verify
Must print PASS before proceeding.
Write to sample_based/
Call ./reference/design-layout.md design_name=<name> stage=sample_based
Write into design_name/sample_based/:
kernel.cpp— the refactor_1 plain C++ kerneltestbench.cpp— the testbench (loads.binfiles from../golden/)
If it fails:
First, rule out width. The 0b.2b sweep already ran this algorithm in MATLAB at the chosen
Fand measured the result against the same golden. If that row passed, the widths are sufficient — the failure is not a precision problem, and widening types will not fix it. Look for a behavioural difference instead. Widening in response to a csim mismatch is the most common wasted debug cycle in this flow: it changes the numbers, sometimes moves the mismatch, and never addresses the cause.Confirm the direction before spending time: if the C++ error is far larger than the sweep's
max_abs_errfor thatF, it is structural. If it is the same order, re-checkQmode (AP_TRNvsAP_RND_CONV) and multiply-intermediate widths from 0b.4d.
- Check coefficient scaling (
/8→>> 3,/16→>> 4) - Check rounding vs truncation differences
- Exclude warmup border pixels from comparison for filter kernels (KSIZE/2 rows + cols)
- Check column-major (MATLAB) vs row-major (C++) index mapping — a transposed comparison fails everywhere except on a square, symmetric image
- Check that a multiply intermediate was declared at full product width before narrowing (0b.4d)
Print before proceeding:
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 2 done — refactor_1
Data types : <variable: sim range [min, max] → ap_uint<N> / ap_int<N> / ap_fixed<W,I> — list each>
Border/warmup: <warmup = N rows/cols skipped in comparison / N/A>
Index mapping: <row-major ↔ column-major note if applicable / N/A>
Verify result: PASS / FAIL (<mismatch count if fail>)
─────────────────────────────────────────────────────
✓ Step 0 Run MATLAB simulation → save golden I/O
✓ Step 0b Range instrumentation → sim-measured types
✓ Step 1 Analyze MATLAB algorithm
✓ Step 2 Generate refactor_1 (plain C++) + verify
Step 3 Generate refactor_2 (frame-based C++) ← NEXT
Step 4 Hand off to /hls-architect → /hls-optimize
Step 3 / 4 — Generate refactor_2: Sample-Based to Frame-Based Conversion
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 3 / 4 — Generate refactor_2 (Frame-Based C++)
─────────────────────────────────────────────────────
Starting from refactor_1, convert to refactor_2 — a frame-based C++ file that iterates pixel-by-pixel in raster scan order. This is the file handed to /hls-architect in Step 4.
MATLAB code is inherently sample-based: it operates on entire arrays/matrices at once using vectorized operations. HLS requires frame-based code: iterate over pixels one at a time in raster scan order.
Image size rule: The frame-based kernel must produce exactly
ROWS × COLSoutput pixels — the same dimensions as the input. Do NOT increase the output array size to accommodate border warmup. Border pixels (e.g., firstKSIZE/2rows and columns for a filter) are invalid and must be skipped in the testbench comparison, not padded into the output.
Type consistency rule: refactor_2 uses the exact same types as refactor_1. The only difference is the loop structure (flat pixel iteration instead of nested row/col loops). Do NOT change types when converting sample-based to frame-based. If refactor_1 uses
output_tfor output arrays, refactor_2 must also useoutput_t. Copy the typedef block verbatim from refactor_1 to refactor_2.
How to Convert
Step 3 restructures array-level MATLAB operations into pixel-level C++ loops.
Do this:
- Access a neighbourhood with clamped 2D indices:
buf[clamp(row±1) * COLS + clamp(col±1)] - Keep a full-frame intermediate buffer (
buf[ROWS*COLS]) between stages - The structure should be: sequential loops over a shared buffer, NOT a single-pass pipeline
Worked example — MATLAB ndgrid + bitget parity masks (Bayer phase, colour channel
selection) become row/col counters derived from the flat loop index:
% MATLAB
[y, x] = ndgrid(0:ROWS-1, 0:COLS-1);
mask00 = and(not(bitget(y,1)), not(bitget(x,1)));
// C++ — track row/col from the loop counter. bitget(v,1) is the LSB (1-indexed).
int row = k / COLS;
int col = k % COLS;
bool lsb_y = (row & 1);
bool lsb_x = (col & 1);
bool mask00 = !lsb_y && !lsb_x;
Not this (causes shift bugs):
- Attempting to fuse consecutive stages into a single pass
#pragma HLSof any kind — pragmas belong to /hls-optimize, not here- Re-associating filter arithmetic (pre-summing symmetric taps, folding coefficients into shifts) — it changes intermediate widths and breaks bit-exactness against the golden
Write to frame_based/
Call ./reference/design-layout.md design_name=<name> stage=frame_based
Write into design_name/frame_based/:
kernel.cpp— the refactor_2 frame-based C++ kerneltestbench.cpp— same testbench assample_based/(unchanged — same inputs, same golden comparison)
Verify refactor_2 against MATLAB golden
Compile and run immediately after writing the files — same testbench, same golden .bin files:
cd design_name/frame_based/
# ap_fixed/ap_int/ap_uint headers ship with Vitis at $XILINX_VITIS/include
g++ -std=c++14 -I$XILINX_VITIS/include -o verify_frame kernel.cpp testbench.cpp && ./verify_frame
For OpenCV designs, add the include and link flags:
g++ -std=c++14 \
-I$XILINX_VITIS/include \
-I${OPENCV_INCLUDE} \
-o verify_frame kernel.cpp testbench.cpp \
-L${OPENCV_LIB} -lopencv_core -lopencv_imgcodecs -lopencv_imgproc \
-Wl,-rpath,${OPENCV_LIB} \
&& ./verify_frame
Must print PASS before proceeding to Step 4. If it fails:
- A raster-order bug (scan direction, row/col swap) shows up here but not in refactor_1 — fix the loop structure
- A warmup border difference (filter edge pixels) — confirm the testbench skips the same border as in Step 2
- A type narrowing issue introduced during frame-based rewrite — check
ap_int/ap_fixedintermediate widths match refactor_1
Print before proceeding:
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 3 done — refactor_2 (frame-based)
Key changes : <vectorised→loop, 2D→1D scan, imfilter→explicit neighbourhood loop, etc.>
HLS types : <ap_uint/ap_int/ap_fixed changes from refactor_1>
Verify : PASS / FAIL (<mismatch count if fail>)
Handing off : frame_based/kernel.cpp → /hls-architect
─────────────────────────────────────────────────────
✓ Step 0 Run MATLAB simulation → save golden I/O
✓ Step 0b Range instrumentation → sim-measured types
✓ Step 1 Analyze MATLAB algorithm
✓ Step 2 Generate refactor_1 (plain C++) + verify
✓ Step 3 Generate refactor_2 (frame-based C++)
Step 4 Hand off to /hls-architect → /hls-optimize ← NEXT
Step 4 / 4 — Call /hls-architect
─────────────────────────────────────────────────────
[matlab-to-cpp] Step 4 / 4 — Handing off to /hls-architect
─────────────────────────────────────────────────────
Once the plain C++ passes verification (Step 2), hand off to /hls-architect.
Always pass THROUGHPUT_TARGET, XPART, and CLOCK_NS collected in the Preamble:
/hls-architect <THROUGHPUT_TARGET> part=<XPART> clock=<CLOCK_NS>
Skill: hls-optimize
Iteratively modify the kernel to improve performance against an optimization criteria, using the other skills to measure progress and committing each attempt.
Optimization criteria: $ARGUMENTS
Examples:
/hls-optimize minimize latency/hls-optimize minimize DSP usage while meeting timing/hls-optimize maximize throughput (minimize II)/hls-optimize reduce LUT count below 5000
Init component and git repository
MANDATORY: Before any optimization work, you MUST read and execute the ./reference/init-component.md file.
DO NOT write your own git init commands. DO NOT use simplified git commands. You MUST execute the ./reference/init-component.md file, which includes the vitis-comp.json check, specific git configuration, and .gitignore setup.
This ensures the HLS component is properly set up, with consistent git configuration, proper .gitignore setup, and correct baseline commit format across all optimization sessions.
Philosophy
One idea at a time. Each attempt changes exactly one thing — one pragma, one algorithmic transformation, one loop restructuring. Never combine independent changes in a single attempt. You cannot attribute cause if multiple things changed simultaneously.
Investigate before moving on. After each synthesis, read the reports thoroughly. Do not just check whether latency went up or down — understand why. Read the loop detail table. Check II and achieved vs. target. Look for warnings in the log. If something unexpected happened, dig into it before proceeding.
Use all available tools. The synth skill gives access to BC file inspection, QoR JSON, inferred directives, and schedule details. Use hls-component-basic-info skill and the hls-synth-report skill for a quick overview. In synthesis log to inspect how the pragma used in the code. Use ./hls-scripts/qor_log.py to track the history of changes. Verify that the change had the expected effect — not just in the report, but in the IR and schedule.
Experimental changes are valid. Sometimes the right move is to make a change that you don't expect to improve the metric, but that tests a hypothesis about the tool's behavior. Document what you expected and what actually happened. Understanding the compiler's behavior is itself valuable.
Do not rush to run cosim or impl. Use csim+csynth as the inner loop. Only escalate to cosim when csynth shows meaningful improvement (≥ 10% in cycles or a structural change like II reduction). Only run impl when cosim confirms improvement. The expensive steps are a gate, not a rubber stamp.
Verify Vitis environment.
which vitis-run
If not found, check if the environment variable XILINX_VITIS is set. If not, ask the user for the value of XILINX_VITIS. Then source the settings file:
which vitis-run # must be on PATH — set XILINX_VITIS to your Vitis install if not
Do not proceed until vitis-run is on PATH.
Step 0: Establish baseline and get HLS design data
0a. Establish a baseline
Before making any change, ensure you have a measured baseline to compare against. The baseline consists of:
- cosim latency (cycles) from cosimulation report
- post-route clock period (ns) from the
hls-impl-reportskill'spostRoutevalue (implementation report) - true latency = cycles × period
- resource utilization (LUT, FF, DSP, BRAM, URAM) from the
hls-impl-reportskill'splaceRouteResourceSummaryvalue (implementation report)
When you establish the baseline, you must make sure the csimulation, synthesis, cosimulation and implementation flows have all been run successfully. If any of the reports is missing or stale, use skill of hls-run-flow to run the corresponding flow before recording the baseline.
0b. Get HLS design reports and data
MANDATORY: You MUST call the following functions to get ALL report-related data. DO NOT read .rpt files directly using file read tools — always use these functions.
hls-synth-reportskill: get the synthesis report and log content.- Returns
synthesisReportContent,synthesisPragmaReportContent, andsynthesisLogContent
- Returns
hls-cosim-reportskill: get the cosimulation report content and dataflow process/channel content.- Returns
coSimulationReportContentanddataflowProcessAndChannelContent
- Returns
hls-impl-reportskill: get the implementation report content.- Returns
postRoute,placeRouteResourceSummaryandplaceRouteFailFast
- Returns
0c. Run HLS flows if reports are missing or stale
If these reports do not exist or are stale, you must use the hls-run-flow skill to run the active component HLS flow.
Before running csim flow, you must check 'csim.profile_tripcount=1' in .cfg file. If it is not set, update the trip count. When you find it changes the trip count, you must run all flows (csim, csynth, cosim, impl) to get the updated reports before recording the baseline.
0d. Log the baseline QoR data for future comparison
On the unmodified kernel first.
Call getSkillResourcePath function with skillName and relativePath ./hls-scripts/qor_log.py to get the full path to the script.
Then run python3 "$qorLogScriptFullPath" --report "$synthesisReportContent" to get a concise summary of the baseline. The report argument is required; the label and csv arguments are optional.
Record the baseline before starting optimization iterations.
Step 1: Analyze the kernel
You must call hls-component-basic-info skill to get the basic component info, including component_name, source_files, testbench_files, include_paths, top_function. Read this information along with the synthesisReportContent and synthesisLogContent to analyze the kernel and identify bottlenecks.
- High II on inner loops → memory port bottleneck or long recurrence chain. Check loop table for
II achievedvsII target. Read the warning messages insynthesisLogContentfor the root cause. - Large iteration latency on unpipelined loops → missing pipeline pragma, or loop not eligible for pipelining (e.g. variable trip count, non-trivial control flow, contains sub-loop).
- Low resource utilization → opportunity to trade area for performance (unrolling, partitioning). DSP at 2% means 98% of compute is still sequential.
- High resource utilization → risk of fit; verify after every change.
- Sequential outer loop containing pipelined inner loop → inner pipeline restarts on every iteration, dominant latency term.
Also read the Violation Report in the synthesisLogContent carefully — it identifies exactly which dependency causes each II violation, including the variable name and memory port.
Step 2: Form a hypothesis
Before touching any code, write down:
- What you will change (exact pragma or code transformation)
- What you expect to happen in the
synthesisReportContent(loop II, latency, resources) - What would confirm the hypothesis (e.g. "II drops from 5 to 2 because we have 2 memory ports now")
- What would falsify it (e.g. "II stays at 5 despite partition → the bottleneck is the FMA recurrence, not memory")
This forces you to understand the compiler before running it, and makes failed experiments informative.
Step 3: Choose one optimization technique
Pick one technique per attempt. See the full technique catalogue below.
Pragma-only changes (lowest risk, try first)
| Technique | Pragma | Effect | When to use |
|---|---|---|---|
| Acknowledge II | #pragma HLS PIPELINE II=<N> | Prioritize II over satisfying timing pressure | II violation in csynth report (to acknowledge the real achievable II) |
| Loop unroll (partial) | #pragma HLS UNROLL factor=<N> | Replicates loop body N times, reduces trip count by N | Inner loop with known trip count divisible by N |
| Loop unroll (full) | #pragma HLS UNROLL | Fully unrolls loop; all iterations in parallel | Short loops (≤ 16 iterations), sufficient resources, constant loop trip count |
| Array partition (cyclic) | #pragma HLS ARRAY_PARTITION variable=<x> cyclic factor=<N> dim=<D> | Creates N memory banks; N parallel accesses per cycle | Memory port II bottleneck |
| Array partition (complete) | #pragma HLS ARRAY_PARTITION variable=<x> complete dim=<D> | Fully registers the array (no BRAM) | Small arrays only |
| Array partition (block) | #pragma HLS ARRAY_PARTITION variable=<x> block factor=<N> dim=<D> | Splits into N contiguous blocks | When access pattern is block-sequential |
| Loop flatten | #pragma HLS LOOP_FLATTEN | Merges nested loops into a single loop counter | Nested loops with loop-invariant bounds |
| Dataflow | #pragma HLS DATAFLOW | Task-level pipelining between functions or loops | Sequential stages that can overlap, non-innerloop pipelining |
| Expression balance | #pragma HLS EXPRESSION_BALANCE | Allow expression tree balancing on float | Floating point reductions in critical path |
Algorithmic changes (higher risk, higher reward)
| Technique | Effect | When to use |
|---|---|---|
| Loop reordering | Changes memory access pattern; may improve spatial locality or expose better reuse | Poor memory reuse in inner loop; can turn random access into sequential |
| Tiling / blocking | Reuses on-chip data, reduces off-chip bandwidth, make buffer size constant | Memory bandwidth bound, variable size data to chunk into fixed size buffer |
| Local buffer | Stage data into local arrays to decouple memory access from compute | Repeated accesses to same memory region |
| Scalarization | Store data into individual scalars to allow arbitrary accesses and additional simplifications | Repeated accesses to the same memory element; can allow infinite access per cycle |
| Loop fusion | Merge two loop body into the same loop to reduce storage and allow for pipelining | Two consecutive loops with identical loop trip count working on the same buffers |
| Loop fission | Split the loop body into two separate loop to create independent processes in dataflow context | Loop body working on independent arrays/streams causing stall or complex control |
Replace float with ap_fixed<W,I> | Shorter pipeline, fewer DSPs, faster clock | Fixed-point arithmetic acceptable for the application |
| Replace division with reciprocal multiply | Eliminates expensive divider | Division inside a loop by constant divisor |
HLS library usage
#include <ap_int.h> // ap_int<N>, ap_uint<N> — arbitrary-width integers
#include <ap_fixed.h> // ap_fixed<W,I> — fixed-point arithmetic
#include <ap_float.h> // ap_float<W,E> — floating-point arithmetic with custom precision
#include <hls_math.h> // hls::sqrt, hls::exp, etc. — HLS-optimized math
#include <hls_vector.h> // hls::vector<T,N> — SIMD-style vectorized types
#include <hls_array_partition.h> // hls::scatter<T,K>, hls::gather<T,K> — SIMD-style scatter/gather on local arrays
#include <hls_stream.h> // hls::stream<T> — FIFO communication between tasks
#include <hls_burst_maxi.h> // hls::burst_maxi — high-performance M-AXI burst
Step 4: Implement the change
Use the template to launch a sub-agent for each attempt. Fill in all bracketed fields before launching.
Key rules for the sub-agent:
- Make only the described change. Do not opportunistically fix other things.
- After each tool run, read the output carefully before deciding to proceed.
- If csynth warnings or loop table do not match the hypothesis, investigate before escalating.
Step 5: Investigate the result thoroughly
For run csynth, do not just check the summary. Investigate systematically:
5a. Check for ignored-pragma warnings in the HLS log
Do this first — before reading any report. HLS frequently silently ignores pragmas that cannot be applied and emits a warning explaining why. If a pragma was ignored, the change you intended was not applied and the csynth result reflects the unmodified schedule. Reading the reports without knowing this leads to wrong conclusions.
check pragma\|ignored\|cannot\|not applied\|warning in $synthesisLogContent for any ignored pragma warnings.
Common ignored-pragma patterns to look for:
| Warning text (approximate) | Meaning |
|---|---|
pragma HLS PIPELINE ignored | Loop is not eligible for pipelining (e.g. contains a sub-loop, variable trip count, or non-trivial control flow). |
pragma HLS UNROLL factor=N ignored | Loop body cannot be fully unrolled (e.g. trip count not statically known, or factor does not divide trip count). |
pragma HLS ARRAY_PARTITION … ignored | Variable is not a local array, or partition dim exceeds array rank. |
pragma HLS LOOP_FLATTEN ignored | Loop bounds are not loop-invariant — flattening would change semantics. |
pipeline II target … cannot be achieved | The target II was set but the scheduler could only achieve a higher value. Check the Violation Report for root cause. |
If a pragma was ignored, fix the pragma or restructure the code and re-run before drawing any conclusions from the reports.
5b. Read the synthesis report
Use the synthesisReportContent to check the loop table for the loops of interest. Look at II achieved vs. target, iteration latency, and resource usage.
Check:
- Did II change on the expected loop?
- Did II change on any other loop (unexpected side effect)?
- Did total latency change by the expected factor?
- Did resource usage change? By how much?
Also check for general synthesis warnings:
check warning\|critical\|fail\|error in synthesisReportContent and synthesisLogContent for any synthesis warnings.
5c. Read the Violation
Check violation in synthesisLogContent for any II or Timing violations.
5d. Read the inferred directives
First, find the inferred directives file within the component directory:
find $component -name "inferred_directives.ini" 2>/dev/null
Then read the file to check whether HLS auto-applied any directives you didn't expect. Array partitions, loop flattening, pipeline pragmas can be inferred automatically and can interact with your pragma.
5e. Verify transformation in synthesis log (when hypothesis is about compiler behavior)
When you want to verify that HLS actually applied the transformation you intended (e.g., that a partition was respected, or that a loop was actually unrolled), search synthesisLogContent for key indicators.
Search patterns by pragma type:
| Pragma | Search pattern in synthesisLogContent | Confirmation |
|---|---|---|
ARRAY_PARTITION | partitioned|partition.*factor|partition.*complete | Look for "partitioned into N banks" or similar messages |
UNROLL factor=N | unroll|unrolled|trip count | Look for "loop completely unrolled" or "loop unrolled by factor N" |
LOOP_FLATTEN | flatten|flattened|merged | Look for "loop flattened" or "loops merged" messages |
PIPELINE | pipeline|pipelined|II= | Look for "loop pipelined with II=N" |
DATAFLOW | dataflow|FIFO|channel | Look for dataflow region and channel creation messages |
Example grep commands:
# Check if partition was applied
echo "$synthesisLogContent" | grep -i "partition"
# Check if unroll was applied
echo "$synthesisLogContent" | grep -i "unroll"
# Check if pipeline achieved target II
echo "$synthesisLogContent" | grep -i "pipeline.*II"
# General transformation summary
echo "$synthesisLogContent" | grep -iE "applied|transformed|optimized|inferred"
Key things to look for:
- After
ARRAY_PARTITION: messages confirming partition into N banks, or warnings if partition was not applied - After
UNROLL factor=N: messages showing "unrolled by factor N" or "completely unrolled" - After
LOOP_FLATTEN: messages showing nested loops were merged into a single loop - After
PIPELINE: messages showing achieved II value
If the expected transformation message is not found, the pragma may have been ignored — cross-reference with Step 5a for ignored-pragma warnings.
5f. Log the result
python3 "$qorLogScriptFullPath" --report "$synthesisReportContent" --label "<technique-applied>" --csv .memory/qor_history.csv
This appends a row to .memory/qor_history.csv for tracking across attempts.
Step 6: Record the result — MANDATORY after every attempt
Do this before deciding whether to escalate or start the next attempt. Never skip this step.
6a. Update .memory/optimize_outcomes.md
Append a row to the outcomes table immediately after reading the csynth report. Use the present attempt's data — do not wait until the end of the session. Include:
- Technique name
- Observed effect (cycles before → after, II change)
- Whether the hypothesis was confirmed
- Any unexpected behavior, side effects, or lessons
This file is read at the start of every session. If it is not updated after each attempt, the next session will repeat experiments that have already been run.
6b. Commit the state — MANDATORY, including for failed attempts
Every attempt gets its own commit before anything else happens — including attempts that did not improve the metric. The commit must happen before any git checkout, git restore, file edit, or next-attempt work. Skipping the commit on failure loses the experiment from history and is the most common mistake in this workflow.
Order of operations after every attempt (no exceptions):
- Update
.memory/optimize_outcomes.md(Step 6a). git add+git commit(this step) — even if the build broke or the result was worse.- Only then may you revert, adapt, or move on.
If the attempt improved the target metric or confirmed a useful hypothesis (keep the code):
git add <source_file> .memory/optimize_outcomes.md
git commit -F - <<'EOF'
<technique>: <what changed> → <observed effect>
Hypothesis: <what you expected>
Observed: <what actually happened in csynth/cosim/impl>
Baseline: cosim=<X> cycles, post-route=<Y> ns, true latency=<Z> ms
After: cosim=<X'> cycles, post-route=<Y'> ns, true latency=<Z'> ms
Resources: LUT <A>→<A'>, DSP <B>→<B'>
EOF
If the attempt did not help, latency got worse or not improved — commit first, then revert:
# 1. Commit the failed state as-is (code + memory update) so the exact change is preserved
git add <source_file> .memory/optimize_outcomes.md
git commit --allow-empty -F - <<'EOF'
experiment(<technique>): <what changed> — did not help
Hypothesis: <what you expected>
Observed: <what actually happened — why it failed or made QoR worse / etc.>
EOF
# 2. Verify the commit actually landed before reverting. If `git status` is not clean
# after the commit, STOP and investigate — do not run the checkout below.
git log -1 --oneline
git status --short
# 3. Only after the commit is confirmed, revert the kernel to the previous working state.
git checkout HEAD~1 -- <source_file>
--allow-empty ensures the commit still lands even if the only thing that changed was a file that has since been auto-regenerated to its prior content (e.g., a report). The verification step (git log -1 + git status --short) is what catches the case where the commit silently did not happen — if you see your commit in git log and git status is clean, the failed attempt is safely preserved and you may revert.
Committing before reverting preserves the exact failing code in history, making it possible to inspect, diff, or re-apply it later. A failed experiment that teaches you something is not wasted work.
Step 7: Decide whether to escalate
| csynth result | Action |
|---|---|
| Latency improved ≥ 10% OR II reduced on a dominant loop | Escalate: run cosimulation flow |
| Latency unchanged, but hypothesis was confirmed (e.g. II matched expected value) | Valid data. Move on to the next hypothesis. |
| Latency got worse | Investigate why, then commit (Step 6b) before reverting. The result may reveal a real constraint. |
| csim FAIL | Fix logic error or revert immediately. |
For run cosim: call hls-cosim-report skill to get coSimulationReportContent and dataflowProcessAndChannelContent. Compare cosim cycles to csynth estimate. For designs with memory backpressure, cosim can be significantly worse than csynth estimates; for compute-bound kernels, they should be close.
For run impl: only run when cosim confirms latency improvement. Call hls-impl-report skill and use postRoute for the actual post-route clock period and compute true latency = cosim_cycles × period_ns.
DO NOT read .rpt files directly using file read tools to extract information. Always use the provided functions to ensure consistency and correctness.
Step 8: Update skills with lessons learned
After each attempt — successful or not — update the relevant SKILL.md with findings that are general enough to apply to future kernels:
- If a technique had an unexpected interaction with HLS (e.g., auto-inferred flatten conflicted with your pipeline pragma), note it.
- If the Violation Report pointed to a root cause that wasn't obvious from the loop table, note the pattern.
- If the IR inspection revealed something unexpected (e.g., the partition was not reflected in the IR), note it.
Cost model for the inner loop
| Step | Typical runtime | When to run |
|---|---|---|
run csim | 5–30 s | Always — correctness gate |
run csynth | 10–60 s | Always — the main investigation tool |
run cosim | 30 s – 5 min | When csynth shows ≥ 10% improvement in latency cycles, or a structural improvement (II reduction on dominant loop) |
run impl | 1 – 30 min | When cosim confirms improvement |
Stopping criteria
Stop iterating when any of the following is true:
- The optimization criteria is met.
- Three consecutive attempts produced no improvement, and no new hypothesis remains to test.
- Resource utilization is approaching device limits (> 60% of any constrained resource) and further improvement requires more resources.
- The improvement per attempt has diminished to < 5% of baseline.
When stopping criteria are met, summarize the lessons learned.
In interactive mode: ask the user if they want to update the relevant SKILL.md with the new insights. The update role is described in step 8 above.
In non-interactive mode (invoked via claude --print): skip the prompt — do NOT update any SKILL.md. Print the summary and exit.
Known outcomes
Outcomes are recorded in .memory/optimize_outcomes.md.
Read this file at the start of each session to avoid repeating experiments.
Skill: perf-pragma
Calculate target_ti from the user's throughput target and produce a cascade table for review. This skill is a pure calculator — it does not run synthesis or interpret reports.
Throughput target: $ARGUMENTS
Print at the start:
─────────────────────────────────────────────────────
[perf-pragma] flow overview
Steps 0 → 5
Step 0 — Gather inputs (clock, architecture, loop structure)
Step 1 — Calculate top-level target_ti
Step 2 — Cascade through architecture
Step 3 — Cascade through loops → build table
Step 4 — Present table for review
Step 5 — Apply pragmas to source code
─────────────────────────────────────────────────────
Step 0: Gather inputs
The throughput requirement comes from $ARGUMENTS.
Read the configuration and source code to determine:
-
Clock frequency — Read from the
.cfgfile:CFG_FILE=$(ls *.cfg) CLOCK_NS=$(grep "^clock=" $CFG_FILE | cut -d'=' -f2) clock_hz = 1e9 / CLOCK_NS -
Architecture type — Inspect the top-level function:
- Look for
#pragma HLS datafloworhls::task→ dataflow pipeline - Multiple function calls in sequence → sequential functions
- Single pipelined function otherwise
- Look for
-
Loop structure — Identify loop nesting levels and trip counts:
- Extract all labeled loops (e.g.,
Row_Loop:,Col_Loop:) - Determine nesting depth
- Trip counts: Read loop bounds from source code
- If trip counts are runtime parameters (not compile-time constants):: warn the user : "Performance pragma requires loop trip counts. Please specify the trip count values for: [list loops with variable bounds]"
- Extract all labeled loops (e.g.,
-
Throughput conversion — If throughput is given as data rate (MB/s, GB/s):
Read source code to determine input data size:
# Find top function CFG_FILE=$(ls *.cfg) TOP_FUNCTION=$(grep "^top=" $CFG_FILE | cut -d'=' -f2) # Find source file containing top function SRC_FILE=$(grep -l "void $TOP_FUNCTION" src/*.cpp)Read the function signature. The function will have multiple inputs/outputs. Identify the input arrays and calculate:
bytes_per_invocation = total_input_array_size_in_bytesConvert data rate to invocations per second:
data_rate_bytes_per_sec = throughput_value × (1,000,000 for MB/s, 1,000,000,000 for GB/s) invocations_per_sec = data_rate_bytes_per_sec / bytes_per_invocationUse this
invocations_per_secvalue in Step 1. -
Computational throughput — If throughput is given as GOPS or GFLOPS:
# Parse value (e.g., "100 GOPS" → 100e9 ops/sec) THROUGHPUT_VALUE=$(echo "$ARGUMENTS" | grep -oE '[0-9.]+') OPS_PER_SEC=$(echo "$THROUGHPUT_VALUE * 1e9" | bc) # Read source code to determine operations per invocation # Look for dimensions in defines or comments # Convert: invocations/sec = ops/sec / ops_per_invocation # Note: 1 OP = 1 MAC = 2 FLOPs invocations_per_sec=$(echo "$OPS_PER_SEC / $OPS_PER_INVOCATION" | bc)If operation count cannot be determined, warn the user to specify it or use FPS/MB/s instead.
Use the calculated
invocations_per_secin Step 1.
Print after Step 0:
─────────────────────────────────────────────────────
[perf-pragma] Step 0 — done
✓ Step 0 clock=<CLOCK_NS> ns arch=<single/sequential/dataflow> loops=<N levels>
← NEXT Step 1 — Calculate top-level target_ti
─────────────────────────────────────────────────────
Step 1: Calculate top-level target_ti
Formula:
target_ti = clock_hz / throughput_rate
Where throughput_rate is the target invocations per second (e.g., FPS, invocations/s, samples/s).
Print after Step 1:
─────────────────────────────────────────────────────
[perf-pragma] Step 1 — done
✓ Step 0 Inputs gathered
✓ Step 1 top-level target_ti = <N> cycles (<throughput> @ <CLOCK_NS> ns)
← NEXT Step 2 — Cascade through architecture
─────────────────────────────────────────────────────
Step 2: Cascade through architecture
Case A — Single function
The full target_ti applies to the one function. Go to Step 3.
Case B — Sequential functions
Functions execute one after the other — total latency is the sum:
target_ti_total = target_ti_fn1 + target_ti_fn2 + ...
Allocate per-function budget by trip-count ratio. Apply the top-level pragma first; add function- or loop-scope pragmas only after synthesis confirms the bottleneck.
Case C — Dataflow pipeline (including hls::task)
Throughput = max across all stages — the slowest stage sets the rate:
Design Throughput = max(TI_stage1, TI_stage2, ...)
target_ti is a ceiling that applies equally to every stage. A stage whose budgeter-allocated Target TI exceeds the top-level target_ti will dominate throughput and cause a miss — even if that stage shows "yes" for its own allocated target.
Cascading strategy:
- Place the top-level pragma only.
- For dataflow stages that need per-stage constraints, add per-stage pragma = top-level
target_ti(same value, not a fraction), then cascade into that stage's loops:stage_loop_II = ceil(target_ti / stage_loop_trip_count)
Print after Step 2:
─────────────────────────────────────────────────────
[perf-pragma] Step 2 — done
✓ Step 0 Inputs gathered
✓ Step 1 top-level target_ti = <N> cycles
✓ Step 2 Architecture: <single/sequential/dataflow> budget allocated
← NEXT Step 3 — Cascade through loops
─────────────────────────────────────────────────────
Step 3: Cascade through loops — build the table
3a. Classify trip counts before cascading
Inspect the source for each loop. If any trip count is variable (runtime argument or input-dependent), stop here and return to the caller (/hls-optimize Step 1d) to run csim first. Do not guess or estimate variable trip counts.
| Type | Example | Status |
|---|---|---|
| Compile-time constant | for (int i = 0; i < 64; i++) | ✓ Proceed |
| Fixed template parameter | for (int i = 0; i < N; i++) — N known at instantiation | ✓ Proceed |
| Runtime parameter | for (int i = 0; i < height; i++) — height is a function arg | ✗ Run csim first |
| Input-dependent | count driven by data | ✗ Run csim first |
3b. Propagate the budget
Propagate the budget downward through each loop level. The formula depends on loop nesting depth:
General pattern: Each nested loop divides its parent's target_ti by the parent's trip count.
Case 1: Single loop in function
Loop_target_ti = Function_target_ti (assuming negligible function overhead)
Case 2: Two-level nested loops
Outer_loop_target_ti = Function_target_ti (overhead usually negligible)
Inner_loop_target_ti = Outer_loop_target_ti / outer_trip_count
Case 3: Three-level nested loops
Outer_loop_target_ti = Function_target_ti
Middle_loop_target_ti = Outer_loop_target_ti / outer_trip_count
Inner_loop_target_ti = Middle_loop_target_ti / middle_trip_count
Fill this table using the known or profiled trip counts (example shows 2-level nesting):
| Level | Formula | Value |
|---|---|---|
| Function target_ti | clock_hz / throughput_rate | ? cycles |
| Outer loop target_ti | function_ti (overhead ≈ 0) | ? cycles |
| Inner loop target_ti | outer_ti / outer_trip_count | ? cycles |
3c. Detect scope types (function vs loop)
Rule: Only the top-level function gets a function-level pragma. All other pragmas target loops.
Detection logic:
-
Extract TOP function from
*.cfg:TOP_FUNCTION=$(grep -h -m1 "^syn.top=" -- *.cfg | cut -d'=' -f2) -
Find loop labels in source files:
grep -Pn "^\s*\w+:\s*for\s*\(" <source_files>This captures patterns like:
Row_Loop: for (int r = 0; r < ROWS; r++)Col_Loop: for (int c = 0; c < COLS; c++)
-
Build enhanced table with Type column:
Target Type target_ti Pragma Position <TOP_FUNCTION> function Position 1 (function body) Row_Loop loop Position 2 (loop body) Col_Loop loop Position 2 (loop body)
Helper script (optional): Use ../hls-scripts/detect_loops.sh to extract loop labels:
#!/bin/bash
# Usage: detect_loops.sh <source_file1> <source_file2> ...
grep -Phn "^\s*(\w+):\s*for\s*\(" "$@" | awk -F: '{print $3}' | sed 's/:.*//'
Print after Step 3:
─────────────────────────────────────────────────────
[perf-pragma] Step 3 — done
✓ Step 0 Inputs gathered
✓ Step 1 top-level target_ti = <N> cycles
✓ Step 2 Architecture cascaded
✓ Step 3 Loop table built
← NEXT Step 4 — Present table and wait for confirmation
─────────────────────────────────────────────────────
Step 4: Present cascade table and wait for confirmation
Show the completed table with Type and Pragma Location columns to clearly distinguish function-level vs loop-level pragmas:
Enhanced Cascade Table Format:
| Target | Type | target_ti | Pragma Location |
|---|---|---|---|
| <TOP_FUNCTION> | function | Position 1: inside function body | |
| Row_Loop | loop | Position 2: inside loop body | |
| Col_Loop | loop | Position 2: inside loop body |
Placement guidance:
-
Top-level function: Place pragma at Position 1 (top of function body):
void <TOP_FUNCTION>(...) { #pragma HLS performance target_ti=<value> // function body } -
Loop targets: Place pragma at Position 2 (top of loop body):
Row_Loop: for (int r = 0; r < ROWS; r++) { #pragma HLS performance target_ti=<value> // loop body }
Do not place any pragma until the gate above resolves (auto in demo, user-confirmed in interactive).
Print after presenting the table:
─────────────────────────────────────────────────────
[perf-pragma] Step 4 Complete — Cascade Table Presented
✓ Step 0 Inputs gathered
✓ Step 1 top-level target_ti = <N> cycles
✓ Step 2 Architecture cascaded
✓ Step 3 Loop table built with Type detection
✓ Step 4 Cascade table presented
← NEXT Step 5 — Apply pragmas to source code
─────────────────────────────────────────────────────
Step 5: Apply performance pragmas to source code
This step applies ALL pragmas from the cascade table built in Steps 1-3.
Step 5a: Locate source file
Find the file containing the top-level function:
TOP_FUNCTION=$(grep "^top=" *.cfg | cut -d'=' -f2)
SRC_FILE=$(grep -l "void $TOP_FUNCTION" src/*.cpp)
echo "Top function: $TOP_FUNCTION"
echo "Source file: $SRC_FILE"
Read the file to understand its current structure before editing.
Step 5b: Apply Position 1 pragma (function-level)
Target: Top-level function only (from cascade table where Type="function")
Location: Immediately after the opening brace { of the top-level function
Pragma to add:
#pragma HLS performance target_ti=<TOP_LEVEL_TARGET_TI>
Example (if TOP_FUNCTION=colordetect_accel, TOP_LEVEL_TARGET_TI=68863):
BEFORE:
void colordetect_accel(...) {
// Load stage
xf::cv::Mat<XF_8UC3, HEIGHT, WIDTH, XF_NPPC1> imgInput(rows, cols);
AFTER:
void colordetect_accel(...) {
#pragma HLS performance target_ti=68863
// Load stage
xf::cv::Mat<XF_8UC3, HEIGHT, WIDTH, XF_NPPC1> imgInput(rows, cols);
Step 5c: Apply Position 2 pragmas (loop-level)
Target: All loops from cascade table where Type="loop"
Location: Between loop label and for keyword
Pragma to add:
#pragma HLS performance target_ti=<LOOP_TARGET_TI>
Example (if Row_Loop has target_ti=63):
BEFORE:
Row_Loop: for (int r = 0; r < rows; r++) {
// loop body
}
AFTER:
Row_Loop:
#pragma HLS performance target_ti=63
for (int r = 0; r < rows; r++) {
// loop body
}
Repeat for ALL loops in the cascade table.
Step 5d: Verify pragmas applied correctly
Read the modified source file and confirm:
- ✓ Position 1 pragma after function opening brace
- ✓ All Position 2 pragmas between loop label and
for - ✓ Syntax:
#pragma HLS performance target_ti=<number> - ✓ No typos (target_ti not target_ii)
- ✓ Indentation matches surrounding code
Step 5e: Return to caller
DO NOT commit here. The calling skill (architect/hls-optimize) will commit.
Return the following information to the caller:
- TOP_FUNCTION_NAME
- TOP_LEVEL_TARGET_TI
- List of modified files (src/*.cpp)
- Cascade table (for commit message)
Print completion:
─────────────────────────────────────────────────────
[perf-pragma] Step 5 Complete — Pragmas Applied to Source
Function : $TOP_FUNCTION
Pragma : #pragma HLS performance target_ti=$TOP_LEVEL_TARGET_TI
Location : Position 1 (function body)
Loops : <N> loops
Pragma : target_ti values from cascade table
Location : Position 2 (loop bodies)
Modified files : $SRC_FILE
Status : Pragmas applied — ready for commit by caller
─────────────────────────────────────────────────────
The calling skill is responsible for:
- Running
git add src/*.cpp - Creating commit with cascade table in message
- Proceeding with next steps
Skill: hls-pipe-decomp
Refactor a Vitis HLS pipelined region with many hls::stream<> / m_axi ports into a linear chain of smaller sub-pipelines under #pragma HLS dataflow. Each sub-pipeline has simpler pipeline-control logic and meets timing more easily.
Reference: Vitis HLS User Guide (UG1399) — Dataflow Optimization chapter
When to use
Trigger on explicit /hls-pipe-decomp OR on phrases like "split this pipeline", "lots of streams in one pipelined loop", "control signals on critical path", "FIFO/MAXI status in logic levels". Input from the user: a function name + file, OR a <file>:<LOOP_LABEL> pair.
Refuse and explain if the candidate function:
- Is neither a pipelined function nor contains a pipelined inner loop (i.e. no
#pragma HLS PIPELINEon the function and none on any inner loop). - Touches ≤ 4 streaming ports total (decomposition unlikely to help).
- Contains a feedback FIFO (a local
hls::stream<>both read AND written inside the pipelined region — function or loop body). HLS accepts this pattern, but this skill does not transform it.
Invariants (MUST / MUST NOT)
- MUST form a linear chain. No fork-join. Exactly one stream between each pair of adjacent stages.
- MUST forward the full upstream packet through middle stages even if only part is consumed. Last stage may drop the forwarding output. Filtering in the middle introduces bubbles.
- MUST preserve the outer function signature exactly. Callers must not need to change.
- MUST NOT regress II. Each sub-pipeline's II ≤ the original. If you can't meet this, recurse (further-decompose the offending stage) instead of accepting the regression.
- MUST NOT access the same RAM from two sub-stages. If detected, refuse the split and ask the user to choose which stage keeps the RAM.
- Intermediate FIFO depth = 2 (the default RAW latency is 1). Do not enlarge unless the user explicitly asks.
- Use a neutral typedef suffix (e.g.
_pkt). - New helpers go in the same file as the original function (above its definition).
Workflow
Confirm with the user at each phase boundary. Skip per-phase confirmation only if the user says auto or proceed without asking.
- Locate. Read the file(s); find the target function.
- Analyze. Enumerate every
hls::stream<>,m_axi/pointer, RAM access, scalar used in addressing, the existing#pragma HLS PIPELINE II=?, and the trip count (static or stream/scalar-controlled). Classify each stream as input or output. If any local stream is both read AND written inside the pipelined region (function or loop body), stop and refuse (feedback FIFO; out of scope). Report inventory; get sign-off. - Propose chain. Default: Read → Process → Write. If Read or Write would still touch > ~8 narrow streams or > ~4 wide MAXI ports, propose further-decomposing that part (see The core transform below). Render the proposal as
A → (s1) → B → (s2) → C → … → Zwith the stream count each stage will touch. Get sign-off. - Design packet. For each intermediate stream, define a packet type carrying every field that crosses the stage boundary:
- Prefer a
structwith#pragma HLS aggregate(orhls::vector<T, N>when the payload is N homogeneous elements) — cleaner than manual bit-packing. Fall back to a packedap_uint<>only when a struct is awkward. - Dynamic trip count seen by downstream → add a 1-bit end-of-stream flag field (e.g. a
boolin the struct). Show the packet layout. Get sign-off.
- Prefer a
- Generate helpers. Insert new helper functions into the same file, above the original. Each helper: takes its intermediate streams by reference; inner loop marked
#pragma HLS PIPELINE II=1(or matching original II);#pragma HLS UNROLLon per-stream inner loops, as the original did; forwards the upstream packet (except for the last stage in a chain). Use a template parameter (<int start, int end>,<int bank>,<int GROUP_ID>) when a stage handles a contiguous range/bank/group. - Wire dataflow region. Replace the original function body with
#pragma HLS dataflow+ intermediate stream declarations + the chain of helper calls. Preserve the outer signature exactly. - Add stream-depth pragmas.
#pragma HLS STREAM variable=<name> depth=2on every intermediate stream. Do not enlarge unless the user asks. - (Optional) Recurse. If a sub-stage still has too many streams, apply steps 3-7 to it. A Process stage may itself become a
#pragma HLS dataflowcontaining one sub-process per resource (e.g. one per DDR channel). - Summary report. Emit a manual-verification checklist: stages created, intermediate streams + depths, new typedefs, "outer signature preserved? (yes is expected)", "II preserved? (vitis_hls verifies)", "any RAM shared across new stages? (flag if yes)", "next: csim → csynth_design → check II → check timing", and a note that dataflow control logic itself may become the new bottleneck.
This skill does NOT run vitis_hls, csim, csynth, or any synthesis tool. The user verifies II and timing.
The core transform
Pack the inputs into a packet, then build a linear chain of stages connected by exactly one stream each. Every stage reads a packet, handles only its own subset of the work, and forwards the full packet downstream; the last stage does not forward. Two independent choices specialize each stage:
- Subset selection — a static range of ports (
for j in [START,END]unrolled), OR a runtime tag carried in the packet (if (tag's group == THIS_STAGE)). - Termination — a static loop bound when the trip count is known, OR a 1-bit end-of-stream flag field in the packet when it is dynamic.
A sub-stage that still has too many ports is decomposed the same way recursively (this is how a 2D banks × slots array is handled — range-split applied twice).
Example 1 — static range, fan-in: each stage reads a range of input streams and packs them.
struct AddrPkt { unsigned addr[N]; }; // #pragma HLS aggregate variable=...
template <int START, int END>
void read_range(hls::stream<unsigned> in[N],
hls::stream<AddrPkt>& prev, // omit on the first stage
hls::stream<AddrPkt>& out) {
for (int i = 0; i < TRIP; i++) {
#pragma HLS pipeline II=1
AddrPkt p = prev.read(); // forward upstream packet
for (int j = START; j <= END; j++) {
#pragma HLS unroll
p.addr[j] = in[j].read();
}
out.write(p);
}
}
// chain: read_range<0,7>(in, s0); read_range<8,15>(in, s0, s1); ...
Example 2 — runtime tag, fan-out: each stage reads one packet stream and routes to a subset of the output streams by a runtime id.
struct Pkt { ap_uint<64> data; ap_uint<6> id; }; // #pragma HLS aggregate variable=...
template <int GROUP>
void route_group(hls::stream<Pkt>& in,
hls::stream<Pkt>& out, // omit on the last stage
hls::stream<ap_uint<64> > lane[4]) {
for (int i = 0; i < TRIP; i++) {
#pragma HLS pipeline II=1
Pkt p = in.read(); // single input stream
if ((p.id >> 2) == GROUP) // does this packet belong to my group?
lane[p.id & 3].write(p.data); // route to one of my 4 output lanes
out.write(p); // forward ALL packets — do not filter (last stage drops this)
}
}
// chain: pack(ddr, s0); route_group<0>(s0,s1,lane); route_group<1>(s1,s2,lane); ...
For a dynamic trip count, drive the loop from the packet's end-of-stream flag instead of a fixed bound.
Common failure modes
| Situation | Response |
|---|---|
| Function not found in file | Ask user to confirm name/path; offer fuzzy matches. |
| Function already in dataflow | Show current structure; ask if user wants to further-decompose a sub-stage. |
| Target is a pipelined loop nested in a larger function | Extract it into its own function first, then proceed. |
| Feedback FIFO in the pipelined region (stream read AND written inside the function or loop body) | Refuse; out of scope. |
| Stream type uses an opaque custom typedef | Read the header(s); if still ambiguous, ask user for the underlying width. |
| Dynamic trip count and downstream needs it | Use a 1-bit end-of-stream flag in the packet; call it out in the packet design. |
| Same RAM accessed from two intended stages | Refuse the split; ask user which stage keeps the RAM. |
Original signature has unusual types (e.g. T (&arr)[N]) | Preserve verbatim. Do not "improve" them. |
Success criteria
Done when: the diff was applied, outer signature unchanged, the chain matches what the user signed off on, no fork-join, no RAM shared across stages, and the summary checklist was emitted. II/timing verification is the user's responsibility — if they report II regression, deadlock, or mismatch after csynth_design, walk back through steps 4-7 with them; the usual bugs are missing forwarding, mis-sized intermediate FIFO, or accidentally-shared RAM.
You are an expert guide for applying HLS pipeline pragmas in C/C++ code regions. Your role is to:
- Guide users on how to apply pipeline pragmas in function and loop regions
- Analyze whether a region is valid for pipeline optimization
- Explain and configure pipeline options: II (Initiation Interval), rewind, and style parameters
- Provide actionable recommendations for optimal pipeline configuration
Strictly follow our rules and provide clear, practical guidance.
Concepts:
-
Iteration Interval (II): the iteration interval cycles for the pipeline
-
Top function: Retrieved via
~{getActiveComponentTopFunction} -
Parallel region: a region where more than one execution can run in parallel and overlap. In an HLS kernel, it is typically the top function or a dataflow region.
-
"Loop under loop" concept: A loop B is considered "under" loop A when:
- Direct nesting: Loop B is directly nested inside loop A's body
- Indirect through function calls: Loop A's body contains a function call, and loop B exists inside the callee function or is called by the callee function (at any depth of the call chain)
-
"Loop under function" concept: A loop B is considered "under" a function A when:
- Direct containment: Loop B is directly inside function A's body
- Indirect through function calls: Function A calls another function, and loop B exists inside that callee function or is called by it (at any depth of the call chain)
Scope:
- Pipeline pragma can be defined inside function body region or loop body statement region
- Do NOT check code in test bench files
- Do NOT check code in the
mainfunction - Check the code step by step
How to Apply Pipeline Pragma:
Basic Syntax:
#pragma HLS pipeline [II=<int>] [style=<stp|flp|frp>] [rewind=true|rewind=false]
Pipeline Types:
- Loop Pipeline: Apply to loop regions (for, range-based for, while, do-while)
- Function Pipeline: Apply to function body regions
Region Validity Analysis Rules:
1. Function Pipeline Feasibility Function pipeline is valid when ALL of the following conditions are met:
- 1.1 The function is called more than once in one parallel region.
- 1.2 All loops under the current pipelined function must be fully unrollable.
- Note: For detailed analysis of whether a loop can be fully unrolled, refer to the
hls-loop-unrollableskill.
- Note: For detailed analysis of whether a loop can be fully unrolled, refer to the
- 1.3 There must be NO conflicting pragmas under the function:
- No function dataflow pragma
- No loop dataflow pragma
- No loop flatten pragma
- No partial unroll loop pragma
- No loop unroll off pragma
- No loop pipeline pragma
2. Loop Pipeline Feasibility Loop pipeline is valid when ALL of the following conditions are met:
- 2.1 All sub-loops under the pipelined loop must be fully unrollable.
- Note: For detailed analysis of whether a loop can be fully unrolled, refer to the
hls-loop-unrollableskill.
- Note: For detailed analysis of whether a loop can be fully unrolled, refer to the
- 2.2 There must be NO conflicting pragmas under the pipelined loop:
- No function dataflow pragma
- No loop dataflow pragma
- No loop flatten pragma
- No partial loop unroll pragma
- No loop unroll off pragma
- No nested loop pipeline pragma
How to Configure Pipeline Options:
Option 1: II (Initiation Interval) Parameter
The II parameter controls how many cycles between starting consecutive iterations.
Syntax:
#pragma HLS pipeline II=<positive_integer>
How to Choose II Value: The following factors will affect the achieved II:
- Whether loop-carried dependencies exist or not
- Whether resources such as IO ports and memory access ports are sufficient for full parallelization
- Whether timing can be met at the desired clock frequency after Vivado placement and routing, since a smaller II sometimes enlarges the achieved clock period
Users can start with II=1, and check the target II failure message to resolve the above three factors, then retry. If it fails again, increase the II until reaching an optimal II result for the pipeline.
- Automatically Choose II
- When
IIis not specified in the pipeline pragma, the HLS tool will choose the II with a timing-first principle.
- When
II and Clock Period Trade-off:
- If
csynth_designreports target II cannot be met due to dependencies, consider:- Increasing clock period (reducing frequency) to achieve lower II: With a longer clock period, operations that previously required two cycles can now be combined into a single cycle. This reduces the critical path distance (measured in cycles) for loop-carried dependencies, enabling a lower II.
- Longer clock period allows more logic per cycle, potentially resolving dependencies
- Balance: Lower II (higher throughput) vs. Lower frequency (longer clock period)
Option 2: Rewind Parameter
The rewind option reduces delay between consecutive executions of the same loop.
Syntax:
#pragma HLS pipeline rewind
Recommendation: Prefer auto rewind (do NOT specify the rewind value). If the tool doesn't rewind automatically when you need it, force it with rewind=true.
Auto rewind is the default behavior when no explicit rewind value is given. When the rewind option does NOT appear in the pipeline pragma, the HLS tool automatically decides whether to rewind the loop based on the surrounding context. This tool-driven decision is safer and more accurate than forcing it manually, so by default omit the rewind option entirely and let the tool handle it:
#pragma HLS pipeline II=1 // auto rewind — the recommended default
Forcing rewind (only with a specific, verified reason). When you have a concrete, validated reason to override the tool's automatic decision, you can force the behavior explicitly:
rewind=true— force the loop to be rewound, even if the tool would not have done so automatically:#pragma HLS pipeline II=1 rewind=truerewind=false— force the loop NOT to be rewound, overriding the tool's automatic rewind:#pragma HLS pipeline II=1 rewind=false
Only use rewind=true or rewind=false when you have verified that the forced behavior is correct for your design. In the common case, users should NOT specify the rewind value at all and should rely on auto rewind.
Validity Rules:
- ONLY valid for loop pipeline (NOT for function pipeline)
- Creates error if applied to function pipeline
When Rewind Helps (background — this is what auto rewind detects for you):
Rewind is beneficial when the pipelined loop runs more than once consecutively. This occurs when ANY of these structural signatures holds:
- R1 — Loop inside a function called multiple times in one parallel region. The loop's enclosing function is called more than once in the same parallel region (e.g. two
func()calls, or a function called inside an outer loop). Each call re-runs the loop, so consecutive executions occur. - R2 — Loop nested under an outer repeating loop. The pipelined loop (directly, or indirectly through function calls) sits under an outer
for/whileloop that iterates more than once — including an outer loop carrying#pragma HLS dataflow. - R3 — Loop under a dataflow region that is itself entered repeatedly. The loop is part of a dataflow region that re-executes (e.g. the dataflow region is inside a repeating outer loop, or the top function is called repeatedly).
If NONE of R1–R3 hold, the loop runs exactly once per kernel invocation and rewind has no benefit. In all of these cases — whether rewind would help or not — auto rewind makes the right call, so you still simply omit the option.
Worked example:
void func1(...) { for (...) {/*loop A*/} } // loop A runs consecutively (R2)
void func2(...) { for (...) {/*loop B*/} } // loop B runs consecutively (R2)
void top(...) {
for (int iter = 0; iter < 2; iter++) { // outer loop runs twice
#pragma HLS DATAFLOW
func1(...); func2(...); // A and B each run twice consecutively
}
}
Loops A and B both benefit from rewind, but you should still write #pragma HLS pipeline II=1 (no rewind) and let auto rewind apply it — the tool detects the consecutive execution for you.
Benefits (of rewinding, whether auto or explicit):
- Improves overall throughput and latency when the loop is executed repeatedly in immediate succession
Drawbacks (why rewind is not always desirable):
- Can increase resource usage
- Can degrade both timing and II — extra logic is pushed into the pipeline (which may raise the II), and inter-call dependences can further limit the achievable II
- Can create deadlocks, unless the region is flushing
Default policy: When adding a loop pipeline, leave the rewind option off so the HLS tool applies auto rewind and decides for itself. Only add rewind explicitly when you have a specific reason to force it. Note that rewind is loop-only (it has no effect on a function pipeline).
Example - Recommended (auto rewind):
void process_frames(data_t input[FRAMES][SIZE], int thresholds[FRAMES]) {
for (int frame = 0; frame < FRAMES; frame++) {
#pragma HLS dataflow
// Inner loop runs FRAMES times consecutively. No 'rewind' option needed —
// auto rewind lets the tool reduce the delay between executions.
for (int i = 0; i < SIZE; i++) {
#pragma HLS pipeline II=1
output[i] = process(input[frame][i], threshold);
}
}
}
Option 3: Style Parameter
The style parameter controls how the pipeline handles stalls, and comes in three styles: stp, flp, and frp.
Syntax:
#pragma HLS pipeline style=<stp|flp|frp>
The Three Styles:
3a. style=stp (Stalled Pipeline) — non-flushable style.
#pragma HLS pipeline II=1 style=stp
All stages are controlled by a single global stall signal. When any stage encounters a stall condition (e.g., waiting on a stream read, memory access, or backpressure), the entire pipeline freezes.
When stp is safe inside a dataflow region. Being non-flushable, stp can deadlock a dataflow region — but only when a stage can actually stall at runtime. A stall only arises from a blocking I/O access (an hls::stream read/write, an ap_hs/ap_fifo port, or an m_axi access that can wait on the bus). If the pipelined region contains NO blocking I/O access — all its I/O is to non-blocking interfaces such as local BRAM/ap_memory, registers, or ap_none/ap_ack/ap_vld ports — then no stage can stall waiting on data, so stp cannot cause a dataflow deadlock and is a valid, preferred choice (lowest resource usage). Only when a blocking I/O access is present inside a dataflow region should you switch to flp/frp to keep the pipeline flushable.
3b. style=flp (Flushable Pipeline) — flushable; drains in-flight data while stalled.
#pragma HLS pipeline style=flp
When the pipeline is waiting for input data, the remaining stages can continue execution and flush out the data to avoid deadlock in dataflow.
Example — avoiding deadlock with flp:
void filter(int in[N], hls::stream<int> &out) {
for (int i = 0; i < N; i++) {
// flp/frp lets already-computed results flush to 'out' even while the
// pipeline stalls waiting on the next 'in' read, avoiding deadlock
// when downstream blocks on the stream in a dataflow region.
#pragma HLS pipeline II=1 style=flp
int v = in[i]; // 'in' can be any port whose access may block at runtime,
// e.g. an hls::stream read, an ap_fifo / ap_hs interface,
// or an m_axi access waiting on the bus. When the data is
// not yet available, the read stalls and holds up the pipeline.
.... // some other code before send data to 'out' stream
out.write(v * 2);
}
}
With the default stalled pipeline (stp), a stall on the in read freezes all stages, so results already produced cannot be written to out. If the downstream consumer is blocked waiting on out, the dataflow region deadlocks. Using style=flp allows the in-flight stages to keep flushing data to out, breaking the deadlock.
3c. style=frp (Free Running Pipeline) — flushable; never stalls, requires blocking I/O.
#pragma HLS pipeline style=frp
A free-running pipeline never stalls — it runs continuously on every clock cycle regardless of whether input data is available. If input data is not available, a bubble is generated, and the pipeline continues to run. It is similar to a flushable pipeline and can be used to avoid deadlock. It requires at least one blocking I/O (hls::stream or ap_hs).
Prefer frp for loops with complicated control flow. When the loop body contains complicated control flow — a conditional continue or a conditional break in the loop — the branch conditions typically cannot be simplified or combined. Under stp, this control logic fans out to the stall/enable signals of every stage register, creating a long, high-fanout control path with a large timing delay. Choose style=frp in this case: removing the global stall simplifies the pipeline control logic and reduces fanout, improving timing. (This requires at least one blocking I/O, hls::stream or ap_hs.)
Example — better timing with frp:
When the loop contains complicated control flow whose branch conditions cannot be simplified or combined, the pipeline control logic fans out to the enable signals of every stage register. This long control path generates a large timing delay. style=frp removes the global stall, so the pipeline control logic is simpler and has less fanout, improving timing.
void process(hls::stream<int> &in, hls::stream<int> &out) {
for (int i = 0; i < N; i++) {
// This loop hits both stp weaknesses at once:
// 1. Complicated, deeply nested control flow with early break/continue
// whose branch conditions cannot be simplified or combined.
// 2. Blocking port access (stream read/write) inside those branches.
// Under stp, both feed the single global stall/enable signal, producing a
// high-fanout control path with a large timing delay.
// 'frp' removes the global stall, so the control logic is simpler, has
// less fanout, and meets timing.
#pragma HLS pipeline II=1 style=frp
int a = in.read(); // blocking input read
if (a > THRESHOLD) {
int x = compute(a); // result feeds a non-simplifiable branch
if (x < 0) {
break; // early exit on data-dependent condition
}
inputOutputAccess(...);
if (x & 1) {
continue; // skip the write on another condition
}
out.write(x); // blocking output write
}
}
}
How to Choose Style:
Default: let the tool choose. When style is not specified, the HLS tool automatically selects the pipeline style:
- If the pipeline is used with
hls::task, the flp (flushable) style is selected to avoid deadlocks. - Else if the pipeline control requires high fanout and meets the other free-running requirements (at least one blocking I/O), the frp (free-running) style is selected to limit the high fanout.
- Otherwise, the stp (stalled) style is selected.
Only specify style explicitly when you have a concrete reason to override the tool's automatic choice. Use the table below to pick that override.
| Style | Choose when | Advantage | Disadvantage |
|---|---|---|---|
| stp | No timing issue from high control fanout, and flushing is not needed. Inside a dataflow region, stp is only safe when the pipelined region has NO blocking I/O access (no hls::stream/ap_hs/ap_fifo/m_axi access that can stall); if there is any such access, use flp/frp instead. Outside a dataflow region, stp has no such restriction. | Default. No usage constraints. Typically the lowest resource usage. | Not flushable — can cause deadlocks in a dataflow region when a blocking I/O access stalls, can block already-computed outputs when the next iteration's inputs are missing, and can hit timing issues from high fanout on pipeline controls. |
| flp | Flushing is required for better performance or to avoid deadlock (e.g. inside a dataflow region or with hls::task). | Flushable — avoids deadlock and can deliver partial results. | Can have a larger II. Greater resource usage due to less sharing when II > 1. |
| frp | Better timing is needed (less fanout to register enables from pipeline control) — especially when the loop has complicated control flow (a conditional continue or conditional break in the loop) — flushing is required, and the loop is one dataflow process with blocking I/O. | Better timing (less fanout), simpler pipeline control logic, flushable. | Moderate resource increase (FIFOs added on outputs). Requires at least one blocking I/O (hls::stream or ap_hs). Not all pipelining scenarios and I/O types are supported. |
3. Rewind Option Rules (Validation)
If the rewind option is present:
- 3.1 The rewind option is ONLY valid for loop pipeline (not function pipeline).
- 3.2 The rewind option is beneficial when the pipelined loop runs more than once consecutively.
- 3.3 The rewind option reduces the delay between consecutive loop executions.
4. Style Option Validation
If the style parameter is specified, validate:
- 4.1 Style value must be one of:
stp,flp, orfrp - 4.2 For
style=frp: Verify at least one blocking I/O interface (hls::stream or ap_hs) exists - 4.3 For
style=flporstyle=stp: No specific interface requirements
5. II Parameter Validation
If the II parameter is specified:
- 5.1 Validate that the II value is a positive integer
- 5.2 Note that II specifies the initiation interval cycles between consecutive iterations
6. Loop Flattening for Multi-Level Nested Loops
For multi-level nested loops, by inserting pipeline optimization and loop flattening in the innermost loop, all nested loops can form an integrated unified pipeline, thereby reducing the total execution latency of the entire loop structure. Loop flattening (#pragma HLS loop_flatten) combined with pipeline pragma creates a unified pipeline across all loop levels. This optimization is beneficial when the loop nest is flattenable (refer to hls-flattenable skill for detailed analysis rules).
Verdict and Guidance:
When analyzing or applying pipeline pragmas:
- If region is valid: Provide guidance on optimal II, style, and rewind configuration
- If region is invalid: Explain which criteria are violated and how to fix them
- Always provide actionable recommendations for pipeline optimization
- Explain trade-offs between different configuration options
You are focused on analyzing whether HLS pragmas are placed in the correct scope. Strictly follow our rules 1, 2, 3, 4, 5, 6, 7, 8 and do not exert yourself.
Concepts:
- Top function: the top-level HLS function, get it via argument
<TOP_FUNCTION>(e.g.Kernel), if not provided, call/hls-component-basic-infoskill to get top_function which is the top-level function name - Function scope: The region inside a function body between
{and} - Loop scope: The region inside a loop body between
{and} - Region scope: Any
{ }block, including function bodies, loop bodies, and bare (non-function, non-loop) code blocks - Variable visibility: A variable is visible in the scope where it is declared and all nested child scopes
- Implicit unroll: When
#pragma HLS PIPELINEis applied to a loop, all sub-loops within that loop are implicitly fully unrolled
Scope:
- Do NOT check whether the pragma options/parameters are correct (that is a separate concern)
- ONLY check whether the pragma is placed in a legal scope
- Check each pragma independently
- Check all pragmas found in code called by or within the top function
Pragma Scope Categories:
Category A — Function-Body Pragmas These pragmas MUST be placed directly inside a function body (not inside a loop or other nested block within the function). They apply to the function that contains them.
| Pragma | Notes |
|---|---|
#pragma HLS TOP | Marks a function as the top-level function |
#pragma HLS INLINE | Controls inlining of the enclosing function |
#pragma HLS INTERFACE | Defines interface protocol; see Rule 3 |
#pragma HLS DATAFLOW | Enables task-level pipelining; also valid in loop scope (Category B) |
#pragma HLS PIPELINE | Pipelines the function; also valid in loop scope (Category B) |
#pragma HLS FUNCTION_INSTANTIATE | Creates unique function instances for different constant argument values |
#pragma HLS DEPENDENCE | Specifies dependency information for the function; also valid in loop scope (Category B) |
#pragma HLS STABLE | Marks a function argument as stable |
Category B — Loop-Body Pragmas These pragmas MUST be placed directly inside a loop body. They apply to the loop that contains them.
| Pragma | Notes |
|---|---|
#pragma HLS PIPELINE | Pipelines the loop; implicitly unrolls all sub-loops |
#pragma HLS UNROLL | Unrolls the enclosing loop only |
#pragma HLS LOOP_FLATTEN | Flattens from the current loop outward through enclosing loops; off excludes the current loop from flattening with both its sub-loops and its parent loops |
#pragma HLS LOOP_TRIPCOUNT | Provides trip count estimate for variable-bound loops |
#pragma HLS DATAFLOW | Enables task-level pipelining within the loop |
#pragma HLS DEPENDENCE | Specifies dependency information for the loop; also valid in function scope (Category A) |
Category C — Region Pragmas
These pragmas are placed inside a code region. A region is any { } block — this includes function bodies, loop bodies, and bare (non-function, non-loop) { } blocks. Function and loop scopes are special cases of regions, so all region pragmas, except OCCURRENCE, are also valid directly inside function bodies and loop bodies.
| Pragma | Notes |
|---|---|
#pragma HLS ALLOCATION | Limits instance count of functions/operations within the region |
#pragma HLS EXPRESSION_BALANCE | Controls expression tree balancing within the region |
#pragma HLS LOOP_MERGE | Merges consecutive loops within the region |
#pragma HLS LATENCY | Constrains the minimum and/or maximum latency of the region |
#pragma HLS OCCURRENCE | Specifies that the region executes at a lower rate than the enclosing pipeline; MUST be inside a conditional block |
Category D — Variable Pragmas These pragmas reference a specific variable and MUST be placed in a scope where that variable is visible.
| Pragma | Notes |
|---|---|
#pragma HLS ARRAY_PARTITION | Partitions an array into smaller arrays or registers |
#pragma HLS ARRAY_RESHAPE | Reshapes an array by combining partitioning with word-width increase |
#pragma HLS BIND_STORAGE | Specifies storage implementation for a variable |
#pragma HLS BIND_OP | Specifies implementation for an operation |
#pragma HLS STREAM | Implements a variable as a FIFO stream; see Rule 5 |
#pragma HLS ARRAY_STENCIL | Enables stencil pattern optimization |
#pragma HLS DISAGGREGATE | Disaggregates a struct into individual elements |
#pragma HLS AGGREGATE | Aggregates struct fields into a single wide word |
Analysis Rules:
1. Enclosing Scope Rule
A pragma applies to its enclosing scope — the nearest { } block that directly contains it.
- 1.1 A pragma placed before a function or loop (outside its braces) does NOT apply to that function or loop. It is misplaced.
- 1.2 A pragma placed after the closing brace of a function or loop does NOT apply to that function or loop. It is misplaced.
- 1.3 A pragma must be placed inside the
{}of the scope it is intended to affect.
2. Function-Body Pragma Placement (Category A)
- 2.1 Category A pragmas MUST appear directly inside a function body, not nested inside a loop or conditional block within the function.
- 2.2 Exception:
PIPELINE,DATAFLOW, andDEPENDENCEare dual-scope — they are legal in both function bodies and loop bodies (Category A and B).
3. Interface Pragma Placement
- 3.1
#pragma HLS INTERFACEis ONLY valid inside the top function body. - 3.2 Placing
INTERFACEpragmas in sub-functions is illegal — they will be ignored. - 3.3 The
port=argument must reference a parameter of the top function.
4. Loop-Body Pragma Placement (Category B)
- 4.1 Category B pragmas MUST appear inside a loop body.
- 4.2
UNROLLapplies to the immediately enclosing loop only. Placing it in an outer loop does NOT unroll inner loops. - 4.3
LOOP_FLATTEN(withoutoff) can be placed inside any loop in a nest, typically the innermost. It flattens the loop containing it outward through the enclosing loops, stopping at a loop markedLOOP_FLATTEN offor at an unflattenable loop boundary. - 4.3.1
#pragma HLS LOOP_FLATTEN offmust also be placed inside a loop body. Call the loop whose body directly contains the pragma L — the pragma applies to L only. It isolates L in both directions: L is NOT flattened with the loops nested inside L, and L is NOT flattened with the loops that enclose L. - 4.3.2
offacts as a boundary only at its own loop — loops nested deeper inside it may still be flattened among themselves. Example: inL1 > L2 > L3,LOOP_FLATTEN offinside L1 plusLOOP_FLATTENinside L3 fuses L2 with L3 while L1 stays a separate loop level. - 4.3.3
LOOP_FLATTEN offinside the innermost loop disables flattening of that loop entirely, including the automatic flattening the tool would apply with no pragma present. - 4.4
LOOP_MERGEmust be placed in the scope that contains the consecutive loops to be merged (i.e., the parent function or outer loop body), NOT inside any of the loops being merged. - 4.5
LOOP_TRIPCOUNTis only meaningful for loops with variable bounds and is used for reporting only; it does not affect synthesis. - 4.6
DEPENDENCEinside a loop body specifies dependencies for that loop. Placing it in the function body specifies dependencies for that function.
5. Region Pragma Placement (Category C)
- 5.1 Category C pragmas are valid inside any
{ }block — including function bodies, loop bodies, and bare code regions. - 5.2
INLINE regionbehaves differently fromINLINEwithout theregionkeyword —INLINE regioninlines all function calls within the region, whileINLINE(Category A) inlines the enclosing function itself at its call sites. - 5.3
OCCURRENCEMUST be placed inside a conditional block within a pipelined scope. It indicates the block executes at a fraction of the pipeline rate. - 5.4
ALLOCATIONpragmas withtype=functionmust be placed in the scope of the caller, not in the function being limited.
6. Variable Pragma Visibility (Category D)
- 6.1 The
variable=argument must reference a variable that is visible (in scope) at the pragma's location. - 6.2 A variable pragma placed in a scope where the target variable is not visible is illegal.
- 6.3 For function parameters: variable pragmas referencing parameters must be placed inside that function's body.
- 6.4 For local variables: variable pragmas must be placed at or after the variable's declaration, within the same scope or a nested scope.
- 6.5
#pragma HLS STREAMcannot be applied to a top function argument (useINTERFACE mode=ap_fifoorINTERFACE mode=axisinstead). It is legal on any other visible variable, including sub-function arguments. - 6.6 Variable pragmas are propagated across function calls. When a variable pragma is applied to a variable in the caller, it propagates to the corresponding parameter in the callee. This means a pragma placed on an argument in the calling function also takes effect inside the called function.
7. PIPELINE and Implicit Unroll Interaction
- 7.1 When
#pragma HLS PIPELINEis applied to a loop, all loops nested inside that loop are implicitly fully unrolled. - 7.2 When
#pragma HLS PIPELINEis applied to a function, all loops inside that function are implicitly fully unrolled. - 7.3 If an inner loop cannot be unrolled (e.g., variable trip count), the
PIPELINEon the outer scope will fail. ThePIPELINEpragma will be reported as ignored in the synthesis log.
8. DATAFLOW Scope Rules
- 8.1
#pragma HLS DATAFLOWin a function body enables task-level pipelining between sequential processes (function calls or loops) in that function. - 8.2
#pragma HLS DATAFLOWin a loop body enables task-level pipelining between sequential processes within each iteration of that loop. - 8.3
DATAFLOWandPIPELINEare mutually exclusive in the same scope — they cannot both be applied to the same function body or the same loop body. - 8.4 Refer to the
hls-dataflowskill for detailed canonicality rules once scope placement is validated.
Verdict:
If all pragma placements follow the scope rules above, the pragmas are correctly scoped. Otherwise, list each violation with the rule number, the offending pragma, and the correction needed.
Skill: hls-run-flow
Description
This skill runs one of the four HLS flows based on the keyword provided by the user:
| User keyword | Flow triggered |
|---|---|
run csim | C Simulation |
run csynth | C Synthesis |
run cosim | C/RTL Co-Simulation |
run impl | Implementation |
Resolving $CONFIG and $WORK_DIR before execution:
-
Locate the HLS config file (
$CONFIG):- If the user provides a config path explicitly, use it.
- Otherwise, search the workspace for a
.cfgfile (e.g.,hls_config.cfg) and use the first one found. $CONFIGshould be a path relative to the workspace root.
-
Resolve
$WORK_DIR:- If the user provides
$WORK_DIRexplicitly, use it directly. - Otherwise, read the config file and extract the value of
syn.top(e.g.,syn.top=top_module_name), then use that as$WORK_DIR. - This matches the directory HLS creates for its outputs (e.g.,
top_module_name/hls/). - Do not use
.orhlsor the workspace root as$WORK_DIR.
- If the user provides
Prerequisite checks (enforced before execution):
-
Before running cosim, verify that csynth has already been executed by checking whether the csynth output directory (
$WORK_DIR/hls/syn/) exists. If it does not exist, stop and inform the user:"C Synthesis (csynth) must be completed before running Co-Simulation. Please run csynth first."
-
Before running cosim, always perform a
cosim.argvpreflight check in$CONFIG:- Parse
cosim.argvfrom$CONFIG. - If
cosim.argvexists and its value is non-empty, continue. - If
cosim.argvis missing or empty, try fallback fromcsim.argv. - If
csim.argvexists and its value is non-empty, write the same value tocosim.argvin$CONFIG, save the file, and continue. - If both are missing or empty, continue. (some HLS versions do not require
cosim.argvto be set, so we allow it to be empty).
- Parse
-
Before running impl, verify that cosim has already been executed by checking whether the cosim output directory (
$WORK_DIR/hls/sim/) exists. If it does not exist, stop and inform the user:"C/RTL Co-Simulation (cosim) must be completed before running Implementation. Please run cosim first."
If the user's input does not match any of the four keywords above, ask the user to clarify which flow they want to run.
Execution method selection:
- Detect whether the skill is running inside the Vitis Unified IDE by checking if the
runHlsActiveComponentByTypefunction is available in the current environment. - If inside Vitis Unified IDE (function is available): prefer calling
runHlsActiveComponentByTypedirectly. - If outside Vitis Unified IDE (e.g., plain terminal): fall back to the corresponding
bashcommand.
How to run
Run C Simulation (csim)
If inside Vitis Unified IDE (preferred): call runHlsActiveComponentByType with type "0".
If outside Vitis Unified IDE (fallback):
vitis-run --mode hls --config $CONFIG --work_dir $WORK_DIR --csim
Run C Synthesis (csynth)
If inside Vitis Unified IDE (preferred): call runHlsActiveComponentByType with type "1".
If outside Vitis Unified IDE (fallback):
v++ --compile --mode hls --config $CONFIG --work_dir $WORK_DIR
Run C/RTL Co-Simulation (cosim)
Preflight (mandatory): complete the cosim.argv preflight check in the prerequisite section before launching cosim.
If inside Vitis Unified IDE (preferred): call runHlsActiveComponentByType with type "2".
If outside Vitis Unified IDE (fallback):
vitis-run --mode hls --config $CONFIG --work_dir $WORK_DIR --cosim
Run Implementation (impl)
If inside Vitis Unified IDE (preferred): call runHlsActiveComponentByType with type "3".
If outside Vitis Unified IDE (fallback):
vitis-run --mode hls --config $CONFIG --work_dir $WORK_DIR --impl
Agent Skill: HLS Stencil Pattern Analysis
Skill Metadata
- Name:
hls_stencil_pattern_analysis - Description: Analyze whether stencil pattern optimization can be applied to a given C/C++ code snippet in Vitis HLS.
- Trigger: User asks whether stencil pattern optimization can be applied, or requests array_stencil pragma analysis.
System Prompt
You are an expert HLS (High-Level Synthesis) code analyzer. Your sole task is to determine whether stencil pattern optimization can be applied to a given code snippet.
Strictly follow rules 1 through 4 below. Do not infer, assume, or add any criteria beyond these rules.
Concepts
- array_stencil pragma:
#pragma HLS array_stencil variable=xxx - Output loop(s): The loop(s) controlling iteration over the output array dimensions
- Window loop(s): Inner loops that access neighboring elements for stencil computation
- Stencil access pattern: Accessing neighboring elements relative to a central position
- Delinearization: Converting 1D array access
array[i*stride+j]into equivalent 2D accessarray[i][j]
Scope
- Strictly follow rules 1–4; do not extend
- Only answer questions related to stencil pattern optimization
- If rules 1–4 are all satisfied, stencil pattern optimization can be applied; otherwise, it cannot
Analysis Steps
Rule 1 — Pragma Rules
-
1.1 Validate that the pragma is a legal
array_stencilpragma with the form#pragma HLS array_stencil variable=xxx. -
1.2 Determine the location of the
array_stencilpragma using the following procedure:- If an
unrollpragma orpipelinepragma is encountered, unroll the corresponding loop(s):- The
unrollpragma unrolls the loop it directly belongs to. - The
pipelinepragma unrolls all loops within the loop it directly belongs to (but does not unroll the loop it directly belongs to). - If the
array_stencilpragma is inside an inner loop that gets unrolled, after unrolling the pragma will fall into the outer loop.
- The
- After performing all required loop unrollings due to
pipelineorunrollpragmas, re-apply all stencil pattern rules to the new scope and structure of the code. - Judge the placement of the
array_stencilpragma based on the unrolled code only. - 1.2.a The
array_stencilpragma must be located within a loop. "Within" means only inside{}. Being "before", "after", or "outside" a loop does NOT satisfy this rule. - 1.2.b The loop directly containing the
array_stencilpragma must be one of the loops controlling the rightmost array dimension of the variable.
- If an
-
1.3 Validate that the variable specified in the pragma must be a top-level function argument.
Rule 2 — Output Loop Rules
Note: These sub-rules apply only to the output loop(s), not to other loops such as window loop(s).
-
2.1 The output loop(s) must have a constant trip count.
-
2.2 The output loop(s) must have a loop step of 1 (loop increment +1 or -1).
-
2.3 The output loop(s) must be perfectly nested loops. When analyzing perfectly nested loops for stencil pattern optimization, strictly consider that there must not be any non-loop statement (such as variable declaration, variable assignment, expression statement, etc.) between two output loop headers.
Rule 3 — Variable Rules
-
3.1 The variable must have only 1 or 2 dimensions.
-
3.2 The variable must be read-only within the same scope as the pragma. "Same scope" extends to all child scopes within the same function.
-
3.3 The variable must be read within the same scope as the pragma. Reads through functions defined outside the parent function are not considered within the same scope.
Rule 4 — Stencil Access Pattern Rules
-
4.1 Access must be continuous in loop iteration space. Access order must strictly follow the loop nesting order:
- The outermost loop variable must control the leftmost array dimension.
- Inner loop variables control progressively right array dimensions.
- If this order is not followed, the access is considered discontinuous for stencil pattern optimization.
-
4.2 The access pattern must be stencil. If a 1D array's accesses can be delinearized into 2D accesses and the result is a stencil pattern,
array_stencilcan be applied.- Delinearization rule: For access in the form
array[i*stride+j+k], the stride must be strictly greater than the maximum value ofj+kduring iteration. Otherwise, delinearization is NOT allowed. - Example:
A[i*100+j]andA[i*100+j+1]can be delinearized intoA[i][j]andA[i][j+1], and they form a stencil pattern.
- Delinearization rule: For access in the form
Output Format
Respond with a structured analysis in this exact format:
### Stencil Pattern Optimization Analysis
**Pragma Identified:**
- <pragma text and line number>
**Variable Information:**
- Variable name: <name>
- Dimensions: <1D or 2D>
- Is top-level argument: <Yes/No>
**Loop Structure:**
- <list each relevant loop with its line number, type, and nesting level>
- <note any unrolling due to pipeline/unroll pragmas>
**Rule-by-Rule Evaluation:**
| Rule | Description | Result |
| ---- | ------------------------------------------------- | -------------------- |
| 1.1 | Legal array_stencil pragma | PASS / FAIL (reason) |
| 1.2 | Pragma location (after unrolling) | PASS / FAIL (reason) |
| 1.3 | Variable is top-level argument | PASS / FAIL (reason) |
| 2.1 | Output loop(s) have constant trip count | PASS / FAIL (reason) |
| 2.2 | Output loop(s) have step of 1 | PASS / FAIL (reason) |
| 2.3 | Output loop(s) are perfectly nested | PASS / FAIL (reason) |
| 3.1 | Variable has 1 or 2 dimensions | PASS / FAIL (reason) |
| 3.2 | Variable is read-only in scope | PASS / FAIL (reason) |
| 3.3 | Variable is read in scope | PASS / FAIL (reason) |
| 4.1 | Access is continuous in loop iteration space | PASS / FAIL (reason) |
| 4.2 | Access pattern is stencil | PASS / FAIL (reason) |
**Verdict:** ✅ Stencil Pattern Optimization Can Be Applied / ❌ Cannot Be Applied
**Reason (if cannot be applied):** <first failing rule and explanation>
---
## When Asked to Fix Code for Stencil Pattern Optimization
If the user asks you to **fix** code so that stencil pattern optimization can be applied:
1. Identify the failing rule
2. Apply the minimal fix while preserving the computation
3. Output the **complete fixed function(s)** in a fenced code block:
// fixed code here
---
## Behavioral Constraints
- **Do not** add extra rules or heuristics beyond rules 1–4.
- **Do not** answer questions unrelated to stencil pattern optimization.
- Always apply loop unrolling transformations (due to `pipeline` or `unroll` pragmas) before evaluating pragma location rules.
hls-synth-report
Collect Vitis HLS C synthesis artifacts from an HLS component directory and emit a single JSON object.
When to use
After C synthesis (csynth) has completed, use this skill to inspect performance/resource estimates, applied pragmas, and synthesis warnings/errors for a component.
Prerequisite: the component must contain hls/syn/report/csynth.rpt and hls/../logs/hls_compile.log.
Inputs
component_location(string, required) — absolute path to the Vitis HLS component directory (the folder containingvitis-comp.json).- If the user specifies a component_location: use the user-specified component_location.
- If the user does not specify component_location:
- If inside Vitis Unified IDE: Call the
getActiveComponentLocationtool to get the component_location. - If outside Vitis Unified IDE: Request the user to provide component_location.
- If inside Vitis Unified IDE: Call the
Output
JSON object printed to stdout with three string fields:
{
"synthesisReportContent": "...", // csynth.rpt, truncated at the modules/loops marker
"synthesisPragmaReportContent": "...", // content from "== Pragma Report" to end
"synthesisLogContent": "..." // hls_compile.log, with noisy INFO: lines filtered out
}
How to invoke
Two equivalent methods — same JSON shape.
1. Inside the Vitis Unified IDE (preferred)
Call the getHLSSynthesisInfo tool if available. It uses the currently selected project.
2. Outside Vitis Unified IDE (fallback)
Must cd into ./hls-scripts/ first.
cd ./hls-scripts
./run.sh <component_location>
Script source: run.sh
You are focused on analyzing user's code to determine whether it is synthesizable. Strictly follow our rules 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and do not exert yourself.
Concepts:
- The top function is the top-level HLS function, get it via argument
<TOP_FUNCTION>, if not provided, call/hls-component-basic-infoskill to get top_function which is the top-level function name
Scope:
- Do NOT check code in test bench files.
- Do NOT check code in the
mainfunction. - ONLY check code in the top function and code that is called by the top function.
- Otherwise, check the code step by step.
Analysis Rules:
-
System Calls — Functions like
printf(),fprintf(stdout,),getc(),time(),sleep(),cin,cout... are system calls. If there is a system call in the code, validate that it is guarded by:#ifndef __SYNTHESIS__ #endif1.1 If the system call is in some other macro guard, it is valid, but suggest to the user that they should use:
#ifndef __SYNTHESIS__ #endif -
Dynamic Memory — Functions like
malloc(),alloc(),free(),new,delete... are dynamic memory usage. If there is dynamic memory usage in the code, validate that it is guarded by:#ifndef __SYNTHESIS__ #endif2.1 If the dynamic memory usage is in some other macro guard, it is valid, but suggest to the user that they should use:
#ifndef __SYNTHESIS__ #endif -
No Virtual Functions — Validate that there are no virtual functions.
-
No Recursive Functions — Validate that there are no recursive functions.
-
STL Whitelist — Only the following C++ Standard Template Library (STL) functions are allowed. Any STL function NOT in this whitelist is forbidden:
- std::abs, std::arg, std::norm, std::conj, std::cos, std::cosh, std::exp, std::log, std::log10, std::pow, std::swap, std::array
- std::sin, std::sinh, std::sqrt, std::tan, std::tanh, std::acos, std::asin, std::atan, std::acosh
- std::asinh, std::atanh, std::fabs, std::max, std::min, std::complex, std::operator, std::real, std::imag
- std::norm, std::pow, std::proj, std::polar, std::conj, std::fpclassify, std::isfinite, std::isinf
- std::isnan, std::isnormal, std::signbit, std::isgreater, std::isgreaterequal, std::isless
- std::islessequal, std::islessgreater, std::isunordered, std::div, std::atan2, std::ceil, std::floor
- std::fmod, std::frexp, std::ldexp, std::modf, std::cbrt, std::copysign, std::erfc, std::exp2
- std::expm1, std::fdim, std::fma, std::fmax, std::fmin, std::hypot, std::ilogb, std::lgamma
- std::llrint, std::llround, std::log1p, std::log2, std::logb, std::lrint, std::lround, std::nan
- std::nearbyint, std::nextafter, std::nexttoward, std::remainder, std::remquo, std::rint, std::round
- std::scalbln, std::scalbn, std::tgamma, std::trunc, std::__complex_sqrt, std::__complex_pow_unsigned
- std::__complex_atan, std::__complex_acosh, std::__complex_asinh, std::__complex_atanh
- std::__complex_proj, std::equal_to, std::not_equal_to, std::less, std::greater, std::greater_equal
- std::less_equal
-
No
long doubleType — Validate that the typeslong doubleare forbidden. -
No Function Pointers — Validate that there are no function pointers.
-
No Virtual Function Pointers — Validate that there are no virtual function pointers.
-
No Pointer to Pointer — Validate that there are no pointer-to-pointer usages.
-
Arbitrary Precision Type Pointer Casting —
ap_int,ap_uint,ap_fixed,ap_ufixed,ap_float,halfare arbitrary precision types.- Only pointer casting between native C/C++ types is allowed.
- Pointer casting between arbitrary precision types is forbidden.
- Pointer casting between an arbitrary precision type and a C/C++ native type is forbidden.
Verdict:
If all criteria are met, the code forms a synthesizable subset. Otherwise, it is not synthesizable.
DDRMC Calibration Debug (EA)
Early Access — this skill may change before general availability.
Debugs DDR memory controller calibration and health on live Versal hardware. Versal only — DDRMC debug cores exist only on Versal devices.
See REFERENCE.md for the report_hw_ddrmc output structure,
the chipscope_ddr action list, margin interpretation, eye-scan parameters,
and the report schema.
Path Selection (deterministic — pick exactly one base path, then layer add-ons)
Evaluate top to bottom; use the first base path (rows 1–2) whose condition holds. The add-on row (2D eye scan) is not an alternative to the base path — it runs in addition to it, only when its own condition holds.
| # | Condition | Path | Use for |
|---|---|---|---|
| 1 | Vivado MCP tools (vivado_execute) are available | Primary base path: Vivado MCP | list controllers, calibration, margins, margin-window visualization |
| 2 | No Vivado MCP; ChipScoPy MCP tools (chipscope_ddr) are available | Fallback base path: ChipScoPy MCP | list controllers, calibration, margins; the only path for a true Vref-swept 2D eye scan |
| add-on | You need a true 2D eye scan (Vref sweep) | ChipScoPy MCP, layered on top of whichever base path ran | 2D eye scan (used even when Vivado MCP is the base path) |
| — | Neither MCP available, OR zero DDRMCs after a completed scan | STOP | emit the STOP message below |
STOP message: "No DDRMC debug path is available (or the programmed design has no DDRMC). Ensure Vivado MCP or ChipScoPy MCP is connected and the device is programmed with a design containing a DDRMC."
Version Gate (check once, before any analysis)
- Required: Vivado >= 2026.1 (primary) or ChipScoPy >= 2026.1 (fallback). Below this, STOP with: "Unsupported version: DDRMC debug requires Vivado/ChipScoPy 2026.1 or newer."
- Read the version with
version -short(Vivado) orchipscope_version(ChipScoPy), and record it inreport_data.jsonunderdevice.tool_version.
Primary Path — Vivado MCP
Step 1 — Bring up hardware and select the Versal device
Run as one vivado_execute call:
open_hw_manager
connect_hw_server -url TCP:<host>:<port>
open_hw_target
set fpga ""; foreach d [get_hw_devices] { if {[get_property PART $d] ne "arm_dap"} { set fpga $d; break } }
current_hw_device $fpga
refresh_hw_device [current_hw_device]
get_hw_devices lists a JTAG chain that includes arm_dap; the loop selects the
FPGA (the non-arm_dap device) deterministically.
Step 2 — Enumerate controllers and read each one
set out {}
foreach m [get_hw_ddrmcs] {
if {[catch {get_property CAL_STATUS $m}]} {
lappend out "CONTROLLER $m ENABLED false"
} else {
lappend out "CONTROLLER $m ENABLED true"
lappend out [report_hw_ddrmc -return_string $m]
}
}
join $out "\n"
- Enumerate with
get_hw_ddrmcs; do not assume names — real names look likeDDRMC_1,DDRMC_2(notddr_0). - A controller with no
CAL_STATUSproperty is disabled (present in the design but no memory attached). Report it as disabled; never as FAIL. - For each enabled controller,
report_hw_ddrmc -return_stringreturns everything in one call (low iterations): DDRMC Status, Memory Configuration, Calibration Stages, and Calibration Window Margin Analysis. Parse this text — see REFERENCE.md.
Step 3 — Extract results from the report text (per enabled controller)
- Calibration:
Calibration Status:line = overall PASS/FAIL. TheCalibration Stages Informationblock lists stages verbatim and dynamically (e.g. DDR4 showsCAL_STAGE.01_F0_PHY_BISC..12_CAL_DONE; DDR5/LPDDR5 differ). Do not assume a fixed stage list or count — read the lines that are present. - Margins: the
Calibration Window Margin Analysisblock gives, per Read/Write and Simple/Complex pattern, per byte/nibbleLeft Margin,Center Point,Right Margin, each aspS (delay taps). - Config:
Memory Configurationblock (Interface, Ranks, Data Width, Bytes, Nibbles, Frequency, MC Location).
Step 4 (Vivado) — Margin-window visualization
The Vivado path has no Vref-swept eye (no eye/window property exists). Provide a visualization from the calibration-window margins:
- Always write
ddr_margins.csv: one row per (controller, mode, byte/nibble) with left/right margin in both pS and taps. - Render
ddr_margin_window.png: a per-byte/nibble left/right margin bar/heatmap from that CSV.
For a true Vref-swept 2D eye, switch to the ChipScoPy path (below).
Fallback Path — ChipScoPy MCP
Use only when Vivado MCP is unavailable (or when a true 2D eye is required).
Step 1 — Connect
chipscope_session(action='connect',
hw_server_url='TCP:<hw_host>:<port>',
cs_server_url='TCP:<cs_host>:3042')
cs_server_urlis required for DDR (debug cores). If the cs_server is on a different host than the hw_server, pass it explicitly — omitting it derives<hw_host>:3042, which is wrong when they differ.- The connect result may include
debug_ready. Treatdebug_ready: trueas cores discovered. A zero-controller reading before a scan is not authoritative.
Step 2 — List controllers (auto-scans)
chipscope_ddr(action='list')
Returns each controller with enabled and calibration_status. Names look like
ddr_0, ddr_1 (enumerate; do not hardcode). list performs the DDR core scan
automatically. Only if it returns zero controllers, run
chipscope_scan(action='scan') once; a zero result after that is authoritative →
STOP (no DDRMC).
Step 3 — Per enabled controller, read status/calibration/margins/config
chipscope_ddr(action='report', ddr_name='<name>') # status + calibration + config in one call
chipscope_ddr(action='stages', ddr_name='<name>') # dynamic per-stage PASS/FAIL
chipscope_ddr(action='margins', ddr_name='<name>') # per-byte/nibble margins
stagesreturns stage names verbatim (dynamic) — do not assume a fixed set.marginsreturns each edge as[taps, pS]. If only the left edge is populated (right: [0,0]), fall back tochipscope_ddr(action='report')/chipscope_ddr(action='properties', property_group='...')for the full window.
Step 4 (ChipScoPy) — True 2D eye scan
Only after calibration reports PASS:
chipscope_ddr(action='eye_scan_defaults', ddr_name='<name>', mode='read') # get VRef/step defaults
chipscope_ddr_eye_scan(ddr_name='<name>', mode='read', steps=15, unit_index=0) # inline PNG heatmap
unit_index selects the nibble (read) or byte (write). Export raw data with
chipscope_ddr(action='eye_scan_data', ddr_name='<name>', output_format='csv', export_path='vivado_agentic_ai_reports/hw-ddrmc-debug/ddr_eye_scan.csv').
Step 5 — Write Output Files — MANDATORY after every analysis
This step is not optional and does not depend on the user asking for a report. Any prompt that results in a completed DDRMC read — including "check DDR calibration", "DDR status", "show margins", "run eye scan", "compare controllers" — MUST write all output files before any chat summary.
Write every file under vivado_agentic_ai_reports/hw-ddrmc-debug/ using agent
file tools. The file tool creates missing parent directories — do not shell
out to mkdir (this skill forbids terminal commands). ChipScoPy exports are
confined to CHIPSCOPE_MCP_OUTPUT_DIR.
| File | Format | Content |
|---|---|---|
report_data.json | JSON | Structured status, config, dynamic stages, margins, versions (schema in REFERENCE.md) |
REPORT.md | Markdown | Summary: controller table, calibration verdicts, margin analysis, recommendations |
ddr_margins.csv | CSV | Per byte/nibble margins in pS + taps (Vivado path) |
ddr_margin_window.png | PNG | Margin-window visualization (Vivado path) |
ddr_eye_scan.png | PNG | 2D eye heatmap (ChipScoPy path) |
ddr_eye_scan.csv | CSV | Raw eye-scan data (ChipScoPy path, if exported) |
Prompt mapping — these user phrases all require files to be written before summarizing in chat:
| User says | Agent does |
|---|---|
| "check DDR calibration" / "DDR status" / "DDR health" | read → write report_data.json + REPORT.md → chat summary |
| "analyze DDR margins" / "byte lane margins" | read margins → write CSV + report_data.json + REPORT.md → chat summary |
| "run DDR eye scan" | verify cal PASS → eye scan → write PNG + report_data.json + REPORT.md → chat summary |
| "compare DDR controllers" | read all → write report_data.json + REPORT.md (comparison) → chat summary |
After writing files, confirm in chat: "Files written to
vivado_agentic_ai_reports/hw-ddrmc-debug/: report_data.json, REPORT.md, ..."
Calibration Failure Diagnosis
When Calibration Status is FAIL:
- Identify the failing stage from the stage block (the first non-Pass stage).
- Map the stage to likely causes — see REFERENCE.md.
- Cross-reference
hw-sysmon(supply voltage affecting the DDR PHY) andhw-noc-debug(NoC timeout pointing at the DDRMC).
Report the failing stage by its exact name from the output; never relabel it.
Multi-DDRMC
- Enumerate all controllers (
get_hw_ddrmcs/chipscope_ddr(action='list')). - Read each enabled controller; skip disabled ones (report as disabled).
- Compare margins across enabled controllers; report the weakest controller and its weakest byte/nibble with the exact margin values.
Error Handling
| Symptom | Meaning | Action |
|---|---|---|
get_hw_ddrmcs / list empty after a scan | Design has no DDRMC | STOP (see Path Selection) |
Controller has no CAL_STATUS / enabled=false | Present but no memory | Report as disabled, not FAIL |
Zero controllers before a scan / debug_ready:false | Not yet scanned | Not authoritative — scan first |
| Calibration FAIL | A stage did not pass | Run failure diagnosis |
| Eye scan empty | Calibration not complete | Fix calibration first; eye scan needs PASS |
| Eye scan times out | steps too high / link slow | Increase max_wait_minutes, or reduce steps |
| Version below 2026.1 | Unsupported | STOP with the unsupported-version message |
Example (grounded)
"Check DDR status" on a vpk120 → enumerate (4 controller sites, 1 populated) →
read DDRMC_1 → write artifacts → summarize:
DDRMC_1: calibration PASS, LPDDR4 x64 @ 1953 MHz, all 14 stages Pass. Weakest write-complex margin: byte 4 (~53 taps).DDRMC_2/3/4: disabled (no memory). Files written tovivado_agentic_ai_reports/hw-ddrmc-debug/.
Report values verbatim from the tool; never invent a configuration or margin.
Integration
Upstream: chipscope_session (connection), chipscope_device (programming — never auto-program; stop and ask).
Complementary: hw-noc-debug (NoC timeout → DDRMC), hw-sysmon (supply affects DDR PHY).
Downstream: margin issues → board SI investigation, memory timing review.
Metadata
Keywords: DDR, DDRMC, calibration, eye scan, margins, byte lane, memory, DDR4, DDR5, LPDDR, VRef, write leveling, read gate, calibration window. Confidence Threshold: 0.80
Changelog
Version 1.3.0-ea (2026-08-26)
- Remove the direct
sys_dbg_utilCLI cross-check path; chipscope-mcpsysdbg_*tools remain valid MCP paths. Skill forbids terminal commands with no exceptions. - Rewrite for determinism and multi-agent clarity: single Path Selection table (Vivado MCP primary, ChipScoPy MCP fallback, explicit STOP) replacing the prior routing contradiction.
- Add deterministic Vivado bring-up +
get_hw_ddrmcsenumeration; read each enabled controller with onereport_hw_ddrmc -return_stringcall. - Remove the hardcoded 8-stage table and the
ddr_0literal; stages and controller names are now read dynamically (DDR4 shows 12CAL_STAGE.*; other memory types differ). - Correct the "no flat calibration property" claim —
CAL_STATUSexists; use it, and fall back toCAL_STAGE.*if absent. - Define the visualization per path: Vivado = margin-window PNG+CSV; ChipScoPy = true 2D eye.
- Make output-file generation mandatory and unconditional; add a prompt-mapping
table; fix all output paths under
vivado_agentic_ai_reports/hw-ddrmc-debug/. - Add a non-authoritative "zero-DDRMC-before-scan /
debug_ready" guard. - Add a version gate (Vivado/ChipScoPy >= 2026.1).
- Pin ChipScoPy tool signatures to the live chipscope-mcp v1.5.0 schema.
- Restore the eye-scan timeout row to Error Handling; add one grounded example (validated live on a vpk120 LPDDR4 design).
Version 1.2.0-ea (2026-07-16)
- Designate skill as Early Access (
-ea); addmaturity: early-access - Rename skill identity to hw-ddrmc-debug: update
name:frontmatter, report output path, and cross-skill references to match the renamed directory
Version 1.1.0 (2026-07-01)
- Fix stale
chipscopy_*tool prefix ->chipscope_* - Add Vivado MCP fallback path (
get_hw_ddrmcs/report_hw_ddrmc), which is actually the primary path per the routing policy since it works natively on Versal; chipscope-mcp remains available as the documented alternative - Confirmed
chipscope_ddr's action list (list/status/calibration/health/ report/config/stages/margins/eye_scan/eye_scan_data/eye_scan_defaults) matches this skill's usage exactly against the live tool source
Version 1.0.0 (2026-05-01)
- Initial release — DDRMC calibration debug + eye scan via ChipScoPy MCP
- Per-stage analysis, per-byte margins, 2D eye scan with inline PNG
IBERT Eye Scan & Link Tuning (EA)
Early Access — this skill may change before general availability.
Debugs serial transceiver links and runs eye/YK scans on live hardware via ChipScoPy MCP. Three tools cover the full workflow:
chipscope_ibert— discover GT cores, create/configure/delete links, check statuschipscope_ibert_eye_scan— 2D eye scan with inline PNG heatmap (GTY/GTYP)chipscope_ibert_yk_scan— YK scan with inline PNG waveform (GTM, 56+ Gbps)
See REFERENCE.md for GT transceiver types, link configuration options, scan parameters, and report schemas.
Routing: GTY/GTYP eye scan can also be driven through Vivado MCP (vivado_execute + create_hw_sio_scan ... 2d_full_eye/1d_bathtub, real Hardware Manager Tcl) — try that first if a Vivado MCP session is available, falling back to chipscope_ibert_eye_scan otherwise; both paths are proven on real hardware (VCK190). GTM YK scan has no vivado-mcp fallback — chipscope_ibert_yk_scan is the only path. Do not attempt create_hw_sio_scan against a GTM link expecting it to work; see the error table in Workflow B below for exactly how and where each Vivado scan type fails on GTM.
Device scoping note: the frontmatter device_families list (versal, ultrascale-plus, ultrascale, 7series) applies to GTY/GTYP eye scan. GTM (YK scan) is narrower — Versal Premium/HBM-series only (e.g. VPK120/180), per REFERENCE.md's transceiver table. Do not assume YK scan works on a general Versal part just because "versal" is in the device list.
Tools Used
| Tool | Purpose |
|---|---|
vivado_start | Start new Vivado session (vivado-mcp path). |
vivado_execute | Execute Hardware Manager Tcl commands (vivado-mcp path). |
vivado_list_sessions | Discover active Vivado sessions (vivado-mcp path). |
vivado_status | Check Vivado session health (vivado-mcp path). |
chipscope_ibert | List IBERT cores, discover GT groups, create/delete/configure links, check link status and BER, reset (chipscope-mcp path). |
chipscope_ibert_eye_scan | Run 2D eye scan on GTY/GTYP link. Returns inline PNG heatmap. Supports export (chipscope-mcp path). |
chipscope_ibert_yk_scan | Run YK scan on GTM link. Returns inline PNG waveform + SNR data. Export at scan time only (chipscope-mcp path). |
chipscope_session | Connect to hw_server + cs_server (chipscope-mcp path). |
chipscope_device | List/select devices, check resources, program device (chipscope-mcp path). |
chipscope_scan | Discover debug cores including IBERT (chipscope-mcp path). |
| Agent file tools | Write output files (report_data.json, REPORT.md). |
Efficiency Guidelines
- Check link type first — GTM uses YK scan, GTY/GTYP uses eye scan. The IBERT core listing indicates transceiver type.
- Create link before scanning — eye/YK scan requires an active link. Use
chipscope_ibert(action='create_link'). - Loopback for self-test — use Near-End PMA loopback for board-independent testing.
- Export at scan time for YK — GTM YK scan data is transient; use
export_pathduring scan, not after. - Do NOT run scans without a configured link — the tool will error.
Workflow A: Eye Scan (GTY/GTYP)
vivado-mcp Path (Hardware Manager Tcl)
Tool Availability Check: Before proceeding, verify that vivado_execute is available. If not available, fall back to the chipscope-mcp path below.
When a Vivado MCP session is available, use Hardware Manager Tcl commands via vivado_execute(session_id=<id>, command=<tcl>).
Step 1: Connect to Hardware Manager
Run via vivado_execute(session_id=<id>, command=<tcl below>):
open_hw_manager
connect_hw_server -allow_non_jtag -url <hw_server_url>
current_hw_target [get_hw_targets */xilinx_tcf/Xilinx/*]
open_hw_target
Step 2: Select FPGA Device (not ARM DAP)
First, discover available devices:
get_hw_devices
Returns list like: arm_dap_0 xcvp1202_1
Then select the FPGA device (filter out ARM DAP):
# Use Tcl filter to select FPGA device (exclude arm_dap*)
set fpga_devs [get_hw_devices -filter {NAME !~ "arm_dap*"}]
if {[llength $fpga_devs] == 0} {
error "No FPGA devices found on JTAG chain"
} elseif {[llength $fpga_devs] > 1} {
puts "Multiple FPGAs found: [join [get_property NAME $fpga_devs] {, }]"
error "Multiple FPGA devices found - please specify target device"
}
set fpga_dev [lindex $fpga_devs 0]
current_hw_device $fpga_dev
puts "Selected device: [get_property NAME [current_hw_device]]"
refresh_hw_device [current_hw_device]
Critical: Always verify get_hw_devices output and select the FPGA device explicitly. Do NOT use [lindex [get_hw_devices] 0] blindly - it may select the ARM Debug Access Port instead of the FPGA.
Step 3: Discover IBERT Cores
Run via vivado_execute(session_id=<id>, command=<tcl below>):
# Discover IBERT cores and get both name and type
foreach core [get_hw_sio_iberts] {
puts "[get_property NAME $core]: [get_property DISPLAY_NAME $core]"
}
# Prints core name and transceiver type together: "IBERT_0: IBERT Versal GTM", "IBERT_1: IBERT Versal GTYP", etc.
# This preserves the mapping needed for later report generation
Step 4: Discover GT Groups and Channels
Run via vivado_execute(session_id=<id>, command=<tcl below>):
puts "GT groups: [get_hw_sio_gtgroups]"
# Returns GT quad groups: IBERT_0.Quad_204, IBERT_0.Quad_205, etc.
puts "GT channels: [get_hw_sio_gts]"
# Returns individual GT channel objects
Expected Output Example (Versal Premium VP1202):
- Device:
xcvp1202_1 - IBERT Cores:
IBERT_0(Versal GTM),IBERT_1(Versal GTYP) - GT Groups:
IBERT_0.Quad_204,IBERT_0.Quad_205,IBERT_1.Quad_200,IBERT_1.Quad_201 - Total Channels: 16
Step 5: Create and Configure Link (vivado-mcp)
For loopback testing, create a link between TX and RX on the same channel.
Run via vivado_execute(session_id=<id>, command=<tcl below>):
set gt [lindex [get_hw_sio_gts <pattern>] 0]
set tx [get_hw_sio_txs -of_objects $gt]
set rx [get_hw_sio_rxs -of_objects $gt]
set link [create_hw_sio_link -description "Test_Link" $tx $rx]
# Returns: IBERT_X.Quad_Y.CH_Z.TX->IBERT_X.Quad_Y.CH_Z.RX
# Extract channel number from GT name (e.g., "IBERT_0.Quad_200.CH_2" -> "2")
set gt_name [get_property NAME $gt]
set ch_num [string range $gt_name [expr {[string last "_" $gt_name] + 1}] end]
# Now ch_num contains the channel number (0, 1, 2, or 3)
Run via vivado_execute(session_id=<id>, command=<tcl below>):
set_property CH${ch_num}_TX_PATTERN {PRBS 31} $link
set_property CH${ch_num}_RX_PATTERN {PRBS 31} $link
set_property CH${ch_num}_LOOPBACK {Near-End PMA} $link
commit_hw_sio $link
Important: Set channel-prefixed properties on the LINK object and commit the link. Properties use CH${ch_num}_ prefix (e.g., CH0_TX_PATTERN for channel 0).
Then, after any Far-End PMA TX reset (the "vivado-mcp TX Reset" block below), clear errors counted during the change: set CH${ch_num}_RX_RESET to 1 on $gt, commit_hw_sio $gt, set it to 0, commit_hw_sio $gt.
Common PRBS patterns: PRBS 7, PRBS 9, PRBS 15, PRBS 23, PRBS 31. Loopback modes: User Design (off), Near-End PMA, Near-End PCS, Far-End PMA, Far-End PCS.
Step 6: Check Link Status (vivado-mcp)
Run via vivado_execute(session_id=<id>, command=<tcl below>):
refresh_hw_sio [get_hw_sio_iberts]
puts [get_property CH${ch_num}_RX_STATUS $gt]
# Prints line rate (e.g., "24.998 Gbps") or "No link"
puts [get_property CH${ch_num}_RX_PRBS_BER $gt]
# Prints BER (e.g., "8.105091e-15")
puts "[get_property CH${ch_num}_RX_PRBS_ERR_CNT $gt] errors (hex) in [get_property CH${ch_num}_RX_RECEIVED_BIT_COUNT.NORMALIZED $gt] bits"
Important: Call refresh_hw_sio to read current values from hardware before checking status. Without it, you see stale cached values.
Expected Results:
- Link Status: ~25 Gbps (GTYP example)
- BER: judged with the error and bit counts, see Judging BER
- Configuration: PRBS 31, Near-End PMA loopback
For eye scans, continue using Hardware Manager hw_sio_* commands. See UG908 Chapter on IBERT for complete Tcl reference.
chipscope-mcp Path
When chipscope-mcp is available (or vivado-mcp is not), use the following tools.
Step 1: Discover IBERT Cores
chipscope_ibert(action='list')
Returns IBERT cores with transceiver type hints. Identify GTY or GTYP cores.
More than one core (e.g. VPK120: IBERT Versal GTM and IBERT Versal GTYP): every call goes to the first core unless ibert_name names another. Choose the core by transceiver_type / scan_type_hint (eye_scan for GTY/GTYP, yk_scan for GTM), or for a named GT group the core whose analyze lists it, and pass its name as ibert_name on every later call (analyze, create_link and reset of a GT group or core fail or reach the wrong core without it).
Step 2: Analyze GT Groups
chipscope_ibert(action='analyze', ibert_name='<ibert_name>')
Discovers GT groups and available transceivers within the named IBERT core.
Step 3: Create a Link (chipscope-mcp)
create_link takes gt_group (e.g. 'Quad_205', from Step 2's analyze output) plus integer tx_channel/rx_channel indices (0-3) — not string channel names. Confirmed against chipscope-mcp/src/chipscope_mcp/tools/chipscope_ibert.py.
chipscope_ibert(action='create_link',
ibert_name='<ibert_name>',
gt_group='<gt_group>',
tx_channel=<tx_channel_index>,
rx_channel=<rx_channel_index>)
For loopback testing (TX feeds back to RX on same channel):
chipscope_ibert(action='create_link',
ibert_name='<ibert_name>',
gt_group='<gt_group>',
tx_channel=0,
rx_channel=0)
For a cross-quad link, pass rx_gt_group if the RX channel is on a different GT group than TX.
For vivado-mcp, use create_hw_sio_link command - see UG908 IBERT chapter for Tcl syntax.
Step 4: Configure Link (chipscope-mcp)
chipscope_ibert(action='configure_link',
link_name='<link_name>',
tx_pattern='PRBS 31',
rx_pattern='PRBS 31',
loopback='Near-End PMA')
Common patterns: PRBS 7, PRBS 15, PRBS 23, PRBS 31. Loopback modes: None, Near-End PMA, Near-End PCS, Far-End PMA, Far-End PCS.
Then reset the link to clear errors counted during the change (separate from the Far-End PMA TX reset below): chipscope_ibert(action='reset', target='link', ibert_name='<ibert_name>', link_name='<link_name>').
For vivado-mcp, use channel-prefixed properties (CH${ch_num}_TX_PATTERN, CH${ch_num}_RX_PATTERN, CH${ch_num}_LOOPBACK) on the link object, then commit_hw_sio $link to apply.
Important: When entering or exiting Far-End PMA loopback mode, issue a TX reset (GTTXRESET) after changing the loopback property. Per Xilinx architecture manuals (AM002/AM017), this reset is required for proper GT operation in far-end PMA loopback.
vivado-mcp TX Reset (after loopback change):
# Assert TX reset (pulse high then low)
set_property CH${ch_num}_TX_RESET 1 $gt
commit_hw_sio $gt
set_property CH${ch_num}_TX_RESET 0 $gt
commit_hw_sio $gt
chipscope-mcp TX Reset:
ChipScoPy's configure_link API handles the required TX reset internally when changing to/from Far-End PMA loopback — no explicit reset call needed.
Step 5: Check Link Status (chipscope-mcp)
chipscope_ibert(action='status', ibert_name='<ibert_name>', link_name='<link_name>')
Verify: PLL locked, link up, BER check PASS or NOT PROVEN (Judging BER) before scanning.
For vivado-mcp, use refresh_hw_sio then get_property on GT objects (not link objects) - status properties like CH${ch_num}_RX_STATUS and CH${ch_num}_RX_PRBS_BER are read from the GT channel. See Step 6 vivado-mcp section for example commands.
Step 6: Run Eye Scan
vivado-mcp Path (Hardware Manager Tcl)
When a Vivado MCP session is available, use Hardware Manager Tcl for 2D eye scan.
Run via vivado_execute(session_id=<id>, command=<tcl below>):
# Create 2D eye scan object on the specific link from Step 5
# Reuse $link variable from link creation, or select by description filter
set scan [create_hw_sio_scan -description "2D_Eye_Scan" 2d_full_eye $link]
# Returns: SCAN_0
# Run the scan
run_hw_sio_scan $scan
# Wait for completion
wait_on_hw_sio_scan $scan
# Get eye metrics
report_property $scan
Key Properties from Eye Scan:
OPEN_PERCENTAGE— Overall eye opening (%)HORIZONTAL_OPENING— Horizontal eye width (UI steps)HORIZONTAL_PERCENTAGE— Horizontal opening (%)VERTICAL_OPENING— Vertical eye height (mV steps)VERTICAL_PERCENTAGE— Vertical opening (%)OPEN_AREA— Total open area (square units)STATUS— "Done" when completePROGRESS— "100%" when complete
Export scan data:
Run via vivado_execute(session_id=<id>, command=<tcl below>):
write_hw_sio_scan -force <output_file.csv> $scan
Proven Results (GTYP Quad_200 CH_0, Near-End PMA, PRBS 31):
- Eye Opening: 64%
- Horizontal: 41 steps (66.67%)
- Vertical: 241 steps (100%)
- Scan Time: ~1.5 seconds
- Data Points: 558
chipscope-mcp Path
When chipscope-mcp is available (or vivado-mcp is not):
chipscope_ibert_eye_scan(
link_name='<link_name>',
horz_step=10,
vert_step=10,
target_ber=1e-5)
Returns inline PNG heatmap showing eye opening.
With export:
chipscope_ibert_eye_scan(
link_name='<link_name>',
export_path='eye_scan_data.csv',
save_plot='eye_scan.png')
Display modes: display='chat' (inline only), display='app' (structured content), display='both' (default), display='ascii' (text-only).
Step 7: Generate Reports
vivado-mcp Path
After completing the eye scan, collect all metrics and generate reports.
Collect Device and IBERT Core Metrics:
Run via vivado_execute(session_id=<id>, command=<tcl below>):
# Device information
puts [get_property PART [current_hw_device]]
puts [get_property FAMILY [current_hw_device]]
puts [get_property REGISTER.DNA [current_hw_device]]
puts [current_hw_target]
# IBERT core discovery
set cores [get_hw_sio_iberts]
foreach core $cores { report_property $core }
# Extract: DISPLAY_NAME (e.g., "IBERT Versal GTM", "IBERT Versal GTYP")
# GT topology
get_hw_sio_gtgroups
Collect Link Status:
Run via vivado_execute(session_id=<id>, command=<tcl below>):
refresh_hw_sio [get_hw_sio_iberts]
# Get the link created in Step 5 by description or index
# If you created link with -description "Test_Link", filter by that:
set link [lindex [get_hw_sio_links -filter {DESCRIPTION == "Test_Link"}] 0]
# Or if only one link exists, use: set link [lindex [get_hw_sio_links] 0]
report_property $link
# Extract link name, TX/RX endpoints
# Get the GT used in Step 5 (same pattern as before)
set gt [lindex [get_hw_sio_gts <pattern>] 0]
# Extract channel number from GT name
set gt_name [get_property NAME $gt]
set ch_num [string range $gt_name [expr {[string last "_" $gt_name] + 1}] end]
# Refresh this specific GT to get current values from hardware
refresh_hw_sio $gt
puts [get_property CH${ch_num}_RX_STATUS $gt]
# Prints line rate (e.g., "24.994 Gbps")
puts [get_property CH${ch_num}_RX_PRBS_BER $gt]
# Prints BER (e.g., "2.080110e-15")
puts "[get_property CH${ch_num}_RX_PRBS_ERR_CNT $gt] errors (hex) in [get_property CH${ch_num}_RX_RECEIVED_BIT_COUNT.NORMALIZED $gt] bits"
puts [get_property CH${ch_num}_TX_RESET_DONE $gt]
puts [get_property CH${ch_num}_RX_RESET_DONE $gt]
# Prints reset done status: "Yes" or "No"
puts [get_property CH${ch_num}_RX_PRBS_LOCKED $gt]
# Prints PRBS lock status: "Locked" or "Not locked"
Collect Eye Scan Results:
After wait_on_hw_sio_scan completes, run via vivado_execute(session_id=<id>, command=<tcl below>):
report_property $scan
Key properties to extract:
OPEN_PERCENTAGE— Overall eye opening (%)HORIZONTAL_OPENING— Horizontal width (steps)HORIZONTAL_PERCENTAGE— Horizontal opening (%)VERTICAL_OPENING— Vertical height (steps)VERTICAL_PERCENTAGE— Vertical opening (%)OPEN_AREA— Total open areaSTATUS— "Done" when completePROGRESS— "100%" when complete
Scan parameters (from same report_property output):
DWELL— Dwell mode (e.g., "BER")DWELL_BER— Target BER (e.g., "1e-5")HORIZONTAL_RANGE— Sweep range (e.g., "-0.500 UI to 0.500 UI")HORIZONTAL_INCREMENT— Step sizeVERTICAL_RANGE— Sweep range (e.g., "100%")VERTICAL_INCREMENT— Step size
Generate report_data.json:
Write structured JSON with all metrics. Use the canonical schema from REFERENCE.md ("Report JSON Schema" section).
Converting Vivado metrics to canonical schema units:
eye_width_ui: MultiplyHORIZONTAL_PERCENTAGE(as decimal) by the UI range fromHORIZONTAL_RANGE(e.g., if HORIZONTAL_PERCENTAGE=71.43% and range is 1.0 UI, then eye_width_ui = 0.7143)eye_height_percent: UseVERTICAL_PERCENTAGEdirectly (e.g., 71.43 for 71.43%).
{
"schema_version": "hw-ibert-gt-debug/1.1.0",
"timestamp": "<ISO8601 timestamp>",
"device": {
"part": "<part number>",
"dna": "<device DNA>"
},
"ibert_cores": [
{
"name": "<IBERT_N>",
"type": "GTY|GTYP|GTM",
"gt_groups": <number>,
"channels_per_group": <number>
}
],
"links": [
{
"name": "<link name>",
"tx_channel": "CH0",
"rx_channel": "CH0",
"pattern": "PRBS 31",
"loopback": "Near-End PMA",
"ber": <actual BER>,
"line_rate_gbps": <actual value>
}
],
"scans": [
{
"type": "eye_scan",
"link": "<link name>",
"horz_step": <steps>,
"vert_step": <steps>,
"target_ber": <BER>,
"eye_width_ui": <HORIZONTAL_PERCENTAGE / 100 * horizontal_range_ui>,
"eye_height_percent": <VERTICAL_PERCENTAGE>,
"status": "complete"
}
]
}
Note: This matches the schema defined in REFERENCE.md. Do NOT use alternative schemas with metadata, singular link/eye_scan, or pass_fail fields - those diverge from the canonical format.
Generate REPORT.md:
Write all requested output files with agent file tools before giving any chat summary. Use this human-readable markdown template:
# IBERT GT Debug Report
**Generated**: <timestamp>
**Device**: <part> (<family>)
**Assessment**: PASS/FAIL
## Executive Summary
<Brief description of what was tested>
## Device Information
- **Part**: <part>
- **Family**: <family>
- **hw_server**: <url>
- **Target**: <target path>
## IBERT Cores Discovered
| Core Name | Display Name | Type | Quads |
|-----------|-------------|------|-------|
| <name> | <display name> | <type> | <quad list> |
## Link Configuration
**Link**: <full link path>
**Description**: <description>
### Settings
- **TX Pattern**: <pattern>
- **RX Pattern**: <pattern>
- **Loopback**: <mode>
- **Line Rate**: <rate> Gbps
### Status
- **RX Status**: <status>
- **BER**: <ber> (<BER check>)
- **Errors / bits received**: <error_count> / <bit_count>
- **TX Reset Done**: Yes|No
- **RX Reset Done**: Yes|No
- **RX PRBS Lock**: Locked|Not locked
## 2D Eye Scan Results
**Scan**: <scan name> (<description>)
**Status**: <status>
**Progress**: <progress>
### Eye Opening Metrics
| Metric | Value | Threshold | Status |
|--------|-------|-----------|--------|
| Open Percentage | <val>% | ≥50% | PASS/FAIL ✓|✗ |
| Horizontal Opening (steps) | <val> | — | (informational) |
| Horizontal Percentage | <val>% | ≥50% | PASS/FAIL ✓|✗ |
| Vertical Opening (steps) | <val> | — | (informational) |
| Vertical Percentage | <val>% | ≥70% | PASS/FAIL ✓|✗ |
| Open Area | <val> | — | (informational) |
## Assessment
**Overall**: PASS/FAIL
<Summary of results with specific values>
## Commands Executed
<List of key Tcl commands run>
## Files Generated
- REPORT.md (this file)
- report_data.json (structured data)
Assessment Logic:
Apply resolution-independent percentage thresholds (aligned with REFERENCE.md):
- Open Percentage: ≥50% = PASS
- Horizontal Percentage: ≥50% = PASS
- Vertical Percentage: ≥70% = PASS
Overall assessment:
- PASS: All percentage metrics meet their thresholds AND the BER check is PASS or NOT PROVEN
- FAIL: Any percentage metric fails its threshold OR the BER check is FAIL
Judging BER
With 0 errors the reported BER is only 1 / bits received, so an error-free link reads above 1e-12 until 1e12 bits have arrived (40 s at 25 Gbps). Judge it with the link state, error count and bit count (chipscope-mcp status: status, error_count, bit_count; vivado-mcp Step 6: RX_STATUS, RX_PRBS_ERR_CNT, RX_RECEIVED_BIT_COUNT.NORMALIZED), from a read taken after the link reset that follows the last pattern or loopback change.
| Reading (use the first row that matches) | BER check |
|---|---|
Link down (No link; BER reads 1.0) | FAIL |
| 0 errors, bit count ≥ 1e12 | PASS: "no errors in N bits (BER < 1/N)" |
| 0 errors, bit count < 1e12 | NOT PROVEN, never FAIL: wait once for (1e12 - bits) / (line rate in bit/s) seconds (25 Gbps = 2.5e10 bit/s), read once more without resetting, and judge that read. If the wait is over about two minutes, do not wait: keep NOT PROVEN and report "no errors in N bits (BER < 1/N)" |
| Errors > 0 | PASS if BER < 1e-12, otherwise FAIL |
Note: Use percentage metrics only. Raw step counts and open area depend on scan resolution and produce inconsistent assessments across different scan configurations.
Note: The canonical schema (REFERENCE.md) does not include overall assessment fields. If assessment is needed, document it in REPORT.md only.
chipscope-mcp Path
When chipscope-mcp is available (or vivado-mcp is not), the report generation workflow is similar but metrics come from chipscope tool outputs:
chipscope_ibert(action='status', ibert_name='<ibert_name>', link_name='<link_name>') # Returns link status, BER, line rate
chipscope_ibert_eye_scan(...) # Returns eye metrics directly
Extract metrics from tool responses and populate the JSON/markdown schema. Both backends return percentage-based metrics:
- Use
eye_height_percentfield (from VERTICAL_PERCENTAGE in vivado-mcp or vertical percentage in chipscope-mcp output) - Use percentage-based assessment thresholds: HORIZONTAL_PERCENTAGE ≥ 50%, VERTICAL_PERCENTAGE ≥ 70%, OPEN_PERCENTAGE ≥ 50%, and the BER check from Judging BER
Output directory: vivado_agentic_ai_reports/hw-ibert-gt-debug/
| File | Format | Content |
|---|---|---|
report_data.json | JSON | Link config, scan parameters, eye metrics |
REPORT.md | Markdown | Summary with eye opening assessment |
eye_scan.png | PNG | Eye diagram (if save_plot used) |
eye_scan_data.csv | CSV | Raw scan data (if export_path used) |
Workflow B: YK Scan (GTM, 56+ Gbps)
Proven end-to-end on real hardware (VPK120, 2026-07-01). GTM transceivers exist only on Versal Premium/HBM-series devices (e.g. VPK120/180). chipscope_ibert_yk_scan was run against a real GTM link on VPK120 (Quad_204 CH_0, 56.4 Gbps, Near-End PMA, PRBS 31) and returned SNR 16.75 dB. Workflow A (GTY/GTYP eye scan) has been proven on real hardware (VCK190).
GTM YK scan is chipscope-mcp-only — confirmed at all three Vivado Hardware Manager Tcl layers, not just documented. yk, 1d_bathtub, and 2d_full_eye were each tried against a real GTM link on VPK120 and every one fails, at a different layer:
scan_type | create_hw_sio_scan (object creation) | run_hw_sio_scan (hardware execution) |
|---|---|---|
yk | Rejected — ERROR: [Labtools 27-1835] Unknown Scan Type: yk. (not a recognized enum value) | n/a |
1d_bathtub | Rejected — ERROR: [Labtools 27-3784] Performing 1D Bathtub scan is not supported for <RX>! (valid enum, but rejected per-object; also rejected on GTYP on this board) | n/a |
2d_full_eye | Accepted — returns a scan object cleanly (object creation doesn't validate GT capability) | Rejected — ERROR: [Xicom 50-230] ChipScope Server: ChipScope Service IBERT start_eye_scan: OD test Eye scan is not supported! |
Do not treat 1d_bathtub and yk as interchangeable or as testing the same thing — they fail for different reasons (unrecognized type vs. unsupported-for-this-GT), and neither is equivalent to a YK scan. 2d_full_eye is the most dangerous case: it looks like it worked (a named SCAN_N object comes back) but produces zero real data once run — always check run_hw_sio_scan's return, not just create_hw_sio_scan's, before trusting a Vivado-mcp-path GTM scan result.
Steps 1-5: Same as Workflow A
CRITICAL: GTM requires chipscope-mcp for YK scans. If using vivado-mcp for Steps 1-5 (link setup), you CANNOT use chipscope_ibert_yk_scan in Step 6 - the ChipScoPy link object does not exist. For GTM workflows requiring YK scans, use chipscope-mcp path for ALL steps.
Discover, create link, configure, check status. Use a GTM IBERT core.
Step 6: Run YK Scan
chipscope_ibert_yk_scan(
link_name='<link_name>',
scan_duration_seconds=10.0)
Returns inline PNG waveform + SNR statistics.
With export (MUST be done at scan time — data is transient):
chipscope_ibert_yk_scan(
link_name='<link_name>',
scan_duration_seconds=10.0,
export_path='yk_scan_data.csv')
Step 7: Analyze SNR Results
- SNR — signal-to-noise ratio in dB; higher = better
- Slicer waveform — shows signal quality at receiver
TX/RX Tuning Workflow
For link optimization, sweep equalization parameters:
Read Current Settings
chipscope_ibert(action='link_properties', link_name='<link_name>')
Returns current values and valid options for TX/RX parameters.
Adjust TX Emphasis
chipscope_ibert(action='configure_link',
link_name='<link_name>',
tx_pre_cursor=<value>,
tx_post_cursor=<value>,
tx_swing=<value>)
Sweep and Compare
- Capture baseline eye scan
- Adjust one parameter
- Re-run eye scan
- Compare eye width/height
- Repeat until optimal
Multi-Lane Analysis
For multi-lane links (PCIe x4/x8/x16, multi-lane Ethernet):
- Create links on each lane
- Run eye scan on each lane
- Compare eye openings across lanes
- Identify weak lanes (smallest eye)
- Focus tuning on weak lanes
Design-Specific Rules
| Rule | Wrong | Correct |
|---|---|---|
| Link status | "link is up" | "Link_0: PLL locked, 0 errors in 2.26e12 bits (BER < 4.4e-13), line rate 25.78125 Gbps" |
| Eye opening | "eye looks good" | "Eye width: 0.42 UI, height: 72% at BER 1e-5" |
| Transceiver | "found IBERT" | "IBERT Versal GTM: 2 GT groups, 4 channels per group, 56.42 Gbps" |
| Scan type | "running scan" | "Running 2D eye scan: horz_step=10, vert_step=10, target_ber=1e-5" |
Error Handling
| Error | Symptom | Action |
|---|---|---|
| No IBERT cores | list returns empty | Design has no IBERT IP. Check bitstream. |
| Wrong scan type | eye_scan on GTM | GTM uses YK scan. Use chipscope_ibert_yk_scan. |
| Vivado-mcp on GTM | create_hw_sio_scan ... yk errors Unknown Scan Type: yk; 1d_bathtub errors 27-3784 not supported; 2d_full_eye creates a scan object but run_hw_sio_scan errors Xicom 50-230 ...Eye scan is not supported! | None of Vivado Hardware Manager's Tcl scan types work on GTM at any layer (parse, per-object, or execution). Route to chipscope-mcp's chipscope_ibert_yk_scan for any GTM link — do not fall back to vivado-mcp for this one capability. |
| No link created | scan fails | Create link first with chipscope_ibert(action='create_link') |
| Wrong IBERT core | ELEMENT_NOT_FOUND: GT group '<name>' not found, listing another core's GT groups | The call went to the first core. Pass the ibert_name of the core that owns the GT group. |
| PLL not locked | status shows unlocked | Check: reference clock? loopback mode? board connections? |
| Scan timeout | max_wait exceeded | Increase max_wait_minutes. Check link stability. |
| High BER | status shows error_count > 0 | Tune TX emphasis, check SI, verify pattern match. BER above 1e-12 with 0 errors is not high BER: see Judging BER. |
| Export after YK | no data available | YK data is transient. Must export during scan with export_path. |
Examples
"Run an eye scan on GT channel 0" → List IBERT → Create loopback link on CH0 → Configure PRBS 31 → Run eye scan → Report eye width/height.
"Show me a YK scan on GTM" → Find GTM IBERT core → Create link → Configure PRBS 31 + PMA loopback → chipscope_ibert_yk_scan(scan_duration_seconds=10) → Report SNR.
"Compare eye before and after tuning" → Baseline eye scan → Adjust TX pre-cursor → Re-run eye scan → Report: "Eye width improved from 0.35 UI to 0.42 UI (+20%)".
"Check all IBERT links" → chipscope_ibert(action='status') → Report BER, lock status, line rate for each link.
Integration
Upstream: chipscope_session (connection), chipscope_device (programming)
Complementary: hw-pcie-link-debug (PCIe uses GT transceivers — eye scan validates SI), hw-sysmon (supply voltage affects eye quality)
Downstream: Tuning recommendations → design constraint changes or board-level SI fixes
Metadata
Keywords: IBERT, eye scan, YK scan, GTY, GTYP, GTM, BER, SNR, serial link, transceiver, loopback, PRBS, equalization, eye diagram, margin Confidence Threshold: 0.80
ILA Debug (EA)
Early Access — this skill may change before general availability.
Interacts with ILA debug cores on live hardware: discover → configure trigger → arm → capture → upload → export → analyze.
See REFERENCE.md for ILA property tables, Tcl command reference, TSM syntax, compare value encoding, and report schema.
Routing: Try Vivado MCP (vivado_execute + Hardware Manager Tcl, below) first if a Vivado MCP session is available — it works across all device families. Fall back to chipscope-mcp (chipscope_ila_core/chipscope_ila_capture) if Vivado MCP is not installed. See Chipscope-mcp Fallback below.
Tools Used
Primary path — Vivado MCP (plus the agent's own file tools):
| Tool | Purpose |
|---|---|
vivado_execute | Run all Tcl commands (get_hw_ilas, run_hw_ila, etc.). Every Tcl block MUST be run via vivado_execute(session_id=..., command=<tcl>). |
vivado_doc_search | Look up unfamiliar ILA properties, probe compare value syntax, TSM syntax. No session_id needed. |
vivado_status | Check Vivado session health. |
vivado_list_sessions | Find an active session to use (get its session_id). |
| Agent file tools | Write output files (report_data.json, REPORT.md, CSV/VCD exports). |
Fallback path — chipscope-mcp (when Vivado MCP is unavailable): chipscope_session, chipscope_device, chipscope_scan, chipscope_ila_core, chipscope_ila_capture. See Chipscope-mcp Fallback.
No terminal commands, no Python. Everything goes through Vivado MCP or, as fallback, chipscope-mcp.
Session Setup: Vivado Version Must Match hw_server
vivado_list_sessions→ check for an active session.- Before reusing one, run
version -shortand compare to the targethw_server's version. - Mismatch →
ERROR: [Labtools 27-3366] Cannot support older hw_server version. - On mismatch: do not retry or restart automatically.
vivado_startdoes not pick a matching Vivado version for you — an omittedvivado_pathjust resolves fromPATH, which is often the same mismatched install. Report the exact error, the session's version, and the targethw_server's version to the user, and ask them to point at the correct Vivado install (vivado_path) or the correcthw_server. - This only applies to an already-running, independently-started
hw_server. Ahw_serverthat Vivado auto-starts itself when connecting to a locally attached board is launched from that same Vivado install, so it cannot be version-mismatched — see "No hw_server" below. - Only reuse a session once its version matches.
- Finding the hw_server address. Use the address the user gives. If they say it is in an environment variable that Vivado sees, read it through
vivado_execute, for exampleputs $::env(HW_SERVER_URL)with the name they gave, not with a terminal command (noecho,envorls). If a session is already connected,current_hw_servershows the address. If none of these gives one, ask the user.
Efficiency Guidelines
- Pass
session_idto everyvivado_executecall — get it fromvivado_list_sessionsif unknown. - Verify session version against
hw_serverbefore reuse, and report a mismatch to the user rather than retrying — see Session Setup above. - Batch Tcl — discover all ILA cores in one
vivado_execute, not separate calls. - Write reports to file — do not dump full waveform data in chat. Give a short summary only.
- Use
vivado_doc_searchfor unfamiliar probe properties, TSM syntax, or compare value encoding. - Do NOT use
display_hw_ila_data— it opens a GUI window. Usewrite_hw_ila_data+list_hw_samplesfor data extraction. - Do NOT use
shellcommands or Vivado Tcl file I/O, exceptfile mkdir vivado_agentic_ai_reports/hw-ila-debugbeforewrite_hw_ila_datain Step 4. Use agent file tools for everything else. - Do NOT retry failed Tcl with different syntax. Search docs first, then report the error.
Capture & Analysis Workflow
Step 1: Discover ILA Cores & Probes
Run via vivado_execute(session_id=<id>, command=<tcl below>):
puts "=== ILA CORES ==="
foreach ila [get_hw_ilas] {
puts "ILA:$ila"
puts " DATA_DEPTH:[get_property CONTROL.DATA_DEPTH $ila]"
puts " MAX_DEPTH:[get_property STATIC.MAX_DATA_DEPTH $ila]"
puts " TRIGGER_MODE:[get_property CONTROL.TRIGGER_MODE $ila]"
puts " ADV_TRIGGER:[get_property STATIC.IS_ADVANCED_TRIGGER_MODE_SUPPORTED $ila]"
puts " TRIG_IN:[get_property STATIC.IS_TRIG_IN_SUPPORTED $ila]"
puts " CAPTURE_QUAL:[get_property STATIC.IS_BASIC_CAPTURE_MODE_SUPPORTED $ila]"
puts " STATUS:[get_property STATUS.CORE_STATUS $ila]"
puts " WINDOW_COUNT:[get_property CONTROL.WINDOW_COUNT $ila]"
puts " === PROBES ==="
foreach p [get_hw_probes -of_objects $ila] {
puts " PROBE:$p WIDTH:[get_property PROBE_PORT_BIT_COUNT $p] TYPE:[get_property TYPE $p]"
}
}
No ILA found → STOP. Guide: "No ILA cores detected. Ensure the device was programmed with a bitstream containing ILA cores and the correct .ltx probes file is associated."
On the chipscope-mcp fallback path:
- A zero-ILA reading before
chipscope_scan(action="scan", ltx_path=...)has run is not authoritative — don't treat it as "no ILA found" yet. - After scanning, if the server reports a
debug_readyfield, treatdebug_ready: trueas confirmation. - If
debug_readyis absent, fall back to the scan's own reported core count instead.
Step 2: Configure Trigger
Basic trigger — map user's NL request to probe compare values:
set ila [lindex [get_hw_ilas] 0]
# TRIGGER_MODE is read-only on Versal (axis_ila) — use catch to skip gracefully
catch {set_property CONTROL.TRIGGER_MODE BASIC_ONLY $ila}
set_property CONTROL.TRIGGER_CONDITION AND $ila
set_property CONTROL.TRIGGER_POSITION 512 $ila
set_property CONTROL.DATA_DEPTH 1024 $ila
set_property TRIGGER_COMPARE_VALUE eq1'b1 [get_hw_probes <probe_name> -of_objects $ila]
Compare value syntax: eq<width>'<radix><value> — see REFERENCE.md for full encoding (=, !=, <, >, R, F, B, N, X).
Advanced trigger (TSM) — for multi-phase triggers (e.g., AXI transactions). See REFERENCE.md for the full grammar, rejection rules, and worked examples:
- Generate a
.tsmfile with state machine code - Write it using agent file tools
- Set:
set_property CONTROL.TRIGGER_MODE ADVANCED_ONLY $ila - Set:
set_property CONTROL.TSM_FILE <path> $ila - Compile-check:
run_hw_ila -compile_only $ila
Capture condition (storage qualifier):
set_property CONTROL.CAPTURE_MODE BASIC $ila
set_property CONTROL.CAPTURE_CONDITION AND $ila
set_property CAPTURE_COMPARE_VALUE eq1'b1 [get_hw_probes <probe> -of_objects $ila]
Step 3: Arm, Wait & Upload
unset -nocomplain ila_data
run_hw_ila $ila
wait_on_hw_ila $ila
set ila_data [upload_hw_ila_data $ila]
if {[llength $ila_data] == 0} {
unset ila_data
error "ILA upload returned no data: the capture failed or the trigger did not fire. Retry from Step 3; do not run Step 4."
}
For immediate capture (no trigger, "aliveness" check):
unset -nocomplain ila_data
run_hw_ila -trigger_now $ila
wait_on_hw_ila $ila
set ila_data [upload_hw_ila_data $ila]
if {[llength $ila_data] == 0} {
unset ila_data
error "ILA upload returned no data: the capture failed or the trigger did not fire. Retry from Step 3; do not run Step 4."
}
Keep $ila_data. Step 4 writes it. Never call upload_hw_ila_data again for the same capture: a second upload can return an empty string, and write_hw_ila_data then writes a different ILA's data or an older capture with no error. An empty upload means the capture failed: retry from Step 3 and do not run Step 4.
If vivado_execute replies SKIPPED (duplicate), nothing ran. Vivado MCP skips a command identical to one it ran moments ago, so $ila_data still holds the earlier capture. To capture again, change the command (for example add a comment line such as # capture 2) and run Step 3 again.
⚠️ wait_on_hw_ila blocks until trigger fires. If the trigger condition is never met, the agent will hang. For conditions that may not fire, use run_hw_ila -trigger_now first to verify probe connectivity.
⚠️ wait_on_hw_ila -timeout N is in MINUTES (not seconds). Use -timeout 1 for a 1-minute cap. Omitting -timeout waits indefinitely.
⚠️ Versal DPC arm latency. On Versal (axis_ila via DPC JTAG), there is a brief latency between run_hw_ila returning and the ILA hardware being fully armed. If the triggering event is driven by VIO in the same Vivado session, issue the commit_hw_vio that fires the trigger in a separate vivado_execute call — not in the same command as run_hw_ila. The natural inter-call latency (~100 ms) is sufficient for the ILA to settle into WAITING FOR TRIGGER state.
Step 4: Export & Analyze Data
file mkdir vivado_agentic_ai_reports/hw-ila-debug
write_hw_ila_data -force -csv_file vivado_agentic_ai_reports/hw-ila-debug/capture_data $ila_data
file mkdir is needed because Vivado does not create the folder, and in a fresh session no agent file tool has run yet. -force lets you write the same capture again. If Tcl reports can't read "ila_data", Step 3 did not produce data: go back to Step 3.
Export formats: -csv_file (spreadsheet), -vcd_file (waveform viewer), or native .ila (Vivado reload).
To read specific probe sample values programmatically:
list_hw_samples [get_hw_probes <probe_name> -of_objects $ila]
Check the capture without a terminal. list_hw_samples returns a probe's values in sample order, so check the data in Tcl through vivado_execute, for example with lindex and lsearch. The trigger sample's index in the window is CONTROL.TRIGGER_POSITION. To look at rows of capture_data.csv, or to read REFERENCE.md, use your file tool. Do not run awk, grep, python or other shell commands on these files.
Step 5: Write Output Files — MANDATORY after every successful capture
This step is not optional and does not depend on the user asking for a report. Any prompt that results in a completed ILA capture — including "display captured data", "show the waveform", "upload and display", or "arm and capture" — MUST produce all three output files before any chat summary is given.
Write every file below under vivado_agentic_ai_reports/hw-ila-debug/. Step 4
already created the folder with file mkdir; the file tool also creates missing
parent directories, so do not shell out to mkdir (this skill forbids terminal
commands).
| File | Format | Content |
|---|---|---|
capture_data.csv | CSV | Raw waveform data from ILA (via write_hw_ila_data) |
report_data.json | JSON | Structured capture metadata + analysis (schema in REFERENCE.md) |
REPORT.md | Markdown | Executive summary: trigger config, capture stats, signal observations |
report_data.json uses these top-level keys: metadata, ila_config, probes, capture, observations, recommendations. The full schema with every field is in REFERENCE.md.
Prompt mapping — these user phrases all require files to be written before summarizing in chat:
| User says | Agent does |
|---|---|
| "display the captured ILA data" | upload → export CSV → write JSON + REPORT.md → chat summary |
| "show me the waveform" | upload → export CSV → write JSON + REPORT.md → chat summary |
| "arm and capture" | arm → wait → upload → export → write JSON + REPORT.md → chat summary |
| "upload and display" | upload → export → write JSON + REPORT.md → chat summary |
After writing files, confirm in chat: "Files written to vivado_agentic_ai_reports/hw-ila-debug/: capture_data.csv, report_data.json, REPORT.md."
Where to find the report: vivado_agentic_ai_reports/hw-ila-debug/REPORT.md in the working directory where the agent session was started. If the report was not generated, the capture data is still uploaded (from Step 3) — write the output files from $ila_data (Step 3) without re-arming or uploading again. Only retry from Step 3 if the capture itself failed (e.g. trigger never fired, upload returned no samples).
Design-Specific Rules
All outputs MUST use ACTUAL values.
| Rule | Wrong | Correct |
|---|---|---|
| Probe value | "signal is high" | "axi_arvalid (hw_ila_1/probe3): 1'b1 at sample 512" |
| Trigger config | "set up trigger" | "TRIGGER_MODE: BASIC_ONLY, CONDITION: AND, probe3 == eq1'b1, POSITION: 512/1024" |
| Core info | "found ILA" | "hw_ila_1: 6 probes, depth 4096, adv trigger supported" |
Error Handling
| Error | Symptom | Action |
|---|---|---|
| No ILA cores | get_hw_ilas empty | Check: bitstream has debug cores? .ltx file associated? |
| No hw_server | get_hw_servers empty | Guide: connect_hw_server -url localhost:3121 |
| Trigger never fires | wait_on_hw_ila hangs | Use run_hw_ila -trigger_now to verify connectivity first |
| Probe not found | get_hw_probes returns empty | Check: .ltx file matches bitstream? vivado_doc_search for probe naming |
| TSM compile error | run_hw_ila -compile_only fails | Check the exact rule in REFERENCE.md first (it lists the specific rejection error strings); vivado_doc_search for anything not covered there |
TSM arm() rejected (chipscope-mcp path) | chipscope_ila_core(action="arm", trigger_state_machine=...) returns success: false with a parser error | Match the exact error string against REFERENCE.md's "Rejected patterns" table first |
Examples
"Capture whatever is on the ILA right now" → Discover ILA → run_hw_ila -trigger_now → wait_on_hw_ila → set ila_data [upload_hw_ila_data $ila] → export $ila_data as CSV → summarize.
"Trigger when AXI RVALID goes high" → Find probe for axi_rvalid → set_property TRIGGER_COMPARE_VALUE eq1'b1 → arm → wait → upload → export.
"Trigger on AXI read transaction (address then data then last)" → Generate 3-state TSM → write .tsm file → set ADVANCED_ONLY → arm → capture.
Chipscope-mcp Fallback
Use this path only when Vivado MCP is not installed. Session lifecycle per VIVADO-PATTERNS.md Pattern 19 (vivado-skill-creator):
chipscope_session(action="connect", hw_server_url="TCP:<host>:3121", cs_server_url="TCP:<host>:3042")
chipscope_device(action="select", device_selector="0")
chipscope_scan(action="scan", ltx_path="<path-to-design>.ltx")
ILA — discover, arm, capture:
chipscope_ila_core(action="list")
chipscope_ila_core(action="probes", ila_name="<ila-name>")
chipscope_ila_core(action="set_trigger", ila_name="<ila-name>", probe_trigger_values={"<probe>": ["==", "0x...1"]})
chipscope_ila_core(action="arm", ila_name="<ila-name>", trigger_immediately=False, window_count=<n>, window_size=<n>, trigger_position=<n>)
# For a multi-phase (TSM) trigger instead of a single probe compare, pass
# trigger_state_machine=<program text> to arm() -- see REFERENCE.md's TSM
# section for grammar, rejection rules, and worked examples.
chipscope_ila_capture(action="wait", ila_name="<ila-name>", timeout_minutes=<n>)
chipscope_ila_capture(action="upload", ila_name="<ila-name>")
chipscope_ila_capture(action="export", ila_name="<ila-name>", file_path="vivado_agentic_ai_reports/hw-ila-debug/capture_data.csv", export_format="CSV")
Confirmed tool schema notes:
chipscope_ila_coreactions:list/status/probes/reset_probes/set_trigger/set_capture/arm/trigger_immediatechipscope_ila_captureactions:wait/upload/get_data/export- Use
ila_name=(notcore=) export'sfile_pathis required — always pass it explicitly undervivado_agentic_ai_reports/hw-ila-debug/so it lands where Step 5 requires
NEVER auto-program PDI. Stop and ask before chipscope_device(action="program").
Integration
Complementary: hw-vio-debug drives stimulus → ILA captures response (combined debug session)
Downstream: Export CSV/VCD for offline analysis in external waveform viewers
Metadata
Keywords: ILA, trigger, capture, waveform, probe, debug, CSV, VCD, TSM, state machine, compare value
NoC Debug (EA)
Early Access — this skill may change before general availability.
Automate NoC debugging on AMD Versal devices. Produces a root-cause report identifying the exact AXI master instance, the error rule, and actionable fix guidance.
Prerequisites
- chipscope-mcp server with
sysdbg_noc - Vivado MCP server (
vivado_execute) hw_server+cs_serveraccess to a Versal board- PDI/LTX pair for the design
- Vivado project (.xpr) or routed checkpoint (.dcp)
Tool Priority
chipscope_session, chipscope_device, chipscope_scan → hardware access
sysdbg_noc(action="analyze", output_format="json") → authoritative analyzer (do NOT manually decode registers)
vivado_execute → design correlation, artifact extraction, HSI API
Preflight (Fail-Fast)
Before starting, verify both MCP servers respond. If either fails, STOP immediately and tell the user.
chipscope_session(action="status")— if not connected, connect with user-provided URLsvivado_execute("puts {ready}")— if no session, start one with path from mcp.json--vivado-patharg +/bin/vivado
PDI Programming Approval
NEVER auto-program. Ask once before programming:
🚨 PDI: /path/to/design.pdi → Proceed? (yes/no)
Exception: if the user's instruction explicitly authorizes programming (e.g., "program and debug", "test all designs"), treat as pre-authorized.
Pipeline: 3 Steps
Run all steps sequentially. Do not pause between steps unless a hard failure blocks progress.
Step 1: Connect, Program, and Scan
Goal: Establish hardware access, program the device, and discover debug cores.
chipscope_session(action="connect", hw_server_url="TCP:<host>:3121", cs_server_url="TCP:<host>:3042")
chipscope_device(action="select", device_selector="0")
Then obtain PDI approval and program:
chipscope_device(action="reset") # ALWAYS reset before programming to clear sticky NPI error registers
chipscope_device(action="program", pdi_path="<pdi_path>")
chipscope_device(action="program_log") # check for EAM errors: "EAM Interrupt", "NoC NMU Error", "NoC NSU Error"
chipscope_scan(action="scan", ltx_path="<ltx_path>")
Why reset? NoC NPI error registers (ISR, ERR_NUM, ERR_INFO) are sticky and survive reprogramming. Without a reset, stale errors from prior runs contaminate the analysis.
PASS: Programming succeeded and scan completed. FAIL: Programming failed → STOP.
Step 2: Design Preparation
Goal: Extract routed-design artifacts for correlation.
Batch Vivado commands — combine into minimal calls:
# Call 1: Open project and run
vivado_execute("open_project <xpr_path>; set runs [get_runs impl_*]; puts $runs")
# If multiple impl runs, ask user which one. If single, use it.
vivado_execute("open_run <selected_run>")
# Call 2: Extract all artifacts (report_noc is a built-in Vivado 2026.1+ command)
vivado_execute("set outdir vivado-agentic-ai-reports/hw-noc-debug/<DESIGN_ID>/artifacts; file mkdir $outdir; report_noc -json $outdir/noc_report.json; write_noc_solution -force $outdir/noc_solution.ncr; write_hw_platform -fixed -force -file $outdir/design.xsa; puts DONE")
Required artifacts: noc_report.json (or .txt via -file), .ncr, .xsa, PDI, LTX (optional).
If design is not routed or PDI is missing → STOP, tell user to build first. Never run synthesis or implementation.
PASS: All artifacts extracted. FAIL: Design not routed or artifacts cannot be generated.
Step 3: Analysis and Root Cause
Goal: Run sysdbg_noc, correlate findings with design, identify the AXI master.
3a: Run Analyzer
sysdbg_noc(action="analyze", output_format="json")
If findings_count > 0, re-run with verbose=true for full register context.
Validate: schema_version == "noc.1.0.0". If not → STOP, runtime issue.
If findings_count == 0: report "No NoC errors detected", skip correlation, write report, close project.
3b: Correlate Each Finding
For EACH finding with findings_count > 0:
Findings may appear at NMU or NSU components. The correlation path differs:
NMU Findings (component_family == "NOC_NMU")
-
Map NMU to design instance: Match
module_base_addressagainstnoc_report.jsonNMU entries to get the physical site (e.g.,NOC_NMU512_X0Y0) and NoC port name (e.g.,S01_AXI).# Alternative: use netlist directly vivado_execute("foreach c [get_cells -hierarchical -filter {REF_NAME =~ NOC_NMU*}] { puts \"$c : [get_property SITE $c]\" }") -
Identify AXI master — try HSI first, then BD fallback:
# Method 1: HSI (works for Xilinx IP masters) vivado_execute("hsi::open_hw_design <outdir>/design.xsa") vivado_execute("set pin [hsi::get_intf_pins axi_noc_0/<nmu_port>]; set net [hsi::get_intf_nets -of_objects $pin]; set cells [hsi::get_cells -of_objects $net]; foreach c $cells { puts \"Cell: $c IP_NAME=[common::get_property IP_NAME $c]\" }") vivado_execute("hsi::close_hw_design [hsi::current_hw_design]")# Method 2: BD fallback (works for RTL module_ref cells where HSI returns empty) vivado_execute("open_bd_design [get_files *.bd]; set net [get_bd_intf_nets -of_objects [get_bd_intf_pins axi_noc_0/<nmu_port>]]; set src [get_bd_intf_pins -of_objects $net -filter {MODE == Master}]; set master [get_bd_cells -of_objects $src]; puts \"Master: $master IP=[get_property VLNV $master]\"") -
Error address from registers: Combine
REG_1ST_ERR_INFO_5(addr_l) andREG_1ST_ERR_INFO_6(addr_u) to reconstruct the 64-bit target address.
NSU Findings (component_family == "NOC_NSU")
NSU errors indicate the problem was caught at the slave endpoint (e.g., protocol violations like oversized AXSIZE). The NSU does not directly identify the master — trace backwards:
-
Map NSU to design instance: Match
module_base_addressagainstnoc_report.jsonNSU entries to get the physical site and NoC master port (e.g.,M00_AXI).vivado_execute("foreach c [get_cells -hierarchical -filter {REF_NAME =~ NOC_NSU*}] { puts \"$c : [get_property SITE $c]\" }") -
Identify which master(s) route through this NSU: Use the NCR file or address map to find all NMU→NSU paths. The
axidfield inREG_ERR_LOG_INFO_3encodes the source — cross-reference with the NMU port's AXID configuration. -
Extract protocol details from NSU error registers:
REG_ERR_LOG_INFO_3:axsize(bits 24-26),axid(bits 0-15)REG_ERR_LOG_INFO_4:axburst(bits 20-21)REG_ERR_LOG_INFO_6:addr_u(upper address)
Error Details Extraction
- Extract from analyzer JSON:
- Always available:
node_name,module_base_address,isr.active_bits,err_num.decode - When
err_num.rule.status == "decoded": userule.descriptionandrule.corrective_action - When
err_num.rule.status == "not_applicable": derive fix guidance from ISR bit name + ERR_NUM decode fields (see Fix Guidance table below)
- Always available:
Fix Guidance (when rule.status == "not_applicable")
| ISR Bit | Error Type | Typical Root Cause | Corrective Action |
|---|---|---|---|
addr_map_wr | Write decode error | Write to unmapped NoC address | Verify target address is within a mapped slave region in the NoC address editor. Check VALID_ADDR parameter or software pointer. |
addr_map_rd | Read decode error | Read from unmapped NoC address | Same as addr_map_wr but for read path. Check read address generation logic. |
xlx_infos_wr | Protocol/info write | AXSIZE exceeds port data width, or other protocol violation | Check AXSIZE vs NoC port data width. Ensure master's burst parameters match the NoC port configuration. |
xlx_infos_rd | Protocol/info read | Read protocol violation | Same as xlx_infos_wr but for read path. |
timeout | Transaction timeout | Slave not responding within timeout period | Check slave readiness, clock domain crossings, or increase NoC timeout via sysdbg_noc_timeout. |
3c: Close Vivado
vivado_execute("close_project")
Output
Generate ONE report file at:
<workspace>/vivado-agentic-ai-reports/hw-noc-debug/<DESIGN_ID>/noc_debug_report.md
Also save the raw analyzer JSON at:
<workspace>/vivado-agentic-ai-reports/hw-noc-debug/<DESIGN_ID>/sysdbg_noc.json
Report Template
# {{DESIGN_ID}} — NoC Debug Report
## Environment
| Item | Value |
|------|-------|
| Device | {{part}} |
| Board | {{hw_server_url}} |
| PDI | `{{pdi_path}}` |
| Analyzer | sysdbg_noc {{schema_version}} |
## Findings ({{findings_count}} total)
{{REPEAT for each finding}}
### Finding {{index}}: {{node_name}}
| Field | Value |
|-------|-------|
| Component | {{component_family}} |
| Physical Site | {{nmu/nsu_site}} |
| Module Base | {{module_base_address}} |
| Error Type | {{isr_active_bit_name}} |
| Error Rule | {{rule_description OR derived from ISR bit (see Fix Guidance table)}} |
| Severity | {{severity OR "Error" if rule not available}} |
| Burst Type | {{burst_type}} |
| AXID | {{axid}} |
| AXLEN / AXSIZE | {{axlen}} / {{axsize}} |
| Error Address | {{reconstructed from err_info_5 + err_info_6}} |
#### Source AXI Master
| Field | Value |
|-------|-------|
| Instance | {{master_instance}} |
| IP Type | {{ip_name}} |
| VLNV | {{vlnv}} |
| NMU Port | {{nmu_port}} |
#### Connectivity Path
{{master}}/M_AXI → {{noc}}/{{port}} → NMU ({{nmu_site}}) → NoC → NSU ({{nsu_site}}) → {{slave}}
#### Fix
{{corrective_action from analyzer, or derived from rule + design context}}
{{/REPEAT}}
## Status: {{PASS|FAIL}} — {{one-line summary}}
Key Constraints
sysdbg_nocowns all error decoding. Never manually decode ERR_NUM or ISR registers.- Use HSI API for master identification first. If HSI returns empty (common for RTL
module_refcells), fall back to BD-levelget_bd_intf_netsor netlist-levelget_nets. - Never run synthesis or implementation.
- Extract NCR only from routed design, never from post-synthesis.
- Use
hsi::open_hw_designfor XSA — never unzip. - Always
close_projectwhen done. program_logis boot-time context only, not a substitute forsysdbg_noc.- Always reset device before programming (
chipscope_device(action="reset")) to clear sticky NPI error registers. - Findings can appear at NMU (master-side) or NSU (slave-side). Handle both in correlation.
- When
err_num.rule.status == "not_applicable", derive corrective action from the ISR bit name using the Fix Guidance table above.
NoC Performance Debug (EA)
Early Access — this skill may change before general availability.
Automate NoC bandwidth/latency/QoS debugging on AMD Versal devices. Produces a report identifying the bottleneck NoC site(s), measured vs. configured bandwidth/latency, and actionable tuning guidance.
This skill talks to hardware only. It does not drive Vivado and never opens a project, runs a Tcl session, synthesizes, or implements anything. All design context comes from artifact files the user supplies.
Prerequisites
- chipscope-mcp server with
chipscope_nocandchipscope_noc_perfmon(sysdbg_nocoptional, for an error sanity-check) hw_server+cs_serveraccess to a Versal board- PDI/LTX pair for the design
- Optional design artifacts supplied by the user (see Step 2):
noc_report.json,.ncr,.nts
Tool Priority
chipscope_session, chipscope_device, chipscope_scan → hardware access
chipscope_noc(action="discover") → enumerate NoC elements, get valid element_names
chipscope_noc_perfmon(action="measure") → authoritative bandwidth/latency samples (do NOT estimate from raw register reads)
sysdbg_noc(action="analyze") → optional: rule out NoC *errors* masquerading as a performance issue
user-supplied noc_report.json / .ncr / .nts → optional: hierarchy names, QoS class, configured bandwidth baseline
Preflight (Fail-Fast)
Before starting, verify the chipscope-mcp server responds. If it fails, STOP immediately and tell the user.
chipscope_session(action="status")— if not connected, connect with user-provided URLs
PDI Programming Approval
NEVER auto-program. Ask once before programming:
🚨 PDI: /path/to/design.pdi → Proceed? (yes/no)
Exception: if the user's instruction explicitly authorizes programming (e.g., "program and debug", "test all designs"), treat as pre-authorized.
Perfmon Monitor Authorization
chipscope_noc_perfmon configures hardware performance monitors, which changes device state. Never call it without explicit approval:
🚨 Configure NoC performance monitors on: <site_labels> → Proceed? (yes/no)
Exception: if the user's instruction explicitly pre-authorizes measurement (e.g., "measure NoC bandwidth", "profile the NoC", "check throughput"), treat as pre-authorized.
Configure the full site-monitor set once. Do not split monitor setup across multiple perfmon calls or batches.
Pipeline: 7 Steps
Run all steps sequentially. Do not pause between steps unless a hard failure blocks progress or an approval gate above requires it.
Step 1: Connect, Program, and Scan
Goal: Establish hardware access, program the device, and discover debug cores.
chipscope_session(action="connect", hw_server_url="TCP:<host>:3121", cs_server_url="TCP:<host>:3042")
chipscope_device(action="select", device_selector="0")
Then obtain PDI approval and program:
chipscope_device(action="reset") # ALWAYS reset before programming to clear sticky NPI error registers
chipscope_device(action="program", pdi_path="<pdi_path>")
chipscope_device(action="program_log") # check for EAM errors: "EAM Interrupt", "NoC NMU Error", "NoC NSU Error"
chipscope_scan(action="scan", ltx_path="<ltx_path>")
Optional error sanity-check: performance complaints are sometimes actually NoC errors (timeouts, decode errors) stalling traffic rather than a bandwidth/latency/QoS shortfall. If sysdbg_noc is available:
sysdbg_noc(action="analyze", output_format="json")
If findings_count > 0, tell the user NoC errors are present and may explain the perceived slowdown (the hw-noc-debug skill root-causes these). Ask whether to address those first or continue with performance measurement regardless — do not silently skip this warning.
PASS: Programming succeeded and scan completed. FAIL: Programming failed → STOP.
Step 2: Request Design Artifacts From the User
Goal: Obtain optional design context for labeling and baselines. Never generate these files — the user must supply them.
Ask once:
Optional NoC design artifacts (press Enter to skip any):
1. noc_report.json — NoC report (hierarchy names, physical sites, ports)
2. *.ncr — NoC compiler results (NMU→NSU routing solution)
3. *.nts — NoC traffic specification (bandwidth / QoS requirements)
Supply paths, or reply `none` to continue with hardware site names only.
Read whatever the user provides and build the design context:
- From
noc_report.json: map each physical site (e.g.,NOC_NMU512_X0Y0,DDRMC_X0Y0) to its design hierarchy name and NoC port (e.g.,S01_AXI). - From
.ncr: NMU→NSU routing, so you can identify which masters share an NSU or a path. - From
.nts: configured read/write bandwidth requirement and QoS class (Best Effort / Isochronous / Low Latency) per connection. This is the only valid "expected" baseline.
When a site resolves to a hierarchy name, label it with the hardware site in parentheses:
<hierarchy_name> (<hw_site_name>)
Examples:
chipscopy_i/axi_noc_0/S01_AXI (NOC_NMU512_X0Y0)
chipscopy_i/ddrmc_0 (DDRMC_X0Y0)
If the user supplies nothing (or a lookup fails): do not attempt to resolve design instance/hierarchy names by any other means. Use the Vivado site names reported by ChipScoPy exactly as-is (e.g., NOC_NMU512_X0Y0), and state in the report that no design artifacts were available, so no configured bandwidth/QoS baseline exists.
PASS: Artifacts loaded, or the user explicitly chose to continue without them. FAIL: A supplied path is unreadable → tell the user and ask for a corrected path or permission to continue without it.
Step 3: Discover Enabled Sites
Goal: Build the command-line selection list of observable sites.
chipscope_noc(action="discover", limit=50)
Cross-reference discovered element_names against the design context from Step 2 (by base address / site) so each measurable element gets a user-friendly label when possible.
- Keep only enabled / observable sites returned by discovery. Do not offer disabled or unresolved non-measurable entries.
- Refer to sites by the resolved hierarchy label when artifacts were supplied. Otherwise use the ChipScoPy site name as the label.
- If the user named a suspect path or IP, sort matching sites first.
chipscope_noc_perfmonaccepts 1–8 element_names per call. If discovery finds more than 8 viable sites, you may show more than 8 in the selection list, but the user must choose a final set of ≤8 before configuration.- For any element classified as DDRMC, ask the user for
ddrmc_freq_mhzunless it is unambiguously available in a supplied artifact — never guess a frequency.
Step 4: Ask the User Which Sites to Observe
Goal: Let the user choose the final monitor set before configuration.
Present all enabled observable sites as a command-line friendly numbered list:
Available observable sites:
[1] chipscopy_i/axi_noc_0/S01_AXI (NOC_NMU512_X0Y0)
[2] chipscopy_i/axi_noc_0/M00_AXI (NOC_NSU512_X0Y1)
[3] chipscopy_i/ddrmc_0 (DDRMC_X0Y0)
...
Reply with comma-separated numbers or ranges (example: 1,3,5-7), or `all`.
Without artifacts the same list uses raw site names:
Available observable sites:
[1] NOC_NMU512_X0Y0
[2] NOC_NSU512_X0Y1
[3] DDRMC_X0Y0
- Do not auto-select sites unless the user already provided an explicit site list.
- Real terminal checkboxes are not required; use the numbered multi-select format above because it works reliably in plain CLI chat.
- If the user selects more than 8 sites, ask them to narrow the list to ≤8. Never silently trim a user selection.
- Preserve the user's chosen display labels for the rest of the session and in the final report.
Step 5: Configure the Monitor Set
Get Perfmon Monitor Authorization (see above) using the resolved site labels, then configure the final ≤8-site set in one go. Keep the selected element_names fixed for the rest of the live session.
chipscope_noc_perfmon(action="measure", element_names=[...], sample_count=8, timeout_seconds=30, ddrmc_freq_mhz={...if applicable...}, authorize_monitor_configuration=true)
- This first call establishes the monitor configuration for the chosen sites and may also return the first sample window.
- Do not reconfigure mid-session, and do not split site-monitor setup across multiple calls.
Step 6: Collect and Live-Plot
Goal: Stream measurements in the terminal for up to 30 seconds.
After configuration, continue measuring the same site set and redraw a terminal view on each refresh:
Time Site Label Read BW Write BW Latency
00.0 chipscopy_i/axi_noc_0/S01_AXI (NOC_NMU512_X0Y0) ###### ## ###
00.0 chipscopy_i/ddrmc_0 (DDRMC_X0Y0) ### ##### ####
- Use simple ASCII bars/sparklines or aligned numeric columns; optimize for a readable terminal, not rich graphics.
- Refresh until either:
- the user presses Escape, or
- 30 seconds of wall-clock time have elapsed.
- If raw Escape-key capture is unavailable in the client, fall back to a clear typed-stop instruction such as
Type esc and press Enter to stop early. - Note: the burst ends when the fastest element completes, so slower elements may return fewer samples than requested. Record the actual sample count returned per element — flag any element that returned noticeably fewer samples than requested as low-confidence.
PASS: Live data displayed for the configured monitor set. FAIL: Timeout or empty samples → retry once, then report as inconclusive for that element rather than fabricating a value.
Step 7: Analyze and Correlate
Goal: Identify the bottleneck site(s), correlate to the design when artifacts allow, and produce tuning guidance.
7a: Compute Metrics
For each measured site, compute avg/peak read & write bandwidth and avg/peak latency across returned samples.
7b: Flag Bottlenecks
Flag a site as a bottleneck when any of:
- Measured bandwidth is materially below its configured requirement from the
.ntstraffic spec (under-delivering). - Measured bandwidth is near the NoC port's physical capacity (data width × frequency) — i.e., saturated, which explains why other traffic on the same path is starved.
- Latency is high for a connection the
.ntsdeclares Isochronous or Low Latency (these classes have tight latency budgets; Best Effort connections tolerate more).
If no .nts was supplied, report the raw measured numbers and say explicitly that no baseline was available for comparison — do not invent a target.
7c: Correlate Each Flagged Site
With artifacts:
- Use
noc_report.jsonto name the design instance and NoC port behind the flagged site. - Use the
.ncrrouting solution to find the NMU→NSU paths that share the flagged endpoint, since contention from a second master is a common cause of an otherwise well-provisioned connection underperforming. - Use the
.ntsentry for that connection to state the configured requirement and QoS class.
Without artifacts: report the ChipScoPy site name, the measured numbers, and stop there. Do not speculate about which IP or hierarchy instance drives the site.
7d: Tuning Guidance
Base guidance on what was actually measured — pick from (do not apply mechanically, match to the finding):
- Under-delivering vs. requirement: review the NoC bandwidth/QoS allocation for this connection; confirm the connection isn't sharing an NMU/NSU with contending traffic.
- Saturated port: rebalance traffic across NMU/NSU paths, increase burst size to improve efficiency, or reduce contending traffic on the same path.
- High latency on Isochronous/Low Latency connection: verify the QoS class is actually applied on the NoC path (not silently downgraded to Best Effort); check for a shared NSU with bursty Best Effort traffic starving it.
- DDRMC-adjacent bottleneck: check DDR page policy/bank conflicts and whether
ddrmc_freq_mhzused matches the actual running frequency.
Output
Generate ONE report file at:
<workspace>/chipscope-agentic-ai-reports/hw-noc-perfmon/<DESIGN_ID>/noc_perfmon_report.md
Also save the raw perfmon samples (and, if run, the sysdbg_noc JSON) at:
<workspace>/chipscope-agentic-ai-reports/hw-noc-perfmon/<DESIGN_ID>/chipscope_noc_perfmon.json
<workspace>/chipscope-agentic-ai-reports/hw-noc-perfmon/<DESIGN_ID>/sysdbg_noc.json (if run)
Report Template
# {{DESIGN_ID}} — NoC Performance Debug Report
## Environment
| Item | Value |
|------|-------|
| Device | {{part}} |
| Board | {{hw_server_url}} |
| PDI | `{{pdi_path}}` |
| Design artifacts | {{noc_report.json / .ncr / .nts supplied, or "none — hardware site names only"}} |
| Error sanity-check | {{sysdbg_noc findings_count, or "not run"}} |
## Measured Sites ({{count}} total, {{deferred_count}} deferred — see below)
{{REPEAT for each measured site}}
### Site {{index}}: {{site_label}}
| Field | Value |
|-------|-------|
| Hierarchy Label | {{hierarchy_name, or "unresolved — no artifacts"}} |
| Hardware Site | {{hw_site_name}} |
| Component | {{NMU/NSU/DDRMC}} |
| Connection | {{source}} → {{destination}}, or "unknown" |
| QoS Class | {{from .nts, or "unknown"}} |
| Configured Requirement | {{read/write BW from .nts, or "no baseline available"}} |
| Measured Bandwidth (avg/peak) | R: {{...}} / W: {{...}} |
| Measured Latency (avg/peak) | {{...}} |
| Samples Returned | {{n}} / {{requested}} {{note if truncated}} |
| Bottleneck? | {{yes/no + reason}} |
{{IF bottleneck AND artifacts supplied}}
#### Connectivity Path
{{master}} → {{noc}}/{{port}} → NMU ({{nmu_site_label}}) → NoC → NSU ({{nsu_site_label}}) → {{slave}}
{{/IF}}
#### Tuning Guidance
{{guidance from 7d, tailored to this finding}}
{{/REPEAT}}
## Deferred Sites
{{list of sites not measured due to the 8-per-call limit, with reason for deprioritization}}
## Status: {{PASS|FAIL}} — {{one-line summary}}
Key Constraints
- This skill never drives Vivado. Do not open projects, run Tcl, use HSI, or read an XSA — design context comes only from user-supplied
noc_report.json,.ncr, and.ntsfiles. - Ask the user for the NoC artifacts once, and continue gracefully when they decline.
- Without artifacts, use the ChipScoPy Vivado site names verbatim and never guess hierarchy or instance names.
chipscope_noc_perfmonowns all bandwidth/latency measurement. Never estimate throughput or latency from raw register reads.- Never call
chipscope_noc_perfmonwithout explicit Perfmon Monitor Authorization (or clear pre-authorization) — it changes device state. - Always ask the user which enabled sites to observe unless they already supplied an explicit site list.
- Max 8
element_namespermeasurecall — choose the final monitor set up front, configure all site monitors in that single call, and report any deferred sites instead of silently dropping them. - DDRMC elements require
ddrmc_freq_mhz; take it from a supplied artifact or ask the user — never guess. - Keep one fixed configured monitor set for the whole live-plot session. Do not reconfigure or re-batch once streaming begins.
- Live plotting is terminal-oriented and time-boxed: stop on Escape when supported, otherwise typed
esc, or after 30 seconds. - Sample counts can differ per element because the burst ends when the fastest element finishes; flag any element with a truncated sample count as lower-confidence.
- Use the
.ntsconfigured bandwidth/QoS requirements as the only "expected" baseline. If no.ntsis supplied, say so — don't invent a target. sysdbg_nocis an optional sanity-check for errors masquerading as performance issues, not a substitute for perfmon measurement. If it does turn up findings, surface them prominently — a NoC error is a more likely root cause than a bandwidth/QoS shortfall.- Always reset device before programming (
chipscope_device(action="reset")) to clear sticky NPI error registers.
PCIe Link Debug (EA)
Early Access — this skill may change before general availability.
Debugs PCIe link bring-up and link training on live AMD Versal hardware via
ChipScoPy MCP. CPM5 is the only PCIe block currently supported — the skill
detects the CPM version first and reports any other block as out of scope (see
Scope and CPM Version Gate).
The engine is sysdbg_analyze(subsystem='cpm') (the
sys-dbg-util CPM sub-block, bundled by chipscope-mcp) for the block-type gate and
the validated controller state, layered with chipscope_pcie for the LTSSM
state-transition history and chipscope_memory for PCIe configuration space.
See REFERENCE.md for the CPM5 module catalog, the sysdbg_analyze
CPM SubsystemResult shape, the chipscope_pcie response shape, advisory
config-space offsets, and the report schema.
Scope
CPM5 only. This is the block the sys-dbg-util CPM sub-block analyzes. Other PCIe blocks are out of scope and must be reported as such, never failed:
| Block | Families | In scope? |
|---|---|---|
| CPM5 | Premium (VP) | Yes — the subject of this skill |
| CPM4 | AI Core, Prime, AI Edge | No (out of scope) |
| CPM6 | Versal Gen 2 | No (out of scope) |
| PL-PCIE4 / PL-PCIE5 | soft block | No (out of scope) |
| UltraScale+ PCIE4C | US+ | No (not Versal; out of scope) |
The CPM5 gate is authoritative: sysdbg_analyze(subsystem='cpm') reports the
subsystem as unavailable on a non-CPM5 part rather than emitting failures. When
that happens, STOP and report the block as out of scope — do not attempt raw
register reads to force a result.
When out of scope, point the user at the right path rather than stopping blindly:
CPM4 / CPM6 PCIe and PL-PCIE4/5 (soft block) are not yet covered by a dedicated
skill — use register-based reads via the CPM/PCIE address map (AM012) or Vivado
hw_manager; UltraScale+ PCIE4C is non-Versal and outside this suite's scope.
CPM Version Gate (run first, before any analysis)
Detect the CPM version before proceeding. The skill currently supports CPM5 only, so the first action after connecting is to establish which PCIe/CPM block the part carries and stop early if it is not a live CPM5. Do this in two cheap, authoritative steps — never assume the block from the user's wording:
- Identify the device family from the part number —
chipscope_device(action='list')returns a device block withpartandfamily.familyis generic ("versal"for all Versal parts), so it does not distinguish the CPM generation — map from the part-number prefix instead (see Scope):xcvp*→ Premium → expect CPM5;xcvc*/xcvm*/xcve*→ AI Core / Prime / AI Edge → CPM4; Versal Gen 2 → CPM6; others (PL-PCIE, US+ PCIE4C) → no CPM5. This is a hint only — Step 2 is authoritative. - Confirm CPM5 is live —
sysdbg_analyze(action='analyze', subsystem='cpm', output_format='json'). This is the authoritative CPM-version check: sys-dbg-util'scpm.cpm5-versiongate readsCPM5_SLCR.CPM5_VERSION+CPM_PCSR.PCR.PCOMPLETEto separate "not a CPM5 part" from "CPM5 present but unpowered". Consume its verdict; do not re-read the version register yourself.
Decision (STOP unless CPM5 is confirmed live):
| Detected | Meaning | Action |
|---|---|---|
| CPM5 present + powered (modules returned) | In scope | Proceed to Stage 0/1/2 |
| CPM4 / CPM6 (family not Premium) | Different CPM generation | STOP — out of scope, name the detected generation, never FAIL |
| No CPM (PL-PCIE / US+ / soft block) | Not a CPM part | STOP — out of scope |
Premium part but CPM5 unpowered (version reads, PCOMPLETE=0) | Present but not brought up | STOP — report "CPM5 present but not powered/complete", never FAIL |
| Zero modules on a known-CPM5 part | chipscope-mcp older than 1.5.2 | STOP — see Tool Version Gate |
Record the detected block in report_data.json under block — block.type (e.g.
CPM5, CPM4, CPM6, none), block.in_scope, and block.reason (the STOP
reason when out of scope).
Tools Used
| Tool | Purpose |
|---|---|
sysdbg_analyze | Stage 0 engine. subsystem='cpm' — CPM5 block-type gate + validated per-controller link state, PHY-ready handshake, DPLL lock, sticky interrupts (ISR), and captive-GT status. |
chipscope_pcie | Stage 1. LTSSM current state + state-transition graph (history the CSR cannot see): status, ltssm_graph (DOT + optional PNG), trace. Requires a PCIe link-debug core in the design. |
chipscope_memory | Stage 2 (advisory). PCIe configuration-space reads (Vendor/Device ID, Command, BARs). |
chipscope_session | Connect to hw_server + cs_server. |
chipscope_device | List/select devices, check resources. |
chipscope_scan | Debug-core discovery. Run once (action='scan') when debug_ready is false/absent, before treating an empty chipscope_pcie(action='list') as "no core" (Step 4). |
chipscope_version | Read tool version for the tool version gate + report. |
| Agent file tools | Write output files. |
Tool Version Gate (chipscope-mcp >= 1.5.2)
- Required: chipscope-mcp >= 1.5.2. This is the release that supports CPM PCIe
analysis (
sysdbg_analyzeacceptssubsystem='cpm'and returns modules). Read the running version withchipscope_versionat the start of the session and record it inreport_data.jsonunderdevice.tool_version. - If the connected chipscope-mcp is older than 1.5.2 — or
sysdbg_analyze(subsystem='cpm')is rejected / returns zero modules on a known-CPM5 device — STOP and ask for a newer server: "This skill requires chipscope-mcp >= 1.5.2 for CPM PCIe analysis. Please connect a chipscope-mcp >= 1.5.2 and retry."
Efficiency Guidelines
- Gate on CPM5 first — run Stage 0 before anything else. If CPM5 is not present/live, stop; there is nothing downstream to read.
- cs_server is required — CPM5 captive-GT status (Stage 0) and the LTSSM graph (Stage 1) both need a cs_server connection. Connect with both URLs up front.
- The LTSSM graph needs a PCIe debug core —
chipscope_pcieonly works when the design instantiates a PCIe link-debug core. If it is absent, Stage 0 still gives the current link state; Stage 1's history is simply unavailable. - Do NOT write to PCIe registers without user confirmation — this can affect link state.
- Do NOT use terminal commands or Vivado Tcl. Use ChipScoPy MCP tools only.
Mandatory Workflow
Step 1 — Connect (hw_server + cs_server)
chipscope_session(action='status')
If not connected (cs_server is required for CPM captive GT and the LTSSM graph):
chipscope_session(action='connect',
hw_server_url='TCP:<hw_host>:3121',
cs_server_url='TCP:<cs_host>:3042')
If the cs_server is on a different host than the hw_server, pass it explicitly —
omitting it derives <hw_host>:3042, which is wrong when they differ.
Step 2 — CPM version gate
Run the CPM Version Gate now,
before any deeper reads: identify the device family (chipscope_device) and confirm
CPM5 is live (sysdbg_analyze(action='analyze', subsystem='cpm', output_format='json')). STOP unless a live CPM5 is
confirmed — report the detected generation as out of scope, never FAIL. Only when
CPM5 is confirmed do you continue to Stage 0 below.
Step 3 (Stage 0) — Validated controller state — sysdbg_analyze
sysdbg_analyze(action='analyze', subsystem='cpm', output_format='json')
The same call that confirmed CPM5 in Step 2 is the source of the validated state
(reuse its result — no need to call twice). The result is a SubsystemResult
(schema_version: "subsystem.1.0.0"); see
REFERENCE.md.
- Gate already passed: the block-type/CPM-version gate ran in Step 2. If it did not confirm a live CPM5, you are not here. Do not fall back to raw reads.
- Controllers: the pipeline folds each controller's apertures into one
CPM5_CONTROLLER{N}module (per thegroupingsblock), with one group per aperture. Enumerate them; do not hardcode names or a controller count. - Per controller, read the validated properties (verbatim from the tool):
link_state— LTSSM state + PHY-ready handshake (pass= up,fail/warnotherwise). Consume the tool's decoded string and status; do not re-decode a raw LTSSM value against a hardcoded table.- ISR sticky interrupts (expected 0), DPLL lock (PCSRLOCK/CALERROR), and captive-GT status.
- Unused controllers: an aperture that reads back as unused (read failure / all-ones) is reported NOT-AVAILABLE, never FAIL. Report it as unavailable.
- Negotiated speed/width are info only — never validated (the tool cannot know
the target config). Surface them, do not fail on them. Advisory downgrade
check: when both the advertised max (
cpm5_pcie_attrmax link speed/width) and the negotiated values (cpm5_dma_csr) are present, note negotiated < advertised as an info-level downgrade ("negotiated Gen3 x4 below advertised Gen4 x8"). This is advisory context (possible SI / partner limit → considerhw-ibert-gt-debug), never a FAIL/WARN, and is simply absent on a PIO design (no DMA status aperture).
Status taxonomy — consume the tool's status, do not invent one. Every property
carries a status; treat it exactly as sys-dbg-util reports it (the same way DDRMC
treats a controller with no CAL_STATUS as disabled, never FAIL):
Tool status | Meaning | Report as |
|---|---|---|
pass | Verified good | PASS |
fail | Hard failure | FAIL (only these count as errors) |
warn | Live but not proven good (e.g. link training disabled) | WARN — never FAIL |
expected_info | Expected-by-design (e.g. PIO build has no DMA PHY aperture; shared-LCPLL lane) | INFO — never FAIL, never WARN |
unchecked / info | Informational (e.g. negotiated speed/width) | INFO — never validated |
not_available | Aperture/controller unused or unreadable | NOT-AVAILABLE — never FAIL |
Per-controller roll-up (verbatim, deterministic): a controller's verdict is the
worst of its validated property statuses — any fail → FAIL; else any warn
→ WARN; else if inaccessible → NOT-AVAILABLE; else PASS.
expected_info/info/unchecked never escalate the verdict. A Stage-1 LTSSM
bounce is diagnostic context, NOT a verdict input — sys-dbg-util's link_state
owns the verdict, so a controller in L0 stays PASS even when its transition
history shows recovery re-entry (real trained links accumulate large cumulative
transition counts; see Step 4).
Negotiated speed/width are optional. On a PIO design the DMA status aperture
is absent, so sysdbg_analyze(cpm) reports link_status = "Status Aperture Absent (PIO design)" (expected_info) and there are no negotiated speed/width
properties. Their absence is expected — never treat a missing speed/width as an
error. When you need the trained rate, Stage 1's PCIe debug core carries it
(link_info/link_speed/link_width), still info-only.
Step 4 (Stage 1) — LTSSM state-transition graph — chipscope_pcie
The CSR (Stage 0) gives the current LTSSM state; the PCIe link-debug core gives the history — which distinguishes "trained cleanly on the first try" from "bounced through recovery/detect before reaching L0".
chipscope_pcie(action='list') # confirm a PCIe debug core exists
chipscope_pcie(action='status') # current_state, visited_states, states, transitions
chipscope_pcie(action='ltssm_graph',
save_plot='vivado_agentic_ai_reports/hw-pcie-link-debug/ltssm_graph.png') # DOT (+ PNG)
chipscope_pcie(action='trace') # raw hierarchical state trace
- Encoding-agnostic — consume what the tool returns.
chipscope_pciesurfaces the LTSSMcurrent_state(a name),visited_states, per-state visitation codes instates, per-edge traversal counts intransitions("src->dst": count), and the DOT graph — all derived from the debug-core IP. Do not maintain or assume a fixed LTSSM state set, numeric encoding, or graph shape in this skill: report the names and counts as given. This keeps the skill correct for future CPM blocks whose LTSSM encoding differs.- Real names are tool-defined and case-specific. On CPM5 hardware the state
names come back lowercase and dotted (e.g.
l0,r.eq,r.speed,polling.active), and the DOT node casing may differ from thestateskeys (the DOT rendersL0/R.Eq). Never string-match a state name, assume a casing, or cross-reference names betweenstatesanddot. Correlatecurrent_state/visited_statesto thestatesmap by the visitation codes, not by name equality across sources.
- Real names are tool-defined and case-specific. On CPM5 hardware the state
names come back lowercase and dotted (e.g.
- Interpretation (generic, encoding-independent):
- The current link verdict comes from Stage 0
link_state.status, not from string-matching a state name here. - Bounce / instability is ADVISORY, not a verdict. The meaningful signal is
re-entry of the settled state: the total traversals into
current_stateis greater than one (the link left its current state and came back — recovery/ detect re-entry). Do not use a naive "any edge count > 1": transition counts are cumulative over the trace window, so a healthy trained L0 link normally shows large counts on ordinary edges — treating that as a bounce false-positives (a real-hardware finding). Surface bounce as context ("reached L0 but re-entered recovery N×, consider IBERT"), but let Stage 0link_stateown PASS/WARN/FAIL — never downgrade a PASS link on bounce alone.
- The current link verdict comes from Stage 0
- A zero/empty core reading is only authoritative after a scan. Like the DDRMC
and ILA skills, do not treat an empty
chipscope_pcie(action='list')as "no core" until debug-core discovery has run: if the connect/session result exposesdebug_ready, treatdebug_ready: trueas cores discovered; if it isfalse/absent, runchipscope_scan(action='scan')once and re-list. Only a zero result after a completed scan is authoritative. - No PCIe debug core? After a completed scan,
chipscope_pciereturnsCORE_NOT_FOUND. That is a degrade, not a failure: record Stage 1 as unavailable and continue with the Stage 0 current state. (Its own error message points back tosysdbg_analyze(subsystem='cpm')for exactly this reason.)
Step 5 (Stage 2, advisory) — PCIe configuration space — chipscope_memory
Config-space reads add host-enumeration context (did the RP enable the endpoint?).
These offsets are advisory — verify the CPM5 config-space base for the design
before trusting decoded fields. See
REFERENCE.md ([TO CONFIRM]).
chipscope_memory(action='read', address=<cfg_base + 0x00>, count=1, word_size='w') # Device/Vendor ID
chipscope_memory(action='read', address=<cfg_base + 0x04>, count=1, word_size='w') # Command/Status
chipscope_memory(action='read', address=<cfg_base + 0x10>, count=6, word_size='w') # BAR0-5
- Vendor ID = 0xFFFF → device not present on the bus / link went down after training.
- Command reg (0x04) Memory Space Enable (bit 1) = 0 while link is up → host enumerated but did not enable the endpoint ("link up, no data transfer").
- Command reg (0x04) Bus Master Enable (bit 2) = 0 while link is up → endpoint cannot initiate DMA ("link trained, but no traffic") — a classic "link up, nothing works" cause. Advisory.
- All BARs = 0 → host has not enumerated the endpoint (enumeration timing / BAR sizing). Mark decoded config-space findings advisory in the report.
Step 6 — GT eye scan → delegate to hw-ibert-gt-debug
This skill does not run GT eye scans. When Stage 0 reports captive-GT concerns,
or the link shows SI-like symptoms (bounce, speed/width downgrade), cite the
captive-GT status from Stage 0 and hand off to the hw-ibert-gt-debug skill for
the transceiver-level eye scan. Record the handoff in the report.
Step 7 — Write Output Files — MANDATORY after every analysis
This step is not optional and does not depend on the user asking for a report. Any prompt that results in a completed PCIe read — "check PCIe link", "PCIe status", "LTSSM state", "PCIe link training", "why is the link down" — MUST write all output files before any chat summary.
Write every file under vivado_agentic_ai_reports/hw-pcie-link-debug/ using agent
file tools (they create missing parents — do not shell out to mkdir;
terminal commands are forbidden). ChipScoPy exports are confined to
CHIPSCOPE_MCP_OUTPUT_DIR.
| File | Format | Content |
|---|---|---|
report_data.json | JSON | Block type, per-controller link state/ISR/DPLL, LTSSM current+graph, config space, versions (schema in REFERENCE.md) |
REPORT.md | Markdown | Summary: controller table, link verdicts, LTSSM analysis, config-space (advisory), recommendations, IBERT handoff |
ltssm_graph.dot | DOT | LTSSM graph text from chipscope_pcie(action='ltssm_graph') |
ltssm_graph.png | PNG | LTSSM graph image (best-effort; save_plot) |
pcie_config.csv | CSV | Decoded config-space reads (advisory) |
After writing files, confirm in chat: "Files written to
vivado_agentic_ai_reports/hw-pcie-link-debug/: report_data.json, REPORT.md, ..."
Verdict casing (report_data.json and REPORT.md must agree): per-property and
per-controller status values are lowercase (pass|fail|warn|unchecked|expected_info|not_available);
the rolled-up summary.overall is uppercase (PASS|WARN|FAIL|OUT_OF_SCOPE). Use the
same casing in REPORT.md.
Where to find the report / recovery: the report lives at
vivado_agentic_ai_reports/hw-pcie-link-debug/REPORT.md in the working directory
where the session started. If the analysis completed but the files were not written,
re-emit them from the Stage 0/Stage 1 results already read — do not reconnect or
re-run the analysis. Only re-read (from Step 2) if the analysis itself failed.
Link Failure Diagnosis
When link_state is not pass:
- Read the tool's
link_statestring + messages verbatim (e.g. "PHY Never Ready", "Not in L0") — never relabel it. - Correlate within the controller: PHY-ready handshake, DPLL lock, sticky ISR.
- Use Stage 1
transitionsto tell "never trained" (stuck early, current state far from up) from "trained then unstable" (settled state re-entered repeatedly — advisory, does not by itself change a PASSlink_state). - Cross-reference
hw-ibert-gt-debug(captive-GT eye scan),hw-sysmon(GT supply), andhw-noc-debug(NoC timeout at the endpoint).
Correlation is within-module only — controller↔quad lane mapping is design-dependent, so no cross-module rule is hard-wired.
Multiple Controllers
CPM5 can expose more than one PCIe controller. Like the DDRMC skill's multi-DDRMC handling:
- Enumerate every module from Stage 0 — never hardcode names or a count, and never index by position (controller 0 is frequently the idle one).
- Tell PCIe controllers from captive-GT modules. Stage 0 returns two kinds of
module: PCIe controllers (
module_type: cpm5_controller, carry alink_state) and captive-GT blocks (module_type: cpm5_gtyp_cfg, nolink_state— these are the captive quads delegated tohw-ibert-gt-debug). Only the former are link controllers; do not treat a GT-cfg module as a PCIe link. - Read each accessible PCIe controller (link_state, ISR, DPLL, and its Stage 1
LTSSM). A controller present but with training disabled reports
link_state = "Not Configured (link training disabled)"(warn); an aperture that reads unused is NOT-AVAILABLE. Neither is a FAIL, and both can coexist with an active L0 controller — that mix is normal and rolls up to WARN overall. - Correlate the LTSSM trace to the right controller. A design usually
instantiates one PCIe debug core (
chipscope_pcie→ e.g.PCIe_0); attach its LTSSM history to the controller that actually brought a link up (the accessible PCIe controller whoselink_stateis up / most-progressed), not controller 0. - Roll up
summary.overallas the worst controller verdict: any controller FAIL → FAIL; else any WARN → WARN; else if none accessible → OUT_OF_SCOPE/no-controllers; else PASS. - Name the worst controller with its exact
link_statestring + status and the corroborating ISR/DPLL/LTSSM evidence — never a bare "PCIe failed".
Design-Specific Rules
| Rule | Wrong | Correct |
|---|---|---|
| Link status | "PCIe is up" | "CPM5_CONTROLLER0 link_state=L0 (Link Up), ISR=0, DPLL locked" |
| LTSSM | "link training" | "current_state=polling, never reached l0 — see transition graph" |
| Bounce | "link is bad" (downgrading a PASS) | "link_state=L0 (PASS, per Stage 0); LTSSM shows l0 re-entered 231× — advisory: run IBERT for SI" |
| Speed/width | "running at Gen4" / "speed missing = error" | "Negotiated Gen4 x8 (info only); or absent on a PIO design (DMA status aperture absent) — not an error" |
| Block type | "PCIe failed" | "Not a live CPM5 — out of scope for this skill" |
Error Handling
| Symptom | Meaning | Action |
|---|---|---|
sysdbg_analyze(cpm) returns 0 modules on CPM5 | chipscope-mcp older than 1.5.2 | STOP (version gate) |
| Subsystem unavailable / not CPM5 | Wrong block | STOP, report out of scope (never FAIL) |
| Controller aperture unused (all-ones/read fail) | Present but not instantiated | Report NOT-AVAILABLE, never FAIL |
chipscope_pcie → CORE_NOT_FOUND | No PCIe link-debug core in design | Degrade Stage 1; keep Stage 0 current state |
| cs_server not connected | Captive GT + LTSSM graph unavailable | Connect cs_server; without it, skip captive GT/graph |
link_state = PHY Never Ready | GT PHY never initialized | Check refclk/GT power; hand off to hw-ibert-gt-debug / hw-sysmon |
| Vendor ID 0xFFFF | Device not present / link down | Correlate with LTSSM current state + transitions |
Examples
"Check the CPM5 PCIe link" → connect → sysdbg_analyze(cpm) → CPM5 present,
CPM5_CONTROLLER0 link_state=L0, ISR=0, DPLL locked → chipscope_pcie shows a
clean single traverse to the up state → write artifacts → "Link up (Gen5 x8, info
only), trained cleanly."
"PCIe link won't train" → sysdbg_analyze(cpm) link_state="Not in L0",
current_state (Stage 1) stuck in Polling → "Never reached L0; speed negotiation
stage. Check partner + refclk; hand off to hw-ibert-gt-debug."
"Link is up but flaky" → link_state=L0 (PASS — the verdict stays PASS) but Stage 1 shows the settled state re-entered many times (recovery churn) → advisory: "In L0, but re-entered recovery repeatedly — SI-marginal. Run hw-ibert-gt-debug eye scan on the captive quad." (Bounce is context, not a downgrade.)
"Debug PCIe on an AI Edge part" → sysdbg_analyze(cpm) reports not CPM5 →
"Out of scope: this skill covers CPM5 (Premium) only."
Integration
Upstream: chipscope_session (connection), chipscope_device (programming — never auto-program; stop and ask).
Complementary: hw-ibert-gt-debug (captive-GT eye scan on PCIe lanes), hw-noc-debug (NoC timeout → PCIe endpoint), hw-sysmon (supply affecting the GT).
Downstream: SI findings → board respin, equalization tuning, partner configuration.
Metadata
Keywords: PCIe, CPM5, LTSSM, link training, link state, PHY ready, DPLL, configuration space, Gen3, Gen4, Gen5, BAR, Bus Master Enable, link speed, link width, captive GT, IBERT. Confidence Threshold: 0.80
VIO Debug (EA)
Early Access — this skill may change before general availability.
Interacts with VIO debug cores on live hardware: discover → read inputs → drive outputs → monitor activity.
See REFERENCE.md for VIO property tables and Tcl command reference.
Routing: Try Vivado MCP (vivado_execute + Hardware Manager Tcl, below) first if a Vivado MCP session is available — it works across all device families. Fall back to chipscope-mcp (chipscope_vio) if Vivado MCP is not installed. See Chipscope-mcp Fallback below.
Tools Used
Primary path — Vivado MCP (plus the agent's own file tools):
| Tool | Purpose |
|---|---|
vivado_execute | Run all Tcl commands (get_hw_vios, commit_hw_vio, etc.). Every Tcl block MUST be run via vivado_execute(session_id=..., command=<tcl>). |
vivado_doc_search | Look up unfamiliar VIO properties. No session_id needed. |
vivado_status | Check Vivado session health. |
vivado_list_sessions | Find an active session to use (get its session_id). |
| Agent file tools | Write output files (vio_snapshot.json, REPORT.md). |
Fallback path — chipscope-mcp (when Vivado MCP is unavailable): chipscope_session, chipscope_device, chipscope_scan, chipscope_vio. See Chipscope-mcp Fallback.
No terminal commands, no Python. Everything goes through Vivado MCP or, as fallback, chipscope-mcp.
Session Setup: Vivado Version Must Match hw_server
vivado_list_sessions→ check for an active session.- Before reusing one, run
version -shortand compare to the targethw_server's version. - Mismatch →
ERROR: [Labtools 27-3366] Cannot support older hw_server version. - On mismatch: do not retry or restart automatically.
vivado_startdoes not pick a matching Vivado version for you — an omittedvivado_pathjust resolves fromPATH, which is often the same mismatched install. Report the exact error, the session's version, and the targethw_server's version to the user, and ask them to point at the correct Vivado install (vivado_path) or the correcthw_server. - This only applies to an already-running, independently-started
hw_server. Ahw_serverthat Vivado auto-starts itself when connecting to a locally attached board is launched from that same Vivado install, so it cannot be version-mismatched — see "No hw_server" below. - Only reuse a session once its version matches.
Efficiency Guidelines
- Pass
session_idto everyvivado_executecall — get it fromvivado_list_sessionsif unknown. - Verify session version against
hw_serverbefore reuse, and report a mismatch to the user rather than retrying — see Session Setup above. - Batch Tcl — discover all VIO cores in one
vivado_execute, not separate calls. - Write reports to file — do not dump full probe data in chat. Give a short summary only.
- Use
vivado_doc_searchfor unfamiliar probe properties. - Do NOT use
shellcommands or Vivado Tcl file I/O. Use agent file tools. - Do NOT retry failed Tcl with different syntax. Search docs first, then report the error.
Monitor & Control Workflow
Step 1: Discover VIO Cores & Probes
puts "=== VIO CORES ==="
foreach vio [get_hw_vios] {
puts "VIO:$vio INSTANCE:[get_property INSTANCE_NAME $vio] REFRESH:[get_property CORE_REFRESH_RATE_MS $vio]"
puts " === INPUT PROBES ==="
foreach p [get_hw_probes -of_objects $vio -filter {TYPE == vio_input}] {
refresh_hw_vio $vio
puts " IN:$p VALUE:[get_property INPUT_VALUE $p] ACTIVITY:[get_property ACTIVITY_VALUE $p]"
}
puts " === OUTPUT PROBES ==="
foreach p [get_hw_probes -of_objects $vio -filter {TYPE == vio_output}] {
puts " OUT:$p VALUE:[get_property OUTPUT_VALUE $p]"
}
}
No VIO found → STOP. Guide: "No VIO cores detected. Ensure the device was programmed with a bitstream containing VIO cores and the correct .ltx probes file is associated."
⚠️ After programming or reprogramming, VIO output probe software values may retain stale values from the previous session. Always sync before driving outputs:
refresh_hw_vio -update_output_values [get_hw_vios hw_vio_1]
or reset all outputs to design-time initial values:
reset_hw_vio_outputs [get_hw_vios hw_vio_1]
This ensures the software state matches hardware, so that subsequent set_property OUTPUT_VALUE + commit_hw_vio creates proper signal transitions (e.g., 0→1 edges for pulse-triggered designs).
Step 2: Read Input Values
refresh_hw_vio [get_hw_vios hw_vio_1]
foreach p [get_hw_probes -of_objects [get_hw_vios hw_vio_1] -filter {TYPE == vio_input}] {
puts "$p INPUT:[get_property INPUT_VALUE $p] ACTIVITY:[get_property ACTIVITY_VALUE $p]"
}
Step 3: Drive Output Values
Map user's NL request to probe + value:
set_property OUTPUT_VALUE 1 [get_hw_probes <probe_name> -of_objects [get_hw_vios hw_vio_1]]
commit_hw_vio [get_hw_vios hw_vio_1]
Reset all outputs to initial values:
reset_hw_vio_outputs [get_hw_vios hw_vio_1]
Clear activity detectors:
reset_hw_vio_activity [get_hw_vios hw_vio_1]
Step 4: Write Output Files
⚠️ Write ALL files before giving any summary. Use agent file tools.
Write every file below under vivado_agentic_ai_reports/hw-vio-debug/. The
file tool creates missing parent directories, so do not shell out to mkdir
(this skill forbids terminal commands).
| File | Format | Content |
|---|---|---|
vio_snapshot.json | JSON | All probe names, directions, current values, activity |
REPORT.md | Markdown | VIO core status, probe values table, actions taken |
Design-Specific Rules
All outputs MUST use ACTUAL values.
| Rule | Wrong | Correct |
|---|---|---|
| VIO output | "asserted reset" | "Set OUTPUT_VALUE=1 on rst_n (hw_vio_1), committed" |
| Core info | "found VIO" | "hw_vio_1: 4 input probes, 2 output probes, refresh 500ms" |
Error Handling
| Error | Symptom | Action |
|---|---|---|
| No VIO cores | get_hw_vios empty | Check: bitstream has debug cores? .ltx file associated? |
| No hw_server | get_hw_servers empty | Guide: connect_hw_server -url localhost:3121 |
| VIO out-of-sync | Status shows "Outputs out-of-sync" | Run: refresh_hw_vio -update_output_values [get_hw_vios] |
| Design stalls after a chipscope-mcp write | Write succeeded and readback matches, but inputs stop changing | Partial write. Write every output of the VIO in one call (see Chipscope-mcp Fallback) |
Examples
"What is the VIO reset signal?" → Discover VIO → refresh_hw_vio → read INPUT_VALUE of reset probe → report value + activity.
"Assert reset for 1 cycle" → set_property OUTPUT_VALUE 1 on reset probe → commit_hw_vio → set_property OUTPUT_VALUE 0 → commit_hw_vio.
Chipscope-mcp Fallback
Use this path only when Vivado MCP is not installed. Session lifecycle per VIVADO-PATTERNS.md Pattern 19 (vivado-skill-creator):
chipscope_session(action="connect", hw_server_url="TCP:<host>:3121", cs_server_url="TCP:<host>:3042")
chipscope_device(action="select", device_selector="0")
chipscope_scan(action="scan", ltx_path="<path-to-design>.ltx")
VIO — read inputs:
chipscope_vio(action="read", vio_name="<vio-name>")
VIO — drive outputs: ALWAYS write every output probe of the VIO in one write call.
Some chipscope-mcp versions write only the probes you name. After programming, a write that names only some outputs can leave the VIO's other outputs driving wrong values and stall the design. The tool still returns success, and the readback shows the value you asked for. Writing every output in one call is correct on every version, with or without the fix.
- List the VIO's output probes (entries with
direction"out"):chipscope_vio(action="probes", vio_name="<vio-name>") - Read their current values:
chipscope_vio(action="read", vio_name="<vio-name>", probes=["<out1>", "<out2>", ...]) - Write all of them in one call. Change only what the user asked for; pass the current value for every other output:
chipscope_vio(action="write", vio_name="<vio-name>", probe_values={"<out1>": <current>, "<out2>": <new>, ...}) - Confirm the change through an input probe the output drives (value moving, direction, activity). Do not use the write
readbackas proof.
- A pulse (assert, then deassert) is two
writecalls, each with every output. action="ports_write"has the same problem. If you use it, pass everyprobe_out<N>port.action="reset"restores initial values but does not prevent this. Still write every output afterwards.- If the design already stalled after a partial write, one write of every output recovers it.
Exact action/parameter names must be confirmed against the live chipscope-mcp tool schema before use — do not assume the names above are final without checking chipscope-mcp/src/chipscope_mcp/tools/chipscope_vio.py.
NEVER auto-program PDI. Stop and ask before chipscope_device(action="program").
Integration
Complementary: Drives stimulus for hw-ila-debug capture (combined debug session)
Metadata
Keywords: VIO, probe, input, output, activity, monitor, drive, reset
Explain how AI Engines interact with Segmented Configuration and guide the user through the combined AIE + segmented config design and build flow.
Instructions
-
Explain AI Engine configuration partitioning in a Segmented Configuration design:
- The AIE configuration path and config tile (PLL, clocking) go into boot.pdi
- The AIE array configuration and core ELFs are packaged with pl.pdi into pl_aie.pdi
- An AIE-only PDI can be separately packaged and loaded after pl.pdi if needed
-
Explain XSA export considerations:
- The design must include the AI Engine and its NoC configuration path
write_hw_platformautomatically generates a Segmented Configuration extensible XSA- No additional flags needed — the segmented nature is detected from the project property
-
Explain the Vitis v++ Hardware Flow:
boot.pdi: build and configuration steps are identical to the standard (non-segmented) Vivado flowpl_aie.pdi: build and load process is the same as the standard Vitis flowxclbin: Vitis metadata generated by thev++packager; host application reads it identically to a non-segmented design- No special v++ flags are needed to support Segmented Configuration
-
Explain the Vitis v++ Hardware Emulation (HW_EMU) Flow:
- HW_EMU focuses on simulating application execution, not PDI configuration behavior
- Compatible with Segmented Configuration-enabled designs without modification
- Pre-loads PL contents using RTL simulators (no runtime PDI loading in emulation)
- Dynamically loads AIE configuration using
fpgautil aie_pl.pdi, but ignores PL configuration data (already pre-loaded by simulator) - Host application reads xclbin metadata the same way as in the hardware flow
-
Provide design guidance for AIE + Segmented Configuration:
- Ensure the NoC path connecting PS to the AIE configuration tile has
initial_boot = trueset - This ensures the AIE config tile is initialized in boot.pdi so the array is ready when pld.pdi loads the ELFs
- Verify and set the NoC
initial_bootpaths in Vivado before implementation - Validate with
/segcfg-design-check— run SEGCONFIG DRCs to confirm AIE NoC paths are correct
- Ensure the NoC path connecting PS to the AIE configuration tile has
-
For AIE + PL Reload scenarios:
- The AIE configuration tile (in boot.pdi) remains constant across PL reload operations
- AIE array configuration and ELFs (in pl_aie.pdi) can change with each PL variant
- The golden design must establish the full AIE NoC path superset (same rule as PL boundary)
- Import the NoC solution file from the golden run before compiling AIE variants
-
Reference documentation:
- UG1701: Vitis AI Engine documentation covering Segmented Configuration + AIE emulation flow details
- Use Vivado
write_device_imageto produce boot.pdi and pl_aie.pdi
-
Ask the user which part of the flow they need help with:
- Setting up the design with AIE included
- Exporting XSA for Vitis
- Building with v++ for hardware or emulation
- Running PL reload with AIE variants
Guide the user through running Segmented Configuration DRCs and pr_verify, and generate the corresponding Tcl commands.
Instructions
-
Read
references/segmented-drcs.mdfor the full DRC list with error messages. Readreferences/pr-verify-checks.mdfor pr_verify error codes and what they check. -
Ask the user which checks they need:
- Interactive DRCs (post-synthesis): Validate IO banks, clocking, DDRMC resource sharing
- pr_verify (post-route): Confirm NoC solution compatibility between a golden and variant design for PL reload
-
For DRC checks, generate Tcl:
# Run all Segmented Configuration-specific DRCs on post-synthesis checkpoint report_drc -checks {SEGCONFIG-1 SEGCONFIG-2 SEGCONFIG-3 SEGCONFIG-4 SEGCONFIG-5 SEGCONFIG-6 SEGCONFIG-7} -
Explain each DRC and guidance on resolution:
DRC Checks Resolution SEGCONFIG-1 Shared IO bank (boot + PLD use same bank) IO will not be reprogrammed on PL Reload; accept or move PL IO to a dedicated bank SEGCONFIG-2 Non-LVCMOS PLD port in a shared IO bank Change PLD port IOSTANDARD to LVCMOS SEGCONFIG-3 Clocking tile used by boot design Move clocking resources out of boot domain; typically should be in PLD SEGCONFIG-4 XPLL or CLK_PLL_AND_PHY tile shared by boot and PLD Reorganize clock planning to dedicate tiles to one partition SEGCONFIG-5 Used master X5IO bank not in boot partition (Gen 2) Move master bank DDR connection to boot partition or leave unused SEGCONFIG-6 Reconfigurable pblock contains boot partition resources Resize pblock: get_dfx_footprint -seg_config_bootshows boot tile footprintSEGCONFIG-7 DDRMC subsystem tile shared between boot and PLD partition Redesign DDR connectivity to avoid cross-partition DDRMC subsystem sharing -
For pr_verify (PL Reload compatibility), generate Tcl:
# Compare golden (initial) design against a PL variant (additional) # The -initial DCP must be the golden design containing the superset of connectivity pr_verify -segcfg_only -initial <golden_design>_routed.dcp -additional <variant_design>_routed.dcp -
Explain key pr_verify error codes from the reference file:
- HDPRVerify-01/02/03/37: Part, package, speed grade, and SEGMENTED_CONFIGURATION property must match
- SegConfig-Validation-1/2: Same number of boot paths and endpoints required
- SegConfig-Validation-3: Boot path settings (protocol, dest ID, slave addresses, TC values) must match
- SegConfig-Validation-4: Boot path routing (location, virtual channel, physical routes) must match
- SegConfig-Validation-10: PS/CPM-to-PL interface connections — PLD cannot add new connections
- SegConfig-Validation-12: Boot partition NMU configurations — NSU addresses and IDs must match
- SegConfig-Validation-13–16: All NoC sites in boot partition must match
- SegConfig-Validation-17: PLD cannot add new connections from a boot-path NMU
- SegConfig-Validation-18: PLD cannot add new IO to boot-partition banks
- SegConfig-Validation-20: Boot NMU remap entries cannot be added in PLD designs
-
If pr_verify fails with SegConfig-Validation-12, check that all NSU instances connected to boot NMUs have identical addresses and IDs between golden and variant designs. Use
read_noc_solutionto import the golden .ncr file before implementation. -
If pr_verify fails with SegConfig-Validation-18, check that the PLD design has not added new IO usages in banks included in the boot partition. These banks are used for DDRMC and are not reprogrammed with the PLD image, so adding new IOs here would cause runtime errors.
- Read
references/x5io-bank-sharing-debug.mdfor detailed diagnosing, guidance and resolving IO bank sharing issues in Segmented Configuration designs.
- Read
-
Remind the user that
pr_verifyis required for all PL Reload use cases and must be run on post-route checkpoints. -
Examples of checks performed represented in below table:
| Type of Check | Conditions Required |
|---|---|
| Boot path endpoints | The same number of booth paths and end points are required |
| Boot path settings | Same endpoint type (master/slave), Same protocol used, Same destination ID, Same slave addresses |
| Boot path routing | Same endpoint location, Same virtual channel, Same physical routes |
| Boot path masters connections | The secondary PLD design cannot add new connection from a boot path NMU |
| Boot partition IO usage | The secondary PLD design cannot add new IO to banks included in the boot partition. |
| Boot partition IO usage | These banks are used for DDRMC and are not reprogrammed with the PLD image |
Explain Segmented Configuration design constraints and help the user evaluate their design against known restrictions.
Instructions
-
Read
references/io-bank-guide.mdfor IO bank and clocking constraints. Readreferences/cpm-pcie-guide.mdfor CPM/PCIe-specific requirements. Readreferences/gen2-features.mdfor Gen 2 device-specific features. -
Ask the user which aspects of their design they want to review:
- IO bank sharing (PS and PL on same bank)
- CPM/PCIe use cases
- Gen 2 device features (VCU, ISP, ASU, DPDC, 10GbE)
- General PS-PL boundary awareness
-
Explain Mixed IO Banks (applies to all Versal):
- The boot image programs all IO in any bank required for DDR access (entire bank granularity)
- IO connecting to PL logic becomes active before PL domain is configured
- These IO cannot change functionality during PL Reload (they remain active until full-device reconfiguration)
- Run SEGCONFIG-1 DRC to identify shared IO banks
- PL ports in shared IO banks must use LVCMOS IOSTANDARD (SEGCONFIG-2 DRC)
-
Explain X5IO Granularity (Gen 2 devices only):
- The third X5IO bank from a DDR site can be allocated to PL when only two half-banks are used by DDR5
- Supported only for specific DDR5 configurations: Comp(DDR5) x4 with 16/20 data width, LPDDR5 x16/x32
- Master bank (bank 700, left-most) must be in the boot partition if used by DDR
- Run SEGCONFIG-5 DRC for master bank validation
-
Explain CPM Use Cases:
- CPM Root Port mode: must be held in reset until PLD PDI is loaded; also must be held in reset during PL Reload
- CPM end point (PCIe): Segmented Configuration auto-enables Tandem Configuration for 120ms link training
- Do NOT select Tandem Configuration manually in CPM customization
- To load PLD PDI over QDMA (Gen 1 CIPS): add
boot_device { pcie }to the boot.bif (line afterid = 0x2) - To load PLD PDI over QDMA (Gen 2 PS Wizard): set Secondary Boot = MMI_PCIe in Boot Mode (PLM) settings
- PCIe Extended Configuration Space, QDMA multi-function: NOT available until PL is configured
-
Explain Gen 2 device-specific features that depend on PL:
- VCU & ISP: Bundled with PL domain — unavailable until PLD PDI is loaded
- 10GbE FIFO and TSU: FIFO can be sourced from PL; TSU can use PL clock. Both require PL to be loaded
- ASU Soft Crypto Extension: PL extension enabled in PS Wizard; programmed by PLD PDI
- DPDC (Display Controller): Live/Mixed modes require PL clock. Enable "DP required before PL Config" checkbox to use PS-based GPU_CLK initially, then switch after PL loads (driver support in future release)
- SYSMON auxiliary ports: MIO/HDIO pins for external channel monitoring not available until PL is configured
-
Explain CIPS-inferred PL logic (all Gen 1 Versal):
- Some CIPS features are not entirely in hard blocks
- SYSMON auxiliary port measurements from external pins not possible until pins are configured
-
Provide guidance: for each concern identified, recommend whether to:
- Redesign to avoid the constraint
- Accept and document the behavior gap during the PS-only phase
- Use DRC checks to validate before PDI generation
Agents 2
Custom Op Worker Agent
You are a disciplined executor on a team developing custom AIE operators for VAIML. You do exactly what the team leader assigns -- nothing more, nothing less. You are not an architect, not a planner, not a decision-maker. You are a skilled craftsman who executes precisely within defined boundaries. You are spawned by the vai-custom-op orchestrator to develop one custom AIE operator. Your only job is to run the /vai-custom-op-implementation skill for the single op assigned to you and report the result.
Allowed orchestrators
You may only be called from the vai-custom-op skill as orchestrator.
Task
Invoke /vai-custom-op-implementation with the arguments the orchestrator gave you
(--model, --vitisai-config, --nodes, and --t only if it was provided).
Execute Phases 1-5 in full, including Phase 5 kernel optimization
(board-based measurement with /vai-perf-analysis when a board is reachable).
Apply techniques from BOTH /vai-aie-kernel-development and
/vai-aie-compiler-oriented-optimizations.
Do NOT attempt Phase 6 (stitching) or Phase 7 (end-to-end verification). Those belong to the orchestrator.
Workspace Boundaries
Work only inside the workspace directory assigned to you (typically
<parent_dir>/<op_name>/). You may read files outside it (skill files,
tutorials, reference implementations) but you MUST NOT write outside it. The
integration/ directory belongs to the orchestrator.
Environment
The skill supports two deployment models:
- Sourced venv -- the orchestrator passed
--t <activate_path>. Every shell that runspython3/aiecompilermustsource <activate_path>first. The<ENV_SETUP>placeholder in the/vai-custom-op-implementationSKILL.md examples expands tosource <activate_path>. - Pre-provisioned environment -- no
--twas passed. The Python packages and binaries are already onPATH/PYTHONPATH(e.g. official Vitis AI Docker container). The<ENV_SETUP>placeholder expands to nothing -- omit the line entirely.
Do NOT search the filesystem for an activate script if --t is absent.
Treat its absence as a deliberate signal that the environment is already in
place. If python3 -c "import flexml" fails, report the failure rather than
guessing at a venv to source.
Long-Running Commands (Compile, x86sim, Board Runs)
Compilation, x86sim, and board runs frequently exceed 10 minutes. Prefer
background tasks for long-lasting commands; if background tasks are disabled in
the harness, run them in the foreground. Run compile.py and x86sim in
sub-agents (via the Agent tool) to avoid polluting your context. Do not use
tricks like searching stdout for strings to detect process termination -- rely
on the operating system for process information (e.g. the PID) and on the logs
for output inspection after termination. Be aware of timeouts for long-lasting
commands.
Scripts Available
The /vai-custom-op-implementation skill provides its scripts at <skill_dir>:
compile.py-- VAIML compilation and CPU reference generationrun.py-- inference; runs on hardware, or in x86sim when the config setsrunner_type: "x86sim"compare_npy.py-- numeric comparisononnx_cut.py-- subgraph extractioncreate_custom_op_model.py-- Model B generation
Refer to the tutorials in <skill_dir>/tutorial/ for working examples of
kernels, tiling, and configs.
Final Report
When Phases 1-5 are complete, return a structured report to the orchestrator:
READY_FOR_INTEGRATION
op_name: <op_name>
working_dir: <absolute path>
yaml_path: <absolute path to custom_op_<name>/<name>.yaml>
compile_verdict: SUCCESS (gen_tg_adf non-empty: yes)
numeric_verdict: SUCCESS (max_abs_diff=<val>, mean_abs_diff=<val>)
optimization_verdict: <optimizations applied from vai-aie-kernel-development and
vai-aie-compiler-oriented-optimizations; Phase-4 re-validation after each;
/vai-perf-analysis board results or documented reason no board was reachable;
final kernel classification (vectorized / scalar-with-justification)>
peer_insights: <optional -- anything the orchestrator should forward to peers>
If you failed and cannot recover:
FAILED
op_name: <op_name>
working_dir: <absolute path>
failed_phase: <phase number>
error_summary: <brief description>
attempts_made: <count>
recommendation: <what the orchestrator might try>
Mixed-Precision Worker Agent
You are a disciplined executor for mixed-precision quantization tasks. You perform exactly what the orchestrator / team leader assigns — nothing more, nothing less. You are not an architect, not a planner, not a decision-maker. You are a skilled craftsman who executes precisely within defined boundaries.
Allowed orchestrators
You may only be called from the vai-quantization-guide skill as orchestrator.
Prime Directive
You MUST NOT broaden your scope beyond what the orchestrator explicitly assigned.
Before doing anything outside your assignment:
- Do NOT modify models not assigned to you
- Do NOT operate outside your assigned workspace directory
- Do NOT reuse data and assumptions from previous unrelated runs (e.g., regarding a different ONNX model)
- Do NOT change quantization strategy without orchestrator approval
- Do NOT skip accuracy validation steps
- Do NOT alter tolerance thresholds without explicit instruction
- Do NOT modify an ONNX model directly. A model is quantized ONLY through Quark
configurations — to change the model, write/adjust a Quark config and
requantize. The ONLY permitted exceptions are (a) the
/vai-vaip-patchskill, strictly for the specific edits it supports, and (b) ViT models going through the MHA-MX9 pipeline, which requires graph surgery by construction. In every other case where ad hoc model rewriting seems tempting, write a new Quark configuration instead. - Do NOT change files outside your assigned workspace
When in doubt: ask the orchestrator, don't improvise.
Capabilities
You can execute any of these sub-skills on behalf of the orchestrator:
| Skill | When to Use |
|---|---|
/vai-quantize | Apply quantization to a model using a specified Quark config |
/vai-fe-dtype | Analyze a model and determine correct compiler flags |
/vai-dequantize | Strip quantization from a model |
/vai-vaip-patch | Patch model for VAIP compatibility |
/vai-ffn-quantize | Extract and quantize FFN layers (MLP projections, attention QKV/output projections) |
/vai-partition-analysis | Inspect a VAIML compilation result, report the partition count / AIE-CPU split, and propose frontend-flag or Quark-config changes to reach a single NPU partition |
When assigned a compilation sub-task, use the shared
VAIML compile script (compile.py) deployed as sibling of these skills in the bundle
— look for compile.py in the scripts folder of the
vai-custom-op-implementation skill — compile with
keep_outputs: true, then run /vai-partition-analysis on the result. Report ALL CpuBecause messages and the partition count back to the orchestrator.
Vitis AI Environment — required for compile / board
Every sub-task runs in the same environment: a Vitis AI installation
provides quark for quantization together with flexml and the
VitisAIExecutionProvider for compilation and board execution. There is no
separate Quark venv. Inside the Vitis AI Docker container the environment is
already provisioned and nothing needs sourcing; otherwise source the activate
script the orchestrator passes as --t <path>. In the compile shell:
You can check that Vitis AI is available in your Python environment using:
export DEBUG_VAIML_PARTITION=2
export DEBUG_LOG_LEVEL=info
export BF16_SELECT=True
export ADD_TARGET_TO_CFG=True
python -c "import onnxruntime as ort; assert 'VitisAIExecutionProvider' in ort.get_available_providers()"
If the VitisAI EP is not available, report NEEDS_GUIDANCE and ask the
orchestrator / user for the Vitis AI environment (or activate script) — do not
guess, hardcode, or search the filesystem for one.
For models containing com.amd.quark custom ops (Extended QDQ / EQDQ, BFP),
first patch the model with scripts/patch_model_for_vaip.py (it adds the XIR
shape/data_type attributes and casts zero-points to bf16), then compile the
patched model with the compile script (scripts/compile.py) — it
registers the com.amd.quark custom ops found in the graph before creating the
session. Skipping the patch step makes such models fail with
com.amd.quark:ExtendedDequantizeLinear(-1) is not a registered function/op.
Environment variables
You will get extended output from the compiler if you set the following environment variables:
export DEBUG_VAIML_PARTITION=2
export DEBUG_LOG_LEVEL=info
export BF16_SELECT=True
export ADD_TARGET_TO_CFG=True
Plugin Skills
The worker also supports optional plugin skills located under
skills/experimental-methods/. Plugin skills are not hard-coded in the worker
— they are discovered at runtime.
To invoke a plugin skill:
- Check availability: verify the skill directory exists (e.g.
skills/experimental-methods/<name>/SKILL.md). If it does not exist, reportNEEDS_GUIDANCEto the orchestrator — do not fail silently. - Load the skill: read its
SKILL.mdto understand its arguments, scope, sub-commands/sub-options, and any experimental-feature consent banner. - Obtain consent if required: if the plugin declares an experimental warning banner, display it and wait for user consent before executing.
- Execute: follow the plugin's protocol exactly as you would a built-in skill, honoring its own sub-commands and options.
- Report: include the plugin name in your report.
The orchestrator may request a plugin by name (e.g. /vai-plugin <name> --model ...).
Do not maintain a fixed list of plugins — discover them from the filesystem.
All experimental-feature warnings, consent requirements, and version checks are
defined by each plugin's own SKILL.md; the worker does not hard-code them.
Execution Protocol
On Assignment
- Read your task. Understand exactly what is being asked.
- Acknowledge. Send back what you understood.
- Verify inputs. Confirm model file exists and is valid ONNX.
- Execute. Follow the appropriate skill's protocol.
- Report. Send structured results back to orchestrator.
Report Format
Task: <task_description>
Status: SUCCESS | FAILURE | NEEDS_GUIDANCE
Model: <model_path>
Config: <config_used>
Results:
- Accuracy: PASS/FAIL (atol=X, rtol=Y, pass_rate=Z%)
- PSNR: X dB
- Performance: X ms (mean), Y ms (std)
- Compilation: SUCCESS/FAILURE
- CpuBecause count: N
Notes: <any observations or issues>
Escalation Rules
You MUST escalate to the leader (via SendMessage) when:
- Compilation fails after 2 fix attempts -- you've tried the obvious fixes
- Numeric mismatch persists after 3 debug iterations -- printf debugging hasn't resolved it
- The selected quantization strategy cannot meet user requirements -- ask user to change the strategy and propose the available/allowed ones
- You need to change something outside your workspace -- never do this silently
- You encounter an error you don't understand -- don't guess, ask
- The task requirements are ambiguous -- ask for clarification before proceeding
On Failure
If you encounter an error:
- Attempt ONE independent fix (e.g., missing flag, wrong path)
- If fix doesn't work, report to orchestrator with:
- Error message
- What you tried
- Suggested next steps
- Do NOT attempt more than 2 fixes without orchestrator guidance
Constraints
- Work ONLY with files and models explicitly assigned
- Use ONLY the tolerances specified by the orchestrator
- Do NOT change the quantization config without approval
- Do NOT optimize or refactor code unless asked
- Report ALL CpuBecause messages — these indicate potential issues
- Always validate accuracy after any model modification
Sponsors
Details
- Marketplace
- Xilinx/ross-ai-assistant
- Category
- Community