2019-02-17 18:58:58 +00:00
|
|
|
use std::ffi::CString;
|
2022-08-12 17:22:38 +00:00
|
|
|
use std::io::{self, Write};
|
|
|
|
use std::path::{Path, PathBuf};
|
2019-02-17 18:58:58 +00:00
|
|
|
use std::sync::Arc;
|
|
|
|
use std::{fs, slice, str};
|
2024-07-28 22:13:50 +00:00
|
|
|
|
2019-02-17 18:58:58 +00:00
|
|
|
use libc::{c_char, c_int, c_void, size_t};
|
2023-07-12 21:07:34 +00:00
|
|
|
use llvm::{
|
|
|
|
LLVMRustLLVMHasZlibCompressionForDebugSymbols, LLVMRustLLVMHasZstdCompressionForDebugSymbols,
|
|
|
|
};
|
2021-02-14 16:27:08 +00:00
|
|
|
use rustc_codegen_ssa::back::link::ensure_removed;
|
2020-09-23 15:57:50 +00:00
|
|
|
use rustc_codegen_ssa::back::write::{
|
2020-09-23 16:33:54 +00:00
|
|
|
BitcodeSection, CodegenContext, EmitObj, ModuleConfig, TargetMachineFactoryConfig,
|
|
|
|
TargetMachineFactoryFn,
|
2020-09-23 15:57:50 +00:00
|
|
|
};
|
2019-12-24 22:38:22 +00:00
|
|
|
use rustc_codegen_ssa::traits::*;
|
2020-04-23 18:45:55 +00:00
|
|
|
use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
|
2021-11-08 15:59:36 +00:00
|
|
|
use rustc_data_structures::profiling::SelfProfilerRef;
|
2018-08-07 14:04:34 +00:00
|
|
|
use rustc_data_structures::small_c_str::SmallCStr;
|
2024-06-18 10:35:56 +00:00
|
|
|
use rustc_errors::{DiagCtxtHandle, FatalError, Level};
|
2019-12-24 22:38:22 +00:00
|
|
|
use rustc_fs_util::{link_or_copy, path_to_c_string};
|
2020-03-29 15:19:48 +00:00
|
|
|
use rustc_middle::ty::TyCtxt;
|
2020-03-11 11:49:08 +00:00
|
|
|
use rustc_session::Session;
|
2024-03-19 12:51:22 +00:00
|
|
|
use rustc_session::config::{
|
|
|
|
self, Lto, OutputType, Passes, RemapPathScopeComponents, SplitDwarfKind, SwitchWithOptPath,
|
|
|
|
};
|
2020-05-26 19:07:59 +00:00
|
|
|
use rustc_span::InnerSpan;
|
2020-06-23 16:41:56 +00:00
|
|
|
use rustc_span::symbol::sym;
|
2023-11-13 12:48:23 +00:00
|
|
|
use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo, TlsModel};
|
2024-05-22 04:50:24 +00:00
|
|
|
use tracing::debug;
|
2014-08-11 17:33:58 +00:00
|
|
|
|
2019-02-17 18:58:58 +00:00
|
|
|
use crate::back::lto::ThinBuffer;
|
2023-09-17 12:40:22 +00:00
|
|
|
use crate::back::owned_target_machine::OwnedTargetMachine;
|
2020-02-11 21:37:16 +00:00
|
|
|
use crate::back::profiling::{
|
|
|
|
LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback,
|
2024-07-28 22:13:50 +00:00
|
|
|
};
|
2022-08-19 13:48:15 +00:00
|
|
|
use crate::errors::{
|
2023-07-12 21:07:34 +00:00
|
|
|
CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression,
|
|
|
|
WithLlvmError, WriteBytecode,
|
2024-07-28 22:13:50 +00:00
|
|
|
};
|
2024-09-17 05:28:57 +00:00
|
|
|
use crate::llvm::diagnostic::OptimizationDiagnosticKind::*;
|
2018-01-10 16:58:39 +00:00
|
|
|
use crate::llvm::{self, DiagnosticInfo, PassManager};
|
2019-04-10 11:46:37 +00:00
|
|
|
use crate::type_::Type;
|
|
|
|
use crate::{LlvmCodegenBackend, ModuleLlvm, base, common, llvm_util};
|
2014-08-11 17:33:58 +00:00
|
|
|
|
2024-07-06 12:26:42 +00:00
|
|
|
pub(crate) fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> FatalError {
|
2015-10-23 05:07:19 +00:00
|
|
|
match llvm::last_error() {
|
2023-12-17 23:15:45 +00:00
|
|
|
Some(llvm_err) => dcx.emit_almost_fatal(WithLlvmError(err, llvm_err)),
|
|
|
|
None => dcx.emit_almost_fatal(err),
|
2014-08-11 17:33:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-06 12:26:42 +00:00
|
|
|
fn write_output_file<'ll>(
|
2024-06-18 10:35:56 +00:00
|
|
|
dcx: DiagCtxtHandle<'_>,
|
2019-12-24 22:38:22 +00:00
|
|
|
target: &'ll llvm::TargetMachine,
|
|
|
|
pm: &llvm::PassManager<'ll>,
|
|
|
|
m: &'ll llvm::Module,
|
|
|
|
output: &Path,
|
2020-09-23 16:33:54 +00:00
|
|
|
dwo_output: Option<&Path>,
|
2019-12-24 22:38:22 +00:00
|
|
|
file_type: llvm::FileType,
|
2021-11-08 15:59:36 +00:00
|
|
|
self_profiler_ref: &SelfProfilerRef,
|
2019-12-24 22:38:22 +00:00
|
|
|
) -> Result<(), FatalError> {
|
2022-01-26 15:26:43 +00:00
|
|
|
debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
|
2014-08-11 17:33:58 +00:00
|
|
|
unsafe {
|
2018-11-29 13:09:28 +00:00
|
|
|
let output_c = path_to_c_string(output);
|
2022-01-26 15:26:43 +00:00
|
|
|
let dwo_output_c;
|
|
|
|
let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
|
|
|
|
dwo_output_c = path_to_c_string(dwo_output);
|
|
|
|
dwo_output_c.as_ptr()
|
2020-09-23 16:33:54 +00:00
|
|
|
} else {
|
2022-01-26 15:26:43 +00:00
|
|
|
std::ptr::null()
|
2020-09-23 16:33:54 +00:00
|
|
|
};
|
2022-01-26 15:26:43 +00:00
|
|
|
let result = llvm::LLVMRustWriteOutputFile(
|
|
|
|
target,
|
|
|
|
pm,
|
|
|
|
m,
|
|
|
|
output_c.as_ptr(),
|
|
|
|
dwo_output_ptr,
|
|
|
|
file_type,
|
|
|
|
);
|
2021-11-08 15:59:36 +00:00
|
|
|
|
|
|
|
// Record artifact sizes for self-profiling
|
|
|
|
if result == llvm::LLVMRustResult::Success {
|
|
|
|
let artifact_kind = match file_type {
|
|
|
|
llvm::FileType::ObjectFile => "object_file",
|
|
|
|
llvm::FileType::AssemblyFile => "assembly_file",
|
|
|
|
};
|
|
|
|
record_artifact_size(self_profiler_ref, artifact_kind, output);
|
|
|
|
if let Some(dwo_file) = dwo_output {
|
|
|
|
record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-17 23:15:45 +00:00
|
|
|
result.into_result().map_err(|()| llvm_err(dcx, LlvmError::WriteOutput { path: output }))
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-06 12:26:42 +00:00
|
|
|
pub(crate) fn create_informational_target_machine(
|
2024-08-03 08:45:48 +00:00
|
|
|
sess: &Session,
|
2024-08-04 03:51:37 +00:00
|
|
|
only_base_features: bool,
|
2024-08-03 08:45:48 +00:00
|
|
|
) -> OwnedTargetMachine {
|
2023-09-09 12:00:24 +00:00
|
|
|
let config = TargetMachineFactoryConfig { split_dwarf_file: None, output_obj_file: None };
|
2021-09-24 15:02:02 +00:00
|
|
|
// Can't use query system here quite yet because this function is invoked before the query
|
|
|
|
// system/tcx is set up.
|
2024-08-04 03:51:37 +00:00
|
|
|
let features = llvm_util::global_llvm_features(sess, false, only_base_features);
|
2021-09-24 15:02:02 +00:00
|
|
|
target_machine_factory(sess, config::OptLevel::No, &features)(config)
|
2023-12-17 19:21:26 +00:00
|
|
|
.unwrap_or_else(|err| llvm_err(sess.dcx(), err).raise())
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
|
|
|
|
2024-07-06 12:26:42 +00:00
|
|
|
pub(crate) fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMachine {
|
2020-11-30 16:39:08 +00:00
|
|
|
let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
|
sess/cg: re-introduce split dwarf kind
In #79570, `-Z split-dwarf-kind={none,single,split}` was replaced by `-C
split-debuginfo={off,packed,unpacked}`. `-C split-debuginfo`'s packed
and unpacked aren't exact parallels to single and split, respectively.
On Unix, `-C split-debuginfo=packed` will put debuginfo into object
files and package debuginfo into a DWARF package file (`.dwp`) and
`-C split-debuginfo=unpacked` will put debuginfo into dwarf object files
and won't package it.
In the initial implementation of Split DWARF, split mode wrote sections
which did not require relocation into a DWARF object (`.dwo`) file which
was ignored by the linker and then packaged those DWARF objects into
DWARF packages (`.dwp`). In single mode, sections which did not require
relocation were written into object files but ignored by the linker and
were not packaged. However, both split and single modes could be
packaged or not, the primary difference in behaviour was where the
debuginfo sections that did not require link-time relocation were
written (in a DWARF object or the object file).
This commit re-introduces a `-Z split-dwarf-kind` flag, which can be
used to pick between split and single modes when `-C split-debuginfo` is
used to enable Split DWARF (either packed or unpacked).
Signed-off-by: David Wood <david.wood@huawei.com>
2021-10-08 16:10:17 +00:00
|
|
|
tcx.output_filenames(()).split_dwarf_path(
|
|
|
|
tcx.sess.split_debuginfo(),
|
2022-07-06 12:44:47 +00:00
|
|
|
tcx.sess.opts.unstable_opts.split_dwarf_kind,
|
sess/cg: re-introduce split dwarf kind
In #79570, `-Z split-dwarf-kind={none,single,split}` was replaced by `-C
split-debuginfo={off,packed,unpacked}`. `-C split-debuginfo`'s packed
and unpacked aren't exact parallels to single and split, respectively.
On Unix, `-C split-debuginfo=packed` will put debuginfo into object
files and package debuginfo into a DWARF package file (`.dwp`) and
`-C split-debuginfo=unpacked` will put debuginfo into dwarf object files
and won't package it.
In the initial implementation of Split DWARF, split mode wrote sections
which did not require relocation into a DWARF object (`.dwo`) file which
was ignored by the linker and then packaged those DWARF objects into
DWARF packages (`.dwp`). In single mode, sections which did not require
relocation were written into object files but ignored by the linker and
were not packaged. However, both split and single modes could be
packaged or not, the primary difference in behaviour was where the
debuginfo sections that did not require link-time relocation were
written (in a DWARF object or the object file).
This commit re-introduces a `-Z split-dwarf-kind` flag, which can be
used to pick between split and single modes when `-C split-debuginfo` is
used to enable Split DWARF (either packed or unpacked).
Signed-off-by: David Wood <david.wood@huawei.com>
2021-10-08 16:10:17 +00:00
|
|
|
Some(mod_name),
|
|
|
|
)
|
2020-11-30 16:39:08 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
2023-09-09 12:00:24 +00:00
|
|
|
|
|
|
|
let output_obj_file =
|
|
|
|
Some(tcx.output_filenames(()).temp_path(OutputType::Object, Some(mod_name)));
|
|
|
|
let config = TargetMachineFactoryConfig { split_dwarf_file, output_obj_file };
|
|
|
|
|
2021-09-24 15:02:02 +00:00
|
|
|
target_machine_factory(
|
2023-11-21 19:07:32 +00:00
|
|
|
tcx.sess,
|
2021-09-24 15:02:02 +00:00
|
|
|
tcx.backend_optimization_level(()),
|
|
|
|
tcx.global_backend_features(()),
|
|
|
|
)(config)
|
2023-12-18 11:21:37 +00:00
|
|
|
.unwrap_or_else(|err| llvm_err(tcx.dcx(), err).raise())
|
2019-02-20 20:27:00 +00:00
|
|
|
}
|
2018-10-27 12:29:06 +00:00
|
|
|
|
2024-07-06 12:26:42 +00:00
|
|
|
fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
|
2018-10-27 12:29:06 +00:00
|
|
|
use self::config::OptLevel::*;
|
|
|
|
match cfg {
|
|
|
|
No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
|
|
|
|
Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
|
|
|
|
Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
|
|
|
|
Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
|
|
|
|
Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
|
|
|
|
SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-05 18:16:58 +00:00
|
|
|
fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
|
|
|
|
use config::OptLevel::*;
|
|
|
|
match cfg {
|
|
|
|
No => llvm::PassBuilderOptLevel::O0,
|
|
|
|
Less => llvm::PassBuilderOptLevel::O1,
|
|
|
|
Default => llvm::PassBuilderOptLevel::O2,
|
|
|
|
Aggressive => llvm::PassBuilderOptLevel::O3,
|
|
|
|
Size => llvm::PassBuilderOptLevel::Os,
|
|
|
|
SizeMin => llvm::PassBuilderOptLevel::Oz,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-23 17:49:00 +00:00
|
|
|
fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
|
2020-04-22 21:46:45 +00:00
|
|
|
match relocation_model {
|
2020-04-23 17:49:00 +00:00
|
|
|
RelocModel::Static => llvm::RelocModel::Static,
|
2024-09-18 03:34:49 +00:00
|
|
|
// LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra
|
|
|
|
// attribute.
|
2021-09-10 13:11:56 +00:00
|
|
|
RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
|
2020-04-23 17:49:00 +00:00
|
|
|
RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
|
|
|
|
RelocModel::Ropi => llvm::RelocModel::ROPI,
|
|
|
|
RelocModel::Rwpi => llvm::RelocModel::RWPI,
|
|
|
|
RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
|
2020-04-22 21:46:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-11 23:35:13 +00:00
|
|
|
pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
|
2020-05-07 00:34:27 +00:00
|
|
|
match code_model {
|
|
|
|
Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
|
|
|
|
Some(CodeModel::Small) => llvm::CodeModel::Small,
|
|
|
|
Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
|
|
|
|
Some(CodeModel::Medium) => llvm::CodeModel::Medium,
|
|
|
|
Some(CodeModel::Large) => llvm::CodeModel::Large,
|
|
|
|
None => llvm::CodeModel::None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-06 12:26:42 +00:00
|
|
|
pub(crate) fn target_machine_factory(
|
2019-12-24 22:38:22 +00:00
|
|
|
sess: &Session,
|
|
|
|
optlvl: config::OptLevel,
|
2021-09-24 15:02:02 +00:00
|
|
|
target_features: &[String],
|
2020-09-23 15:57:50 +00:00
|
|
|
) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
|
2020-04-22 21:46:45 +00:00
|
|
|
let reloc_model = to_llvm_relocation_model(sess.relocation_model());
|
2014-08-11 17:33:58 +00:00
|
|
|
|
2018-10-27 12:29:06 +00:00
|
|
|
let (opt_level, _) = to_llvm_opt_settings(optlvl);
|
2024-09-03 08:49:16 +00:00
|
|
|
let use_softfp = if sess.target.arch == "arm" && sess.target.abi == "eabihf" {
|
|
|
|
sess.opts.cg.soft_float
|
|
|
|
} else {
|
2024-09-18 03:34:49 +00:00
|
|
|
// `validate_commandline_args_with_session_available` has already warned about this being
|
|
|
|
// ignored. Let's make sure LLVM doesn't suddenly start using this flag on more targets.
|
2024-09-03 08:49:16 +00:00
|
|
|
false
|
|
|
|
};
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
2020-10-26 19:55:07 +00:00
|
|
|
let ffunction_sections =
|
2022-07-06 12:44:47 +00:00
|
|
|
sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
let fdata_sections = ffunction_sections;
|
2022-07-06 12:44:47 +00:00
|
|
|
let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
2020-05-07 00:34:27 +00:00
|
|
|
let code_model = to_llvm_code_model(sess.code_model());
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
2020-11-08 11:27:51 +00:00
|
|
|
let mut singlethread = sess.target.singlethread;
|
2018-09-01 05:41:17 +00:00
|
|
|
|
|
|
|
// On the wasm target once the `atomics` feature is enabled that means that
|
|
|
|
// we're no longer single-threaded, or otherwise we don't want LLVM to
|
|
|
|
// lower atomic operations to single-threaded operations.
|
2020-12-30 18:52:21 +00:00
|
|
|
if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
|
2018-09-01 05:41:17 +00:00
|
|
|
singlethread = false;
|
|
|
|
}
|
2017-10-23 03:01:00 +00:00
|
|
|
|
2020-10-15 09:44:00 +00:00
|
|
|
let triple = SmallCStr::new(&sess.target.llvm_target);
|
2018-08-23 18:03:22 +00:00
|
|
|
let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
|
2021-09-24 15:02:02 +00:00
|
|
|
let features = CString::new(target_features.join(",")).unwrap();
|
2020-11-08 11:27:51 +00:00
|
|
|
let abi = SmallCStr::new(&sess.target.llvm_abiname);
|
2020-11-23 23:55:10 +00:00
|
|
|
let trap_unreachable =
|
2022-07-06 12:44:47 +00:00
|
|
|
sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
|
|
|
|
let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
|
2017-07-23 15:14:38 +00:00
|
|
|
|
2024-06-21 19:08:49 +00:00
|
|
|
let verbose_asm = sess.opts.unstable_opts.verbose_asm;
|
2020-11-08 11:27:51 +00:00
|
|
|
let relax_elf_relocations =
|
2022-07-06 12:44:47 +00:00
|
|
|
sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
|
2020-11-08 11:27:51 +00:00
|
|
|
|
|
|
|
let use_init_array =
|
2022-07-06 12:44:47 +00:00
|
|
|
!sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
|
2020-04-17 02:40:11 +00:00
|
|
|
|
2021-12-11 01:11:57 +00:00
|
|
|
let path_mapping = sess.source_map().path_mapping().clone();
|
|
|
|
|
2023-11-13 12:48:23 +00:00
|
|
|
let use_emulated_tls = matches!(sess.tls_model(), TlsModel::Emulated);
|
2022-11-10 10:06:34 +00:00
|
|
|
|
2023-07-03 11:11:27 +00:00
|
|
|
// copy the exe path, followed by path all into one buffer
|
|
|
|
// null terminating them so we can use them as null terminated strings
|
|
|
|
let args_cstr_buff = {
|
|
|
|
let mut args_cstr_buff: Vec<u8> = Vec::new();
|
|
|
|
let exe_path = std::env::current_exe().unwrap_or_default();
|
|
|
|
let exe_path_str = exe_path.into_os_string().into_string().unwrap_or_default();
|
|
|
|
|
|
|
|
args_cstr_buff.extend_from_slice(exe_path_str.as_bytes());
|
|
|
|
args_cstr_buff.push(0);
|
|
|
|
|
|
|
|
for arg in sess.expanded_args.iter() {
|
|
|
|
args_cstr_buff.extend_from_slice(arg.as_bytes());
|
|
|
|
args_cstr_buff.push(0);
|
|
|
|
}
|
|
|
|
|
|
|
|
args_cstr_buff
|
|
|
|
};
|
|
|
|
|
2023-07-12 21:07:34 +00:00
|
|
|
let debuginfo_compression = sess.opts.debuginfo_compression.to_string();
|
|
|
|
match sess.opts.debuginfo_compression {
|
|
|
|
rustc_session::config::DebugInfoCompression::Zlib => {
|
|
|
|
if !unsafe { LLVMRustLLVMHasZlibCompressionForDebugSymbols() } {
|
2024-01-04 00:28:14 +00:00
|
|
|
sess.dcx().emit_warn(UnknownCompression { algorithm: "zlib" });
|
2023-07-12 21:07:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
rustc_session::config::DebugInfoCompression::Zstd => {
|
|
|
|
if !unsafe { LLVMRustLLVMHasZstdCompressionForDebugSymbols() } {
|
2024-01-04 00:28:14 +00:00
|
|
|
sess.dcx().emit_warn(UnknownCompression { algorithm: "zstd" });
|
2023-07-12 21:07:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
rustc_session::config::DebugInfoCompression::None => {}
|
|
|
|
};
|
|
|
|
let debuginfo_compression = SmallCStr::new(&debuginfo_compression);
|
|
|
|
|
2024-03-22 14:27:17 +00:00
|
|
|
let file_name_display_preference =
|
|
|
|
sess.filename_display_preference(RemapPathScopeComponents::DEBUGINFO);
|
2023-08-23 13:46:58 +00:00
|
|
|
|
2020-09-23 16:33:54 +00:00
|
|
|
Arc::new(move |config: TargetMachineFactoryConfig| {
|
2023-09-09 12:00:24 +00:00
|
|
|
let path_to_cstring_helper = |path: Option<PathBuf>| -> CString {
|
2023-08-23 13:46:58 +00:00
|
|
|
let path = path.unwrap_or_default();
|
2024-03-22 14:27:17 +00:00
|
|
|
let path = path_mapping
|
|
|
|
.to_real_filename(path)
|
|
|
|
.to_string_lossy(file_name_display_preference)
|
|
|
|
.into_owned();
|
|
|
|
CString::new(path).unwrap()
|
2023-09-09 12:00:24 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
let split_dwarf_file = path_to_cstring_helper(config.split_dwarf_file);
|
|
|
|
let output_obj_file = path_to_cstring_helper(config.output_obj_file);
|
2020-09-23 16:33:54 +00:00
|
|
|
|
2023-09-17 12:40:22 +00:00
|
|
|
OwnedTargetMachine::new(
|
|
|
|
&triple,
|
|
|
|
&cpu,
|
|
|
|
&features,
|
|
|
|
&abi,
|
|
|
|
code_model,
|
|
|
|
reloc_model,
|
|
|
|
opt_level,
|
|
|
|
use_softfp,
|
|
|
|
ffunction_sections,
|
|
|
|
fdata_sections,
|
|
|
|
funique_section_names,
|
|
|
|
trap_unreachable,
|
|
|
|
singlethread,
|
2024-06-21 19:08:49 +00:00
|
|
|
verbose_asm,
|
2023-09-17 12:40:22 +00:00
|
|
|
emit_stack_size_section,
|
|
|
|
relax_elf_relocations,
|
|
|
|
use_init_array,
|
|
|
|
&split_dwarf_file,
|
2023-09-09 12:00:24 +00:00
|
|
|
&output_obj_file,
|
2023-09-17 12:40:22 +00:00
|
|
|
&debuginfo_compression,
|
2023-11-13 12:48:23 +00:00
|
|
|
use_emulated_tls,
|
2023-09-17 12:40:22 +00:00
|
|
|
&args_cstr_buff,
|
|
|
|
)
|
2017-07-23 15:14:38 +00:00
|
|
|
})
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
}
|
|
|
|
|
2018-10-23 15:01:35 +00:00
|
|
|
pub(crate) fn save_temp_bitcode(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
|
|
|
module: &ModuleCodegen<ModuleLlvm>,
|
2019-12-24 22:38:22 +00:00
|
|
|
name: &str,
|
2018-10-23 15:01:35 +00:00
|
|
|
) {
|
|
|
|
if !cgcx.save_temps {
|
2019-12-24 22:38:22 +00:00
|
|
|
return;
|
2017-09-14 03:26:39 +00:00
|
|
|
}
|
2018-10-23 15:01:35 +00:00
|
|
|
unsafe {
|
2023-07-25 21:04:01 +00:00
|
|
|
let ext = format!("{name}.bc");
|
2018-10-23 15:01:35 +00:00
|
|
|
let cgu = Some(&module.name[..]);
|
|
|
|
let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
|
2018-11-29 13:09:28 +00:00
|
|
|
let cstr = path_to_c_string(&path);
|
2018-10-23 15:01:35 +00:00
|
|
|
let llmod = module.module_llvm.llmod();
|
|
|
|
llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-25 21:39:02 +00:00
|
|
|
/// In what context is a dignostic handler being attached to a codegen unit?
|
2024-07-06 12:26:42 +00:00
|
|
|
pub(crate) enum CodegenDiagnosticsStage {
|
2023-06-25 21:39:02 +00:00
|
|
|
/// Prelink optimization stage.
|
|
|
|
Opt,
|
|
|
|
/// LTO/ThinLTO postlink optimization stage.
|
|
|
|
LTO,
|
|
|
|
/// Code generation.
|
|
|
|
Codegen,
|
|
|
|
}
|
|
|
|
|
2024-07-06 12:26:42 +00:00
|
|
|
pub(crate) struct DiagnosticHandlers<'a> {
|
2024-06-18 10:35:56 +00:00
|
|
|
data: *mut (&'a CodegenContext<LlvmCodegenBackend>, DiagCtxtHandle<'a>),
|
2018-06-27 14:57:25 +00:00
|
|
|
llcx: &'a llvm::Context,
|
2021-11-12 00:00:00 +00:00
|
|
|
old_handler: Option<&'a llvm::DiagnosticHandler>,
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> DiagnosticHandlers<'a> {
|
2024-07-06 12:26:42 +00:00
|
|
|
pub(crate) fn new(
|
2019-12-24 22:38:22 +00:00
|
|
|
cgcx: &'a CodegenContext<LlvmCodegenBackend>,
|
2024-06-18 10:35:56 +00:00
|
|
|
dcx: DiagCtxtHandle<'a>,
|
2019-12-24 22:38:22 +00:00
|
|
|
llcx: &'a llvm::Context,
|
2023-06-25 21:39:02 +00:00
|
|
|
module: &ModuleCodegen<ModuleLlvm>,
|
|
|
|
stage: CodegenDiagnosticsStage,
|
2019-12-24 22:38:22 +00:00
|
|
|
) -> Self {
|
2021-11-12 00:00:00 +00:00
|
|
|
let remark_passes_all: bool;
|
|
|
|
let remark_passes: Vec<CString>;
|
|
|
|
match &cgcx.remark {
|
|
|
|
Passes::All => {
|
|
|
|
remark_passes_all = true;
|
|
|
|
remark_passes = Vec::new();
|
|
|
|
}
|
|
|
|
Passes::Some(passes) => {
|
|
|
|
remark_passes_all = false;
|
|
|
|
remark_passes =
|
|
|
|
passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
let remark_passes: Vec<*const c_char> =
|
|
|
|
remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
|
2023-06-25 21:39:02 +00:00
|
|
|
let remark_file = cgcx
|
|
|
|
.remark_dir
|
|
|
|
.as_ref()
|
|
|
|
// Use the .opt.yaml file suffix, which is supported by LLVM's opt-viewer.
|
|
|
|
.map(|dir| {
|
|
|
|
let stage_suffix = match stage {
|
|
|
|
CodegenDiagnosticsStage::Codegen => "codegen",
|
|
|
|
CodegenDiagnosticsStage::Opt => "opt",
|
|
|
|
CodegenDiagnosticsStage::LTO => "lto",
|
|
|
|
};
|
|
|
|
dir.join(format!("{}.{stage_suffix}.opt.yaml", module.name))
|
|
|
|
})
|
|
|
|
.and_then(|dir| dir.to_str().and_then(|p| CString::new(p).ok()));
|
|
|
|
|
2023-08-07 15:56:57 +00:00
|
|
|
let pgo_available = cgcx.opts.cg.profile_use.is_some();
|
2023-12-17 23:15:45 +00:00
|
|
|
let data = Box::into_raw(Box::new((cgcx, dcx)));
|
2017-07-23 15:14:38 +00:00
|
|
|
unsafe {
|
2021-11-12 00:00:00 +00:00
|
|
|
let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
|
|
|
|
llvm::LLVMRustContextConfigureDiagnosticHandler(
|
|
|
|
llcx,
|
|
|
|
diagnostic_handler,
|
|
|
|
data.cast(),
|
|
|
|
remark_passes_all,
|
|
|
|
remark_passes.as_ptr(),
|
|
|
|
remark_passes.len(),
|
2023-06-25 21:39:02 +00:00
|
|
|
// The `as_ref()` is important here, otherwise the `CString` will be dropped
|
|
|
|
// too soon!
|
|
|
|
remark_file.as_ref().map(|dir| dir.as_ptr()).unwrap_or(std::ptr::null()),
|
2023-08-07 15:56:57 +00:00
|
|
|
pgo_available,
|
2021-11-12 00:00:00 +00:00
|
|
|
);
|
|
|
|
DiagnosticHandlers { data, llcx, old_handler }
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
|
|
|
}
|
2014-09-12 15:17:58 +00:00
|
|
|
}
|
|
|
|
|
2017-07-23 15:14:38 +00:00
|
|
|
impl<'a> Drop for DiagnosticHandlers<'a> {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
unsafe {
|
2021-11-12 00:00:00 +00:00
|
|
|
llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
|
2018-07-14 23:52:45 +00:00
|
|
|
drop(Box::from_raw(self.data));
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
|
|
|
}
|
2014-09-12 15:17:58 +00:00
|
|
|
}
|
|
|
|
|
2020-05-26 19:07:59 +00:00
|
|
|
fn report_inline_asm(
|
2019-12-24 22:38:22 +00:00
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
2020-05-26 19:07:59 +00:00
|
|
|
msg: String,
|
2020-06-09 13:37:59 +00:00
|
|
|
level: llvm::DiagnosticLevel,
|
2024-02-21 09:18:59 +00:00
|
|
|
mut cookie: u64,
|
2020-05-26 19:07:59 +00:00
|
|
|
source: Option<(String, Vec<InnerSpan>)>,
|
2019-12-24 22:38:22 +00:00
|
|
|
) {
|
2020-05-26 19:07:59 +00:00
|
|
|
// In LTO build we may get srcloc values from other crates which are invalid
|
|
|
|
// since they use a different source map. To be safe we just suppress these
|
|
|
|
// in LTO builds.
|
|
|
|
if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
|
|
|
|
cookie = 0;
|
|
|
|
}
|
2020-06-09 13:37:59 +00:00
|
|
|
let level = match level {
|
2024-01-04 00:44:37 +00:00
|
|
|
llvm::DiagnosticLevel::Error => Level::Error,
|
2024-01-09 01:28:45 +00:00
|
|
|
llvm::DiagnosticLevel::Warning => Level::Warning,
|
2020-06-09 13:37:59 +00:00
|
|
|
llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
|
|
|
|
};
|
2024-02-21 09:18:59 +00:00
|
|
|
cgcx.diag_emitter.inline_asm_error(cookie.try_into().unwrap(), msg, level, source);
|
2014-09-27 08:33:36 +00:00
|
|
|
}
|
|
|
|
|
2018-07-13 10:59:41 +00:00
|
|
|
unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
|
2017-07-23 15:14:38 +00:00
|
|
|
if user.is_null() {
|
2019-12-24 22:38:22 +00:00
|
|
|
return;
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
2024-07-14 18:27:57 +00:00
|
|
|
let (cgcx, dcx) =
|
|
|
|
unsafe { *(user as *const (&CodegenContext<LlvmCodegenBackend>, DiagCtxtHandle<'_>)) };
|
2014-09-12 15:17:58 +00:00
|
|
|
|
2024-07-14 18:27:57 +00:00
|
|
|
match unsafe { llvm::diagnostic::Diagnostic::unpack(info) } {
|
2015-01-22 18:43:39 +00:00
|
|
|
llvm::diagnostic::InlineAsm(inline) => {
|
2021-07-28 19:31:47 +00:00
|
|
|
report_inline_asm(cgcx, inline.message, inline.level, inline.cookie, inline.source);
|
2015-01-22 18:43:39 +00:00
|
|
|
}
|
|
|
|
|
2014-09-12 15:17:58 +00:00
|
|
|
llvm::diagnostic::Optimization(opt) => {
|
2023-12-18 00:15:13 +00:00
|
|
|
dcx.emit_note(FromLlvmOptimizationDiag {
|
2023-07-14 16:09:04 +00:00
|
|
|
filename: &opt.filename,
|
|
|
|
line: opt.line,
|
|
|
|
column: opt.column,
|
|
|
|
pass_name: &opt.pass_name,
|
|
|
|
kind: match opt.kind {
|
2024-09-17 05:28:57 +00:00
|
|
|
OptimizationRemark => "success",
|
|
|
|
OptimizationMissed | OptimizationFailure => "missed",
|
|
|
|
OptimizationAnalysis
|
|
|
|
| OptimizationAnalysisFPCommute
|
|
|
|
| OptimizationAnalysisAliasing => "analysis",
|
|
|
|
OptimizationRemarkOther => "other",
|
2023-07-14 16:09:04 +00:00
|
|
|
},
|
|
|
|
message: &opt.message,
|
|
|
|
});
|
2014-08-11 17:33:58 +00:00
|
|
|
}
|
2019-12-24 22:38:22 +00:00
|
|
|
llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
|
2024-07-14 18:27:57 +00:00
|
|
|
let message = llvm::build_string(|s| unsafe {
|
2018-03-12 17:11:59 +00:00
|
|
|
llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
|
2019-12-24 22:38:22 +00:00
|
|
|
})
|
|
|
|
.expect("non-UTF8 diagnostic");
|
2024-01-04 00:28:14 +00:00
|
|
|
dcx.emit_warn(FromLlvmDiag { message });
|
2018-03-12 17:11:59 +00:00
|
|
|
}
|
2020-09-29 11:20:56 +00:00
|
|
|
llvm::diagnostic::Unsupported(diagnostic_ref) => {
|
2024-07-14 18:27:57 +00:00
|
|
|
let message = llvm::build_string(|s| unsafe {
|
2020-09-29 11:20:56 +00:00
|
|
|
llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
|
|
|
|
})
|
|
|
|
.expect("non-UTF8 diagnostic");
|
2023-12-18 00:15:13 +00:00
|
|
|
dcx.emit_err(FromLlvmDiag { message });
|
2020-09-29 11:20:56 +00:00
|
|
|
}
|
2019-12-24 22:38:22 +00:00
|
|
|
llvm::diagnostic::UnknownDiagnostic(..) => {}
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-05 18:16:58 +00:00
|
|
|
fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
|
|
|
|
match config.pgo_gen {
|
|
|
|
SwitchWithOptPath::Enabled(ref opt_dir_path) => {
|
|
|
|
let path = if let Some(dir_path) = opt_dir_path {
|
|
|
|
dir_path.join("default_%m.profraw")
|
|
|
|
} else {
|
|
|
|
PathBuf::from("default_%m.profraw")
|
|
|
|
};
|
|
|
|
|
|
|
|
Some(CString::new(format!("{}", path.display())).unwrap())
|
|
|
|
}
|
|
|
|
SwitchWithOptPath::Disabled => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
|
|
|
|
config
|
|
|
|
.pgo_use
|
|
|
|
.as_ref()
|
|
|
|
.map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
|
|
|
|
}
|
|
|
|
|
2021-05-07 07:41:37 +00:00
|
|
|
fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
|
|
|
|
config
|
|
|
|
.pgo_sample_use
|
|
|
|
.as_ref()
|
|
|
|
.map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
|
|
|
|
}
|
|
|
|
|
2022-08-10 16:16:20 +00:00
|
|
|
fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
|
2023-02-15 11:43:41 +00:00
|
|
|
config.instrument_coverage.then(|| CString::new("default_%m_%p.profraw").unwrap())
|
2022-08-10 16:16:20 +00:00
|
|
|
}
|
|
|
|
|
2022-09-19 18:10:12 +00:00
|
|
|
pub(crate) unsafe fn llvm_optimize(
|
2020-02-11 21:37:16 +00:00
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
2024-06-18 10:35:56 +00:00
|
|
|
dcx: DiagCtxtHandle<'_>,
|
2020-01-05 18:16:58 +00:00
|
|
|
module: &ModuleCodegen<ModuleLlvm>,
|
|
|
|
config: &ModuleConfig,
|
|
|
|
opt_level: config::OptLevel,
|
|
|
|
opt_stage: llvm::OptStage,
|
2021-04-05 13:37:11 +00:00
|
|
|
) -> Result<(), FatalError> {
|
2020-01-05 18:16:58 +00:00
|
|
|
let unroll_loops =
|
|
|
|
opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
|
|
|
|
let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
|
|
|
|
let pgo_gen_path = get_pgo_gen_path(config);
|
|
|
|
let pgo_use_path = get_pgo_use_path(config);
|
2021-05-07 07:41:37 +00:00
|
|
|
let pgo_sample_use_path = get_pgo_sample_use_path(config);
|
2020-01-05 18:16:58 +00:00
|
|
|
let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
|
2022-08-10 16:16:20 +00:00
|
|
|
let instr_profile_output_path = get_instr_profile_output_path(config);
|
2024-02-01 21:16:30 +00:00
|
|
|
let sanitize_dataflow_abilist: Vec<_> = config
|
|
|
|
.sanitizer_dataflow_abilist
|
|
|
|
.iter()
|
|
|
|
.map(|file| CString::new(file.as_str()).unwrap())
|
|
|
|
.collect();
|
|
|
|
let sanitize_dataflow_abilist_ptrs: Vec<_> =
|
|
|
|
sanitize_dataflow_abilist.iter().map(|file| file.as_ptr()).collect();
|
2020-01-05 18:16:58 +00:00
|
|
|
// Sanitizer instrumentation is only inserted during the pre-link optimization stage.
|
|
|
|
let sanitizer_options = if !is_lto {
|
2020-06-14 00:00:00 +00:00
|
|
|
Some(llvm::SanitizerOptions {
|
|
|
|
sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
|
|
|
|
sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
|
2023-07-11 23:19:42 +00:00
|
|
|
sanitize_cfi: config.sanitizer.contains(SanitizerSet::CFI),
|
2024-02-01 21:16:30 +00:00
|
|
|
sanitize_dataflow: config.sanitizer.contains(SanitizerSet::DATAFLOW),
|
|
|
|
sanitize_dataflow_abilist: sanitize_dataflow_abilist_ptrs.as_ptr(),
|
|
|
|
sanitize_dataflow_abilist_len: sanitize_dataflow_abilist_ptrs.len(),
|
2023-07-11 23:19:42 +00:00
|
|
|
sanitize_kcfi: config.sanitizer.contains(SanitizerSet::KCFI),
|
2020-06-14 00:00:00 +00:00
|
|
|
sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
|
|
|
|
sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
|
2020-01-05 18:16:58 +00:00
|
|
|
sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
|
2020-06-14 00:00:00 +00:00
|
|
|
sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
|
2021-01-23 02:32:38 +00:00
|
|
|
sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
|
|
|
|
sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
|
2022-09-11 23:36:19 +00:00
|
|
|
sanitize_kernel_address: config.sanitizer.contains(SanitizerSet::KERNELADDRESS),
|
|
|
|
sanitize_kernel_address_recover: config
|
|
|
|
.sanitizer_recover
|
|
|
|
.contains(SanitizerSet::KERNELADDRESS),
|
2020-01-05 18:16:58 +00:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
2023-02-15 11:43:41 +00:00
|
|
|
let mut llvm_profiler = cgcx
|
|
|
|
.prof
|
|
|
|
.llvm_recording_enabled()
|
|
|
|
.then(|| LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()));
|
2020-02-11 21:37:16 +00:00
|
|
|
|
2021-09-29 20:58:33 +00:00
|
|
|
let llvm_selfprofiler =
|
|
|
|
llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
|
|
|
|
|
2022-06-10 18:53:25 +00:00
|
|
|
let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
|
2021-04-05 13:37:11 +00:00
|
|
|
|
2021-11-24 10:43:40 +00:00
|
|
|
let llvm_plugins = config.llvm_plugins.join(",");
|
2021-11-19 16:01:41 +00:00
|
|
|
|
2024-07-14 18:27:57 +00:00
|
|
|
let result = unsafe {
|
|
|
|
llvm::LLVMRustOptimize(
|
|
|
|
module.module_llvm.llmod(),
|
|
|
|
&*module.module_llvm.tm,
|
|
|
|
to_pass_builder_opt_level(opt_level),
|
|
|
|
opt_stage,
|
|
|
|
cgcx.opts.cg.linker_plugin_lto.enabled(),
|
|
|
|
config.no_prepopulate_passes,
|
|
|
|
config.verify_llvm_ir,
|
2024-08-29 10:12:31 +00:00
|
|
|
config.lint_llvm_ir,
|
2024-07-14 18:27:57 +00:00
|
|
|
using_thin_buffers,
|
|
|
|
config.merge_functions,
|
|
|
|
unroll_loops,
|
|
|
|
config.vectorize_slp,
|
|
|
|
config.vectorize_loop,
|
|
|
|
config.no_builtins,
|
|
|
|
config.emit_lifetime_markers,
|
|
|
|
sanitizer_options.as_ref(),
|
|
|
|
pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
|
|
|
|
pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
|
|
|
|
config.instrument_coverage,
|
|
|
|
instr_profile_output_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
|
|
|
|
config.instrument_gcov,
|
|
|
|
pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
|
|
|
|
config.debug_info_for_profiling,
|
|
|
|
llvm_selfprofiler,
|
|
|
|
selfprofile_before_pass_callback,
|
|
|
|
selfprofile_after_pass_callback,
|
|
|
|
extra_passes.as_ptr().cast(),
|
|
|
|
extra_passes.len(),
|
|
|
|
llvm_plugins.as_ptr().cast(),
|
|
|
|
llvm_plugins.len(),
|
|
|
|
)
|
|
|
|
};
|
2023-12-17 23:15:45 +00:00
|
|
|
result.into_result().map_err(|()| llvm_err(dcx, LlvmError::RunLlvmPasses))
|
2020-01-05 18:16:58 +00:00
|
|
|
}
|
|
|
|
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
// Unsafe due to LLVM calls.
|
2022-09-19 18:10:12 +00:00
|
|
|
pub(crate) unsafe fn optimize(
|
2019-12-24 22:38:22 +00:00
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
2024-06-18 10:35:56 +00:00
|
|
|
dcx: DiagCtxtHandle<'_>,
|
2019-12-24 22:38:22 +00:00
|
|
|
module: &ModuleCodegen<ModuleLlvm>,
|
|
|
|
config: &ModuleConfig,
|
2021-04-05 13:37:11 +00:00
|
|
|
) -> Result<(), FatalError> {
|
2021-12-03 02:06:36 +00:00
|
|
|
let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name);
|
2019-09-27 12:04:36 +00:00
|
|
|
|
2018-08-20 15:13:01 +00:00
|
|
|
let llmod = module.module_llvm.llmod();
|
|
|
|
let llcx = &*module.module_llvm.llcx;
|
2023-12-17 23:15:45 +00:00
|
|
|
let _handlers = DiagnosticHandlers::new(cgcx, dcx, llcx, module, CodegenDiagnosticsStage::Opt);
|
2014-09-12 15:17:58 +00:00
|
|
|
|
2018-05-08 13:10:16 +00:00
|
|
|
let module_name = module.name.clone();
|
2017-07-25 15:26:24 +00:00
|
|
|
let module_name = Some(&module_name[..]);
|
2016-05-14 00:48:32 +00:00
|
|
|
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
if config.emit_no_opt_bc {
|
2017-09-14 03:26:39 +00:00
|
|
|
let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
|
2018-11-29 13:09:28 +00:00
|
|
|
let out = path_to_c_string(&out);
|
2024-07-14 18:27:57 +00:00
|
|
|
unsafe { llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr()) };
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
}
|
|
|
|
|
2019-11-18 00:00:00 +00:00
|
|
|
if let Some(opt_level) = config.opt_level {
|
2022-09-16 23:18:27 +00:00
|
|
|
let opt_stage = match cgcx.lto {
|
|
|
|
Lto::Fat => llvm::OptStage::PreLinkFatLTO,
|
|
|
|
Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
|
|
|
|
_ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
|
|
|
|
_ => llvm::OptStage::PreLinkNoLTO,
|
|
|
|
};
|
2024-07-14 18:27:57 +00:00
|
|
|
return unsafe { llvm_optimize(cgcx, dcx, module, config, opt_level, opt_stage) };
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
2021-04-05 13:37:11 +00:00
|
|
|
Ok(())
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
2020-09-09 04:51:16 +00:00
|
|
|
pub(crate) fn link(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
2024-06-18 10:35:56 +00:00
|
|
|
dcx: DiagCtxtHandle<'_>,
|
2020-09-09 04:51:16 +00:00
|
|
|
mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
|
|
|
|
) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
|
|
|
|
use super::lto::{Linker, ModuleBuffer};
|
2022-10-13 09:00:36 +00:00
|
|
|
// Sort the modules by name to ensure deterministic behavior.
|
2020-09-09 04:51:16 +00:00
|
|
|
modules.sort_by(|a, b| a.name.cmp(&b.name));
|
|
|
|
let (first, elements) =
|
|
|
|
modules.split_first().expect("Bug! modules must contain at least one module.");
|
|
|
|
|
|
|
|
let mut linker = Linker::new(first.module_llvm.llmod());
|
|
|
|
for module in elements {
|
2022-04-01 19:01:47 +00:00
|
|
|
let _timer = cgcx.prof.generic_activity_with_arg("LLVM_link_module", &*module.name);
|
2020-09-09 04:51:16 +00:00
|
|
|
let buffer = ModuleBuffer::new(module.module_llvm.llmod());
|
2023-12-17 23:15:45 +00:00
|
|
|
linker
|
|
|
|
.add(buffer.data())
|
|
|
|
.map_err(|()| llvm_err(dcx, LlvmError::SerializeModule { name: &module.name }))?;
|
2020-09-09 04:51:16 +00:00
|
|
|
}
|
|
|
|
drop(linker);
|
|
|
|
Ok(modules.remove(0))
|
|
|
|
}
|
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
pub(crate) unsafe fn codegen(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
2024-06-18 10:35:56 +00:00
|
|
|
dcx: DiagCtxtHandle<'_>,
|
2019-12-24 22:38:22 +00:00
|
|
|
module: ModuleCodegen<ModuleLlvm>,
|
|
|
|
config: &ModuleConfig,
|
|
|
|
) -> Result<CompiledModule, FatalError> {
|
2021-12-03 02:06:36 +00:00
|
|
|
let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &*module.name);
|
2014-12-09 18:44:51 +00:00
|
|
|
{
|
2018-08-20 15:13:01 +00:00
|
|
|
let llmod = module.module_llvm.llmod();
|
|
|
|
let llcx = &*module.module_llvm.llcx;
|
|
|
|
let tm = &*module.module_llvm.tm;
|
2018-06-27 14:57:25 +00:00
|
|
|
let module_name = module.name.clone();
|
|
|
|
let module_name = Some(&module_name[..]);
|
2023-12-17 23:15:45 +00:00
|
|
|
let _handlers =
|
|
|
|
DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::Codegen);
|
2017-10-20 01:44:33 +00:00
|
|
|
|
2018-06-27 14:57:25 +00:00
|
|
|
if cgcx.msvc_imps_needed {
|
|
|
|
create_msvc_imps(cgcx, llcx, llmod);
|
2017-10-20 01:44:33 +00:00
|
|
|
}
|
|
|
|
|
2018-06-27 14:57:25 +00:00
|
|
|
// A codegen-specific pass manager is used to generate object
|
|
|
|
// files for an LLVM module.
|
|
|
|
//
|
|
|
|
// Apparently each of these pass managers is a one-shot kind of
|
|
|
|
// thing, so we create a new one for each type of output. The
|
|
|
|
// pass manager passed to the closure should be ensured to not
|
|
|
|
// escape the closure itself, and the manager should only be
|
|
|
|
// used once.
|
2019-12-24 22:38:22 +00:00
|
|
|
unsafe fn with_codegen<'ll, F, R>(
|
|
|
|
tm: &'ll llvm::TargetMachine,
|
|
|
|
llmod: &'ll llvm::Module,
|
2024-01-12 10:23:04 +00:00
|
|
|
no_builtins: bool,
|
2019-12-24 22:38:22 +00:00
|
|
|
f: F,
|
|
|
|
) -> R
|
|
|
|
where
|
|
|
|
F: FnOnce(&'ll mut PassManager<'ll>) -> R,
|
2018-06-27 14:57:25 +00:00
|
|
|
{
|
2024-07-14 18:27:57 +00:00
|
|
|
unsafe {
|
|
|
|
let cpm = llvm::LLVMCreatePassManager();
|
|
|
|
llvm::LLVMAddAnalysisPasses(tm, cpm);
|
|
|
|
llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
|
|
|
|
f(cpm)
|
|
|
|
}
|
2018-06-27 14:57:25 +00:00
|
|
|
}
|
|
|
|
|
2020-03-20 01:09:24 +00:00
|
|
|
// Two things to note:
|
|
|
|
// - If object files are just LLVM bitcode we write bitcode, copy it to
|
|
|
|
// the .o file, and delete the bitcode if it wasn't otherwise
|
|
|
|
// requested.
|
|
|
|
// - If we don't have the integrated assembler then we need to emit
|
|
|
|
// asm from LLVM and use `gcc` to create the object file.
|
2018-06-27 14:57:25 +00:00
|
|
|
|
|
|
|
let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
|
2024-05-23 19:07:43 +00:00
|
|
|
let bc_summary_out =
|
2024-01-19 19:42:43 +00:00
|
|
|
cgcx.output_filenames.temp_path(OutputType::ThinLinkBitcode, module_name);
|
2018-06-27 14:57:25 +00:00
|
|
|
let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
|
|
|
|
|
2020-03-20 01:09:24 +00:00
|
|
|
if config.bitcode_needed() {
|
2020-02-07 14:01:23 +00:00
|
|
|
let _timer = cgcx
|
|
|
|
.prof
|
2021-12-03 02:06:36 +00:00
|
|
|
.generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &*module.name);
|
2024-05-23 19:07:43 +00:00
|
|
|
let thin = ThinBuffer::new(llmod, config.emit_thin_lto, config.emit_thin_lto_summary);
|
2018-11-01 20:06:50 +00:00
|
|
|
let data = thin.data();
|
2018-03-09 15:25:54 +00:00
|
|
|
|
2021-11-08 15:59:36 +00:00
|
|
|
if let Some(bitcode_filename) = bc_out.file_name() {
|
|
|
|
cgcx.prof.artifact_size(
|
|
|
|
"llvm_bitcode",
|
|
|
|
bitcode_filename.to_string_lossy(),
|
|
|
|
data.len() as u64,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-05-23 19:10:04 +00:00
|
|
|
if config.emit_thin_lto_summary
|
|
|
|
&& let Some(thin_link_bitcode_filename) = bc_summary_out.file_name()
|
|
|
|
{
|
2024-05-23 19:07:43 +00:00
|
|
|
let summary_data = thin.thin_link_data();
|
2024-01-19 19:42:43 +00:00
|
|
|
cgcx.prof.artifact_size(
|
|
|
|
"llvm_bitcode_summary",
|
|
|
|
thin_link_bitcode_filename.to_string_lossy(),
|
2024-05-23 19:07:43 +00:00
|
|
|
summary_data.len() as u64,
|
2024-01-19 19:42:43 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
let _timer = cgcx.prof.generic_activity_with_arg(
|
2024-05-23 19:07:43 +00:00
|
|
|
"LLVM_module_codegen_emit_bitcode_summary",
|
2024-01-19 19:42:43 +00:00
|
|
|
&*module.name,
|
|
|
|
);
|
2024-05-23 19:07:43 +00:00
|
|
|
if let Err(err) = fs::write(&bc_summary_out, summary_data) {
|
|
|
|
dcx.emit_err(WriteBytecode { path: &bc_summary_out, err });
|
2024-01-19 19:42:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Introduce `EmitObj`.
Currently, there are three fields in `ModuleConfig` that dictate
how object files are emitted: `emit_obj`, `obj_is_bitcode`, and
`embed_bitcode`.
Some of the combinations of these fields are nonsensical, in particular
having both `obj_is_bitcode` and `embed_bitcode` true at the same time.
Also, currently:
- we needlessly emit and then delete a bytecode file if `obj_is_bitcode`
is true but `emit_obj` is false;
- we needlessly embed bitcode in the LLVM module if `embed_bitcode` is
true and `emit_obj` is false.
This commit combines the three fields into one, with a new type
`EmitObj` (and the auxiliary `BitcodeSection`) which can encode five
different possibilities.
In the old code, `set_flags` would set `obj_is_bitcode` and
`embed_bitcode` on all three of the configs (`modules`, `allocator`,
`metadata`) if the relevant other conditions were met, even if no object
code needed to be emitted for one or more of them. Whereas
`start_async_codegen` would set `emit_obj`, but only for those configs
that need it.
In the new code, `start_async_codegen` does all the work of setting
`emit_obj`, and it only does that for the configs that need it.
`set_flags` no longer sets anything related to object file emission.
2020-03-24 01:24:52 +00:00
|
|
|
if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
|
2021-12-03 02:06:36 +00:00
|
|
|
let _timer = cgcx
|
|
|
|
.prof
|
|
|
|
.generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
|
2022-08-19 13:48:15 +00:00
|
|
|
if let Err(err) = fs::write(&bc_out, data) {
|
2023-12-17 23:15:45 +00:00
|
|
|
dcx.emit_err(WriteBytecode { path: &bc_out, err });
|
2018-06-27 14:57:25 +00:00
|
|
|
}
|
2017-10-20 01:44:33 +00:00
|
|
|
}
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
Introduce `EmitObj`.
Currently, there are three fields in `ModuleConfig` that dictate
how object files are emitted: `emit_obj`, `obj_is_bitcode`, and
`embed_bitcode`.
Some of the combinations of these fields are nonsensical, in particular
having both `obj_is_bitcode` and `embed_bitcode` true at the same time.
Also, currently:
- we needlessly emit and then delete a bytecode file if `obj_is_bitcode`
is true but `emit_obj` is false;
- we needlessly embed bitcode in the LLVM module if `embed_bitcode` is
true and `emit_obj` is false.
This commit combines the three fields into one, with a new type
`EmitObj` (and the auxiliary `BitcodeSection`) which can encode five
different possibilities.
In the old code, `set_flags` would set `obj_is_bitcode` and
`embed_bitcode` on all three of the configs (`modules`, `allocator`,
`metadata`) if the relevant other conditions were met, even if no object
code needed to be emitted for one or more of them. Whereas
`start_async_codegen` would set `emit_obj`, but only for those configs
that need it.
In the new code, `start_async_codegen` does all the work of setting
`emit_obj`, and it only does that for the configs that need it.
`set_flags` no longer sets anything related to object file emission.
2020-03-24 01:24:52 +00:00
|
|
|
if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
|
2021-12-03 02:06:36 +00:00
|
|
|
let _timer = cgcx
|
|
|
|
.prof
|
|
|
|
.generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name);
|
2024-07-14 18:27:57 +00:00
|
|
|
unsafe {
|
|
|
|
embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
|
|
|
|
}
|
2018-06-27 14:57:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-20 01:46:27 +00:00
|
|
|
if config.emit_ir {
|
2021-12-03 02:06:36 +00:00
|
|
|
let _timer =
|
|
|
|
cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &*module.name);
|
2020-03-20 01:46:27 +00:00
|
|
|
let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
|
|
|
|
let out_c = path_to_c_string(&out);
|
|
|
|
|
|
|
|
extern "C" fn demangle_callback(
|
|
|
|
input_ptr: *const c_char,
|
|
|
|
input_len: size_t,
|
|
|
|
output_ptr: *mut c_char,
|
|
|
|
output_len: size_t,
|
|
|
|
) -> size_t {
|
|
|
|
let input =
|
|
|
|
unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
|
|
|
|
|
2022-02-18 23:48:49 +00:00
|
|
|
let Ok(input) = str::from_utf8(input) else { return 0 };
|
2020-03-20 01:46:27 +00:00
|
|
|
|
|
|
|
let output = unsafe {
|
|
|
|
slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
|
|
|
|
};
|
|
|
|
let mut cursor = io::Cursor::new(output);
|
|
|
|
|
2022-02-18 23:48:49 +00:00
|
|
|
let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
|
2020-03-20 01:46:27 +00:00
|
|
|
|
2023-07-25 21:04:01 +00:00
|
|
|
if write!(cursor, "{demangled:#}").is_err() {
|
2020-03-20 01:46:27 +00:00
|
|
|
// Possible only if provided buffer is not big enough
|
|
|
|
return 0;
|
2017-06-29 14:52:43 +00:00
|
|
|
}
|
|
|
|
|
2020-03-20 01:46:27 +00:00
|
|
|
cursor.position() as size_t
|
2020-01-01 01:24:05 +00:00
|
|
|
}
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
2024-07-14 18:27:57 +00:00
|
|
|
let result =
|
|
|
|
unsafe { llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback) };
|
2021-11-08 15:59:36 +00:00
|
|
|
|
|
|
|
if result == llvm::LLVMRustResult::Success {
|
|
|
|
record_artifact_size(&cgcx.prof, "llvm_ir", &out);
|
|
|
|
}
|
|
|
|
|
2023-12-17 23:15:45 +00:00
|
|
|
result.into_result().map_err(|()| llvm_err(dcx, LlvmError::WriteIr { path: &out }))?;
|
2020-03-20 01:46:27 +00:00
|
|
|
}
|
2020-01-01 01:24:05 +00:00
|
|
|
|
2020-03-24 03:06:47 +00:00
|
|
|
if config.emit_asm {
|
2021-12-03 02:06:36 +00:00
|
|
|
let _timer =
|
|
|
|
cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &*module.name);
|
2020-03-20 01:46:27 +00:00
|
|
|
let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
|
|
|
|
|
2020-03-24 03:06:47 +00:00
|
|
|
// We can't use the same module for asm and object code output,
|
|
|
|
// because that triggers various errors like invalid IR or broken
|
|
|
|
// binaries. So we must clone the module to produce the asm output
|
|
|
|
// if we are also producing object code.
|
|
|
|
let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
|
2024-07-14 18:27:57 +00:00
|
|
|
unsafe { llvm::LLVMCloneModule(llmod) }
|
2020-03-24 03:06:47 +00:00
|
|
|
} else {
|
|
|
|
llmod
|
|
|
|
};
|
2024-07-14 18:27:57 +00:00
|
|
|
unsafe {
|
|
|
|
with_codegen(tm, llmod, config.no_builtins, |cpm| {
|
|
|
|
write_output_file(
|
|
|
|
dcx,
|
|
|
|
tm,
|
|
|
|
cpm,
|
|
|
|
llmod,
|
|
|
|
&path,
|
|
|
|
None,
|
|
|
|
llvm::FileType::AssemblyFile,
|
|
|
|
&cgcx.prof,
|
|
|
|
)
|
|
|
|
})?;
|
|
|
|
}
|
2020-03-20 01:46:27 +00:00
|
|
|
}
|
|
|
|
|
2020-03-26 02:53:03 +00:00
|
|
|
match config.emit_obj {
|
|
|
|
EmitObj::ObjectCode(_) => {
|
2020-03-24 03:06:47 +00:00
|
|
|
let _timer = cgcx
|
|
|
|
.prof
|
2021-12-03 02:06:36 +00:00
|
|
|
.generic_activity_with_arg("LLVM_module_codegen_emit_obj", &*module.name);
|
2020-09-23 16:33:54 +00:00
|
|
|
|
|
|
|
let dwo_out = cgcx.output_filenames.temp_path_dwo(module_name);
|
sess/cg: re-introduce split dwarf kind
In #79570, `-Z split-dwarf-kind={none,single,split}` was replaced by `-C
split-debuginfo={off,packed,unpacked}`. `-C split-debuginfo`'s packed
and unpacked aren't exact parallels to single and split, respectively.
On Unix, `-C split-debuginfo=packed` will put debuginfo into object
files and package debuginfo into a DWARF package file (`.dwp`) and
`-C split-debuginfo=unpacked` will put debuginfo into dwarf object files
and won't package it.
In the initial implementation of Split DWARF, split mode wrote sections
which did not require relocation into a DWARF object (`.dwo`) file which
was ignored by the linker and then packaged those DWARF objects into
DWARF packages (`.dwp`). In single mode, sections which did not require
relocation were written into object files but ignored by the linker and
were not packaged. However, both split and single modes could be
packaged or not, the primary difference in behaviour was where the
debuginfo sections that did not require link-time relocation were
written (in a DWARF object or the object file).
This commit re-introduces a `-Z split-dwarf-kind` flag, which can be
used to pick between split and single modes when `-C split-debuginfo` is
used to enable Split DWARF (either packed or unpacked).
Signed-off-by: David Wood <david.wood@huawei.com>
2021-10-08 16:10:17 +00:00
|
|
|
let dwo_out = match (cgcx.split_debuginfo, cgcx.split_dwarf_kind) {
|
|
|
|
// Don't change how DWARF is emitted when disabled.
|
|
|
|
(SplitDebuginfo::Off, _) => None,
|
|
|
|
// Don't provide a DWARF object path if split debuginfo is enabled but this is
|
|
|
|
// a platform that doesn't support Split DWARF.
|
|
|
|
_ if !cgcx.target_can_use_split_dwarf => None,
|
|
|
|
// Don't provide a DWARF object path in single mode, sections will be written
|
|
|
|
// into the object as normal but ignored by linker.
|
|
|
|
(_, SplitDwarfKind::Single) => None,
|
|
|
|
// Emit (a subset of the) DWARF into a separate dwarf object file in split
|
|
|
|
// mode.
|
|
|
|
(_, SplitDwarfKind::Split) => Some(dwo_out.as_path()),
|
2020-09-23 16:33:54 +00:00
|
|
|
};
|
|
|
|
|
2024-07-14 18:27:57 +00:00
|
|
|
unsafe {
|
|
|
|
with_codegen(tm, llmod, config.no_builtins, |cpm| {
|
|
|
|
write_output_file(
|
|
|
|
dcx,
|
|
|
|
tm,
|
|
|
|
cpm,
|
|
|
|
llmod,
|
|
|
|
&obj_out,
|
|
|
|
dwo_out,
|
|
|
|
llvm::FileType::ObjectFile,
|
|
|
|
&cgcx.prof,
|
|
|
|
)
|
|
|
|
})?;
|
|
|
|
}
|
2020-01-01 01:24:05 +00:00
|
|
|
}
|
2015-11-27 19:44:33 +00:00
|
|
|
|
2020-03-26 02:53:03 +00:00
|
|
|
EmitObj::Bitcode => {
|
|
|
|
debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
|
2022-08-19 13:48:15 +00:00
|
|
|
if let Err(err) = link_or_copy(&bc_out, &obj_out) {
|
2023-12-17 23:15:45 +00:00
|
|
|
dcx.emit_err(CopyBitcode { err });
|
2020-03-26 02:53:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if !config.emit_bc {
|
|
|
|
debug!("removing_bitcode {:?}", bc_out);
|
2023-12-17 23:15:45 +00:00
|
|
|
ensure_removed(dcx, &bc_out);
|
2020-03-20 22:15:07 +00:00
|
|
|
}
|
2018-06-27 14:57:25 +00:00
|
|
|
}
|
2020-03-26 02:53:03 +00:00
|
|
|
|
|
|
|
EmitObj::None => {}
|
2015-11-27 19:44:33 +00:00
|
|
|
}
|
|
|
|
|
2022-11-03 14:34:24 +00:00
|
|
|
record_llvm_cgu_instructions_stats(&cgcx.prof, llmod);
|
2018-06-27 14:57:25 +00:00
|
|
|
}
|
2020-03-24 03:06:47 +00:00
|
|
|
|
2022-11-07 15:15:24 +00:00
|
|
|
// `.dwo` files are only emitted if:
|
|
|
|
//
|
|
|
|
// - Object files are being emitted (i.e. bitcode only or metadata only compilations will not
|
|
|
|
// produce dwarf objects, even if otherwise enabled)
|
|
|
|
// - Target supports Split DWARF
|
|
|
|
// - Split debuginfo is enabled
|
|
|
|
// - Split DWARF kind is `split` (i.e. debuginfo is split into `.dwo` files, not different
|
|
|
|
// sections in the `.o` files).
|
|
|
|
let dwarf_object_emitted = matches!(config.emit_obj, EmitObj::ObjectCode(_))
|
|
|
|
&& cgcx.target_can_use_split_dwarf
|
|
|
|
&& cgcx.split_debuginfo != SplitDebuginfo::Off
|
|
|
|
&& cgcx.split_dwarf_kind == SplitDwarfKind::Split;
|
2019-12-24 22:38:22 +00:00
|
|
|
Ok(module.into_compiled_module(
|
Introduce `EmitObj`.
Currently, there are three fields in `ModuleConfig` that dictate
how object files are emitted: `emit_obj`, `obj_is_bitcode`, and
`embed_bitcode`.
Some of the combinations of these fields are nonsensical, in particular
having both `obj_is_bitcode` and `embed_bitcode` true at the same time.
Also, currently:
- we needlessly emit and then delete a bytecode file if `obj_is_bitcode`
is true but `emit_obj` is false;
- we needlessly embed bitcode in the LLVM module if `embed_bitcode` is
true and `emit_obj` is false.
This commit combines the three fields into one, with a new type
`EmitObj` (and the auxiliary `BitcodeSection`) which can encode five
different possibilities.
In the old code, `set_flags` would set `obj_is_bitcode` and
`embed_bitcode` on all three of the configs (`modules`, `allocator`,
`metadata`) if the relevant other conditions were met, even if no object
code needed to be emitted for one or more of them. Whereas
`start_async_codegen` would set `emit_obj`, but only for those configs
that need it.
In the new code, `start_async_codegen` does all the work of setting
`emit_obj`, and it only does that for the configs that need it.
`set_flags` no longer sets anything related to object file emission.
2020-03-24 01:24:52 +00:00
|
|
|
config.emit_obj != EmitObj::None,
|
2022-11-07 15:15:24 +00:00
|
|
|
dwarf_object_emitted,
|
2019-12-24 22:38:22 +00:00
|
|
|
config.emit_bc,
|
2024-04-06 13:07:54 +00:00
|
|
|
config.emit_asm,
|
|
|
|
config.emit_ir,
|
2019-12-24 22:38:22 +00:00
|
|
|
&cgcx.output_filenames,
|
|
|
|
))
|
2016-06-30 20:32:13 +00:00
|
|
|
}
|
|
|
|
|
2021-12-07 16:28:16 +00:00
|
|
|
fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
|
2023-07-25 21:04:01 +00:00
|
|
|
let mut asm = format!(".section {section_name},\"{section_flags}\"\n").into_bytes();
|
2021-12-07 16:28:16 +00:00
|
|
|
asm.extend_from_slice(b".ascii \"");
|
|
|
|
asm.reserve(data.len());
|
|
|
|
for &byte in data {
|
|
|
|
if byte == b'\\' || byte == b'"' {
|
|
|
|
asm.push(b'\\');
|
|
|
|
asm.push(byte);
|
|
|
|
} else if byte < 0x20 || byte >= 0x80 {
|
|
|
|
// Avoid non UTF-8 inline assembly. Use octal escape sequence, because it is fixed
|
|
|
|
// width, while hex escapes will consume following characters.
|
|
|
|
asm.push(b'\\');
|
|
|
|
asm.push(b'0' + ((byte >> 6) & 0x7));
|
|
|
|
asm.push(b'0' + ((byte >> 3) & 0x7));
|
|
|
|
asm.push(b'0' + ((byte >> 0) & 0x7));
|
|
|
|
} else {
|
|
|
|
asm.push(byte);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
asm.extend_from_slice(b"\"\n");
|
|
|
|
asm
|
|
|
|
}
|
|
|
|
|
2023-09-07 13:48:50 +00:00
|
|
|
fn target_is_apple(cgcx: &CodegenContext<LlvmCodegenBackend>) -> bool {
|
2024-09-17 06:18:32 +00:00
|
|
|
let triple = cgcx.opts.target_triple.triple();
|
|
|
|
triple.contains("-ios")
|
|
|
|
|| triple.contains("-darwin")
|
|
|
|
|| triple.contains("-tvos")
|
|
|
|
|| triple.contains("-watchos")
|
|
|
|
|| triple.contains("-visionos")
|
2023-09-07 13:48:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn target_is_aix(cgcx: &CodegenContext<LlvmCodegenBackend>) -> bool {
|
|
|
|
cgcx.opts.target_triple.triple().contains("-aix")
|
|
|
|
}
|
|
|
|
|
2023-12-03 11:02:31 +00:00
|
|
|
//FIXME use c string literals here too
|
2023-09-07 13:48:50 +00:00
|
|
|
pub(crate) fn bitcode_section_name(cgcx: &CodegenContext<LlvmCodegenBackend>) -> &'static str {
|
|
|
|
if target_is_apple(cgcx) {
|
|
|
|
"__LLVM,__bitcode\0"
|
|
|
|
} else if target_is_aix(cgcx) {
|
|
|
|
".ipa\0"
|
|
|
|
} else {
|
|
|
|
".llvmbc\0"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-09 15:25:54 +00:00
|
|
|
/// Embed the bitcode of an LLVM module in the LLVM module itself.
|
|
|
|
///
|
|
|
|
/// This is done primarily for iOS where it appears to be standard to compile C
|
|
|
|
/// code at least with `-fembed-bitcode` which creates two sections in the
|
|
|
|
/// executable:
|
|
|
|
///
|
|
|
|
/// * __LLVM,__bitcode
|
|
|
|
/// * __LLVM,__cmdline
|
|
|
|
///
|
|
|
|
/// It appears *both* of these sections are necessary to get the linker to
|
2020-05-07 05:34:31 +00:00
|
|
|
/// recognize what's going on. A suitable cmdline value is taken from the
|
|
|
|
/// target spec.
|
2018-03-09 15:25:54 +00:00
|
|
|
///
|
|
|
|
/// Furthermore debug/O1 builds don't actually embed bitcode but rather just
|
|
|
|
/// embed an empty section.
|
|
|
|
///
|
|
|
|
/// Basically all of this is us attempting to follow in the footsteps of clang
|
|
|
|
/// on iOS. See #35968 for lots more info.
|
2019-12-24 22:38:22 +00:00
|
|
|
unsafe fn embed_bitcode(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
|
|
|
llcx: &llvm::Context,
|
|
|
|
llmod: &llvm::Module,
|
2020-05-07 05:34:31 +00:00
|
|
|
cmdline: &str,
|
2020-05-07 23:48:30 +00:00
|
|
|
bitcode: &[u8],
|
2019-12-24 22:38:22 +00:00
|
|
|
) {
|
2020-04-23 18:45:55 +00:00
|
|
|
// We're adding custom sections to the output object file, but we definitely
|
|
|
|
// do not want these custom sections to make their way into the final linked
|
|
|
|
// executable. The purpose of these custom sections is for tooling
|
|
|
|
// surrounding object files to work with the LLVM IR, if necessary. For
|
|
|
|
// example rustc's own LTO will look for LLVM IR inside of the object file
|
|
|
|
// in these sections by default.
|
|
|
|
//
|
|
|
|
// To handle this is a bit different depending on the object file format
|
|
|
|
// used by the backend, broken down into a few different categories:
|
|
|
|
//
|
|
|
|
// * Mach-O - this is for macOS. Inspecting the source code for the native
|
|
|
|
// linker here shows that the `.llvmbc` and `.llvmcmd` sections are
|
|
|
|
// automatically skipped by the linker. In that case there's nothing extra
|
|
|
|
// that we need to do here.
|
|
|
|
//
|
|
|
|
// * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
|
|
|
|
// `.llvmcmd` sections, so there's nothing extra we need to do.
|
|
|
|
//
|
|
|
|
// * COFF - if we don't do anything the linker will by default copy all
|
|
|
|
// these sections to the output artifact, not what we want! To subvert
|
|
|
|
// this we want to flag the sections we inserted here as
|
2021-12-07 16:28:16 +00:00
|
|
|
// `IMAGE_SCN_LNK_REMOVE`.
|
2020-04-23 18:45:55 +00:00
|
|
|
//
|
|
|
|
// * ELF - this is very similar to COFF above. One difference is that these
|
|
|
|
// sections are removed from the output linked artifact when
|
|
|
|
// `--gc-sections` is passed, which we pass by default. If that flag isn't
|
|
|
|
// passed though then these sections will show up in the final output.
|
|
|
|
// Additionally the flag that we need to set here is `SHF_EXCLUDE`.
|
2021-12-07 16:28:16 +00:00
|
|
|
//
|
2023-03-23 09:27:53 +00:00
|
|
|
// * XCOFF - AIX linker ignores content in .ipa and .info if no auxiliary
|
|
|
|
// symbol associated with these sections.
|
|
|
|
//
|
2021-12-07 16:28:16 +00:00
|
|
|
// Unfortunately, LLVM provides no way to set custom section flags. For ELF
|
|
|
|
// and COFF we emit the sections using module level inline assembly for that
|
|
|
|
// reason (see issue #90326 for historical background).
|
2023-09-07 13:48:50 +00:00
|
|
|
let is_aix = target_is_aix(cgcx);
|
|
|
|
let is_apple = target_is_apple(cgcx);
|
2024-07-14 18:27:57 +00:00
|
|
|
unsafe {
|
|
|
|
if is_apple || is_aix || cgcx.opts.target_triple.triple().starts_with("wasm") {
|
|
|
|
// We don't need custom section flags, create LLVM globals.
|
|
|
|
let llconst = common::bytes_in_context(llcx, bitcode);
|
|
|
|
let llglobal = llvm::LLVMAddGlobal(
|
|
|
|
llmod,
|
|
|
|
common::val_ty(llconst),
|
2024-08-20 21:04:48 +00:00
|
|
|
c"rustc.embedded.module".as_ptr(),
|
2024-07-14 18:27:57 +00:00
|
|
|
);
|
|
|
|
llvm::LLVMSetInitializer(llglobal, llconst);
|
|
|
|
|
|
|
|
let section = bitcode_section_name(cgcx);
|
|
|
|
llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
|
|
|
|
llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
|
|
|
|
llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
|
|
|
|
|
|
|
|
let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
|
|
|
|
let llglobal = llvm::LLVMAddGlobal(
|
|
|
|
llmod,
|
|
|
|
common::val_ty(llconst),
|
2024-08-20 21:04:48 +00:00
|
|
|
c"rustc.embedded.cmdline".as_ptr(),
|
2024-07-14 18:27:57 +00:00
|
|
|
);
|
|
|
|
llvm::LLVMSetInitializer(llglobal, llconst);
|
|
|
|
let section = if is_apple {
|
|
|
|
c"__LLVM,__cmdline"
|
|
|
|
} else if is_aix {
|
|
|
|
c".info"
|
|
|
|
} else {
|
|
|
|
c".llvmcmd"
|
|
|
|
};
|
2024-08-20 21:04:48 +00:00
|
|
|
llvm::LLVMSetSection(llglobal, section.as_ptr());
|
2024-07-14 18:27:57 +00:00
|
|
|
llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
|
2023-03-23 09:27:53 +00:00
|
|
|
} else {
|
2024-07-14 18:27:57 +00:00
|
|
|
// We need custom section flags, so emit module-level inline assembly.
|
|
|
|
let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
|
|
|
|
let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
|
|
|
|
llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
|
|
|
|
let asm = create_section_with_flags_asm(".llvmcmd", section_flags, cmdline.as_bytes());
|
|
|
|
llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
|
|
|
|
}
|
2020-04-23 18:45:55 +00:00
|
|
|
}
|
2018-03-09 15:25:54 +00:00
|
|
|
}
|
|
|
|
|
2017-10-17 20:08:13 +00:00
|
|
|
// Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
|
|
|
|
// This is required to satisfy `dllimport` references to static data in .rlibs
|
2022-11-16 20:34:16 +00:00
|
|
|
// when using MSVC linker. We do this only for data, as linker can fix up
|
2017-10-17 20:08:13 +00:00
|
|
|
// code references on its own.
|
|
|
|
// See #26591, #27438
|
2018-10-23 15:01:35 +00:00
|
|
|
fn create_msvc_imps(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
|
|
|
llcx: &llvm::Context,
|
2019-12-24 22:38:22 +00:00
|
|
|
llmod: &llvm::Module,
|
2018-10-23 15:01:35 +00:00
|
|
|
) {
|
2017-10-17 20:08:13 +00:00
|
|
|
if !cgcx.msvc_imps_needed {
|
2019-12-24 22:38:22 +00:00
|
|
|
return;
|
2017-10-17 20:08:13 +00:00
|
|
|
}
|
|
|
|
// The x86 ABI seems to require that leading underscores are added to symbol
|
2019-05-16 22:05:56 +00:00
|
|
|
// names, so we need an extra underscore on x86. There's also a leading
|
2018-11-27 02:59:49 +00:00
|
|
|
// '\x01' here which disables LLVM's symbol mangling (e.g., no extra
|
2017-10-17 20:08:13 +00:00
|
|
|
// underscores added in front).
|
2019-12-24 22:38:22 +00:00
|
|
|
let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
|
2019-04-09 12:47:00 +00:00
|
|
|
|
2017-10-17 20:08:13 +00:00
|
|
|
unsafe {
|
2022-12-06 05:07:28 +00:00
|
|
|
let ptr_ty = Type::ptr_llcx(llcx);
|
2017-10-17 20:08:13 +00:00
|
|
|
let globals = base::iter_globals(llmod)
|
|
|
|
.filter(|&val| {
|
2019-12-24 22:38:22 +00:00
|
|
|
llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
|
|
|
|
&& llvm::LLVMIsDeclaration(val) == 0
|
2017-10-17 20:08:13 +00:00
|
|
|
})
|
2019-04-09 12:47:00 +00:00
|
|
|
.filter_map(|val| {
|
|
|
|
// Exclude some symbols that we know are not Rust symbols.
|
2019-12-04 20:00:28 +00:00
|
|
|
let name = llvm::get_value_name(val);
|
2019-12-24 22:38:22 +00:00
|
|
|
if ignored(name) { None } else { Some((val, name)) }
|
2019-04-09 12:47:00 +00:00
|
|
|
})
|
|
|
|
.map(move |(val, name)| {
|
2017-10-17 20:08:13 +00:00
|
|
|
let mut imp_name = prefix.as_bytes().to_vec();
|
2019-12-04 20:00:28 +00:00
|
|
|
imp_name.extend(name);
|
2017-10-17 20:08:13 +00:00
|
|
|
let imp_name = CString::new(imp_name).unwrap();
|
|
|
|
(imp_name, val)
|
|
|
|
})
|
|
|
|
.collect::<Vec<_>>();
|
2019-04-09 12:47:00 +00:00
|
|
|
|
2017-10-17 20:08:13 +00:00
|
|
|
for (imp_name, val) in globals {
|
2024-08-20 21:04:48 +00:00
|
|
|
let imp = llvm::LLVMAddGlobal(llmod, ptr_ty, imp_name.as_ptr());
|
2022-12-06 05:07:28 +00:00
|
|
|
llvm::LLVMSetInitializer(imp, val);
|
2017-10-17 20:08:13 +00:00
|
|
|
llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
|
|
|
|
}
|
|
|
|
}
|
2019-04-09 12:47:00 +00:00
|
|
|
|
|
|
|
// Use this function to exclude certain symbols from `__imp` generation.
|
|
|
|
fn ignored(symbol_name: &[u8]) -> bool {
|
|
|
|
// These are symbols generated by LLVM's profiling instrumentation
|
|
|
|
symbol_name.starts_with(b"__llvm_profile_")
|
|
|
|
}
|
2017-10-17 20:08:13 +00:00
|
|
|
}
|
2021-11-08 15:59:36 +00:00
|
|
|
|
|
|
|
fn record_artifact_size(
|
|
|
|
self_profiler_ref: &SelfProfilerRef,
|
|
|
|
artifact_kind: &'static str,
|
|
|
|
path: &Path,
|
|
|
|
) {
|
|
|
|
// Don't stat the file if we are not going to record its size.
|
|
|
|
if !self_profiler_ref.enabled() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(artifact_name) = path.file_name() {
|
|
|
|
let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
|
|
|
|
self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);
|
|
|
|
}
|
|
|
|
}
|
2022-11-03 14:34:24 +00:00
|
|
|
|
|
|
|
fn record_llvm_cgu_instructions_stats(prof: &SelfProfilerRef, llmod: &llvm::Module) {
|
|
|
|
if !prof.enabled() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let raw_stats =
|
2023-11-21 19:07:32 +00:00
|
|
|
llvm::build_string(|s| unsafe { llvm::LLVMRustModuleInstructionStats(llmod, s) })
|
2022-11-03 14:34:24 +00:00
|
|
|
.expect("cannot get module instruction stats");
|
|
|
|
|
|
|
|
#[derive(serde::Deserialize)]
|
|
|
|
struct InstructionsStats {
|
|
|
|
module: String,
|
|
|
|
total: u64,
|
|
|
|
}
|
|
|
|
|
|
|
|
let InstructionsStats { module, total } =
|
|
|
|
serde_json::from_str(&raw_stats).expect("cannot parse llvm cgu instructions stats");
|
|
|
|
prof.artifact_size("cgu_instructions", module, total);
|
|
|
|
}
|