Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

gccrs#4719: Add unsafe_cell

Link: Rust-GCC/gccrs#4719

Definition:

#![allow(unused)]
fn main() {
#[lang = "unsafe_cell"]
#[stable(feature = "rust1", since = "1.0.0")]
#[repr(transparent)]
#[repr(no_niche)] // rust-lang/rust#68303.
pub struct UnsafeCell<T: ?Sized> {
    value: T,
}
}

Objective

This PR implements the unsafe_cell lang item to the compilers.

Changes Made

Registered the lang item. Since gccrs currently lacks niche-filling optimizations, this patch does not include any changes related to type layout size adjustments. The focus is purely on correctly handling aliasing and mutability semantics at the compiler level.

Why is this needed for alloc?

UnsafeCell<T> is the foundational primitive for interior mutability in Rust. The alloc crate requires it to implement data structures that manage shared state or raw memory buffers, ensuring the compiler’s optimizer does not make incorrect assumptions about memory immutability.

Test Case

#![allow(unused)]
fn main() {
pub fn normal_ref(_a: &i32) {/* ... */}
//                ^^^^^^^^ this's gimple will looks like 'const i32 & const _a'
//                                                        ^^^^^       ^^^^^
//                  both pointee and pointer are const <────┴───────────┘

pub fn unsafe_ref(_b: &UnsafeCell<i32>) {/* ... */}
//                ^^^^^^^^^^^^^^^^^^^^
//                this's gimple will looks like 'struct UnsafeCell<i32> & const _b;
//                                                                        ^^^^^
//                       pointer is const, but pointee is NOT const! <──────┘
}

The compiler correctly translates UnsafeCell references to GIMPLE, dropping the const qualifier from the pointee, thereby safely allowing internal mutation.