Skip to content

Convert -Ctarget-cpu into a target-modifier for AVR, AMDGCN and NVPTX #150732

Open
kulst wants to merge 2 commits into
rust-lang:mainfrom
kulst:cpu_is_target_modifier
Open

Convert -Ctarget-cpu into a target-modifier for AVR, AMDGCN and NVPTX #150732
kulst wants to merge 2 commits into
rust-lang:mainfrom
kulst:cpu_is_target_modifier

Conversation

@kulst

@kulst kulst commented Jan 6, 2026

Copy link
Copy Markdown
Contributor

View all comments

Crates built for AVR, AMDGCN and NVPTX that specify different values for -Ctarget-cpu cannot be soundly linked together.
This PR attempts to make rustc ensure that no crates with disagreeing values for -Ctarget-cpu are linked together. This is achieved by converting -Ctarget-cpu into a target-modifier depending on --target.
To do this, the consistency check for -Ctarget-cpu considers mismatching values as inconsistent only for targets for which the new flag requires_consistent_cpu is set in their target spec.

Why should -Ctarget-cpu be a target-modifier for nvptx?

PTX is a single-module contract

PTX requires a binary to start with .version (`ptx$$`) then .target (`sm_$$`). If the ptx contains instructions that are not supported by either .version or .target, the binary is ill-formed and will be rejected by ptxas. The concept of features that can be mixed and matched in a binary does not exist for nvptx and is therefore not supported by LLVM.

It prevents the production of bitcode that cannot be codegen'd after linking

A target modifier should prevent configurations that are not composable across crates when those crates are linked together. The most prominent example is when enabling a target feature changes the ABI, making cross-crate calls inherently unsound.

In the case of nvptx, ABI mismatch is (at least for now) not the core problem motivating target modifiers. NVIDIA’s documented PTX calling convention has remained stable since ptx20.

However, in the current state it is possible to produce bitcode that cannot be codegen'd after linking, because some operations are only lowerable for sufficiently new SM/PTX levels. In the best case this results in an LLVM error during the final llc step, but this is not something we should rely on for correctness.

nvptx has a special compilation pipeline where instead of linking the final PTX object, instead LLVM bitcode is linked. The resulting artifact is then compiled in one invocation.
Now consider crate A which is independently compiled into bitcode with the following rustc arguments:

//@ compile-flags: --target nvptx64-nvidia-cuda -C target-cpu=sm_70 --crate-type=rlib
#[cfg(target_feature = "sm_70")]
fn foo() { 
    // cannot be lowered to ptx before "sm_70: so currently produces an LLVM error
}
#[cfg(not(target_feature = "sm_70"))]
fn foo() {
    // can be lowered to ptx before "sm_70"
}
pub fn bar() {
    foo()
}

Crate A is a dependency of crate B. In the rustc invocation of crate B

  1. crate B is compiled into bitcode, too
  2. both bitcode artifacts are bitcode-linked by llvm-link
  3. the resulting bitcode artifact is compiled by llc -mcpu=sm_60

This should now ideally create an LLVM error, because the linked bitcode contains code paths that were selected under sm_70 assumptions but the final NVPTX codegen is targeting sm_60, where those operations are not lowerable. An LLVM error here is better than silent miscompilation, but it’s not a promise we should rely on.

A real example where this could happen is the lowering of atomic loads and stores with non-relaxed orderings, which is known to depend on the selected SM level.

Why should -Ctarget-cpu be a target-modifier for amdgcn and avr?

  • In case of AVR the target-cpu defines the ISA, which is encoded in the ELF header flags, amdgcn also encodes the cpu directly into those flags
  • To not rely on lld which currently prevents it for both by looking at those flags AVR and amdgcn

Previous discussions about the topic can be found here and here.

I also created a Zulip discussion.

I am unsure if a MCP is needed before proceeding. If you think so please let me know.

Creating target-modifiers for NVPTX target-features is to be done in a follow-up.

cc @kjetilkjeka as target maintainer for NVPTX
cc @Flakebi as target maintainer for amdgcn
cc @Patryk27 as target maintainer for AVR
cc @RalfJung you were very involved in the discussions so far

Target modifier tracking issue: #136966

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Jan 6, 2026
@kulst kulst changed the title Making -Ctarget-cpu a target-modifier on NVPTX Make -Ctarget-cpu a target-modifier on NVPTX Jan 6, 2026
@kulst

kulst commented Jan 6, 2026

Copy link
Copy Markdown
Contributor Author

@rustbot label: +O-NVPTX

@rustbot rustbot added the O-NVPTX Target: the NVPTX LLVM backend for running rust on GPUs, https://llvm.org/docs/NVPTXUsage.html label Jan 6, 2026
@kulst kulst changed the title Make -Ctarget-cpu a target-modifier on NVPTX Convert -Ctarget-cpu into a target-modifier on NVPTX Jan 7, 2026
@kulst kulst changed the title Convert -Ctarget-cpu into a target-modifier on NVPTX Convert -Ctarget-cpu into a target-modifier for NVPTX Jan 7, 2026
@kulst
kulst force-pushed the cpu_is_target_modifier branch from 7164067 to a8f5e96 Compare January 7, 2026 21:26
@kulst
kulst marked this pull request as ready for review January 7, 2026 21:34
@rustbot

rustbot commented Jan 7, 2026

Copy link
Copy Markdown
Collaborator

Some changes occurred in src/doc/rustc/src/platform-support

cc @Noratrieb

These commits modify compiler targets.
(See the Target Tier Policy.)

@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jan 7, 2026
@rustbot rustbot removed the S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. label Jan 7, 2026
@rustbot

rustbot commented Jan 7, 2026

Copy link
Copy Markdown
Collaborator

r? @nnethercote

rustbot has assigned @nnethercote.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@kulst

kulst commented Jan 7, 2026

Copy link
Copy Markdown
Contributor Author

r? @bjorn3 as you suggested this change.

@rustbot rustbot assigned bjorn3 and unassigned nnethercote Jan 7, 2026
Comment thread compiler/rustc_target/src/spec/targets/nvptx64_nvidia_cuda.rs Outdated
@kjetilkjeka

Copy link
Copy Markdown
Contributor

It works out really nice with -CTarget-cpu being able to be a target modifier.

It would be nice to know what the plan was with the ptx isa version as well. I asked that question here

@RalfJung

RalfJung commented Jan 8, 2026

Copy link
Copy Markdown
Member

I can't vouch for the implementation, but the approach sounds good. :)

Cc @Darksonn

@kulst

kulst commented Jan 10, 2026

Copy link
Copy Markdown
Contributor Author

I have added some explanation of why -Ctarget-cpu should be a target-modifier for nvptx to the PR. Please let me know if something is missing or if there are other assumptions about the topic.

@Darksonn Darksonn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

There might already be relevant tests, but I want to see tests that this only makes -Ctarget-cpu into a target modifier in this case, and not for all targets.

View changes since this review

@Darksonn Darksonn added the F-target_modifiers `#![feature(target_modifiers)]` label Jan 10, 2026
Comment thread compiler/rustc_session/src/options.rs Outdated
Comment thread tests/ui/target_modifiers/incompatible_target_cpu.error_generated.stderr Outdated
@kulst
kulst force-pushed the cpu_is_target_modifier branch from a8f5e96 to e5cbf49 Compare January 11, 2026 00:43
@rustbot

rustbot commented Jan 11, 2026

Copy link
Copy Markdown
Collaborator

Some changes occurred to the intrinsics. Make sure the CTFE / Miri interpreter
gets adapted for the changes, if necessary.

cc @rust-lang/miri, @RalfJung, @oli-obk, @lcnr

The reflection data structures are tied exactly to the implementation
in the compiler. Make sure to also adjust `rustc_const_eval/src/const_eval/type_info.rs

cc @oli-obk

triagebot.toml has been modified, there may have been changes to the review queue.

cc @davidtwco, @wesleywiser

Some changes occurred in tests/ui/stack-protector

cc @rust-lang/project-exploit-mitigations, @rcvalle

Some changes occurred to the CTFE / Miri interpreter

cc @rust-lang/miri

Some changes occurred in src/tools/clippy

cc @rust-lang/clippy

Some changes occurred to the CTFE machinery

cc @RalfJung, @oli-obk, @lcnr

@rustbot rustbot added A-CI Area: Our Github Actions CI A-meta Area: Issues & PRs about the rust-lang/rust repository itself labels Jan 11, 2026
@kulst
kulst force-pushed the cpu_is_target_modifier branch 3 times, most recently from e67d6fb to feaf183 Compare July 14, 2026 22:10
@kulst

kulst commented Jul 14, 2026

Copy link
Copy Markdown
Contributor Author

I have revised the tests and integrated the other suggestions.

  • tests/run-make/target-cpu-as-target-modifier now uses a stable test logic to verify that only the intented targets treat -Ctarget-cpu as a target modifier and all other builtin-targets do not.
  • the two tests about which -Ctarget-cpu value takes precendence in metadata and llvm-ir are combined into tests/run-make/target-cpu-precedence
  • to make it easier to test the values of target modifiers, I have also expanded the -Zls option to be used with target_modifiers
  • the target_cpu comparison logic now uses reparse when comparing against a target's default cpu; this way, changing reparse does not have to be in sync with the comparison logic

@rustbot ready

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jul 14, 2026
@kulst
kulst requested a review from bjorn3 July 15, 2026 08:50
@kulst
kulst force-pushed the cpu_is_target_modifier branch from feaf183 to 18bf1d8 Compare July 15, 2026 10:04
@rust-bors

This comment has been minimized.

- Boolean target modifiers are now mentioned without a trailing `=` in the
messages.
- Wording improved for unset target modifiers.
@kulst
kulst force-pushed the cpu_is_target_modifier branch from 18bf1d8 to 078858d Compare July 15, 2026 14:30
@rustbot

rustbot commented Jul 15, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

@bjorn3

bjorn3 commented Jul 17, 2026

Copy link
Copy Markdown
Member

Apologies for the delay.

@bors r+

@rust-bors

rust-bors Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

📌 Commit 078858d has been approved by bjorn3

It is now in the queue for this repository.

@rust-bors rust-bors Bot added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 17, 2026
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Jul 17, 2026
…orn3

Convert `-Ctarget-cpu` into a target-modifier for AVR, AMDGCN and NVPTX

Crates built for AVR, AMDGCN and NVPTX that specify different values for `-Ctarget-cpu` cannot be soundly linked together.
This PR attempts to make `rustc` ensure that no crates with disagreeing values for `-Ctarget-cpu` are linked together. This is achieved by converting `-Ctarget-cpu` into a target-modifier depending on `--target`.
To do this, the consistency check for `-Ctarget-cpu` considers mismatching values as inconsistent only for targets for which the new flag `requires_consistent_cpu` is set in their target spec.

**Why should `-Ctarget-cpu` be a target-modifier for `nvptx`?**
<details><summary>PTX is a single-module contract</summary>
<p>
PTX requires a binary to start with .version (`ptx$$`) then .target (`sm_$$`). If the ptx contains instructions that are not supported by either .version or .target, the binary is ill-formed and will be rejected by ptxas. The concept of features that can be mixed and matched in a binary does not exist for nvptx and is therefore not supported by LLVM.
</p>
</details>

<details><summary>It prevents the production of bitcode that cannot be codegen'd after linking</summary>
<p>
A target modifier should prevent configurations that are not composable across crates when those crates are linked together. The most prominent example is when enabling a target feature changes the ABI, making cross-crate calls inherently unsound.

In the case of nvptx, ABI mismatch is (at least for now) not the core problem motivating target modifiers. NVIDIA’s documented PTX calling convention has [remained stable since ptx20](https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/index.html#function-calling-sequence).

However, in the current state it is possible to produce bitcode that cannot be codegen'd after linking, because some operations are only lowerable for sufficiently new SM/PTX levels. In the best case this results in an LLVM error during the final llc step, but this is not something we should rely on for correctness.

nvptx has a special compilation pipeline where instead of linking the final PTX object, instead LLVM bitcode is linked. The resulting artifact is then compiled in one invocation.
Now consider crate A which is independently compiled into bitcode with the following rustc arguments:

```Rust
//@ compile-flags: --target nvptx64-nvidia-cuda -C target-cpu=sm_70 --crate-type=rlib
#[cfg(target_feature = "sm_70")]
fn foo() {
    // cannot be lowered to ptx before "sm_70: so currently produces an LLVM error
}
#[cfg(not(target_feature = "sm_70"))]
fn foo() {
    // can be lowered to ptx before "sm_70"
}
pub fn bar() {
    foo()
}
```
Crate A is a dependency of crate B. In the *rustc* invocation of crate B
1. crate B is compiled into bitcode, too
2. both bitcode artifacts are bitcode-linked by *llvm-link*
3. the resulting bitcode artifact is compiled by *llc -mcpu=sm_60*

This should now ideally create an LLVM error, because the linked bitcode contains code paths that were selected under `sm_70` assumptions but the final NVPTX codegen is targeting `sm_60`, where those operations are not lowerable. An LLVM error here is better than silent miscompilation, but it’s not a promise we should rely on.

A real example where this could happen is the lowering of atomic loads and stores with non-relaxed orderings, which is known to depend on the selected SM level.
</p>
</details>

**Why should `-Ctarget-cpu` be a target-modifier for `amdgcn` and `avr`?**
- In case of AVR the target-cpu defines the ISA, which is encoded in the ELF header flags, amdgcn also encodes the cpu directly into those flags
- To not rely on *lld* which currently prevents it for both by looking at those flags [AVR](https://github.com/llvm/llvm-project/blob/597ffbe09d5f774f861ee55e50022bf84d7f98e2/lld/test/ELF/avr-flags.s) and [amdgcn](https://github.com/llvm/llvm-project/blob/597ffbe09d5f774f861ee55e50022bf84d7f98e2/lld/test/ELF/amdgpu-elf-flags-err.s)

Previous discussions about the topic can be found [here](rust-lang#131799 (comment)) and [here](rust-lang#141468).

I also created a [Zulip discussion](https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/Making.20-Ctarget-cpu.20a.20target-modifier.20on.20NVPTX/with/566622679).

I am unsure if a MCP is needed before proceeding. If you think so please let me know.

Creating *target-modifiers* for NVPTX *target-features* is to be done in a follow-up.

cc @kjetilkjeka as target maintainer for NVPTX
cc @Flakebi as target maintainer for amdgcn
cc @Patryk27 as target maintainer for AVR
cc @RalfJung you were very involved in the discussions so far

Target modifier tracking issue: rust-lang#136966
rust-bors Bot pushed a commit that referenced this pull request Jul 17, 2026
…uwer

Rollup of 16 pull requests

Successful merges:

 - #150732 (Convert `-Ctarget-cpu` into a target-modifier for AVR, AMDGCN and NVPTX )
 - #159301 (Update Enzyme to handle LLVM23)
 - #159365 (fix: point at method call chain when a return-position `impl Trait` assoc type diverges)
 - #159402 (Clarify safety requirements for SIMD shl/shr and masked load/store)
 - #159410 (rustdoc: remove old `--emit` types)
 - #158398 (Comment about empty run_passes, fixup of #158040)
 - #158843 (Fix ICE in `write_interface` when the interface file can't be written)
 - #159302 (Implement `Debug` helpers via `Cell`)
 - #159332 (Honor field-level lint attributes in non_snake_case)
 - #159386 (add a fallback for `fmuladdf*`)
 - #159391 (Update tests for LLVM 23)
 - #159400 (Update books)
 - #159401 (Gate `tests/debuginfo/function-call.rs` on min GDB 15.1)
 - #159404 ([aarch64][win] Pass oversized c-variadic args indirectly on Arm64EC)
 - #159405 (Manually implement Clone for GrowableBitSet)
 - #159415 (rustdoc: rename the doc parts metadata params)
@JonathanBrouwer

Copy link
Copy Markdown
Contributor

💔 I suspect this PR failed tests as part of a rollup
@bors r-

After fixing the problem, consider running a try job for the failed job before re-approving.

Link to failure: #159437 (comment)

@rust-bors rust-bors Bot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. labels Jul 17, 2026
@rust-bors

rust-bors Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

This pull request was unapproved.

This PR was contained in a rollup (#159437), which was unapproved.

View changes since this unapproval

…and NVPTX

For AVR, AMDGCN, and NVPTX, crates built with different target CPU values are
not generally link-compatible.

Add a `requires_consistent_cpu` flag to the target spec and enable it for these
targets. When the flag is set, treat `-Ctarget-cpu` as a target modifier and
require all linked crates to agree on its value.

Reject `-Ctarget-cpu=native` before codegen for targets that set
`requires_consistent_cpu` to true. Also do not include `native` in the printed
`target-cpus` list for such targets.

Add tests covering:
- which built-in targets set `requires-consistent-cpu`
- cross-crate behavior with and without `requires-consistent-cpu`
- that an omitted `-Ctarget-cpu` compares equal to an explicitly specified
  default CPU
- rejection and printing behavior for `native`
- precedence of repeated `-Ctarget-cpu` flags in metadata comparison and LLVM IR
@kulst
kulst force-pushed the cpu_is_target_modifier branch from 078858d to 76d5107 Compare July 17, 2026 13:52
@kulst

kulst commented Jul 17, 2026

Copy link
Copy Markdown
Contributor Author

Apologies for the inconvenience, unfortunately I missed to adapt tests/assembly-llvm/nvptx-arch-target-cpu.rs accordingly.
Mirroring the failing CI invocation locally runs without errors. We can do a try run of test-various to verify.

@RalfJung

Copy link
Copy Markdown
Member

@bors try jobs=test-various

@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Jul 17, 2026
Convert `-Ctarget-cpu` into a target-modifier for AVR, AMDGCN and NVPTX 


try-job: test-various
@rust-bors

rust-bors Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: d374233 (d374233e25b18d7b6868389547b95c1ad5d5c64b)
Base parent: 4a9d536 (4a9d5368df6450bbd2fc8dde4508c3e5d83bb19d)

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

Labels

A-LLVM Area: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues. A-run-make Area: port run-make Makefiles to rmake.rs F-target_modifiers `#![feature(target_modifiers)]` O-amdgcn Target: the Radeon 9001XT and such O-AVR Target: AVR processors (ATtiny, ATmega, etc.) O-NVPTX Target: the NVPTX LLVM backend for running rust on GPUs, https://llvm.org/docs/NVPTXUsage.html PG-exploit-mitigations Project group: Exploit mitigations S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.