Skip to content

feat(ptx): analyze CFG and lexical normalization - #916

Closed
lucifer1004 wants to merge 15 commits into
NVIDIA:mainfrom
lucifer1004:pr/ptx-v2-cfg-analysis
Closed

lucifer1004 wants to merge 15 commits into
NVIDIA:mainfrom
lucifer1004:pr/ptx-v2-cfg-analysis

Conversation

@lucifer1004

@lucifer1004 lucifer1004 commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

Recovers control flow from parsed PTX and adds two source-level normalizations (anonymous-scope flattening, scoped-register renaming) that prepare a callable for raising into basic blocks (#917). Everything is fail-closed: any construct the analysis cannot prove is a typed hard error, never a guess.

Motivation

PTX text has no block structure, just labels and branches. Raising it into real IR (#917) needs a proven CFG first, and needs lexical scopes flattened (pliron blocks have no nested scopes):

bb0  [ld.param / cvta / mov]        ──fallthrough──▶ bb1
bb1  "$L_loop" [sub / setp / bra]   ──branch──▶ bb1   (loop back-edge)
                                    ──fallthrough──▶ bb2
bb2  [st.global / ret]              exit: Return

The fail-closed error taxonomy:

bra $L_typo;       target not defined       -> Err(UnknownBranchTarget)
brx.idx %r1, tbl;  table defined after use  -> Err(BranchTableAfterUse)
block ends, nothing follows                 -> Err(OpenFallthrough)
.version 9.4       above tested ceiling     -> Err(Version(Unsupported))

What changed (including the review hardening)

  • CFG recovery (ControlFlow::analyze): direct bra, brx.idx via .branchtargets, predicated fallthrough, ret/exit/trap; plan-then-apply rewrites composing into one validated EditScript transaction
  • the v.x hazard is closed. . is a word byte, so v.x lexes as one token and never matched the binding v; after renaming an inner vector register, a leftover v.x silently rebound to an outer register of the same name and assembled with wrong semantics. Rename plans now scan for base.suffix tokens (bank forms included, %r0.x is caught for %r<2>) and hard-error with the token and byte span
  • name-capture guard: a rename target can no longer collide with any label in the callable or any callable name in the module
  • the version ceiling now gates the rewrites, not just the read-only CFG (rewriting newer PTX is the risky direction). One shared version.rs, one typed error, all three entry points gated identically

Testing and validation

  • 35 dialect-ptx tests (6 new for guards and gating); full workspace green
  • round-trip over all 178 real PTX artifacts: 24 genuinely rewritten (gemm_sol alone: 185 renames, 129 scopes flattened), every rewrite reparses complete with identical instruction counts; ptxas accepts the rewritten text
  • 8 artifacts fail closed on nested .param call frames, correctly: flattening those would change .param allocation semantics

Landing

Merges as one unit via #917; this PR then closes as already-fixed.

@nihalpasham nihalpasham added enhancement New feature or request codegen Device code-generation pipeline (Rust MIR to IR to PTX) ptx-dialect Native PTX dialect series: structured PTX IR, CFG analysis, direct-to-PTX path interop Interop with external compilers / frontends labels Aug 16, 2026
lucifer1004 and others added 5 commits August 17, 2026 10:16
Rename the crate directory, package name, workspace entries, and all
dependent imports. Mark the crate publishable since cuda-host (published)
depends on it; the ptx-parse name is free on crates.io.
…ueries

Extracted from PR NVIDIA#915: ten examples' textual PTX assertions move onto
ptx-parse Document queries (callables, directives), with each example
Cargo.lock refreshed for the new path dependency. The dialect half of
that PR is not included.
…ing nothing

instructions_with_matching_head mapped Document::parse errors to an
empty match list, so unparseable PTX read as "no match" and could slip
through the probe validators with a misleading zero-count message.
Return the ParseError instead and propagate it through
matching_instructions, contains_matching_instruction,
InstructionPattern::matches, and selection_matches_policy, matching how
the other migrated call sites surface parse errors.
… dependency

cuda-host now depends on ptx-parse, and every example workspace resolves
cuda-host through its path dependency, so each committed example
Cargo.lock (and the isolated rustc-codegen-cuda lock) gains the two
additive ptx-parse entries. Purely additive, matching the re-lock
pattern from NVIDIA#893.
@nihalpasham
nihalpasham force-pushed the pr/ptx-v2-cfg-analysis branch from cb1a5f7 to 52db71e Compare August 17, 2026 06:43
@nihalpasham

Copy link
Copy Markdown
Collaborator

Rebuilt on the redesigned #915 (your analysis code needed nothing but the crate-rename adaptation, since it reads the parser's Instruction::predicate(), never the removed prefix string). Three hardening changes on top, two of which close correctness holes found in review:

1. The v.x hazard is now a plan-time error (389aedf). The failure it closes:

.reg .v4 .f32 v;          <- outer v
{  .reg .v4 .f32 v;       <- inner v, renamed to v_1
   mov.f32 %f1, v.x;      <- "v.x" is ONE token, never matched the binding
}                            -> silently read the OUTER register, assembled fine, wrong

RegisterAlphaPlan now scans for base.suffix word tokens before planning; if the base resolves to a binding being renamed (including bank forms, so %r0.x is caught for %r<2>), the plan errors with the token and byte span. Whole-vector uses still rename fine.

2. Rename targets can no longer capture label or callable names (35c38fe): every candidate is cross-checked against the callable's labels and all module callable names, deliberately broader than strictly-referenced symbols.

3. The PTX version ceiling now gates the rewrites, not just the read-only CFG (52db71e). Rewriting newer PTX is the risky direction; reading it conservatively is not. The check moved to a shared version.rs with one typed error, gating all three entry points identically. API note: CfgError's three version variants collapsed into CfgError::Version(PtxVersionError); nothing outside dialect-ptx referenced the old ones.

Verified:

  • 35 dialect-ptx tests (6 new for the guards and gates), full workspace green, all CI-mirror scripts pass
  • round-trip over all 178 real PTX artifacts: 24 genuinely rewritten (gemm_sol alone: 185 renames, 129 scopes flattened), every rewrite reparses complete with identical instruction counts; 8 fail closed on nested .param call frames, which is correct (flattening those would change .param allocation semantics); ptxas accepts the rewrites

Closes as already-fixed when #917 merges the stack.

nihalpasham and others added 10 commits August 17, 2026 12:29
Extracted from PR NVIDIA#915: crates/dialect-ptx only (the example-migration
half already landed with the ptx-parse foundation). Imports adapted from
the renamed ptx-syntax crate to ptx-parse.
…attrs

ptx.callable carried the same facts twice: typed attrs (callable_name,
callable_kind, callable_external) for queries and the header string for
printing. The emitter prints only the string, so mutating a typed attr
silently desynced the emitted PTX from the queryable truth.

The header stays the print carrier (it holds parameter lists and
performance directives the dialect does not model yet), but Verify now
re-parses it with ptx-parse and rejects any disagreement with the typed
attrs, naming both values in the error. ptx.scope's header gets the
matching check: a non-empty header must not carry its own terminator
and must not spell a callable, which would bypass ptx.callable's typed
attrs. The contract is documented on both ops.
…cate attr

PTX defines exactly one instruction prefix, the guard predicate, so
ptx.instruction no longer carries a free-form instruction_prefix string.
It now carries an optional typed PredicateAttr (register + negation),
populated by the projection from ptx-parse's parsed predicate. The
emitter derives the textual "@%p1" / "@!%p1" guard from the attribute,
and attribute verification rejects registers that are not %-prefixed.

PtxBuilder grows predicated_instruction(); plain instruction() drops the
prefix parameter. Repo-wide grep confirms nothing but predicate text
ever rode in the prefix string.
…it, reparse

Builds a kernel with a counting loop through PtxBuilder, prints the typed
IR (the loop back-edge carries the typed ptx.predicate attribute), emits
canonical PTX, and checks the guard survives a lossless ptx-parse round
trip.
The license-inventory, crate-overview, and SPDX CI guards require every
workspace member to be listed. Adds dependency-licenses.csv rows and
README Crate Overview rows for both new crates, and the standard SPDX
header on ptx-parse's audit example.
… plan time

'.' is a word byte, so a vector-element use such as v.x lexes as a
single token and never resolves to the binding v. Renaming a nested
binding would leave v.x behind, silently rebinding it to any
same-named outer register and assembling with wrong semantics.
RegisterAlphaPlan now scans the callable body for tokens of the form
R.suffix whenever R is scheduled for renaming and fails closed with a
typed error naming the token and its byte span.
…le names

The occupied-token check only avoids names spelled inside the callable
body. A module callable never referenced in the body, or a label equal
to a bank base name (which the bank availability check skips), can
still end up as a rename target; the rewritten register then captures
branch or call targets and the PTX fails ptxas or assembles with wrong
semantics. RegisterAlphaPlan now cross-checks every chosen target
against the callable's labels and the module's callable names and
fails closed with a typed error naming both symbols.
…eiling

The UnsupportedPtxVersion ceiling previously gated only the read-only
CFG recovery. Rewrites are higher risk than reads: an unaudited ISA
could bind or spell registers in ways the resolver does not model.
The .version validation moves to a shared version module with a typed
PtxVersionError, and RegisterAlphaPlan and ScopeFlattenPlan now fail
closed on missing, invalid, or newer-than-9.3 versions exactly like
ControlFlow::analyze.
@nihalpasham
nihalpasham force-pushed the pr/ptx-v2-cfg-analysis branch from 52db71e to 7d5a91e Compare August 17, 2026 07:01
@nihalpasham nihalpasham added the already-fixed Resolved on a newer commit or branch; no action needed label Aug 17, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Landed on main via the stack head #917 (squash 8eb0dcf); this layer's commits are contained in that merge. Closing as already-fixed per the stack landing plan.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

already-fixed Resolved on a newer commit or branch; no action needed codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request interop Interop with external compilers / frontends ptx-dialect Native PTX dialect series: structured PTX IR, CFG analysis, direct-to-PTX path

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants