Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 15 additions & 9 deletions src/librustc_codegen_llvm/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,15 +333,21 @@ impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
offset: Size,
) -> PlaceRef<'tcx, &'ll Value> {
assert_eq!(alloc.align, layout.align.abi);
let init = const_alloc_to_llvm(self, alloc);
let base_addr = self.static_addr_of(init, alloc.align, None);

let llval = unsafe { llvm::LLVMConstInBoundsGEP(
self.const_bitcast(base_addr, self.type_i8p()),
&self.const_usize(offset.bytes()),
1,
)};
let llval = self.const_bitcast(llval, self.type_ptr_to(layout.llvm_type(self)));
let llty = self.type_ptr_to(layout.llvm_type(self));
let llval = if layout.size == Size::ZERO {
let llval = self.const_usize(alloc.align.bytes());
unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
} else {
let init = const_alloc_to_llvm(self, alloc);
let base_addr = self.static_addr_of(init, alloc.align, None);

let llval = unsafe { llvm::LLVMConstInBoundsGEP(
self.const_bitcast(base_addr, self.type_i8p()),
&self.const_usize(offset.bytes()),
1,
)};
self.const_bitcast(llval, llty)
};
PlaceRef::new_sized(llval, layout, alloc.align)
}

Expand Down
19 changes: 19 additions & 0 deletions src/test/ui/consts/zst_no_llvm_alloc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// run-pass

#[repr(align(4))]
struct Foo;

static FOO: Foo = Foo;

fn main() {
let x: &'static () = &();
assert_eq!(x as *const () as usize, 1);
let x: &'static Foo = &Foo;
assert_eq!(x as *const Foo as usize, 4);
Comment on lines +9 to +12
Copy link
Member

Choose a reason for hiding this comment

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

Does this constitute a stable guarantee that we will allocate ZSTs at certain addresses? I hope not, that seems quite arbitrary to me. After all we also don't guarantee where non-ZST are allocated.


// statics must have a unique address
assert_ne!(&FOO as *const Foo as usize, 4);

assert_eq!(<Vec<i32>>::new().as_ptr(), <&[i32]>::default().as_ptr());
assert_eq!(<Box<[i32]>>::default().as_ptr(), (&[]).as_ptr());
}