Skip to content

lto: use the object crate to load bitcode sections #115136

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
40 changes: 23 additions & 17 deletions compiler/rustc_codegen_llvm/src/back/lto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ use std::path::Path;
use std::slice;
use std::sync::Arc;

use object::Object;
use object::ObjectSection;

/// We keep track of the computed LTO cache keys from the previous
/// session to determine which CGUs we can reuse.
pub const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin";
Expand Down Expand Up @@ -142,23 +145,26 @@ fn prepare_lto(
}

fn get_bitcode_slice_from_object_data(obj: &[u8]) -> Result<&[u8], LtoBitcodeFromRlib> {
let mut len = 0;
let data =
unsafe { llvm::LLVMRustGetBitcodeSliceFromObjectData(obj.as_ptr(), obj.len(), &mut len) };
if !data.is_null() {
assert!(len != 0);
let bc = unsafe { slice::from_raw_parts(data, len) };

// `bc` must be a sub-slice of `obj`.
assert!(obj.as_ptr() <= bc.as_ptr());
assert!(bc[bc.len()..bc.len()].as_ptr() <= obj[obj.len()..obj.len()].as_ptr());

Ok(bc)
} else {
assert!(len == 0);
Err(LtoBitcodeFromRlib {
llvm_err: llvm::last_error().unwrap_or_else(|| "unknown LLVM error".to_string()),
})
// The object crate doesn't understand bitcode files, but we can just sniff for the possible
// magic strings here and return the whole slice directly.
if obj.starts_with(b"\xDE\xC0\x17\x0B") || obj.starts_with(b"BC\xC0\xDE") {
return Ok(obj);
}
match object::read::File::parse(obj) {
Ok(f) => match f
.section_by_name(".llvmbc")
.or_else(|| f.section_by_name(".llvm.lto"))
.or_else(|| f.section_by_name("__LLVM,__bitcode"))
.or_else(|| f.section_by_name(".ipa"))
{
Some(d) => Ok(d.data().unwrap()),
None => Err(LtoBitcodeFromRlib {
llvm_err: "Bitcode section not found in object file".to_string(),
}),
},
Err(e) => {
Err(LtoBitcodeFromRlib { llvm_err: format!("error loading bitcode section: {}", e) })
}
}
}

Expand Down
5 changes: 0 additions & 5 deletions compiler/rustc_codegen_llvm/src/llvm/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2309,11 +2309,6 @@ extern "C" {
len: usize,
Identifier: *const c_char,
) -> Option<&Module>;
pub fn LLVMRustGetBitcodeSliceFromObjectData(
Data: *const u8,
len: usize,
out_len: &mut usize,
) -> *const u8;

pub fn LLVMRustLinkerNew(M: &Module) -> &mut Linker<'_>;
pub fn LLVMRustLinkerAdd(
Expand Down
26 changes: 0 additions & 26 deletions compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1481,32 +1481,6 @@ LLVMRustParseBitcodeForLTO(LLVMContextRef Context,
return wrap(std::move(*SrcOrError).release());
}

// Find the bitcode section in the object file data and return it as a slice.
// Fail if the bitcode section is present but empty.
//
// On success, the return value is the pointer to the start of the slice and
// `out_len` is filled with the (non-zero) length. On failure, the return value
// is `nullptr` and `out_len` is set to zero.
extern "C" const char*
LLVMRustGetBitcodeSliceFromObjectData(const char *data,
size_t len,
size_t *out_len) {
*out_len = 0;

StringRef Data(data, len);
MemoryBufferRef Buffer(Data, ""); // The id is unused.

Expected<MemoryBufferRef> BitcodeOrError =
object::IRObjectFile::findBitcodeInMemBuffer(Buffer);
if (!BitcodeOrError) {
LLVMRustSetLastError(toString(BitcodeOrError.takeError()).c_str());
return nullptr;
}

*out_len = BitcodeOrError->getBufferSize();
return BitcodeOrError->getBufferStart();
}

// Computes the LTO cache key for the provided 'ModId' in the given 'Data',
// storing the result in 'KeyOut'.
// Currently, this cache key is a SHA-1 hash of anything that could affect
Expand Down