1use std::ffi::{CStr, CString};
2use std::io::{self, Write};
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::{fs, slice, str};
6
7use libc::{c_char, c_int, c_void, size_t};
8use rustc_codegen_ssa::back::link::ensure_removed;
9use rustc_codegen_ssa::back::versioned_llvm_target;
10use rustc_codegen_ssa::back::write::{
11 BitcodeSection, CodegenContext, EmitObj, InlineAsmError, ModuleConfig, SharedEmitter,
12 TargetMachineFactoryConfig, TargetMachineFactoryFn,
13};
14use rustc_codegen_ssa::base::wants_wasm_eh;
15use rustc_codegen_ssa::common::TypeKind;
16use rustc_codegen_ssa::traits::*;
17use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, ModuleKind};
18use rustc_data_structures::profiling::SelfProfilerRef;
19use rustc_data_structures::small_c_str::SmallCStr;
20use rustc_errors::{DiagCtxt, DiagCtxtHandle, Level};
21use rustc_fs_util::{link_or_copy, path_to_c_string};
22use rustc_middle::ty::TyCtxt;
23use rustc_session::Session;
24use rustc_session::config::{self, Lto, OutputType, Passes, SplitDwarfKind, SwitchWithOptPath};
25use rustc_span::{BytePos, InnerSpan, Pos, RemapPathScopeComponents, SpanData, SyntaxContext};
26use rustc_target::spec::{CodeModel, FloatAbi, RelocModel, SanitizerSet, SplitDebuginfo, TlsModel};
27use tracing::{debug, trace};
28
29use crate::back::lto::{Buffer, ModuleBuffer};
30use crate::back::owned_target_machine::OwnedTargetMachine;
31use crate::back::profiling::{
32 LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback,
33};
34use crate::builder::SBuilder;
35use crate::builder::gpu_offload::scalar_width;
36use crate::common::AsCCharPtr;
37use crate::context::SimpleCx;
38use crate::diagnostics::{
39 CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, ParseTargetMachineConfig,
40 UnsupportedCompression, WithLlvmError, WriteBytecode,
41};
42use crate::llvm::diagnostic::OptimizationDiagnosticKind::*;
43use crate::llvm::{self, DiagnosticInfo};
44use crate::type_::llvm_type_ptr;
45use crate::{LlvmCodegenBackend, ModuleLlvm, attributes, base, common, llvm_util};
46
47pub(crate) fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> ! {
48 match llvm::last_error() {
49 Some(llvm_err) => dcx.emit_fatal(WithLlvmError(err, llvm_err)),
50 None => dcx.emit_fatal(err),
51 }
52}
53
54fn write_output_file<'ll>(
55 dcx: DiagCtxtHandle<'_>,
56 target: &'ll llvm::TargetMachine,
57 no_builtins: bool,
58 m: &'ll llvm::Module,
59 output: &Path,
60 dwo_output: Option<&Path>,
61 file_type: llvm::FileType,
62 self_profiler_ref: &SelfProfilerRef,
63 verify_llvm_ir: bool,
64) {
65 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/fd8e211ae301c84a86d13cf52a6d3ce08c589e2e/compiler/rustc_codegen_llvm/src/back/write.rs:65",
"rustc_codegen_llvm::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/fd8e211ae301c84a86d13cf52a6d3ce08c589e2e/compiler/rustc_codegen_llvm/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(65u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("write_output_file output={0:?} dwo_output={1:?}",
output, dwo_output) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
66 let output_c = path_to_c_string(output);
67 let dwo_output_c;
68 let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
69 dwo_output_c = path_to_c_string(dwo_output);
70 dwo_output_c.as_ptr()
71 } else {
72 std::ptr::null()
73 };
74 let result = unsafe {
75 let pm = llvm::LLVMCreatePassManager();
76 llvm::LLVMAddAnalysisPasses(target, pm);
77 llvm::LLVMRustAddLibraryInfo(target, pm, m, no_builtins);
78 llvm::LLVMRustWriteOutputFile(
79 target,
80 pm,
81 m,
82 output_c.as_ptr(),
83 dwo_output_ptr,
84 file_type,
85 verify_llvm_ir,
86 )
87 };
88
89 if result == llvm::LLVMRustResult::Success {
91 let artifact_kind = match file_type {
92 llvm::FileType::ObjectFile => "object_file",
93 llvm::FileType::AssemblyFile => "assembly_file",
94 };
95 record_artifact_size(self_profiler_ref, artifact_kind, output);
96 if let Some(dwo_file) = dwo_output {
97 record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
98 }
99 }
100
101 result.into_result().unwrap_or_else(|()| llvm_err(dcx, LlvmError::WriteOutput { path: output }))
102}
103
104pub(crate) fn create_informational_target_machine(sess: &Session) -> OwnedTargetMachine {
105 let config = TargetMachineFactoryConfig { split_dwarf_file: None, output_obj_file: None };
106 target_machine_factory(sess, config::OptLevel::No)(sess.dcx(), config)
107}
108
109pub(crate) fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMachine {
110 let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
111 tcx.output_filenames(()).split_dwarf_path(
112 tcx.sess.split_debuginfo(),
113 tcx.sess.opts.unstable_opts.split_dwarf_kind,
114 mod_name,
115 )
116 } else {
117 None
118 };
119
120 let output_obj_file =
121 Some(tcx.output_filenames(()).temp_path_for_cgu(OutputType::Object, mod_name));
122 let config = TargetMachineFactoryConfig { split_dwarf_file, output_obj_file };
123
124 target_machine_factory(tcx.sess, tcx.backend_optimization_level(()))(tcx.dcx(), config)
125}
126
127fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
128 use self::config::OptLevel::*;
129 match cfg {
130 No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
131 Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
132 More => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
133 Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
134 Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
135 SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
136 }
137}
138
139fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
140 use config::OptLevel::*;
141 match cfg {
142 No => llvm::PassBuilderOptLevel::O0,
143 Less => llvm::PassBuilderOptLevel::O1,
144 More => llvm::PassBuilderOptLevel::O2,
145 Aggressive => llvm::PassBuilderOptLevel::O3,
146 Size => llvm::PassBuilderOptLevel::Os,
147 SizeMin => llvm::PassBuilderOptLevel::Oz,
148 }
149}
150
151fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
152 match relocation_model {
153 RelocModel::Static => llvm::RelocModel::Static,
154 RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
157 RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
158 RelocModel::Ropi => llvm::RelocModel::ROPI,
159 RelocModel::Rwpi => llvm::RelocModel::RWPI,
160 RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
161 }
162}
163
164pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
165 match code_model {
166 Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
167 Some(CodeModel::Small) => llvm::CodeModel::Small,
168 Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
169 Some(CodeModel::Medium) => llvm::CodeModel::Medium,
170 Some(CodeModel::Large) => llvm::CodeModel::Large,
171 None => llvm::CodeModel::None,
172 }
173}
174
175fn to_llvm_float_abi(float_abi: Option<FloatAbi>) -> llvm::FloatAbi {
176 match float_abi {
177 None => llvm::FloatAbi::Default,
178 Some(FloatAbi::Soft) => llvm::FloatAbi::Soft,
179 Some(FloatAbi::Hard) => llvm::FloatAbi::Hard,
180 }
181}
182
183pub(crate) fn target_machine_factory(
184 sess: &Session,
185 optlvl: config::OptLevel,
186) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
187 let _prof_timer = sess.prof.generic_activity("target_machine_factory");
189
190 let reloc_model = to_llvm_relocation_model(sess.relocation_model());
191
192 let (opt_level, _) = to_llvm_opt_settings(optlvl);
193 let float_abi = to_llvm_float_abi(sess.target.llvm_floatabi);
194
195 let ffunction_sections =
196 sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
197 let fdata_sections = ffunction_sections;
198 let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
199
200 let code_model = to_llvm_code_model(sess.code_model());
201
202 let singlethread = sess.target.singlethread(&sess.internal_target_features);
203
204 let triple = SmallCStr::new(&versioned_llvm_target(sess));
205 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
206 let features = CString::new(sess.global_backend_features.join(",")).unwrap();
207 let abi = SmallCStr::new(sess.target.llvm_abiname.desc());
208 let trap_unreachable =
209 sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
210 let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
211
212 let verbose_asm = sess.opts.unstable_opts.verbose_asm;
213 let relax_elf_relocations =
214 sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
215
216 let use_init_array =
217 !sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
218
219 let path_mapping = sess.source_map().path_mapping().clone();
220 let working_dir = sess.source_map().working_dir().clone();
221
222 let use_emulated_tls = #[allow(non_exhaustive_omitted_patterns)] match sess.tls_model() {
TlsModel::Emulated => true,
_ => false,
}matches!(sess.tls_model(), TlsModel::Emulated);
223
224 let debuginfo_compression = match sess.opts.unstable_opts.debuginfo_compression {
225 config::DebugInfoCompression::None => llvm::CompressionKind::None,
226 config::DebugInfoCompression::Zlib => {
227 if llvm::LLVMRustLLVMHasZlibCompression() {
228 llvm::CompressionKind::Zlib
229 } else {
230 sess.dcx().emit_warn(UnsupportedCompression { algorithm: "zlib" });
231 llvm::CompressionKind::None
232 }
233 }
234 config::DebugInfoCompression::Zstd => {
235 if llvm::LLVMRustLLVMHasZstdCompression() {
236 llvm::CompressionKind::Zstd
237 } else {
238 sess.dcx().emit_warn(UnsupportedCompression { algorithm: "zstd" });
239 llvm::CompressionKind::None
240 }
241 }
242 };
243
244 let use_wasm_eh = wants_wasm_eh(&sess.target);
245
246 let large_data_threshold = sess.opts.unstable_opts.large_data_threshold.unwrap_or(0);
247
248 let prof = SelfProfilerRef::clone(&sess.prof);
249 Arc::new(move |dcx: DiagCtxtHandle<'_>, config: TargetMachineFactoryConfig| {
250 let _prof_timer = prof.generic_activity("target_machine_factory_inner");
252
253 let path_to_cstring_helper = |path: Option<PathBuf>| -> CString {
254 let path = path.unwrap_or_default();
255 let path = path_mapping
256 .to_real_filename(&working_dir, path)
257 .path(RemapPathScopeComponents::DEBUGINFO)
258 .to_string_lossy()
259 .into_owned();
260 CString::new(path).unwrap()
261 };
262
263 let split_dwarf_file = path_to_cstring_helper(config.split_dwarf_file);
264 let output_obj_file = path_to_cstring_helper(config.output_obj_file);
265
266 OwnedTargetMachine::new(
267 &triple,
268 &cpu,
269 &features,
270 &abi,
271 code_model,
272 reloc_model,
273 opt_level,
274 float_abi,
275 ffunction_sections,
276 fdata_sections,
277 funique_section_names,
278 trap_unreachable,
279 singlethread,
280 verbose_asm,
281 emit_stack_size_section,
282 relax_elf_relocations,
283 use_init_array,
284 &split_dwarf_file,
285 &output_obj_file,
286 debuginfo_compression,
287 use_emulated_tls,
288 use_wasm_eh,
289 large_data_threshold,
290 )
291 .unwrap_or_else(|err| dcx.emit_fatal(ParseTargetMachineConfig(err)))
292 })
293}
294
295pub(crate) fn save_temp_bitcode(
296 cgcx: &CodegenContext,
297 module: &ModuleCodegen<ModuleLlvm>,
298 name: &str,
299) {
300 if !cgcx.save_temps {
301 return;
302 }
303 let ext = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.bc", name))
})format!("{name}.bc");
304 let path = cgcx.output_filenames.temp_path_ext_for_cgu(&ext, &module.name);
305 write_bitcode_to_file(&module.module_llvm, &path)
306}
307
308fn write_bitcode_to_file(module: &ModuleLlvm, path: &Path) {
309 unsafe {
310 let path = path_to_c_string(&path);
311 let llmod = module.llmod();
312 llvm::LLVMWriteBitcodeToFile(llmod, path.as_ptr());
313 }
314}
315
316pub(crate) enum CodegenDiagnosticsStage {
318 Opt,
320 LTO,
322 Codegen,
324}
325
326pub(crate) struct DiagnosticHandlers<'a> {
327 data: *mut (&'a CodegenContext, &'a SharedEmitter),
328 llcx: &'a llvm::Context,
329 old_handler: Option<&'a llvm::DiagnosticHandler>,
330}
331
332impl<'a> DiagnosticHandlers<'a> {
333 pub(crate) fn new(
334 cgcx: &'a CodegenContext,
335 shared_emitter: &'a SharedEmitter,
336 llcx: &'a llvm::Context,
337 module: &ModuleCodegen<ModuleLlvm>,
338 stage: CodegenDiagnosticsStage,
339 ) -> Self {
340 let remark_passes_all: bool;
341 let remark_passes: Vec<CString>;
342 match &cgcx.remark {
343 Passes::All => {
344 remark_passes_all = true;
345 remark_passes = Vec::new();
346 }
347 Passes::Some(passes) => {
348 remark_passes_all = false;
349 remark_passes =
350 passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
351 }
352 };
353 let remark_passes: Vec<*const c_char> =
354 remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
355 let remark_file = cgcx
356 .remark_dir
357 .as_ref()
358 .map(|dir| {
360 let stage_suffix = match stage {
361 CodegenDiagnosticsStage::Codegen => "codegen",
362 CodegenDiagnosticsStage::Opt => "opt",
363 CodegenDiagnosticsStage::LTO => "lto",
364 };
365 dir.join(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}.opt.yaml", module.name,
stage_suffix))
})format!("{}.{stage_suffix}.opt.yaml", module.name))
366 })
367 .and_then(|dir| dir.to_str().and_then(|p| CString::new(p).ok()));
368
369 let pgo_available = cgcx.module_config.pgo_use.is_some();
370 let data = Box::into_raw(Box::new((cgcx, shared_emitter)));
371 unsafe {
372 let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
373 llvm::LLVMRustContextConfigureDiagnosticHandler(
374 llcx,
375 diagnostic_handler,
376 data.cast(),
377 remark_passes_all,
378 remark_passes.as_ptr(),
379 remark_passes.len(),
380 remark_file.as_ref().map(|dir| dir.as_ptr()).unwrap_or(std::ptr::null()),
383 pgo_available,
384 );
385 DiagnosticHandlers { data, llcx, old_handler }
386 }
387 }
388}
389
390impl<'a> Drop for DiagnosticHandlers<'a> {
391 fn drop(&mut self) {
392 unsafe {
393 llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
394 drop(Box::from_raw(self.data));
395 }
396 }
397}
398
399fn report_inline_asm(
400 cgcx: &CodegenContext,
401 msg: String,
402 level: llvm::DiagnosticLevel,
403 cookie: u64,
404 source: Option<(String, Vec<InnerSpan>)>,
405) -> InlineAsmError {
406 let span = if cookie == 0 || #[allow(non_exhaustive_omitted_patterns)] match cgcx.lto {
Lto::Fat | Lto::Thin => true,
_ => false,
}matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
410 SpanData::default()
411 } else {
412 SpanData {
413 lo: BytePos::from_u32(cookie as u32),
414 hi: BytePos::from_u32((cookie >> 32) as u32),
415 ctxt: SyntaxContext::root(),
416 parent: None,
417 }
418 };
419 let level = match level {
420 llvm::DiagnosticLevel::Error => Level::Error,
421 llvm::DiagnosticLevel::Warning => Level::Warning(None),
422 llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
423 };
424 let msg = msg.trim_prefix("error: ").to_string();
425 InlineAsmError { span, msg, level, source }
426}
427
428unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
429 if user.is_null() {
430 return;
431 }
432 let (cgcx, shared_emitter) = unsafe { *(user as *const (&CodegenContext, &SharedEmitter)) };
433
434 let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
435 let dcx = dcx.handle();
436
437 match unsafe { llvm::diagnostic::Diagnostic::unpack(info) } {
438 llvm::diagnostic::InlineAsm(inline) => {
439 shared_emitter.inline_asm_error(report_inline_asm(
441 cgcx,
442 inline.message,
443 inline.level,
444 inline.cookie,
445 inline.source,
446 ));
447 }
448
449 llvm::diagnostic::Optimization(opt) => {
450 dcx.emit_note(FromLlvmOptimizationDiag {
451 filename: &opt.filename,
452 line: opt.line,
453 column: opt.column,
454 pass_name: &opt.pass_name,
455 kind: match opt.kind {
456 OptimizationRemark => "success",
457 OptimizationMissed | OptimizationFailure => "missed",
458 OptimizationAnalysis
459 | OptimizationAnalysisFPCommute
460 | OptimizationAnalysisAliasing => "analysis",
461 OptimizationRemarkOther => "other",
462 },
463 message: &opt.message,
464 });
465 }
466 llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
467 let message = llvm::build_string(|s| unsafe {
468 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
469 })
470 .expect("non-UTF8 diagnostic");
471 dcx.emit_warn(FromLlvmDiag { message });
472 }
473 llvm::diagnostic::Unsupported(diagnostic_ref) => {
474 let message = llvm::build_string(|s| unsafe {
475 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
476 })
477 .expect("non-UTF8 diagnostic");
478 dcx.emit_err(FromLlvmDiag { message });
479 }
480 llvm::diagnostic::UnknownDiagnostic(..) => {}
481 }
482}
483
484fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
485 match config.pgo_gen {
486 SwitchWithOptPath::Enabled(ref opt_dir_path) => {
487 let path = if let Some(dir_path) = opt_dir_path {
488 dir_path.join("default_%m.profraw")
489 } else {
490 PathBuf::from("default_%m.profraw")
491 };
492
493 Some(CString::new(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", path.display()))
})format!("{}", path.display())).unwrap())
494 }
495 SwitchWithOptPath::Disabled => None,
496 }
497}
498
499fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
500 config
501 .pgo_use
502 .as_ref()
503 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
504}
505
506fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
507 config
508 .pgo_sample_use
509 .as_ref()
510 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
511}
512
513fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
514 config.instrument_coverage.then(|| c"default_%m_%p.profraw".to_owned())
515}
516
517#[derive(#[automatically_derived]
impl ::core::fmt::Debug for AutodiffStage {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
AutodiffStage::PreAD => "PreAD",
AutodiffStage::DuringAD => "DuringAD",
AutodiffStage::PostAD => "PostAD",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for AutodiffStage { }Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AutodiffStage { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AutodiffStage {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
521pub(crate) enum AutodiffStage {
522 PreAD,
523 DuringAD,
524 PostAD,
525}
526
527pub(crate) unsafe fn llvm_optimize(
528 cgcx: &CodegenContext,
529 prof: &SelfProfilerRef,
530 dcx: DiagCtxtHandle<'_>,
531 module: &ModuleCodegen<ModuleLlvm>,
532 thin_lto_buffer: Option<&mut Option<Buffer>>,
533 thin_lto_summary_buffer: Option<&mut Option<Buffer>>,
534 config: &ModuleConfig,
535 opt_level: config::OptLevel,
536 opt_stage: llvm::OptStage,
537 autodiff_stage: AutodiffStage,
538) {
539 let consider_ad = config.autodiff.contains(&config::AutoDiff::Enable);
548 let run_enzyme = autodiff_stage == AutodiffStage::DuringAD;
549 let print_before_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModBefore);
550 let print_after_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModAfter);
551 let print_passes = config.autodiff.contains(&config::AutoDiff::PrintPasses);
552 let passes_after_enzyme = if autodiff_stage == AutodiffStage::PostAD {
553 config.autodiff_post_passes.as_deref()
554 } else {
555 None
556 };
557 let passes_after_enzyme_ptr =
558 passes_after_enzyme.map_or(std::ptr::null(), |s| s.as_c_char_ptr());
559 let passes_after_enzyme_len = passes_after_enzyme.map_or(0, |s| s.len());
560 let merge_functions;
561 let unroll_loops;
562 let vectorize_slp;
563 let vectorize_loop;
564
565 if consider_ad && autodiff_stage != AutodiffStage::PostAD {
574 merge_functions = false;
575 unroll_loops = false;
576 vectorize_slp = false;
577 vectorize_loop = false;
578 } else {
579 unroll_loops =
580 opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
581 merge_functions = config.merge_functions;
582 vectorize_slp = config.vectorize_slp;
583 vectorize_loop = config.vectorize_loop;
584 }
585 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/fd8e211ae301c84a86d13cf52a6d3ce08c589e2e/compiler/rustc_codegen_llvm/src/back/write.rs:585",
"rustc_codegen_llvm::back::write", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/fd8e211ae301c84a86d13cf52a6d3ce08c589e2e/compiler/rustc_codegen_llvm/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(585u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("unroll_loops")
}> =
::tracing::__macro_support::FieldName::new("unroll_loops");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("vectorize_slp")
}> =
::tracing::__macro_support::FieldName::new("vectorize_slp");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("vectorize_loop")
}> =
::tracing::__macro_support::FieldName::new("vectorize_loop");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("run_enzyme")
}> =
::tracing::__macro_support::FieldName::new("run_enzyme");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unroll_loops)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vectorize_slp)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vectorize_loop)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&run_enzyme)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!(?unroll_loops, ?vectorize_slp, ?vectorize_loop, ?run_enzyme);
586 if thin_lto_buffer.is_some() {
587 if !#[allow(non_exhaustive_omitted_patterns)] match opt_stage {
llvm::OptStage::PreLinkNoLTO | llvm::OptStage::PreLinkFatLTO |
llvm::OptStage::PreLinkThinLTO => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("the bitcode for LTO can only be obtained at the pre-link stage"));
}
};assert!(
588 matches!(
589 opt_stage,
590 llvm::OptStage::PreLinkNoLTO
591 | llvm::OptStage::PreLinkFatLTO
592 | llvm::OptStage::PreLinkThinLTO
593 ),
594 "the bitcode for LTO can only be obtained at the pre-link stage"
595 );
596 }
597 let pgo_gen_path = get_pgo_gen_path(config);
598 let pgo_use_path = get_pgo_use_path(config);
599 let pgo_sample_use_path = get_pgo_sample_use_path(config);
600 let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
601 let is_final_stage =
602 !#[allow(non_exhaustive_omitted_patterns)] match opt_stage {
llvm::OptStage::PreLinkFatLTO | llvm::OptStage::PreLinkThinLTO => true,
_ => false,
}matches!(opt_stage, llvm::OptStage::PreLinkFatLTO | llvm::OptStage::PreLinkThinLTO);
603 let instr_profile_output_path = get_instr_profile_output_path(config);
604 let sanitize_dataflow_abilist: Vec<_> = config
605 .sanitizer_dataflow_abilist
606 .iter()
607 .map(|file| CString::new(file.as_str()).unwrap())
608 .collect();
609 let sanitize_dataflow_abilist_ptrs: Vec<_> =
610 sanitize_dataflow_abilist.iter().map(|file| file.as_ptr()).collect();
611 let sanitizer_options = if !is_lto {
613 Some(llvm::SanitizerOptions {
614 sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
615 sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
616 sanitize_cfi: config.sanitizer.contains(SanitizerSet::CFI),
617 sanitize_dataflow: config.sanitizer.contains(SanitizerSet::DATAFLOW),
618 sanitize_dataflow_abilist: sanitize_dataflow_abilist_ptrs.as_ptr(),
619 sanitize_dataflow_abilist_len: sanitize_dataflow_abilist_ptrs.len(),
620 sanitize_kcfi: config.sanitizer.contains(SanitizerSet::KCFI),
621 sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
622 sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
623 sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
624 sanitize_realtime: config.sanitizer.contains(SanitizerSet::REALTIME),
625 sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
626 sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
627 sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
628 sanitize_kernel_address: config.sanitizer.contains(SanitizerSet::KERNELADDRESS),
629 sanitize_kernel_address_recover: config
630 .sanitizer_recover
631 .contains(SanitizerSet::KERNELADDRESS),
632 sanitize_kernel_hwaddress: config.sanitizer.contains(SanitizerSet::KERNELHWADDRESS),
633 sanitize_kernel_hwaddress_recover: config
634 .sanitizer_recover
635 .contains(SanitizerSet::KERNELHWADDRESS),
636 })
637 } else {
638 None
639 };
640
641 fn handle_offload<'ll>(cx: &'ll SimpleCx<'_>, old_fn: &llvm::Value) {
642 let old_fn_ty = cx.get_type_of_global(old_fn);
643 let old_param_types = cx.func_params_types(old_fn_ty);
644 let old_param_count = old_param_types.len();
645 if old_param_count == 0 {
646 return;
647 }
648
649 let first_param = llvm::get_param(old_fn, 0);
650 let c_name = llvm::get_value_name(first_param);
651 let first_arg_name = str::from_utf8(&c_name).unwrap();
652 if first_arg_name == "dyn_ptr" {
656 return;
657 }
658
659 let mut new_param_types = Vec::with_capacity(old_param_count as usize + 1);
661 new_param_types.push(cx.type_ptr());
662
663 for &old_ty in &old_param_types {
665 let new_ty = match cx.type_kind(old_ty) {
666 TypeKind::Half | TypeKind::Float | TypeKind::Double | TypeKind::Integer => {
667 cx.type_i64()
668 }
669 _ => old_ty,
670 };
671 new_param_types.push(new_ty);
672 }
673
674 let ret_ty = unsafe { llvm::LLVMGetReturnType(old_fn_ty) };
676 let new_fn_ty = cx.type_func(&new_param_types, ret_ty);
677
678 let old_fn_name = String::from_utf8(llvm::get_value_name(old_fn)).unwrap();
680 let new_fn_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.offload", &old_fn_name))
})format!("{}.offload", &old_fn_name);
681 let new_fn = cx.add_func(&new_fn_name, new_fn_ty);
682 let a0 = llvm::get_param(new_fn, 0);
683 llvm::set_value_name(a0, CString::new("dyn_ptr").unwrap().as_bytes());
684
685 let bb = SBuilder::append_block(cx, new_fn, "entry");
686 let mut builder = SBuilder::build(cx, bb);
687
688 let mut old_args_rebuilt = Vec::with_capacity(old_param_types.len());
689
690 for (i, &old_ty) in old_param_types.iter().enumerate() {
691 let new_arg = llvm::get_param(new_fn, (i + 1) as u32);
692
693 let rebuilt = match cx.type_kind(old_ty) {
694 TypeKind::Half | TypeKind::Float | TypeKind::Double | TypeKind::Integer => {
695 let num_bits = scalar_width(cx, old_ty);
696
697 let trunc = builder.trunc(new_arg, cx.type_ix(num_bits));
698 builder.bitcast(trunc, old_ty)
699 }
700 _ => new_arg,
701 };
702
703 old_args_rebuilt.push(rebuilt);
704 }
705
706 builder.ret_void();
707
708 unsafe {
711 llvm::RustOffloadWrapper::get_instance().llvm_rust_offload_wrapper(
712 old_fn,
713 new_fn,
714 old_args_rebuilt.as_slice(),
715 );
716 }
717
718 llvm::set_linkage(new_fn, llvm::get_linkage(old_fn));
719 llvm::set_visibility(new_fn, llvm::get_visibility(old_fn));
720
721 unsafe {
723 llvm::LLVMReplaceAllUsesWith(old_fn, new_fn);
724 }
725 let name = llvm::get_value_name(old_fn);
726 unsafe {
727 llvm::LLVMDeleteFunction(old_fn);
728 }
729 llvm::set_value_name(new_fn, &name);
731 }
732
733 if cgcx.target_is_like_gpu
734 && config.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
config::Offload::Device(_) => true,
_ => false,
}matches!(o, config::Offload::Device(_)))
735 {
736 let cx =
737 SimpleCx::new(module.module_llvm.llmod(), module.module_llvm.llcx, cgcx.pointer_size);
738 for func in cx.get_functions() {
739 let offload_kernel = "offload-kernel";
740 if attributes::has_string_attr(func, offload_kernel) {
741 handle_offload(&cx, func);
742 }
743 attributes::remove_string_attr_from_llfn(func, offload_kernel);
744 }
745 }
746
747 let mut llvm_profiler = prof
748 .llvm_recording_enabled()
749 .then(|| LlvmSelfProfiler::new(prof.get_self_profiler().unwrap()));
750
751 let llvm_selfprofiler =
752 llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
753
754 let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
755
756 let llvm_plugins = config.llvm_plugins.join(",");
757
758 let enzyme_fn = if consider_ad {
759 let wrapper = llvm::EnzymeWrapper::get_instance();
760 wrapper.registerEnzymeAndPassPipeline
761 } else {
762 std::ptr::null()
763 };
764
765 let result = unsafe {
766 llvm::LLVMRustOptimize(
767 module.module_llvm.llmod(),
768 &*module.module_llvm.tm.raw(),
769 to_pass_builder_opt_level(opt_level),
770 opt_stage,
771 cgcx.use_linker_plugin_lto,
772 config.no_prepopulate_passes,
773 config.verify_llvm_ir,
774 config.lint_llvm_ir,
775 thin_lto_buffer,
776 thin_lto_summary_buffer,
777 merge_functions,
778 unroll_loops,
779 vectorize_slp,
780 vectorize_loop,
781 config.no_builtins,
782 config.emit_lifetime_markers,
783 enzyme_fn,
784 print_before_enzyme,
785 print_after_enzyme,
786 print_passes,
787 sanitizer_options.as_ref(),
788 pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
789 pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
790 config.instrument_coverage,
791 instr_profile_output_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
792 pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
793 config.debug_info_for_profiling,
794 llvm_selfprofiler,
795 selfprofile_before_pass_callback,
796 selfprofile_after_pass_callback,
797 passes_after_enzyme_ptr,
798 passes_after_enzyme_len,
799 extra_passes.as_c_char_ptr(),
800 extra_passes.len(),
801 llvm_plugins.as_c_char_ptr(),
802 llvm_plugins.len(),
803 )
804 };
805
806 if cgcx.target_is_like_gpu
807 && config.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
config::Offload::Device(_) => true,
_ => false,
}matches!(o, config::Offload::Device(_)))
808 {
809 let device_path = cgcx.output_filenames.path(OutputType::Object);
810 let device_dir = device_path.parent().unwrap();
811 let device_out = device_dir.join("device.bin");
812 let device_out_c = path_to_c_string(device_out.as_path());
813 let ok = unsafe {
815 llvm::RustOffloadWrapper::get_instance().llvm_rust_bundle_images(
816 module.module_llvm.llmod(),
817 module.module_llvm.tm.raw(),
818 device_out_c.as_c_str(),
819 )
820 };
821 if !ok || !device_out.exists() {
822 dcx.emit_err(crate::diagnostics::OffloadBundleImagesFailed);
823 }
824 }
825
826 if !cgcx.target_is_like_gpu && is_final_stage {
830 if let Some(device_path) = config
831 .offload
832 .iter()
833 .find_map(|o| if let config::Offload::Host(path) = o { Some(path) } else { None })
834 {
835 let device_pathbuf = PathBuf::from(device_path);
836 if device_pathbuf.is_relative() {
837 dcx.emit_err(crate::diagnostics::OffloadWithoutAbsPath);
838 } else if device_pathbuf
839 .file_name()
840 .and_then(|n| n.to_str())
841 .is_some_and(|n| n != "device.bin")
842 {
843 dcx.emit_err(crate::diagnostics::OffloadWrongFileName);
844 } else if !device_pathbuf.exists() {
845 dcx.emit_err(crate::diagnostics::OffloadNonexistingPath);
846 }
847 let device_bin_c = path_to_c_string(device_pathbuf.as_path());
848 let ok = unsafe {
849 llvm::RustOffloadWrapper::get_instance().llvm_rust_offload_wrap_images(
850 module.module_llvm.llmod(),
851 device_bin_c.as_c_str(),
852 )
853 };
854 if !ok {
855 dcx.emit_err(crate::diagnostics::OffloadWrapImagesFailed);
856 }
857 }
858 }
859 result.into_result().unwrap_or_else(|()| llvm_err(dcx, LlvmError::RunLlvmPasses))
860}
861
862pub(crate) fn optimize(
864 cgcx: &CodegenContext,
865 prof: &SelfProfilerRef,
866 shared_emitter: &SharedEmitter,
867 module: &mut ModuleCodegen<ModuleLlvm>,
868 config: &ModuleConfig,
869) {
870 let _timer = prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name);
871
872 let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
873 let dcx = dcx.handle();
874
875 let llcx = &*module.module_llvm.llcx;
876 let _handlers =
877 DiagnosticHandlers::new(cgcx, shared_emitter, llcx, module, CodegenDiagnosticsStage::Opt);
878
879 if module.kind == ModuleKind::Regular {
880 save_temp_bitcode(cgcx, module, "no-opt");
881 }
882
883 if let Some(opt_level) = config.opt_level {
886 let opt_stage = match cgcx.lto {
887 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
888 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
889 _ if cgcx.use_linker_plugin_lto => llvm::OptStage::PreLinkThinLTO,
890 _ => llvm::OptStage::PreLinkNoLTO,
891 };
892
893 let consider_ad = config.autodiff.contains(&config::AutoDiff::Enable);
896 let autodiff_stage = if consider_ad { AutodiffStage::PreAD } else { AutodiffStage::PostAD };
897 let (mut thin_lto_buffer, mut thin_lto_summary_buffer) = if (module.kind
902 == ModuleKind::Regular
903 && config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full))
904 || config.emit_thin_lto_summary
905 {
906 (Some(None), config.emit_thin_lto_summary.then_some(None))
907 } else {
908 (None, None)
909 };
910 unsafe {
911 llvm_optimize(
912 cgcx,
913 prof,
914 dcx,
915 module,
916 thin_lto_buffer.as_mut(),
917 thin_lto_summary_buffer.as_mut(),
918 config,
919 opt_level,
920 opt_stage,
921 autodiff_stage,
922 )
923 };
924 if let Some(thin_lto_buffer) = thin_lto_buffer {
925 let thin_lto_buffer = thin_lto_buffer.unwrap();
926 module.thin_lto_buffer = Some(thin_lto_buffer.data().to_vec());
927 let bc_summary_out =
928 cgcx.output_filenames.temp_path_for_cgu(OutputType::ThinLinkBitcode, &module.name);
929 if let Some(thin_lto_summary_buffer) = thin_lto_summary_buffer
930 && let Some(thin_link_bitcode_filename) = bc_summary_out.file_name()
931 {
932 let thin_lto_summary_buffer = thin_lto_summary_buffer.unwrap();
933 let summary_data = thin_lto_summary_buffer.data();
934 prof.artifact_size(
935 "llvm_bitcode_summary",
936 thin_link_bitcode_filename.to_string_lossy(),
937 summary_data.len() as u64,
938 );
939 let _timer = prof.generic_activity_with_arg(
940 "LLVM_module_codegen_emit_bitcode_summary",
941 &*module.name,
942 );
943 if let Err(err) = fs::write(&bc_summary_out, summary_data) {
944 dcx.emit_err(WriteBytecode { path: &bc_summary_out, err });
945 }
946 }
947 }
948 }
949}
950
951pub(crate) fn codegen(
952 cgcx: &CodegenContext,
953 prof: &SelfProfilerRef,
954 shared_emitter: &SharedEmitter,
955 module: ModuleCodegen<ModuleLlvm>,
956 config: &ModuleConfig,
957) -> CompiledModule {
958 let _timer = prof.generic_activity_with_arg("LLVM_module_codegen", &*module.name);
959
960 let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
961 let dcx = dcx.handle();
962
963 {
964 let llmod = module.module_llvm.llmod();
965 let llcx = &*module.module_llvm.llcx;
966 let tm = &*module.module_llvm.tm;
967 let _handlers = DiagnosticHandlers::new(
968 cgcx,
969 shared_emitter,
970 llcx,
971 &module,
972 CodegenDiagnosticsStage::Codegen,
973 );
974
975 if cgcx.msvc_imps_needed {
976 create_msvc_imps(cgcx, llcx, llmod);
977 }
978
979 let bc_out = cgcx.output_filenames.temp_path_for_cgu(OutputType::Bitcode, &module.name);
984 let obj_out = cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, &module.name);
985
986 if config.bitcode_needed() {
987 if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
988 let thin = {
989 let _timer = prof.generic_activity_with_arg(
990 "LLVM_module_codegen_make_bitcode",
991 &*module.name,
992 );
993 ModuleBuffer::new(llmod, cgcx.lto != Lto::Fat)
994 };
995 let data = thin.data();
996 let _timer = prof
997 .generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
998 if let Some(bitcode_filename) = bc_out.file_name() {
999 prof.artifact_size(
1000 "llvm_bitcode",
1001 bitcode_filename.to_string_lossy(),
1002 data.len() as u64,
1003 );
1004 }
1005 if let Err(err) = fs::write(&bc_out, data) {
1006 dcx.emit_err(WriteBytecode { path: &bc_out, err });
1007 }
1008 }
1009
1010 if config.embed_bitcode() && module.kind == ModuleKind::Regular {
1011 let _timer = prof
1012 .generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name);
1013 let thin_bc =
1014 module.thin_lto_buffer.as_deref().expect("cannot find embedded bitcode");
1015 embed_bitcode(cgcx, llcx, llmod, &thin_bc);
1016 }
1017 }
1018
1019 if config.emit_ir {
1020 let _timer =
1021 prof.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &*module.name);
1022 let out =
1023 cgcx.output_filenames.temp_path_for_cgu(OutputType::LlvmAssembly, &module.name);
1024 let out_c = path_to_c_string(&out);
1025
1026 extern "C" fn demangle_callback(
1027 input_ptr: *const c_char,
1028 input_len: size_t,
1029 output_ptr: *mut c_char,
1030 output_len: size_t,
1031 ) -> size_t {
1032 let input =
1033 unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
1034
1035 let Ok(input) = str::from_utf8(input) else { return 0 };
1036
1037 let output = unsafe {
1038 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
1039 };
1040 let mut cursor = io::Cursor::new(output);
1041
1042 let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
1043
1044 if cursor.write_fmt(format_args!("{0:#}", demangled))write!(cursor, "{demangled:#}").is_err() {
1045 return 0;
1047 }
1048
1049 cursor.position() as size_t
1050 }
1051
1052 let result =
1053 unsafe { llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback) };
1054
1055 if result == llvm::LLVMRustResult::Success {
1056 record_artifact_size(prof, "llvm_ir", &out);
1057 }
1058
1059 result
1060 .into_result()
1061 .unwrap_or_else(|()| llvm_err(dcx, LlvmError::WriteIr { path: &out }));
1062 }
1063
1064 if config.emit_asm {
1065 let _timer =
1066 prof.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &*module.name);
1067 let path = cgcx.output_filenames.temp_path_for_cgu(OutputType::Assembly, &module.name);
1068
1069 let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
1074 llvm::LLVMCloneModule(llmod)
1075 } else {
1076 llmod
1077 };
1078 write_output_file(
1079 dcx,
1080 tm.raw(),
1081 config.no_builtins,
1082 llmod,
1083 &path,
1084 None,
1085 llvm::FileType::AssemblyFile,
1086 prof,
1087 config.verify_llvm_ir,
1088 );
1089 }
1090
1091 match config.emit_obj {
1092 EmitObj::ObjectCode(_) => {
1093 let _timer =
1094 prof.generic_activity_with_arg("LLVM_module_codegen_emit_obj", &*module.name);
1095
1096 let dwo_out = cgcx.output_filenames.temp_path_dwo_for_cgu(&module.name);
1097 let dwo_out = match (cgcx.split_debuginfo, cgcx.split_dwarf_kind) {
1098 (SplitDebuginfo::Off, _) => None,
1100 _ if !cgcx.target_can_use_split_dwarf => None,
1103 (_, SplitDwarfKind::Single) => None,
1106 (_, SplitDwarfKind::Split) => Some(dwo_out.as_path()),
1109 };
1110
1111 write_output_file(
1112 dcx,
1113 tm.raw(),
1114 config.no_builtins,
1115 llmod,
1116 &obj_out,
1117 dwo_out,
1118 llvm::FileType::ObjectFile,
1119 prof,
1120 config.verify_llvm_ir,
1121 );
1122 }
1123
1124 EmitObj::Bitcode => {
1125 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/fd8e211ae301c84a86d13cf52a6d3ce08c589e2e/compiler/rustc_codegen_llvm/src/back/write.rs:1125",
"rustc_codegen_llvm::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/fd8e211ae301c84a86d13cf52a6d3ce08c589e2e/compiler/rustc_codegen_llvm/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(1125u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("copying bitcode {0:?} to obj {1:?}",
bc_out, obj_out) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
1126 if let Err(err) = link_or_copy(&bc_out, &obj_out) {
1127 dcx.emit_err(CopyBitcode { err });
1128 }
1129
1130 if !config.emit_bc {
1131 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/fd8e211ae301c84a86d13cf52a6d3ce08c589e2e/compiler/rustc_codegen_llvm/src/back/write.rs:1131",
"rustc_codegen_llvm::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/fd8e211ae301c84a86d13cf52a6d3ce08c589e2e/compiler/rustc_codegen_llvm/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(1131u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("removing_bitcode {0:?}",
bc_out) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("removing_bitcode {:?}", bc_out);
1132 ensure_removed(dcx, &bc_out);
1133 }
1134 }
1135
1136 EmitObj::None => {}
1137 }
1138
1139 record_llvm_cgu_instructions_stats(prof, &module.name, llmod);
1140 }
1141
1142 let dwarf_object_emitted = #[allow(non_exhaustive_omitted_patterns)] match config.emit_obj {
EmitObj::ObjectCode(_) => true,
_ => false,
}matches!(config.emit_obj, EmitObj::ObjectCode(_))
1151 && cgcx.target_can_use_split_dwarf
1152 && cgcx.split_debuginfo != SplitDebuginfo::Off
1153 && cgcx.split_dwarf_kind == SplitDwarfKind::Split;
1154 module.into_compiled_module(
1155 config.emit_obj != EmitObj::None,
1156 dwarf_object_emitted,
1157 config.emit_bc,
1158 config.emit_asm,
1159 config.emit_ir,
1160 &cgcx.output_filenames,
1161 )
1162}
1163
1164fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
1165 let mut asm = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(".section {0},\"{1}\"\n",
section_name, section_flags))
})format!(".section {section_name},\"{section_flags}\"\n").into_bytes();
1166 asm.extend_from_slice(b".ascii \"");
1167 asm.reserve(data.len());
1168 for &byte in data {
1169 if byte == b'\\' || byte == b'"' {
1170 asm.push(b'\\');
1171 asm.push(byte);
1172 } else if byte < 0x20 || byte >= 0x80 {
1173 asm.push(b'\\');
1176 asm.push(b'0' + ((byte >> 6) & 0x7));
1177 asm.push(b'0' + ((byte >> 3) & 0x7));
1178 asm.push(b'0' + ((byte >> 0) & 0x7));
1179 } else {
1180 asm.push(byte);
1181 }
1182 }
1183 asm.extend_from_slice(b"\"\n");
1184 asm
1185}
1186
1187pub(crate) fn bitcode_section_name(cgcx: &CodegenContext) -> &'static CStr {
1188 if cgcx.target_is_like_darwin {
1189 c"__LLVM,__bitcode"
1190 } else if cgcx.target_is_like_aix {
1191 c".ipa"
1192 } else {
1193 c".llvmbc"
1194 }
1195}
1196
1197fn embed_bitcode(
1199 cgcx: &CodegenContext,
1200 llcx: &llvm::Context,
1201 llmod: &llvm::Module,
1202 bitcode: &[u8],
1203) {
1204 if cgcx.target_is_like_darwin
1243 || cgcx.target_is_like_aix
1244 || cgcx.target_arch == "wasm32"
1245 || cgcx.target_arch == "wasm64"
1246 {
1247 let llconst = common::bytes_in_context(llcx, bitcode);
1249 let llglobal = llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.module");
1250 llvm::set_initializer(llglobal, llconst);
1251
1252 llvm::set_section(llglobal, bitcode_section_name(cgcx));
1253 llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
1254 llvm::LLVMSetGlobalConstant(llglobal, llvm::TRUE);
1255
1256 let llconst = common::bytes_in_context(llcx, &[]);
1257 let llglobal = llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.cmdline");
1258 llvm::set_initializer(llglobal, llconst);
1259 let section = if cgcx.target_is_like_darwin {
1260 c"__LLVM,__cmdline"
1261 } else if cgcx.target_is_like_aix {
1262 c".info"
1263 } else {
1264 c".llvmcmd"
1265 };
1266 llvm::set_section(llglobal, section);
1267 llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
1268 } else {
1269 let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
1271 let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
1272 llvm::append_module_inline_asm(llmod, &asm, "", "");
1273 let asm = create_section_with_flags_asm(".llvmcmd", section_flags, &[]);
1274 llvm::append_module_inline_asm(llmod, &asm, "", "");
1275 }
1276}
1277
1278fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
1285 if !cgcx.msvc_imps_needed {
1286 return;
1287 }
1288 let prefix: &[u8] = if cgcx.target_arch == "x86" { b"\x01__imp__" } else { b"\x01__imp_" };
1293
1294 let ptr_ty = llvm_type_ptr(llcx);
1295 let symbols = std::iter::chain(
1296 base::iter_globals(llmod),
1297 base::iter_global_aliases(llmod).filter(|&val| {
1298 llvm::LLVMGetTypeKind(unsafe { llvm::LLVMGlobalGetValueType(val) }).to_rust()
1299 != llvm::TypeKind::Function
1300 }),
1301 )
1302 .map(|val| (val, llvm::get_linkage(val)))
1303 .filter(|&(val, linkage)| {
1304 #[allow(non_exhaustive_omitted_patterns)] match linkage {
llvm::Linkage::ExternalLinkage | llvm::Linkage::WeakAnyLinkage => true,
_ => false,
}matches!(linkage, llvm::Linkage::ExternalLinkage | llvm::Linkage::WeakAnyLinkage)
1305 && !llvm::is_declaration(val)
1306 })
1307 .collect::<Vec<_>>();
1308
1309 for (val, linkage) in symbols {
1310 let name = llvm::get_value_name(val);
1311 if ignored(&name) {
1313 continue;
1314 }
1315
1316 let mut imp_name = prefix.to_vec();
1317 imp_name.extend(name);
1318 let imp_name = CString::new(imp_name).unwrap();
1319
1320 let imp = llvm::add_global(llmod, ptr_ty, &imp_name);
1321
1322 llvm::set_initializer(imp, val);
1323 llvm::set_linkage(imp, linkage);
1324 }
1325
1326 fn ignored(symbol_name: &[u8]) -> bool {
1328 symbol_name.starts_with(b"__llvm_profile_")
1330 }
1331}
1332
1333fn record_artifact_size(
1334 self_profiler_ref: &SelfProfilerRef,
1335 artifact_kind: &'static str,
1336 path: &Path,
1337) {
1338 if !self_profiler_ref.enabled() {
1340 return;
1341 }
1342
1343 if let Some(artifact_name) = path.file_name() {
1344 let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
1345 self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);
1346 }
1347}
1348
1349fn record_llvm_cgu_instructions_stats(prof: &SelfProfilerRef, name: &str, llmod: &llvm::Module) {
1350 if !prof.enabled() {
1351 return;
1352 }
1353
1354 let total = unsafe { llvm::LLVMRustModuleInstructionStats(llmod) };
1355 prof.artifact_size("cgu_instructions", name, total);
1356}