Skip to content

codegen: accept char in device-extern signatures - #1049

Closed
NgoQuocViet2001 wants to merge 2 commits into
NVIDIA:mainfrom
NgoQuocViet2001:device-extern-char
Closed

NgoQuocViet2001 wants to merge 2 commits into
NVIDIA:mainfrom
NgoQuocViet2001:device-extern-char

Conversation

@NgoQuocViet2001

Copy link
Copy Markdown
Contributor

Fixes #875, following @nihalpasham's spec in this comment.

The change

TyKind::Char in rustc_ty_to_device_extern_type now routes through the same unsigned_integer helper u32 uses:

TyKind::Char => unsigned_integer(32),

Not the bool shape and not ZeroExtInteger(32). Extension attributes widen sub-32-bit values into a 32-bit slot; char is already 32 bits and fills the slot as it stands, so it lowers to a plain i32 in the parameter, result and pointee positions alike.

Test surface

Per the updated acceptance criteria, device_ffi_test is the surface rather than a TyCtxt unit test:

  • extern-libs/external_device_funcs.cu gains unsigned int char_to_upper(unsigned int) — ASCII uppercase only, so its return value can never leave the Unicode scalar range.
  • src/main.rs declares it as fn char_to_upper(c: char) -> char; in the existing #[device] extern block, exercising char in both the parameter and the result position, and adds a test_char_ffi kernel that round-trips 'q' (expects 'Q') and 'Z' (expects 'Z'), with a host runner asserting both exactly.
  • The example README documents the mapping, the expected .ll / .ptx shape, and both caveats: a value outside the Unicode scalar range (above 0x10FFFF, or a surrogate in 0xD800..=0xDFFF) is UB once it reaches Rust, and rustc's improper_ctypes lint still fires on char externs.

Test plan

  • Ran: cargo check in crates/rustc-codegen-cuda — clean.
  • Ran: cargo clippy in crates/rustc-codegen-cuda — no new errors or warnings.
  • Ran: cargo fmt --check — clean (see the note below).
  • Ran: rustfmt --edition 2024 --check on the example's main.rs — clean.
  • Not run: scripts/smoketest.sh device_ffi_test — no NVIDIA device on this machine. The expected values in the new runner are the exact 'q' -> 'Q', 'Z' -> 'Z' round trip, so a mismatch fails loudly rather than silently.

One incidental hunk

cargo fmt reflows two calls in the same match (rustc_ty_to_device_extern_type in the RawPtr and Array arms) that it had previously left alone. The old TyKind::Char arm held an over-long string literal, which made rustfmt give up on formatting the enclosing expression; with that line gone it formats the arm bodies it could not reach before. The tree is cargo fmt --check clean before and after, so I took rustfmt's output rather than fighting it — happy to drop those two hunks if you would rather keep the diff to the one arm.

A `#[device]` extern taking or returning Rust `char` was rejected outright,
with the message pointing at a u32 wrapper. `char` is a 32-bit Unicode
scalar value: it already fills a parameter slot and needs no extension
attribute in any position, so it lowers exactly as `u32` does and the C side
declares it `unsigned int`.

Route TyKind::Char through the same helper u32 uses. Nothing else moves --
plain i32 as a parameter, as a result, and behind a pointer.

The device_ffi_test example gains char_to_upper on both sides and a kernel
that round-trips 'q' and 'Z' through it, and its README documents the
mapping along with the two caveats: a value outside the Unicode scalar range
is UB once it reaches Rust, and rustc's improper_ctypes lint still fires.

Fixes NVIDIA#875

@nihalpasham nihalpasham left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified this end to end on an RTX 5090: scripts/smoketest.sh device_ffi_test passes (LTOIR, sm_120), the round-trip prints 'q' -> 'Q' with 'Z' unchanged, and the generated .ll shows declare i32 @char_to_upper(i32) with no extension attribute in any position. The compiler change matches the #875 spec and closes it.

Two things block the merge, both in the example, patch below:

  • The runner doesn't compile: stream.alloc_zeros::<u32>(2) doesn't exist in this repo's cuda-core (that's cudarc's API). The sibling runners use DeviceBuffer::<u32>::zeroed(&stream, 2).
  • The new extern needs #[allow(improper_ctypes)]. The per-example clippy gate runs -D warnings, and the warn-by-default improper_ctypes lint fires on char in a foreign declaration. The attribute survives the #[device] re-emission, so it can sit right on the item.
     // Rust `char` is a 32-bit Unicode scalar, so it lowers to a plain i32
     // parameter slot with no extension attribute -- the C side declares it
-    // `unsigned int`.
+    // `unsigned int`. `improper_ctypes` still flags `char` (no C equivalent);
+    // the u32 mapping above is the supported ABI, so allow it here.
+    #[allow(improper_ctypes)]
     fn char_to_upper(c: char) -> char;
-    let mut d_output = stream.alloc_zeros::<u32>(2).unwrap();
+    let d_output = DeviceBuffer::<u32>::zeroed(&stream, 2).unwrap();

To land it:

  • Apply the patch and push, or tick "Allow edits by maintainers" on this PR and we'll push the commit ourselves; it's already written and validated (fmt, clippy, GPU smoketest all green with it).
  • Keep the two rustfmt reflow hunks in device_codegen.rs. Deleting the long string literal is what unlocks them, and rustfmt demands them.

Once the branch compiles clean we'll approve CI and merge.

@nihalpasham nihalpasham added bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels Aug 20, 2026
Two review fixes from @nihalpasham, both in the example rather than the
compiler change:

- The runner called stream.alloc_zeros, which is cudarc's API and does
  not exist in this repo's cuda-core. Use DeviceBuffer::<u32>::zeroed
  like every sibling runner in this file.
- The per-example clippy gate runs -D warnings, and the warn-by-default
  improper_ctypes lint fires on char in a foreign declaration. The
  attribute survives the #[device] re-emission, so it sits on the item.
@NgoQuocViet2001

Copy link
Copy Markdown
Contributor Author

Both applied exactly as written, pushed. Thank you for taking it to a 5090 and for writing the patch out — that saved a round trip.

  • stream.alloc_zeros::<u32>(2) → DeviceBuffer::<u32>::zeroed(&stream, 2). My mistake: I reached for cudarc's API from memory instead of reading the sibling runners in the same file, all of which already do it the right way. Dropped the now-unneeded mut to match them.
  • #[allow(improper_ctypes)] on char_to_upper, with your comment wording so the reason is on the item rather than implied.

The two rustfmt reflow hunks in device_codegen.rs are untouched — agreed they are load-bearing: deleting the long error string is what lets those two calls fit on one line, and rustfmt then insists.

rustfmt --check is clean on the example. I cannot run the GPU smoketest or the per-example clippy gate here — no NVIDIA hardware on this machine — so your green run is the real signal on those two; I have not re-verified them myself.

Ready for CI approval whenever you are.

@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks, @NgoQuocViet2001 — the core TyKind::Char => unsigned_integer(32) change is sound and is being accepted.

I could not repair this branch directly because maintainer edits are disabled, and its commits do not carry the required DCO trailers/signatures. I therefore landed the change independently, with explicit credit to this PR, in #1179. The maintainer version keeps the parameter/return example and adds the pointer form plus exact sm_90 and sm_100 IR regressions that reject the plausible zeroext i32 mistake.

All exact-head hosted checks on #1179 are green. I am closing this PR only because #1179 supersedes its landing path, not because the compiler idea was declined. #1179 will close #875 when merged.

nihalpasham added a commit that referenced this pull request Aug 24, 2026
* codegen: accept char in device extern signatures

Map Rust char to a plain i32 across parameter, result, and pointee positions. Extend device_ffi_test with a char parameter/return/pointer case and a dual sm_90/sm_100 IR gate that rejects extension attributes.

This independently lands and credits the sound compiler change proposed by @NgoQuocViet2001 in #1049.

Closes #875

Signed-off-by: nihalp <[email protected]>

* style(codegen): apply the backend rustfmt

Signed-off-by: nihalp <[email protected]>

* style(device-ffi): apply the example rustfmt

Signed-off-by: nihalp <[email protected]>

---------

Signed-off-by: nihalp <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

char is rejected in #[device] extern signatures

2 participants