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