Skip to content

Commit 6e5566c

Browse files
committed
lto: load bitcode sections by name
Upstream change llvm/llvm-project@6b539f5 changed `isSectionBitcode` works and it now only respects `.llvm.lto` sections instead of also `.llvmbc`, which it says was never intended to be used for LTO. We instead load sections by name, and sniff for raw bitcode by hand. r? @nikic @rustbot label: +llvm-main
1 parent a5b2ac6 commit 6e5566c

File tree

4 files changed

+86
-16
lines changed

4 files changed

+86
-16
lines changed

compiler/rustc_codegen_llvm/src/back/lto.rs

+23-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
use crate::back::write::{self, save_temp_bitcode, CodegenDiagnosticsStage, DiagnosticHandlers};
1+
use crate::back::write::{
2+
self, bitcode_section_name, save_temp_bitcode, CodegenDiagnosticsStage, DiagnosticHandlers,
3+
};
24
use crate::errors::{
35
DynamicLinkingWithLTO, LlvmError, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib,
46
};
@@ -120,6 +122,7 @@ fn prepare_lto(
120122
info!("adding bitcode from {}", name);
121123
match get_bitcode_slice_from_object_data(
122124
child.data(&*archive_data).expect("corrupt rlib"),
125+
cgcx,
123126
) {
124127
Ok(data) => {
125128
let module = SerializedModule::FromRlib(data.to_vec());
@@ -141,10 +144,26 @@ fn prepare_lto(
141144
Ok((symbols_below_threshold, upstream_modules))
142145
}
143146

144-
fn get_bitcode_slice_from_object_data(obj: &[u8]) -> Result<&[u8], LtoBitcodeFromRlib> {
147+
fn get_bitcode_slice_from_object_data<'a>(
148+
obj: &'a [u8],
149+
cgcx: &CodegenContext<LlvmCodegenBackend>,
150+
) -> Result<&'a [u8], LtoBitcodeFromRlib> {
151+
// We're about to assume the data here is an object file with sections, but if it's raw LLVM IR that
152+
// won't work. Fortunately, if that's what we have we can just return the object directly, so we sniff
153+
// the relevant magic strings here and return.
154+
if obj.starts_with(b"\xDE\xC0\x17\x0B") || obj.starts_with(b"BC\xC0\xDE") {
155+
return Ok(obj);
156+
}
157+
let section_name = bitcode_section_name(cgcx);
145158
let mut len = 0;
146-
let data =
147-
unsafe { llvm::LLVMRustGetBitcodeSliceFromObjectData(obj.as_ptr(), obj.len(), &mut len) };
159+
let data = unsafe {
160+
llvm::LLVMRustGetSliceFromObjectDataByName(
161+
obj.as_ptr(),
162+
obj.len(),
163+
section_name.as_ptr(),
164+
&mut len,
165+
)
166+
};
148167
if !data.is_null() {
149168
assert!(len != 0);
150169
let bc = unsafe { slice::from_raw_parts(data, len) };

compiler/rustc_codegen_llvm/src/back/write.rs

+24-12
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,27 @@ fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data:
853853
asm
854854
}
855855

856+
fn target_is_apple(cgcx: &CodegenContext<LlvmCodegenBackend>) -> bool {
857+
cgcx.opts.target_triple.triple().contains("-ios")
858+
|| cgcx.opts.target_triple.triple().contains("-darwin")
859+
|| cgcx.opts.target_triple.triple().contains("-tvos")
860+
|| cgcx.opts.target_triple.triple().contains("-watchos")
861+
}
862+
863+
fn target_is_aix(cgcx: &CodegenContext<LlvmCodegenBackend>) -> bool {
864+
cgcx.opts.target_triple.triple().contains("-aix")
865+
}
866+
867+
pub(crate) fn bitcode_section_name(cgcx: &CodegenContext<LlvmCodegenBackend>) -> &'static str {
868+
if target_is_apple(cgcx) {
869+
"__LLVM,__bitcode\0"
870+
} else if target_is_aix(cgcx) {
871+
".ipa\0"
872+
} else {
873+
".llvmbc\0"
874+
}
875+
}
876+
856877
/// Embed the bitcode of an LLVM module in the LLVM module itself.
857878
///
858879
/// This is done primarily for iOS where it appears to be standard to compile C
@@ -913,11 +934,8 @@ unsafe fn embed_bitcode(
913934
// Unfortunately, LLVM provides no way to set custom section flags. For ELF
914935
// and COFF we emit the sections using module level inline assembly for that
915936
// reason (see issue #90326 for historical background).
916-
let is_aix = cgcx.opts.target_triple.triple().contains("-aix");
917-
let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
918-
|| cgcx.opts.target_triple.triple().contains("-darwin")
919-
|| cgcx.opts.target_triple.triple().contains("-tvos")
920-
|| cgcx.opts.target_triple.triple().contains("-watchos");
937+
let is_aix = target_is_aix(cgcx);
938+
let is_apple = target_is_apple(cgcx);
921939
if is_apple
922940
|| is_aix
923941
|| cgcx.opts.target_triple.triple().starts_with("wasm")
@@ -932,13 +950,7 @@ unsafe fn embed_bitcode(
932950
);
933951
llvm::LLVMSetInitializer(llglobal, llconst);
934952

935-
let section = if is_apple {
936-
"__LLVM,__bitcode\0"
937-
} else if is_aix {
938-
".ipa\0"
939-
} else {
940-
".llvmbc\0"
941-
};
953+
let section = bitcode_section_name(cgcx);
942954
llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
943955
llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
944956
llvm::LLVMSetGlobalConstant(llglobal, llvm::True);

compiler/rustc_codegen_llvm/src/llvm/ffi.rs

+6
Original file line numberDiff line numberDiff line change
@@ -2319,6 +2319,12 @@ extern "C" {
23192319
len: usize,
23202320
out_len: &mut usize,
23212321
) -> *const u8;
2322+
pub fn LLVMRustGetSliceFromObjectDataByName(
2323+
data: *const u8,
2324+
len: usize,
2325+
name: *const u8,
2326+
out_len: &mut usize,
2327+
) -> *const u8;
23222328

23232329
pub fn LLVMRustLinkerNew(M: &Module) -> &mut Linker<'_>;
23242330
pub fn LLVMRustLinkerAdd(

compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include <stdio.h>
22

3+
#include <cstddef>
34
#include <iomanip>
45
#include <vector>
56
#include <set>
@@ -1511,6 +1512,38 @@ LLVMRustGetBitcodeSliceFromObjectData(const char *data,
15111512
return BitcodeOrError->getBufferStart();
15121513
}
15131514

1515+
// Find a section of an object file by name. Fail if the section is missing or
1516+
// empty.
1517+
extern "C" const char *LLVMRustGetSliceFromObjectDataByName(const char *data,
1518+
size_t len,
1519+
const char *name,
1520+
size_t *out_len) {
1521+
*out_len = 0;
1522+
StringRef Data(data, len);
1523+
MemoryBufferRef Buffer(Data, ""); // The id is unused.
1524+
file_magic Type = identify_magic(Buffer.getBuffer());
1525+
Expected<std::unique_ptr<object::ObjectFile>> ObjFileOrError =
1526+
object::ObjectFile::createObjectFile(Buffer, Type);
1527+
if (!ObjFileOrError) {
1528+
LLVMRustSetLastError(toString(ObjFileOrError.takeError()).c_str());
1529+
return nullptr;
1530+
}
1531+
for (const object::SectionRef &Sec : (*ObjFileOrError)->sections()) {
1532+
Expected<StringRef> Name = Sec.getName();
1533+
if (Name && *Name == name) {
1534+
Expected<StringRef> SectionOrError = Sec.getContents();
1535+
if (!SectionOrError) {
1536+
LLVMRustSetLastError(toString(SectionOrError.takeError()).c_str());
1537+
return nullptr;
1538+
}
1539+
*out_len = SectionOrError->size();
1540+
return SectionOrError->data();
1541+
}
1542+
}
1543+
LLVMRustSetLastError("could not find requested section");
1544+
return nullptr;
1545+
}
1546+
15141547
// Computes the LTO cache key for the provided 'ModId' in the given 'Data',
15151548
// storing the result in 'KeyOut'.
15161549
// Currently, this cache key is a SHA-1 hash of anything that could affect

0 commit comments

Comments
 (0)