Skip to content

Commit 807bbd9

Browse files
committed
Auto merge of #53031 - michaelwoerister:cross-lto, r=<try>
Apply some fixes to cross-language LTO (especially when targeting MSVC) This PR contains a few fixes that were needed in order to get Firefox compiling with Rust/C++ cross-language ThinLTO on Windows. The commits are self-contained and should be self-explanatory. r? @alexcrichton
2 parents 88e0ff1 + 0b253da commit 807bbd9

File tree

15 files changed

+187
-19
lines changed

15 files changed

+187
-19
lines changed

src/librustc/session/config.rs

+1-8
Original file line numberDiff line numberDiff line change
@@ -817,7 +817,7 @@ macro_rules! options {
817817
pub const parse_lto: Option<&'static str> =
818818
Some("one of `thin`, `fat`, or omitted");
819819
pub const parse_cross_lang_lto: Option<&'static str> =
820-
Some("either a boolean (`yes`, `no`, `on`, `off`, etc), `no-link`, \
820+
Some("either a boolean (`yes`, `no`, `on`, `off`, etc), \
821821
or the path to the linker plugin");
822822
}
823823

@@ -1993,13 +1993,6 @@ pub fn build_session_options_and_crate_config(
19931993
(&None, &None) => None,
19941994
}.map(|m| PathBuf::from(m));
19951995

1996-
if cg.lto != Lto::No && incremental.is_some() {
1997-
early_error(
1998-
error_format,
1999-
"can't perform LTO when compiling incrementally",
2000-
);
2001-
}
2002-
20031996
if debugging_opts.profile && incremental.is_some() {
20041997
early_error(
20051998
error_format,

src/librustc/session/mod.rs

+19-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use lint::builtin::BuiltinLintDiagnostics;
2020
use middle::allocator::AllocatorKind;
2121
use middle::dependency_format;
2222
use session::search_paths::PathKind;
23-
use session::config::{OutputType};
23+
use session::config::{OutputType, Lto};
2424
use ty::tls;
2525
use util::nodemap::{FxHashMap, FxHashSet};
2626
use util::common::{duration_to_secs_str, ErrorReported};
@@ -1189,9 +1189,27 @@ pub fn build_session_(
11891189
driver_lint_caps: FxHashMap(),
11901190
};
11911191

1192+
validate_commandline_args_with_session_available(&sess);
1193+
11921194
sess
11931195
}
11941196

1197+
// If it is useful to have a Session available already for validating a
1198+
// commandline argument, you can do so here.
1199+
fn validate_commandline_args_with_session_available(sess: &Session) {
1200+
1201+
if sess.lto() != Lto::No && sess.opts.incremental.is_some() {
1202+
sess.err("can't perform LTO when compiling incrementally");
1203+
}
1204+
1205+
if sess.opts.debugging_opts.cross_lang_lto.enabled() &&
1206+
sess.opts.cg.prefer_dynamic &&
1207+
sess.target.target.options.is_like_msvc {
1208+
sess.err("Linker plugin based LTO is not supported together with \
1209+
`-C prefer-dynamic` when targeting MSVC");
1210+
}
1211+
}
1212+
11951213
/// Hash value constructed out of all the `-C metadata` arguments passed to the
11961214
/// compiler. Together with the crate-name forms a unique global identifier for
11971215
/// the crate.

src/librustc_codegen_llvm/attributes.rs

+14
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,15 @@ pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
123123
.filter(|l| !l.is_empty())
124124
}
125125

126+
pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
127+
let target_cpu = CString::new(cx.tcx.sess.target_cpu().to_string()).unwrap();
128+
llvm::AddFunctionAttrStringValue(
129+
llfn,
130+
llvm::AttributePlace::Function,
131+
cstr("target-cpu\0"),
132+
target_cpu.as_c_str());
133+
}
134+
126135
/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
127136
/// attributes.
128137
pub fn from_fn_attrs(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value, id: DefId) {
@@ -167,6 +176,11 @@ pub fn from_fn_attrs(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value, id: DefId) {
167176
Some(true) | None => {}
168177
}
169178

179+
// Always annotate functions with the target-cpu they are compiled for.
180+
// Without this, ThinLTO won't inline Rust functions into Clang generated
181+
// functions (because Clang annotates functions this way too).
182+
apply_target_cpu_attr(cx, llfn);
183+
170184
let features = llvm_target_features(cx.tcx.sess)
171185
.map(|s| s.to_string())
172186
.chain(

src/librustc_codegen_llvm/back/link.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -1626,8 +1626,12 @@ fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
16261626
fn is_full_lto_enabled(sess: &Session) -> bool {
16271627
match sess.lto() {
16281628
Lto::Yes |
1629-
Lto::Thin |
16301629
Lto::Fat => true,
1630+
Lto::Thin => {
1631+
// If we defer LTO to the linker, we haven't run LTO ourselves, so
1632+
// any upstream object files have not been copied yet.
1633+
!sess.opts.debugging_opts.cross_lang_lto.enabled()
1634+
}
16311635
Lto::No |
16321636
Lto::ThinLocal => false,
16331637
}

src/librustc_codegen_llvm/back/lto.rs

+4
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,10 @@ pub(crate) fn run(cgcx: &CodegenContext,
195195
}
196196
Lto::Thin |
197197
Lto::ThinLocal => {
198+
if cgcx.opts.debugging_opts.cross_lang_lto.enabled() {
199+
unreachable!("We should never reach this case if the LTO step \
200+
is deferred to the linker");
201+
}
198202
thin_lto(&diag_handler, modules, upstream_modules, &arr, timeline)
199203
}
200204
Lto::No => unreachable!(),

src/librustc_codegen_llvm/back/write.rs

+21-7
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,9 @@ unsafe fn optimize(cgcx: &CodegenContext,
546546
llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
547547
llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
548548
let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
549-
let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal;
549+
let prepare_for_thin_lto = cgcx.lto == Lto::Thin ||
550+
cgcx.lto == Lto::ThinLocal ||
551+
(cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
550552
with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
551553
llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
552554
llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
@@ -1321,6 +1323,8 @@ fn execute_work_item(cgcx: &CodegenContext,
13211323
unsafe {
13221324
optimize(cgcx, &diag_handler, &module, config, timeline)?;
13231325

1326+
let linker_does_lto = cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1327+
13241328
// After we've done the initial round of optimizations we need to
13251329
// decide whether to synchronously codegen this module or ship it
13261330
// back to the coordinator thread for further LTO processing (which
@@ -1331,6 +1335,11 @@ fn execute_work_item(cgcx: &CodegenContext,
13311335
let needs_lto = match cgcx.lto {
13321336
Lto::No => false,
13331337

1338+
// If the linker does LTO, we don't have to do it. Note that we
1339+
// keep doing full LTO, if it is requested, as not to break the
1340+
// assumption that the output will be a single module.
1341+
Lto::Thin | Lto::ThinLocal if linker_does_lto => false,
1342+
13341343
// Here we've got a full crate graph LTO requested. We ignore
13351344
// this, however, if the crate type is only an rlib as there's
13361345
// no full crate graph to process, that'll happen later.
@@ -1361,11 +1370,6 @@ fn execute_work_item(cgcx: &CodegenContext,
13611370
// settings.
13621371
let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
13631372

1364-
// Don't run LTO passes when cross-lang LTO is enabled. The linker
1365-
// will do that for us in this case.
1366-
let needs_lto = needs_lto &&
1367-
!cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1368-
13691373
if needs_lto {
13701374
Ok(WorkItemResult::NeedsLTO(module))
13711375
} else {
@@ -2345,8 +2349,18 @@ pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
23452349
}
23462350

23472351
fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2352+
// This should never be true (because it's not supported). If it is true,
2353+
// something is wrong with commandline arg validation.
2354+
assert!(!(tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
2355+
tcx.sess.target.target.options.is_like_msvc &&
2356+
tcx.sess.opts.cg.prefer_dynamic));
2357+
23482358
tcx.sess.target.target.options.is_like_msvc &&
2349-
tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib)
2359+
tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) &&
2360+
// ThinLTO can't handle this workaround in all cases, so we don't
2361+
// emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2362+
// dynamic linking when cross-language LTO is enabled.
2363+
!tcx.sess.opts.debugging_opts.cross_lang_lto.enabled()
23502364
}
23512365

23522366
// Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.

src/librustc_codegen_llvm/base.rs

+1
Original file line numberDiff line numberDiff line change
@@ -596,6 +596,7 @@ fn maybe_create_entry_wrapper(cx: &CodegenCx) {
596596

597597
// `main` should respect same config for frame pointer elimination as rest of code
598598
attributes::set_frame_pointer_elimination(cx, llfn);
599+
attributes::apply_target_cpu_attr(cx, llfn);
599600

600601
let bx = Builder::new_block(cx, llfn, "top");
601602

src/librustc_codegen_llvm/consts.rs

+14-1
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,20 @@ pub fn get_static(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll Value {
183183
llvm::set_thread_local_mode(g, cx.tls_model);
184184
}
185185

186-
if cx.use_dll_storage_attrs && !cx.tcx.is_foreign_item(def_id) {
186+
let needs_dll_storage_attr =
187+
cx.use_dll_storage_attrs && !cx.tcx.is_foreign_item(def_id) &&
188+
// ThinLTO can't handle this workaround in all cases, so we don't
189+
// emit the attrs. Instead we make them unnecessary by disallowing
190+
// dynamic linking when cross-language LTO is enabled.
191+
!cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled();
192+
193+
// If this assertion triggers, there's something wrong with commandline
194+
// argument validation.
195+
debug_assert!(!(cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
196+
cx.tcx.sess.target.target.options.is_like_msvc &&
197+
cx.tcx.sess.opts.cg.prefer_dynamic));
198+
199+
if needs_dll_storage_attr {
187200
// This item is external but not foreign, i.e. it originates from an external Rust
188201
// crate. Since we don't know whether this crate will be linked dynamically or
189202
// statically in the final application, we always mark such symbols as 'dllimport'.

src/librustc_codegen_llvm/context.rs

+3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
use attributes;
1112
use common;
1213
use llvm;
1314
use rustc::dep_graph::DepGraphSafe;
@@ -381,6 +382,7 @@ impl<'b, 'tcx> CodegenCx<'b, 'tcx> {
381382
declare::declare_cfn(self, name, fty)
382383
}
383384
};
385+
attributes::apply_target_cpu_attr(self, llfn);
384386
self.eh_personality.set(Some(llfn));
385387
llfn
386388
}
@@ -412,6 +414,7 @@ impl<'b, 'tcx> CodegenCx<'b, 'tcx> {
412414

413415
let llfn = declare::declare_fn(self, "rust_eh_unwind_resume", ty);
414416
attributes::unwind(llfn, true);
417+
attributes::apply_target_cpu_attr(self, llfn);
415418
unwresume.set(Some(llfn));
416419
llfn
417420
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// This test makes sure that functions get annotated with the proper
12+
// "target-cpu" attribute in LLVM.
13+
14+
// no-prefer-dynamic
15+
// only-msvc
16+
// compile-flags: -C no-prepopulate-passes -Z cross-lang-lto
17+
18+
#![crate_type = "rlib"]
19+
20+
// CHECK-NOT: @{{.*}}__imp_{{.*}}GLOBAL{{.*}} = global i8*
21+
22+
pub static GLOBAL: u32 = 0;
23+
pub static mut GLOBAL2: u32 = 0;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// This test makes sure that functions get annotated with the proper
12+
// "target-cpu" attribute in LLVM.
13+
14+
// only-x86_64
15+
// compile-flags: -C no-prepopulate-passes -C panic=abort
16+
17+
#![crate_type = "staticlib"]
18+
19+
// CHECK-LABEL: define {{.*}} @exported() {{.*}} #0
20+
#[no_mangle]
21+
pub extern fn exported() {
22+
not_exported();
23+
}
24+
25+
// CHECK-LABEL: define {{.*}} @_ZN23target_cpu_on_functions12not_exported{{.*}}() {{.*}} #0
26+
fn not_exported() {}
27+
28+
// CHECK: attributes #0 = {{.*}} "target-cpu"="x86-64"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
-include ../tools.mk
3+
4+
# This test makes sure that we don't loose upstream object files when compiling
5+
# staticlibs with -Zcross-lang-lto
6+
7+
all: staticlib.rs upstream.rs
8+
$(RUSTC) upstream.rs -Z cross-lang-lto -Ccodegen-units=1
9+
10+
# Check No LTO
11+
$(RUSTC) staticlib.rs -Z cross-lang-lto -Ccodegen-units=1 -L. -o $(TMPDIR)/staticlib.a
12+
(cd $(TMPDIR); llvm-ar x ./staticlib.a)
13+
# Make sure the upstream object file was included
14+
ls upstream.*.rcgu.o
15+
16+
# Cleanup
17+
rm $(TMPDIR)/*
18+
19+
# Check ThinLTO
20+
$(RUSTC) upstream.rs -Z cross-lang-lto -Ccodegen-units=1 -Clto=thin
21+
$(RUSTC) staticlib.rs -Z cross-lang-lto -Ccodegen-units=1 -Clto=thin -L. -o $(TMPDIR)/staticlib.a
22+
(cd $(TMPDIR); llvm-ar x ./staticlib.a)
23+
ls upstream.*.rcgu.o
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![crate_type="staticlib"]
12+
13+
extern crate upstream;
14+
15+
#[no_mangle]
16+
pub extern fn bar() {
17+
upstream::foo();
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![crate_type = "rlib"]
12+
13+
pub fn foo() {}

src/test/run-make-fulldeps/cross-lang-lto/Makefile

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# ignore-msvc
21

32
-include ../tools.mk
43

0 commit comments

Comments
 (0)