Skip to content

feat(cuda-macros): add inline PTX macro support - #215

Merged
nihalpasham merged 1 commit into
NVIDIA:mainfrom
pattersonjack:inline-ptx
Jun 15, 2026
Merged

nihalpasham merged 1 commit into
NVIDIA:mainfrom
pattersonjack:inline-ptx

Conversation

@pattersonjack

@pattersonjack pattersonjack commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #149.

Adds cuda_device::ptx_asm!, a CUDA inline PTX macro for device code. This gives cuda-oxide users an escape hatch for advanced optimization and PTX instructions that are not yet exposed as typed device APIs or compiler intrinsics.

The initial implementation supports the common single-output and void-statement cases:

  • CUDA-style %0, %1, ... operand placeholders
  • literal PTX register escaping with doubled percent signs, e.g. %%laneid
  • in("...") operands
  • zero or one out("...") operand
  • up to 16 input operands
  • clobber("memory")
  • options(register_only) for pure register snippets

Default lowering is conservative: inline PTX is emitted as LLVM inline asm with sideeffect and convergent. options(register_only) opts out of both markers for snippets that only read explicit inputs and write the explicit output.

Example

let doubled: u32;

unsafe {
    ptx_asm!(
        "add.u32 %0, %1, %1;",
        out("=r") doubled,
        in("r") x,
        options(register_only),
    );
}

How It Works

The proc macro validates the PTX template and operands at Rust compile time, then lowers the call into hidden cuda_device::ptx marker functions:

  • __ptx_asm_out_N for snippets with an output
  • __ptx_asm_void_N for snippets without an output

Those marker calls carry the PTX template, constraint string, and options as static byte strings. The MIR importer recognizes the marker calls and replaces them with an NVVM dialect inline PTX op instead of importing the marker body.

The lowering path is:

  1. ptx_asm! parses and validates the user syntax.
  2. The macro converts CUDA %N placeholders into LLVM inline asm $N placeholders.
  3. The macro emits a hidden marker call with fixed arity.
  4. MIR import recognizes the marker and creates an inline PTX dialect op.
  5. MIR lowering converts that op to LLVM inline asm.
  6. LLVM export emits asm sideeffect and convergent by default, or omits both for options(register_only).

The collector skips the hidden marker bodies so their unreachable!() fallback does not pull panic machinery into device compilation.

Design Decisions

Default lowering is conservative because arbitrary user PTX may touch memory, depend on scheduling, or have cross-lane/control-flow semantics that are not visible to LLVM. Users can opt into options(register_only) only for pure register snippets with an explicit output and no clobbers.

The hidden marker functions are generated for fixed arities up to 16 because Rust does not have variadic generics. Sixteen inputs seems enough for the initial surface and keeps the marker API simple and explicit.

Missing vs CUDA Inline PTX

This is not full CUDA inline PTX parity yet. Gaps:

  • Multiple outputs are rejected.
  • Read-write operands are not implemented.
  • The "C" constraint is not implemented.
  • Only clobber("memory") and raw LLVM clobbers such as clobber("~{memory}") are supported.
  • options(register_only) is the only option today.

These are documented as current limitations and can be improved independently.

Testing

Run the tests:

cargo test -p cuda-macros -p mir-lower -p llvm-export

Run the example:

cargo oxide run inline_ptx

@nihalpasham nihalpasham self-assigned this Jun 15, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Really nice addition, thanks for the PR. We'd held off on full inline-asm support so far, mostly to keep folks on the typed-intrinsic path instead of reaching for the inline-asm escape hatch. But I think the pathways are clear enough now: where an LLVM intrinsic exists upstream, we model it as an nvvm op and lower it, and where one doesn't, the right move is to also file it upstream so we can pull as much of the error-prone hand-written PTX off users as we can. Inline PTX is the escape hatch for the gap in between

What I really like:

  • You spotted that Rust's asm! can't work here (host is x86, it rejects PTX register classes) and went the marker-call route instead.
  • nvvm.inline_ptx lands at the right pipeline stage and lowers into the same InlineAsmOp our tcgen05/wgmma paths already use.
  • Defaulting to sideeffect + convergent is the safe call and leaves all the existing callers untouched.
  • Good tests (the compile-fail fixtures especially) and the example actually checks its own results.

Two things worth fixing before it goes in:

1. options(register_only) turns off both sideeffect and convergent. Sideeffect-off is great. Convergent-off is the risky one, since the macro can't see what's in the template:

// a shfl.sync inside `if lane < 16`, marked register_only
if.then:  call asm "shfl.sync..."     // not convergent
// opt -O2 then hoists it out:
entry:    call asm "shfl.sync..."     // now ALL lanes run it -> wrong result / hang

(I actually reproduced that hoist under -O2.) Suggestion: keep register_only meaning sideeffect-off only, leave convergent on, and add a separate explicit opt-in like options(register_only, may_diverge) for the rare pure-and-hot case where someone really wants it off.

2. A literal $ in a template crashes llc. Real PTX has these (local labels like $L__BB0):

today:  "$L__BB0: ..."  ->  LLVM ERROR: Bad $ operand number
fix:    double a literal $ to $$  ->  llc prints "$L__BB0: ..." fine

One line in the template conversion plus a test.

On the documented gaps: all fine as follow-ups, nothing there blocks this. If you're up for more after, multiple outputs and read-write (+) operands are the two most worth doing (carry chains, loop accumulators). The clobber set is fine as-is, and the "C"/immediate constraint is low-pri since you can just bake constants into the template.

Some changes to the docs, in priority order:

  • The register_only docs currently sell the footgun as a feature. They say it "omits both markers" and frame dropping convergent as a benefit. That's the one doc change that's not optional, since it actively steers people toward the unsafe usage. It has to be rewritten alongside the convergent fix: "sideeffect-off only" plus a loud "never mark a .sync/collective non-convergent."
  • Slight under-claim: the docs imply only r (32-bit) works. f/d/l/h already flow through fine (tcgen05/wgmma already prove it). Worth listing the supported letters.
  • Minor: the book's quick-reference table advertises the hidden ptx marker module, which users must never call directly. Mark it "internal" or drop the row.

@pattersonjack

Copy link
Copy Markdown
Contributor Author

@nihalpasham Thanks for the detailed review, especially the repro for the convergent issue. I amended the commit to keep the history tidy and addressed the requested changes:

  • Changed options(register_only) to only drop sideeffect; it now keeps convergent.
  • Added explicit options(register_only, may_diverge) for the rare case where dropping convergent is intentional.
  • Escaped literal $ in PTX templates before LLVM inline asm export, with regression coverage for $L__BB0-style labels.
  • Updated the register_only docs to describe the safer default behavior and warn against using may_diverge for .sync / collective snippets.
  • Listed the currently supported constraint letters (h, r, l, q, f, d, plus input-only n) and added macro tests for accepted/rejected constraints.
  • Removed the internal cuda_device::ptx marker module from the public quick-reference tables.

As you mentioned, multiple outputs and read-write (+) operands look like the best next steps after this.

@nihalpasham nihalpasham added enhancement New feature or request codegen Device code-generation pipeline (Rust MIR to IR to PTX) intrinsics Device intrinsics and libdevice math mappings llvm-export Textual LLVM/NVVM IR exporter (llvm-export crate) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) labels Jun 15, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

LGTM 👍🏾

One small thing, nothing for you to do: you turned the "document the constraint letters" suggestion into actually enforcing an allowlist. The friendlier errors are nice, but it does tighten the escape hatch a bit, since an unlisted-but-otherwise-valid constraint is now a hard macro error instead of falling through to LLVM.

Inline PTX is meant to be the "we don't model this yet" hatch, so we'll probably just relax that to a warning or pass-through in a tiny follow-up on our end. Thanks again for this.

@nihalpasham
nihalpasham merged commit 6f663d1 into NVIDIA:main Jun 15, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) llvm-export Textual LLVM/NVVM IR exporter (llvm-export crate)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Inline PTX in code

2 participants