Support using const pointers in asm `const` operand
Implements [RFC#3848](https://github.com/rust-lang/rfcs/pull/3848) with tracking issue rust-lang/rust#128464
This adds support of const pointers for asm `const` in addition to plain integers.
The inline `asm!` support is implemented using `i` constraint, and the `global_asm!` and `naked_asm!` support is implemented by inserting `symbol + offset` and make `symbol` compiler-used. For unnamed consts, it will create additional internal & hidden symbols so that they can be referenced by global_asm.
~~The feature is also implemented for GCC backend but it's untested.~~ Tested now.
codegen: skip stores for entirely-uninit constant aggregate fields
MIR GVN (since rust-lang/rust#147827) propagates MaybeUninit::uninit() as `const <uninit>` in aggregate constructions. Without this fix, codegen would emit a memcpy from an `[N x i8] undef` global for each such field, which LLVM materializes as zero-initialization.
This mirrors the existing `all_bytes_uninit` skip already present for `Rvalue::Use` (added in rust-lang/rust#147827) into the `Rvalue::Aggregate` field loop.
Fixes: rust-lang/rust#157743
With the previous commit, now we can see there are some code duplication
for the handling of `GlobalAlloc` inside backends. Do some clean up to
unify them.
This gives the asm-const code the basic ability to deal wiht pointer and
provenances, which lays the ground work for asm_const_ptr.
Note that `SymStatic` is not fully removed, a specialized is kept and
renamed as `SymThreadLocalStatic`, for `#[thread_local]` statics where CTFE
does not support naming. The `#[thread_local]` is unstable feature and it's
not clear if we want to support this in `sym`, but removal of it should be
a separate PR.
MIR GVN propagates MaybeUninit::uninit() as `const <uninit>` in aggregate
constructions and codegen emits a memcpy from an `[N x i8] undef` global for
each such field, which LLVM materializes as zero-initialization.
Instead of special-casing `all_bytes_uninit` at each call site, add a new
`OperandValue::Uninit` variant that `eval_mir_constant_to_operand` returns for
any all-bytes-uninit constant. `store_with_flags` is a no-op for this variant,
so the fix applies uniformly across `Rvalue::Use`, `Rvalue::Repeat`, and
`Rvalue::Aggregate` without per-site checks. The variant propagates through
field extraction and transmutes, and is handled appropriately at the remaining
call sites (function arguments, discriminant reads, debug info, etc.).
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](597ffbe09d/lld/test/ELF/avr-flags.s) and [amdgcn](597ffbe09d/lld/test/ELF/amdgpu-elf-flags-err.s)
Previous discussions about the topic can be found [here](https://github.com/rust-lang/rust/issues/131799#issuecomment-3390563329) and [here](https://github.com/rust-lang/rust/issues/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: https://github.com/rust-lang/rust/issues/136966
Stop using prefix_tys
*This is a member of a patch series to replace rust-lang/rust#135527.*
This function hints at an early commitment to coroutine memory layout. We should not give promises on how upvars are allocated.
[cg_ssa] Eliminate the `is_backend_{immediate,scalar_pair,ref}` methods
These methods are just mostly just matches on [`BackendRepr`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_abi/enum.BackendRepr.html) now, which makes then not not very valuable. Notably, `cg_clif` gets along just fine without them. In general, it's much nicer to match on `BackendRepr` than to use an `if`-`else` chain of `is_zst`+`is_backend_immediate`+`is_backend_scalar_pair`.
And having them be on `LayoutTypeCodegenMethods` means you need a context to use them, making it more annoying to use them in things like [`OperandValue::is_expected_variant_for_type`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_codegen_ssa/mir/operand/enum.OperandValue.html#method.is_expected_variant_for_type).
So this just removes them, as well as the `is_llvm_*` and `is_gcc_*` versions.
How I migrated callers:
- `is_backend_ref` becomes a (logical-not-ed) call to a new `.is_ssa_standalone()` method. (Better name suggestions welcome for this one. I wanted something to hopefully phrase intent better and positively.)
- `is_backend_immediate` becomes a call to `.backend_repr.is_scalar_or_simd()`.
- `is_backend_scalar_pair` becomes a pattern-match against `BackendRepr::ScalarPair { .. }`.
- some places that used multiples just became a match over `BackendRepr`.
The intent is that this has zero impact on the codegen. It should be a refactor only.
r? codegen
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
Rename ModDefId to ModId and use more
Addresses some FIXMEs.
The `ModDefId` was used pretty sparingly, and honestly I wondered if it should exist at all. After making these changes, I think the type is worth it. Most notably it is now used in `Visibility::Restricted`.
I first renamed `ModDefId` to `ModId` since I think the former is over-specific, and also this is more in line with `BodyId` or `OwnerId`.
I'll wait for initial feedback before fixing rustdoc/clippy.
This function hints at an early commitment to coroutine memory layout.
We should not give promises on how upvars are allocated.
Signed-off-by: Xiangfei Ding <dingxiangfei2009@protonmail.ch>
Pointer authentication config and user facing options
This patch brings:
* unified handling of pointer authentication options through:
`-Zpointer-authentication`, with possible values:
`aarch64-jump-table-hardening`, `auth-traps`, `calls`, `elf-got`,
`function-pointer-type-discrimination`, `indirect-gotos`, `init-fini`,
`init-fini-address-discrimination`, `return-addresses`. Toggled with
`+`/`-`.
* centralized handling of pointer authentication features. Session holds
`pointer_auth_config: Option<PointerAuthConfig>`
* encapsulation of schema for function pointers and init/fini through
`PointerAuthSchema`. This allowed for retiring of `PacMetadata`.
* refactor enabling of pointer authentication in code, instead of
relying on the target (`pauthtest`) use the session
Support EII on Windows MSVC
Tracking issue: rust-lang/rust#125418
The previous PR rust-lang/rust#158294 made function EIIs work on Windows MSVC. This PR fixes support for static EIIs, enabling full EII support on Windows MSVC.
The following fixes are included:
- Keep EII statics out of LLVM internalization
- Mark EII static symbols as `dllimport`
- Emit MSVC `__imp_<symbol>` stubs for aliases to static data
Note: `LLVMAddAlias2` was incorrectly declared in the `llvm-wrapper` extern block previously.
This patch brings:
* unified handling of pointer authentication options through:
`-Zpointer-authentication`, with possible values:
`aarch64-jump-table-hardening`, `auth-traps`, `calls`, `elf-got`,
`function-pointer-type-discrimination`, `indirect-gotos`, `init-fini`,
`init-fini-address-discrimination`, `return-addresses`. Toggled with
`+`/`-`.
* centralized handling of pointer authentication features. Session holds
`pointer_auth_config: Option<PointerAuthConfig>`
* encapsulation of schema for function pointers and init/fini through
`PointerAuthSchema`. This allowed for retiring of `PacMetadata`.
* refactor enabling of pointer authentication in code, instead of
relying on the target (`pauthtest`) use the session
Carry the `b_offset` inside `BackendRepr::ScalarPair`
Inspired by https://github.com/rust-lang/compiler-team/issues/1007 but doesn't actually change any of the layout rules just yet.
This turned out to be a nice change even if we didn't use the extra flexibility, IMHO, because it allowed so many things like
```diff
@@ -222,12 +224,12 @@ fn from_const_alloc<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
let val = read_scalar(offset, size, s, bx.immediate_backend_type(layout));
OperandRef { val: OperandValue::Immediate(val), layout, move_annotation: None }
}
- BackendRepr::ScalarPair(
- a @ abi::Scalar::Initialized { .. },
- b @ abi::Scalar::Initialized { .. },
- ) => {
+ BackendRepr::ScalarPair {
+ a: a @ abi::Scalar::Initialized { .. },
+ b: b @ abi::Scalar::Initialized { .. },
+ b_offset,
+ } => {
let (a_size, b_size) = (a.size(bx), b.size(bx));
- let b_offset = (offset + a_size).align_to(b.default_align(bx).abi);
assert!(b_offset.bytes() > 0);
let a_val = read_scalar(
offset,
```
as *oh my* was that little magic incantation copy-pasted all over the place.
Apologies for the pretty-giant PR. I tried to make it as direct a change as I could: if it was `(..)` before it's `{ .. }` now, if it was `(_, _)` before it's `{ a: _, b: _, b_offset: _ }` now. I kept the names the same so the code lines were unchanged even if normally I might have just renamed things, etc. I'll add some inline notes for places of particular interest.
r? @workingjubilee
Add and use cfg(target_has_threads) to enforce no_thread impl usage
The standard library has fallback code for targets without threads (e.g., using a Cell-based Mutex and similar). Today there's no enforcement in std that those targets truly don't have threads which makes that code potentially unsound. This will let us add a static assertion that the target spec agrees that the target is non-threaded. Getting the target spec wrong is already unsound (e.g., LLVM can make use of that) so it's a reasonable source of truth. This pulls in the atomics target feature into the target code and makes the field itself private to encourage going via the method.
For now the cfg is added as unstable but if we have a use case for user code to use this, happy to cut a tracking issue and make it a regular unstable feature.
Setting a compiler reviewer since the std changes are pretty trivial, and I think anyone can review those reasonably.
cc rust-lang/rust#156366 which prompted looking into this
r? compiler
The standard library has fallback code for targets without threads
(e.g., using a Cell-based Mutex and similar). Today there's no
enforcement in std that those targets truly don't have threads which
makes that code potentially unsound. This will let us add a
static assertion that the target spec agrees that the target is
non-threaded.
Add -Zautodiff_post_passes flag to limit which llvm passes to run after enzyme to make autodiff tests more robust
* Add -Zautodiff_post_passes flag to limit which llvm passes to run after enzyme to make autodiff tests more robust
* Change some llvm ir check in codegen_llvm/autodiff tests
r? @ZuseZ4
rustc_target/asm: add LoongArch LSX/LASX inline asm register support
Add support for LoongArch LSX and LASX registers in inline assembly by introducing the `vreg` and `xreg` register classes, along with their associated vector types and operand modifiers. The new register classes are gated behind the `asm_experimental_reg` feature. Also model the overlap between FPU, LSX, and LASX registers so register conflict checking works correctly for aliased registers.
Rename `align` to `default_align` on `Scalar` and `Primitive`
To emphasize that just because you see a `Scalar(I32)` that doesn't really tell you anything about the alignment it has -- one should be looking at the type (well, the place) for that.
(The `size` method doesn't really have that problem -- i32 is always 4 bytes, no matter the context -- so is left untouched.)
No actual layout or behaviour changes in *this* PR. Just the rename and some comments.
r? @workingjubilee
Move per-function debuginfo methods from codegen to builder methods
In cg_clif the debuginfo for the function we are currently codegening is stored in `FunctionDebugContext`, which is stored in the `FunctionCx`, not in the per-cgu `DebugContext`.
Rollup of 7 pull requests
Successful merges:
- rust-lang/rust#158073 (bootstrap: fix panic when repo path contains spaces by switching to CARGO_ENCODED_RUSTFLAGS)
- rust-lang/rust#158256 (Avoid parser panics bubbling out to proc macros)
- rust-lang/rust#158561 (Avoid building rustdoc for tests without doctests)
- rust-lang/rust#158562 (Improve tracing of steps in bootstrap)
- rust-lang/rust#157445 (Allow section override when using patchable-function-entries)
- rust-lang/rust#158327 (Move attribute and keyword docs from `std` to `core`)
- rust-lang/rust#158591 (Fix spacing issue for unused parentheses lint)