]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_codegen_llvm/src/back/write.rs
New upstream version 1.70.0+dfsg2
[rustc.git] / compiler / rustc_codegen_llvm / src / back / write.rs
CommitLineData
9fa01778 1use crate::back::lto::ThinBuffer;
74b04a01
XL
2use crate::back::profiling::{
3 selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler,
4};
9fa01778 5use crate::base;
dfeec247 6use crate::common;
9fa01778 7use crate::consts;
9ffffee4
FG
8use crate::errors::{
9 CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, WithLlvmError, WriteBytecode,
10};
f2b60f7d 11use crate::llvm::{self, DiagnosticInfo, PassManager};
9fa01778 12use crate::llvm_util;
9fa01778 13use crate::type_::Type;
9fa01778 14use crate::LlvmCodegenBackend;
dfeec247 15use crate::ModuleLlvm;
6a06907d 16use rustc_codegen_ssa::back::link::ensure_removed;
fc512014
XL
17use rustc_codegen_ssa::back::write::{
18 BitcodeSection, CodegenContext, EmitObj, ModuleConfig, TargetMachineFactoryConfig,
19 TargetMachineFactoryFn,
20};
dfeec247 21use rustc_codegen_ssa::traits::*;
f9f354fc 22use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
3c0e092e 23use rustc_data_structures::profiling::SelfProfilerRef;
b7449926 24use rustc_data_structures::small_c_str::SmallCStr;
f035d41b 25use rustc_errors::{FatalError, Handler, Level};
dfeec247 26use rustc_fs_util::{link_or_copy, path_to_c_string};
ba9703b0 27use rustc_middle::ty::TyCtxt;
a2a8927a 28use rustc_session::config::{self, Lto, OutputType, Passes, SplitDwarfKind, SwitchWithOptPath};
ba9703b0 29use rustc_session::Session;
f035d41b 30use rustc_span::symbol::sym;
f9f354fc 31use rustc_span::InnerSpan;
cdc7bbd5 32use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo};
1a4d82fc 33
dfeec247 34use libc::{c_char, c_int, c_uint, c_void, size_t};
60c5eb7d 35use std::ffi::CString;
2c00a5a8
XL
36use std::fs;
37use std::io::{self, Write};
48663c56 38use std::path::{Path, PathBuf};
dfeec247 39use std::slice;
1a4d82fc 40use std::str;
3b2f2976 41use std::sync::Arc;
1a4d82fc 42
9ffffee4 43pub fn llvm_err<'a>(handler: &rustc_errors::Handler, err: LlvmError<'a>) -> FatalError {
7453a54e 44 match llvm::last_error() {
9ffffee4
FG
45 Some(llvm_err) => handler.emit_almost_fatal(WithLlvmError(err, llvm_err)),
46 None => handler.emit_almost_fatal(err),
1a4d82fc
JJ
47 }
48}
49
a2a8927a 50pub fn write_output_file<'ll>(
dfeec247
XL
51 handler: &rustc_errors::Handler,
52 target: &'ll llvm::TargetMachine,
53 pm: &llvm::PassManager<'ll>,
54 m: &'ll llvm::Module,
55 output: &Path,
fc512014 56 dwo_output: Option<&Path>,
dfeec247 57 file_type: llvm::FileType,
3c0e092e 58 self_profiler_ref: &SelfProfilerRef,
dfeec247 59) -> Result<(), FatalError> {
923072b8 60 debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
1a4d82fc 61 unsafe {
a1dfa0c6 62 let output_c = path_to_c_string(output);
923072b8
FG
63 let dwo_output_c;
64 let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
65 dwo_output_c = path_to_c_string(dwo_output);
66 dwo_output_c.as_ptr()
fc512014 67 } else {
923072b8 68 std::ptr::null()
fc512014 69 };
923072b8
FG
70 let result = llvm::LLVMRustWriteOutputFile(
71 target,
72 pm,
73 m,
74 output_c.as_ptr(),
75 dwo_output_ptr,
76 file_type,
77 );
3c0e092e
XL
78
79 // Record artifact sizes for self-profiling
80 if result == llvm::LLVMRustResult::Success {
81 let artifact_kind = match file_type {
82 llvm::FileType::ObjectFile => "object_file",
83 llvm::FileType::AssemblyFile => "assembly_file",
84 };
85 record_artifact_size(self_profiler_ref, artifact_kind, output);
86 if let Some(dwo_file) = dwo_output {
87 record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
88 }
89 }
90
9ffffee4
FG
91 result
92 .into_result()
93 .map_err(|()| llvm_err(handler, LlvmError::WriteOutput { path: output }))
1a4d82fc 94 }
1a4d82fc
JJ
95}
96
f9f354fc 97pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
fc512014 98 let config = TargetMachineFactoryConfig { split_dwarf_file: None };
5e7ed085
FG
99 // Can't use query system here quite yet because this function is invoked before the query
100 // system/tcx is set up.
101 let features = llvm_util::global_llvm_features(sess, false);
102 target_machine_factory(sess, config::OptLevel::No, &features)(config)
9ffffee4 103 .unwrap_or_else(|err| llvm_err(sess.diagnostic(), err).raise())
ea8adc8c
XL
104}
105
fc512014 106pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> &'static mut llvm::TargetMachine {
5869c6ff 107 let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
a2a8927a
XL
108 tcx.output_filenames(()).split_dwarf_path(
109 tcx.sess.split_debuginfo(),
064997fb 110 tcx.sess.opts.unstable_opts.split_dwarf_kind,
a2a8927a
XL
111 Some(mod_name),
112 )
5869c6ff
XL
113 } else {
114 None
115 };
fc512014 116 let config = TargetMachineFactoryConfig { split_dwarf_file };
5e7ed085
FG
117 target_machine_factory(
118 &tcx.sess,
119 tcx.backend_optimization_level(()),
120 tcx.global_backend_features(()),
121 )(config)
9ffffee4 122 .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), err).raise())
532ac7d7 123}
9fa01778 124
dfeec247
XL
125pub fn to_llvm_opt_settings(
126 cfg: config::OptLevel,
127) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
9fa01778
XL
128 use self::config::OptLevel::*;
129 match cfg {
130 No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
131 Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
132 Default => (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
74b04a01
XL
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 Default => llvm::PassBuilderOptLevel::O2,
145 Aggressive => llvm::PassBuilderOptLevel::O3,
146 Size => llvm::PassBuilderOptLevel::Os,
147 SizeMin => llvm::PassBuilderOptLevel::Oz,
148 }
149}
150
f9f354fc
XL
151fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
152 match relocation_model {
153 RelocModel::Static => llvm::RelocModel::Static,
c295e0f8
XL
154 // LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra attribute.
155 RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
f9f354fc
XL
156 RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
157 RelocModel::Ropi => llvm::RelocModel::ROPI,
158 RelocModel::Rwpi => llvm::RelocModel::RWPI,
159 RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
160 }
161}
162
6a06907d 163pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
f9f354fc
XL
164 match code_model {
165 Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
166 Some(CodeModel::Small) => llvm::CodeModel::Small,
167 Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
168 Some(CodeModel::Medium) => llvm::CodeModel::Medium,
169 Some(CodeModel::Large) => llvm::CodeModel::Large,
170 None => llvm::CodeModel::None,
171 }
172}
173
dfeec247
XL
174pub fn target_machine_factory(
175 sess: &Session,
176 optlvl: config::OptLevel,
5e7ed085 177 target_features: &[String],
fc512014 178) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
f9f354fc 179 let reloc_model = to_llvm_relocation_model(sess.relocation_model());
1a4d82fc 180
9fa01778 181 let (opt_level, _) = to_llvm_opt_settings(optlvl);
1a4d82fc
JJ
182 let use_softfp = sess.opts.cg.soft_float;
183
29967ef6 184 let ffunction_sections =
064997fb 185 sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
1a4d82fc 186 let fdata_sections = ffunction_sections;
064997fb 187 let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
1a4d82fc 188
f9f354fc 189 let code_model = to_llvm_code_model(sess.code_model());
1a4d82fc 190
29967ef6 191 let mut singlethread = sess.target.singlethread;
abe05a73 192
b7449926
XL
193 // On the wasm target once the `atomics` feature is enabled that means that
194 // we're no longer single-threaded, or otherwise we don't want LLVM to
195 // lower atomic operations to single-threaded operations.
cdc7bbd5 196 if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
b7449926
XL
197 singlethread = false;
198 }
1a4d82fc 199
29967ef6 200 let triple = SmallCStr::new(&sess.target.llvm_target);
b7449926 201 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
5e7ed085 202 let features = CString::new(target_features.join(",")).unwrap();
29967ef6 203 let abi = SmallCStr::new(&sess.target.llvm_abiname);
fc512014 204 let trap_unreachable =
064997fb
FG
205 sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
206 let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
ea8adc8c 207
9c376795 208 let asm_comments = sess.opts.unstable_opts.asm_comments;
29967ef6 209 let relax_elf_relocations =
064997fb 210 sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
f9f354fc 211
29967ef6 212 let use_init_array =
064997fb 213 !sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
f9f354fc 214
a2a8927a
XL
215 let path_mapping = sess.source_map().path_mapping().clone();
216
353b0b11
FG
217 let force_emulated_tls = sess.target.force_emulated_tls;
218
fc512014 219 Arc::new(move |config: TargetMachineFactoryConfig| {
a2a8927a
XL
220 let split_dwarf_file =
221 path_mapping.map_prefix(config.split_dwarf_file.unwrap_or_default()).0;
fc512014
XL
222 let split_dwarf_file = CString::new(split_dwarf_file.to_str().unwrap()).unwrap();
223
ea8adc8c
XL
224 let tm = unsafe {
225 llvm::LLVMRustCreateTargetMachine(
dfeec247
XL
226 triple.as_ptr(),
227 cpu.as_ptr(),
228 features.as_ptr(),
229 abi.as_ptr(),
ea8adc8c
XL
230 code_model,
231 reloc_model,
232 opt_level,
233 use_softfp,
ea8adc8c
XL
234 ffunction_sections,
235 fdata_sections,
3c0e092e 236 funique_section_names,
abe05a73
XL
237 trap_unreachable,
238 singlethread,
b7449926 239 asm_comments,
0bf4aa26 240 emit_stack_size_section,
60c5eb7d 241 relax_elf_relocations,
f9f354fc 242 use_init_array,
fc512014 243 split_dwarf_file.as_ptr(),
353b0b11 244 force_emulated_tls,
ea8adc8c
XL
245 )
246 };
1a4d82fc 247
9ffffee4 248 tm.ok_or_else(|| LlvmError::CreateTargetMachine { triple: triple.clone() })
ea8adc8c 249 })
1a4d82fc
JJ
250}
251
a1dfa0c6
XL
252pub(crate) fn save_temp_bitcode(
253 cgcx: &CodegenContext<LlvmCodegenBackend>,
254 module: &ModuleCodegen<ModuleLlvm>,
dfeec247 255 name: &str,
a1dfa0c6
XL
256) {
257 if !cgcx.save_temps {
dfeec247 258 return;
ea8adc8c 259 }
a1dfa0c6
XL
260 unsafe {
261 let ext = format!("{}.bc", name);
262 let cgu = Some(&module.name[..]);
263 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
264 let cstr = path_to_c_string(&path);
265 let llmod = module.module_llvm.llmod();
266 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
ea8adc8c
XL
267 }
268}
269
b7449926 270pub struct DiagnosticHandlers<'a> {
a1dfa0c6 271 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
b7449926 272 llcx: &'a llvm::Context,
a2a8927a 273 old_handler: Option<&'a llvm::DiagnosticHandler>,
ea8adc8c
XL
274}
275
276impl<'a> DiagnosticHandlers<'a> {
dfeec247
XL
277 pub fn new(
278 cgcx: &'a CodegenContext<LlvmCodegenBackend>,
279 handler: &'a Handler,
280 llcx: &'a llvm::Context,
281 ) -> Self {
a2a8927a
XL
282 let remark_passes_all: bool;
283 let remark_passes: Vec<CString>;
284 match &cgcx.remark {
285 Passes::All => {
286 remark_passes_all = true;
287 remark_passes = Vec::new();
288 }
289 Passes::Some(passes) => {
290 remark_passes_all = false;
291 remark_passes =
292 passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
293 }
294 };
295 let remark_passes: Vec<*const c_char> =
296 remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
8faf50e0 297 let data = Box::into_raw(Box::new((cgcx, handler)));
ea8adc8c 298 unsafe {
a2a8927a
XL
299 let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
300 llvm::LLVMRustContextConfigureDiagnosticHandler(
301 llcx,
302 diagnostic_handler,
303 data.cast(),
304 remark_passes_all,
305 remark_passes.as_ptr(),
306 remark_passes.len(),
307 );
a2a8927a 308 DiagnosticHandlers { data, llcx, old_handler }
ea8adc8c
XL
309 }
310 }
1a4d82fc
JJ
311}
312
ea8adc8c
XL
313impl<'a> Drop for DiagnosticHandlers<'a> {
314 fn drop(&mut self) {
315 unsafe {
a2a8927a 316 llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
8faf50e0 317 drop(Box::from_raw(self.data));
ea8adc8c
XL
318 }
319 }
1a4d82fc
JJ
320}
321
f9f354fc 322fn report_inline_asm(
dfeec247 323 cgcx: &CodegenContext<LlvmCodegenBackend>,
f9f354fc 324 msg: String,
f035d41b 325 level: llvm::DiagnosticLevel,
f9f354fc
XL
326 mut cookie: c_uint,
327 source: Option<(String, Vec<InnerSpan>)>,
dfeec247 328) {
f9f354fc
XL
329 // In LTO build we may get srcloc values from other crates which are invalid
330 // since they use a different source map. To be safe we just suppress these
331 // in LTO builds.
332 if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
333 cookie = 0;
334 }
f035d41b 335 let level = match level {
3c0e092e 336 llvm::DiagnosticLevel::Error => Level::Error { lint: false },
923072b8 337 llvm::DiagnosticLevel::Warning => Level::Warning(None),
f035d41b
XL
338 llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
339 };
340 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
1a4d82fc
JJ
341}
342
b7449926 343unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
ea8adc8c 344 if user.is_null() {
dfeec247 345 return;
ea8adc8c 346 }
a1dfa0c6 347 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
1a4d82fc
JJ
348
349 match llvm::diagnostic::Diagnostic::unpack(info) {
85aaf69f 350 llvm::diagnostic::InlineAsm(inline) => {
94222f64 351 report_inline_asm(cgcx, inline.message, inline.level, inline.cookie, inline.source);
85aaf69f
SL
352 }
353
1a4d82fc 354 llvm::diagnostic::Optimization(opt) => {
1a4d82fc 355 let enabled = match cgcx.remark {
b7449926
XL
356 Passes::All => true,
357 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
1a4d82fc
JJ
358 };
359
360 if enabled {
9ffffee4
FG
361 diag_handler.emit_note(FromLlvmOptimizationDiag {
362 filename: &opt.filename,
363 line: opt.line,
364 column: opt.column,
365 pass_name: &opt.pass_name,
366 message: &opt.message,
367 });
1a4d82fc
JJ
368 }
369 }
dfeec247 370 llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
9ffffee4 371 let message = llvm::build_string(|s| {
0531ce1d 372 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
dfeec247
XL
373 })
374 .expect("non-UTF8 diagnostic");
9ffffee4 375 diag_handler.emit_warning(FromLlvmDiag { message });
0531ce1d 376 }
1b1a35ee 377 llvm::diagnostic::Unsupported(diagnostic_ref) => {
9ffffee4 378 let message = llvm::build_string(|s| {
1b1a35ee
XL
379 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
380 })
381 .expect("non-UTF8 diagnostic");
9ffffee4 382 diag_handler.emit_err(FromLlvmDiag { message });
1b1a35ee 383 }
dfeec247 384 llvm::diagnostic::UnknownDiagnostic(..) => {}
1a4d82fc
JJ
385 }
386}
387
74b04a01
XL
388fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
389 match config.pgo_gen {
390 SwitchWithOptPath::Enabled(ref opt_dir_path) => {
391 let path = if let Some(dir_path) = opt_dir_path {
392 dir_path.join("default_%m.profraw")
393 } else {
394 PathBuf::from("default_%m.profraw")
395 };
396
397 Some(CString::new(format!("{}", path.display())).unwrap())
398 }
399 SwitchWithOptPath::Disabled => None,
400 }
401}
402
403fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
404 config
405 .pgo_use
406 .as_ref()
407 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
408}
409
c295e0f8
XL
410fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
411 config
412 .pgo_sample_use
413 .as_ref()
414 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
415}
416
f2b60f7d 417fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
9ffffee4 418 config.instrument_coverage.then(|| CString::new("default_%m_%p.profraw").unwrap())
f2b60f7d
FG
419}
420
2b03887a 421pub(crate) unsafe fn llvm_optimize(
74b04a01 422 cgcx: &CodegenContext<LlvmCodegenBackend>,
17df50a5 423 diag_handler: &Handler,
74b04a01
XL
424 module: &ModuleCodegen<ModuleLlvm>,
425 config: &ModuleConfig,
426 opt_level: config::OptLevel,
427 opt_stage: llvm::OptStage,
17df50a5 428) -> Result<(), FatalError> {
74b04a01
XL
429 let unroll_loops =
430 opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
431 let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
432 let pgo_gen_path = get_pgo_gen_path(config);
433 let pgo_use_path = get_pgo_use_path(config);
c295e0f8 434 let pgo_sample_use_path = get_pgo_sample_use_path(config);
74b04a01 435 let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
f2b60f7d 436 let instr_profile_output_path = get_instr_profile_output_path(config);
74b04a01
XL
437 // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
438 let sanitizer_options = if !is_lto {
f035d41b
XL
439 Some(llvm::SanitizerOptions {
440 sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
441 sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
442 sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
443 sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
74b04a01 444 sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
f035d41b 445 sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
6a06907d
XL
446 sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
447 sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
9ffffee4
FG
448 sanitize_kernel_address: config.sanitizer.contains(SanitizerSet::KERNELADDRESS),
449 sanitize_kernel_address_recover: config
450 .sanitizer_recover
451 .contains(SanitizerSet::KERNELADDRESS),
74b04a01
XL
452 })
453 } else {
454 None
455 };
456
9ffffee4
FG
457 let mut llvm_profiler = cgcx
458 .prof
459 .llvm_recording_enabled()
460 .then(|| LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()));
74b04a01 461
c295e0f8
XL
462 let llvm_selfprofiler =
463 llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
464
923072b8 465 let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
17df50a5 466
a2a8927a
XL
467 let llvm_plugins = config.llvm_plugins.join(",");
468
74b04a01
XL
469 // FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
470 // We would have to add upstream support for this first, before we can support
471 // config.inline_threshold and our more aggressive default thresholds.
2b03887a 472 let result = llvm::LLVMRustOptimize(
74b04a01
XL
473 module.module_llvm.llmod(),
474 &*module.module_llvm.tm,
475 to_pass_builder_opt_level(opt_level),
476 opt_stage,
477 config.no_prepopulate_passes,
478 config.verify_llvm_ir,
479 using_thin_buffers,
480 config.merge_functions,
481 unroll_loops,
482 config.vectorize_slp,
483 config.vectorize_loop,
484 config.no_builtins,
f9f354fc 485 config.emit_lifetime_markers,
74b04a01
XL
486 sanitizer_options.as_ref(),
487 pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
488 pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
17df50a5 489 config.instrument_coverage,
f2b60f7d 490 instr_profile_output_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
17df50a5 491 config.instrument_gcov,
c295e0f8
XL
492 pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
493 config.debug_info_for_profiling,
74b04a01
XL
494 llvm_selfprofiler,
495 selfprofile_before_pass_callback,
496 selfprofile_after_pass_callback,
17df50a5
XL
497 extra_passes.as_ptr().cast(),
498 extra_passes.len(),
a2a8927a
XL
499 llvm_plugins.as_ptr().cast(),
500 llvm_plugins.len(),
74b04a01 501 );
9ffffee4 502 result.into_result().map_err(|()| llvm_err(diag_handler, LlvmError::RunLlvmPasses))
74b04a01
XL
503}
504
1a4d82fc 505// Unsafe due to LLVM calls.
dfeec247
XL
506pub(crate) unsafe fn optimize(
507 cgcx: &CodegenContext<LlvmCodegenBackend>,
508 diag_handler: &Handler,
509 module: &ModuleCodegen<ModuleLlvm>,
510 config: &ModuleConfig,
17df50a5 511) -> Result<(), FatalError> {
a2a8927a 512 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name);
e74abb32 513
b7449926
XL
514 let llmod = module.module_llvm.llmod();
515 let llcx = &*module.module_llvm.llcx;
ea8adc8c 516 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
1a4d82fc 517
94b46f34 518 let module_name = module.name.clone();
3b2f2976 519 let module_name = Some(&module_name[..]);
5bcae85e 520
1a4d82fc 521 if config.emit_no_opt_bc {
ea8adc8c 522 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
a1dfa0c6 523 let out = path_to_c_string(&out);
1a4d82fc
JJ
524 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
525 }
526
60c5eb7d 527 if let Some(opt_level) = config.opt_level {
2b03887a
FG
528 let opt_stage = match cgcx.lto {
529 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
530 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
531 _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
532 _ => llvm::OptStage::PreLinkNoLTO,
533 };
534 return llvm_optimize(cgcx, diag_handler, module, config, opt_level, opt_stage);
ea8adc8c 535 }
17df50a5 536 Ok(())
ea8adc8c 537}
1a4d82fc 538
1b1a35ee
XL
539pub(crate) fn link(
540 cgcx: &CodegenContext<LlvmCodegenBackend>,
541 diag_handler: &Handler,
542 mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
543) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
544 use super::lto::{Linker, ModuleBuffer};
2b03887a 545 // Sort the modules by name to ensure deterministic behavior.
1b1a35ee
XL
546 modules.sort_by(|a, b| a.name.cmp(&b.name));
547 let (first, elements) =
548 modules.split_first().expect("Bug! modules must contain at least one module.");
549
550 let mut linker = Linker::new(first.module_llvm.llmod());
551 for module in elements {
04454e1e 552 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_link_module", &*module.name);
1b1a35ee 553 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
c295e0f8 554 linker.add(buffer.data()).map_err(|()| {
9ffffee4 555 llvm_err(diag_handler, LlvmError::SerializeModule { name: &module.name })
1b1a35ee
XL
556 })?;
557 }
558 drop(linker);
559 Ok(modules.remove(0))
560}
561
dfeec247
XL
562pub(crate) unsafe fn codegen(
563 cgcx: &CodegenContext<LlvmCodegenBackend>,
564 diag_handler: &Handler,
565 module: ModuleCodegen<ModuleLlvm>,
566 config: &ModuleConfig,
567) -> Result<CompiledModule, FatalError> {
a2a8927a 568 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &*module.name);
1a4d82fc 569 {
b7449926
XL
570 let llmod = module.module_llvm.llmod();
571 let llcx = &*module.module_llvm.llcx;
572 let tm = &*module.module_llvm.tm;
573 let module_name = module.name.clone();
574 let module_name = Some(&module_name[..]);
575 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
1a4d82fc 576
b7449926
XL
577 if cgcx.msvc_imps_needed {
578 create_msvc_imps(cgcx, llcx, llmod);
579 }
580
581 // A codegen-specific pass manager is used to generate object
582 // files for an LLVM module.
583 //
584 // Apparently each of these pass managers is a one-shot kind of
585 // thing, so we create a new one for each type of output. The
586 // pass manager passed to the closure should be ensured to not
587 // escape the closure itself, and the manager should only be
588 // used once.
dfeec247
XL
589 unsafe fn with_codegen<'ll, F, R>(
590 tm: &'ll llvm::TargetMachine,
591 llmod: &'ll llvm::Module,
592 no_builtins: bool,
593 f: F,
594 ) -> R
595 where
596 F: FnOnce(&'ll mut PassManager<'ll>) -> R,
b7449926
XL
597 {
598 let cpm = llvm::LLVMCreatePassManager();
60c5eb7d 599 llvm::LLVMAddAnalysisPasses(tm, cpm);
b7449926
XL
600 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
601 f(cpm)
602 }
603
ba9703b0
XL
604 // Two things to note:
605 // - If object files are just LLVM bitcode we write bitcode, copy it to
606 // the .o file, and delete the bitcode if it wasn't otherwise
607 // requested.
608 // - If we don't have the integrated assembler then we need to emit
609 // asm from LLVM and use `gcc` to create the object file.
b7449926
XL
610
611 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
612 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
613
ba9703b0 614 if config.bitcode_needed() {
74b04a01
XL
615 let _timer = cgcx
616 .prof
a2a8927a 617 .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &*module.name);
064997fb 618 let thin = ThinBuffer::new(llmod, config.emit_thin_lto);
a1dfa0c6 619 let data = thin.data();
abe05a73 620
3c0e092e
XL
621 if let Some(bitcode_filename) = bc_out.file_name() {
622 cgcx.prof.artifact_size(
623 "llvm_bitcode",
624 bitcode_filename.to_string_lossy(),
625 data.len() as u64,
626 );
627 }
628
ba9703b0 629 if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
a2a8927a
XL
630 let _timer = cgcx
631 .prof
632 .generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
9ffffee4
FG
633 if let Err(err) = fs::write(&bc_out, data) {
634 diag_handler.emit_err(WriteBytecode { path: &bc_out, err });
b7449926 635 }
abe05a73 636 }
abe05a73 637
ba9703b0 638 if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
a2a8927a
XL
639 let _timer = cgcx
640 .prof
641 .generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name);
f9f354fc 642 embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
abe05a73 643 }
b7449926
XL
644 }
645
ba9703b0 646 if config.emit_ir {
a2a8927a
XL
647 let _timer =
648 cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &*module.name);
ba9703b0
XL
649 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
650 let out_c = path_to_c_string(&out);
651
652 extern "C" fn demangle_callback(
653 input_ptr: *const c_char,
654 input_len: size_t,
655 output_ptr: *mut c_char,
656 output_len: size_t,
657 ) -> size_t {
658 let input =
659 unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
660
5e7ed085 661 let Ok(input) = str::from_utf8(input) else { return 0 };
ba9703b0
XL
662
663 let output = unsafe {
664 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
665 };
666 let mut cursor = io::Cursor::new(output);
667
5e7ed085 668 let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
ba9703b0
XL
669
670 if write!(cursor, "{:#}", demangled).is_err() {
671 // Possible only if provided buffer is not big enough
672 return 0;
041b39d2
XL
673 }
674
ba9703b0 675 cursor.position() as size_t
041b39d2
XL
676 }
677
ba9703b0 678 let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
3c0e092e
XL
679
680 if result == llvm::LLVMRustResult::Success {
681 record_artifact_size(&cgcx.prof, "llvm_ir", &out);
682 }
683
9ffffee4
FG
684 result
685 .into_result()
686 .map_err(|()| llvm_err(diag_handler, LlvmError::WriteIr { path: &out }))?;
ba9703b0 687 }
9cc50fc6 688
ba9703b0 689 if config.emit_asm {
a2a8927a
XL
690 let _timer =
691 cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &*module.name);
ba9703b0
XL
692 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
693
694 // We can't use the same module for asm and object code output,
695 // because that triggers various errors like invalid IR or broken
696 // binaries. So we must clone the module to produce the asm output
697 // if we are also producing object code.
698 let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
699 llvm::LLVMCloneModule(llmod)
700 } else {
701 llmod
702 };
703 with_codegen(tm, llmod, config.no_builtins, |cpm| {
fc512014
XL
704 write_output_file(
705 diag_handler,
706 tm,
707 cpm,
708 llmod,
709 &path,
710 None,
711 llvm::FileType::AssemblyFile,
3c0e092e 712 &cgcx.prof,
fc512014 713 )
ba9703b0
XL
714 })?;
715 }
1a4d82fc 716
ba9703b0
XL
717 match config.emit_obj {
718 EmitObj::ObjectCode(_) => {
74b04a01
XL
719 let _timer = cgcx
720 .prof
a2a8927a 721 .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &*module.name);
fc512014
XL
722
723 let dwo_out = cgcx.output_filenames.temp_path_dwo(module_name);
a2a8927a
XL
724 let dwo_out = match (cgcx.split_debuginfo, cgcx.split_dwarf_kind) {
725 // Don't change how DWARF is emitted when disabled.
726 (SplitDebuginfo::Off, _) => None,
727 // Don't provide a DWARF object path if split debuginfo is enabled but this is
728 // a platform that doesn't support Split DWARF.
729 _ if !cgcx.target_can_use_split_dwarf => None,
730 // Don't provide a DWARF object path in single mode, sections will be written
731 // into the object as normal but ignored by linker.
732 (_, SplitDwarfKind::Single) => None,
733 // Emit (a subset of the) DWARF into a separate dwarf object file in split
734 // mode.
735 (_, SplitDwarfKind::Split) => Some(dwo_out.as_path()),
fc512014
XL
736 };
737
b7449926 738 with_codegen(tm, llmod, config.no_builtins, |cpm| {
dfeec247
XL
739 write_output_file(
740 diag_handler,
741 tm,
742 cpm,
743 llmod,
744 &obj_out,
fc512014 745 dwo_out,
dfeec247 746 llvm::FileType::ObjectFile,
3c0e092e 747 &cgcx.prof,
dfeec247 748 )
b7449926 749 })?;
ba9703b0 750 }
b7449926 751
ba9703b0
XL
752 EmitObj::Bitcode => {
753 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
9ffffee4
FG
754 if let Err(err) = link_or_copy(&bc_out, &obj_out) {
755 diag_handler.emit_err(CopyBitcode { err });
b7449926 756 }
1a4d82fc 757
ba9703b0
XL
758 if !config.emit_bc {
759 debug!("removing_bitcode {:?}", bc_out);
6a06907d 760 ensure_removed(diag_handler, &bc_out);
ba9703b0 761 }
b7449926 762 }
7453a54e 763
ba9703b0 764 EmitObj::None => {}
7453a54e 765 }
7453a54e 766
9ffffee4 767 record_llvm_cgu_instructions_stats(&cgcx.prof, llmod);
b7449926
XL
768 drop(handlers);
769 }
ba9703b0 770
487cf647
FG
771 // `.dwo` files are only emitted if:
772 //
773 // - Object files are being emitted (i.e. bitcode only or metadata only compilations will not
774 // produce dwarf objects, even if otherwise enabled)
775 // - Target supports Split DWARF
776 // - Split debuginfo is enabled
777 // - Split DWARF kind is `split` (i.e. debuginfo is split into `.dwo` files, not different
778 // sections in the `.o` files).
779 let dwarf_object_emitted = matches!(config.emit_obj, EmitObj::ObjectCode(_))
780 && cgcx.target_can_use_split_dwarf
781 && cgcx.split_debuginfo != SplitDebuginfo::Off
782 && cgcx.split_dwarf_kind == SplitDwarfKind::Split;
dfeec247 783 Ok(module.into_compiled_module(
ba9703b0 784 config.emit_obj != EmitObj::None,
487cf647 785 dwarf_object_emitted,
dfeec247 786 config.emit_bc,
dfeec247
XL
787 &cgcx.output_filenames,
788 ))
1a4d82fc
JJ
789}
790
a2a8927a
XL
791fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
792 let mut asm = format!(".section {},\"{}\"\n", section_name, section_flags).into_bytes();
793 asm.extend_from_slice(b".ascii \"");
794 asm.reserve(data.len());
795 for &byte in data {
796 if byte == b'\\' || byte == b'"' {
797 asm.push(b'\\');
798 asm.push(byte);
799 } else if byte < 0x20 || byte >= 0x80 {
800 // Avoid non UTF-8 inline assembly. Use octal escape sequence, because it is fixed
801 // width, while hex escapes will consume following characters.
802 asm.push(b'\\');
803 asm.push(b'0' + ((byte >> 6) & 0x7));
804 asm.push(b'0' + ((byte >> 3) & 0x7));
805 asm.push(b'0' + ((byte >> 0) & 0x7));
806 } else {
807 asm.push(byte);
808 }
809 }
810 asm.extend_from_slice(b"\"\n");
811 asm
812}
813
0531ce1d 814/// Embed the bitcode of an LLVM module in the LLVM module itself.
abe05a73 815///
0531ce1d
XL
816/// This is done primarily for iOS where it appears to be standard to compile C
817/// code at least with `-fembed-bitcode` which creates two sections in the
818/// executable:
819///
820/// * __LLVM,__bitcode
821/// * __LLVM,__cmdline
822///
823/// It appears *both* of these sections are necessary to get the linker to
f9f354fc
XL
824/// recognize what's going on. A suitable cmdline value is taken from the
825/// target spec.
0531ce1d
XL
826///
827/// Furthermore debug/O1 builds don't actually embed bitcode but rather just
828/// embed an empty section.
829///
830/// Basically all of this is us attempting to follow in the footsteps of clang
831/// on iOS. See #35968 for lots more info.
dfeec247
XL
832unsafe fn embed_bitcode(
833 cgcx: &CodegenContext<LlvmCodegenBackend>,
834 llcx: &llvm::Context,
835 llmod: &llvm::Module,
f9f354fc
XL
836 cmdline: &str,
837 bitcode: &[u8],
dfeec247 838) {
f9f354fc
XL
839 // We're adding custom sections to the output object file, but we definitely
840 // do not want these custom sections to make their way into the final linked
841 // executable. The purpose of these custom sections is for tooling
842 // surrounding object files to work with the LLVM IR, if necessary. For
843 // example rustc's own LTO will look for LLVM IR inside of the object file
844 // in these sections by default.
845 //
846 // To handle this is a bit different depending on the object file format
847 // used by the backend, broken down into a few different categories:
848 //
849 // * Mach-O - this is for macOS. Inspecting the source code for the native
850 // linker here shows that the `.llvmbc` and `.llvmcmd` sections are
851 // automatically skipped by the linker. In that case there's nothing extra
852 // that we need to do here.
853 //
854 // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
855 // `.llvmcmd` sections, so there's nothing extra we need to do.
856 //
857 // * COFF - if we don't do anything the linker will by default copy all
858 // these sections to the output artifact, not what we want! To subvert
859 // this we want to flag the sections we inserted here as
a2a8927a 860 // `IMAGE_SCN_LNK_REMOVE`.
f9f354fc
XL
861 //
862 // * ELF - this is very similar to COFF above. One difference is that these
863 // sections are removed from the output linked artifact when
864 // `--gc-sections` is passed, which we pass by default. If that flag isn't
865 // passed though then these sections will show up in the final output.
866 // Additionally the flag that we need to set here is `SHF_EXCLUDE`.
a2a8927a
XL
867 //
868 // Unfortunately, LLVM provides no way to set custom section flags. For ELF
869 // and COFF we emit the sections using module level inline assembly for that
870 // reason (see issue #90326 for historical background).
871 let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
872 || cgcx.opts.target_triple.triple().contains("-darwin")
923072b8
FG
873 || cgcx.opts.target_triple.triple().contains("-tvos")
874 || cgcx.opts.target_triple.triple().contains("-watchos");
f9f354fc
XL
875 if is_apple
876 || cgcx.opts.target_triple.triple().starts_with("wasm")
877 || cgcx.opts.target_triple.triple().starts_with("asmjs")
878 {
a2a8927a
XL
879 // We don't need custom section flags, create LLVM globals.
880 let llconst = common::bytes_in_context(llcx, bitcode);
881 let llglobal = llvm::LLVMAddGlobal(
882 llmod,
883 common::val_ty(llconst),
884 "rustc.embedded.module\0".as_ptr().cast(),
885 );
886 llvm::LLVMSetInitializer(llglobal, llconst);
887
888 let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
889 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
890 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
891 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
892
893 let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
894 let llglobal = llvm::LLVMAddGlobal(
895 llmod,
896 common::val_ty(llconst),
897 "rustc.embedded.cmdline\0".as_ptr().cast(),
898 );
899 llvm::LLVMSetInitializer(llglobal, llconst);
900 let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
901 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
902 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
f9f354fc 903 } else {
a2a8927a
XL
904 // We need custom section flags, so emit module-level inline assembly.
905 let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
906 let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
353b0b11 907 llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
a2a8927a 908 let asm = create_section_with_flags_asm(".llvmcmd", section_flags, cmdline.as_bytes());
353b0b11 909 llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
f9f354fc 910 }
abe05a73
XL
911}
912
abe05a73
XL
913// Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
914// This is required to satisfy `dllimport` references to static data in .rlibs
9c376795 915// when using MSVC linker. We do this only for data, as linker can fix up
abe05a73
XL
916// code references on its own.
917// See #26591, #27438
a1dfa0c6
XL
918fn create_msvc_imps(
919 cgcx: &CodegenContext<LlvmCodegenBackend>,
920 llcx: &llvm::Context,
dfeec247 921 llmod: &llvm::Module,
a1dfa0c6 922) {
abe05a73 923 if !cgcx.msvc_imps_needed {
dfeec247 924 return;
abe05a73
XL
925 }
926 // The x86 ABI seems to require that leading underscores are added to symbol
48663c56 927 // names, so we need an extra underscore on x86. There's also a leading
0731742a 928 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
abe05a73 929 // underscores added in front).
dfeec247 930 let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
48663c56 931
abe05a73
XL
932 unsafe {
933 let i8p_ty = Type::i8p_llcx(llcx);
934 let globals = base::iter_globals(llmod)
935 .filter(|&val| {
dfeec247
XL
936 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
937 && llvm::LLVMIsDeclaration(val) == 0
abe05a73 938 })
48663c56
XL
939 .filter_map(|val| {
940 // Exclude some symbols that we know are not Rust symbols.
60c5eb7d 941 let name = llvm::get_value_name(val);
dfeec247 942 if ignored(name) { None } else { Some((val, name)) }
48663c56
XL
943 })
944 .map(move |(val, name)| {
abe05a73 945 let mut imp_name = prefix.as_bytes().to_vec();
60c5eb7d 946 imp_name.extend(name);
abe05a73
XL
947 let imp_name = CString::new(imp_name).unwrap();
948 (imp_name, val)
949 })
950 .collect::<Vec<_>>();
48663c56 951
abe05a73 952 for (imp_name, val) in globals {
dfeec247 953 let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
abe05a73
XL
954 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
955 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
956 }
957 }
48663c56
XL
958
959 // Use this function to exclude certain symbols from `__imp` generation.
960 fn ignored(symbol_name: &[u8]) -> bool {
961 // These are symbols generated by LLVM's profiling instrumentation
962 symbol_name.starts_with(b"__llvm_profile_")
963 }
abe05a73 964}
3c0e092e
XL
965
966fn record_artifact_size(
967 self_profiler_ref: &SelfProfilerRef,
968 artifact_kind: &'static str,
969 path: &Path,
970) {
971 // Don't stat the file if we are not going to record its size.
972 if !self_profiler_ref.enabled() {
973 return;
974 }
975
976 if let Some(artifact_name) = path.file_name() {
977 let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
978 self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);
979 }
980}
9ffffee4
FG
981
982fn record_llvm_cgu_instructions_stats(prof: &SelfProfilerRef, llmod: &llvm::Module) {
983 if !prof.enabled() {
984 return;
985 }
986
987 let raw_stats =
988 llvm::build_string(|s| unsafe { llvm::LLVMRustModuleInstructionStats(&llmod, s) })
989 .expect("cannot get module instruction stats");
990
991 #[derive(serde::Deserialize)]
992 struct InstructionsStats {
993 module: String,
994 total: u64,
995 }
996
997 let InstructionsStats { module, total } =
998 serde_json::from_str(&raw_stats).expect("cannot parse llvm cgu instructions stats");
999 prof.artifact_size("cgu_instructions", module, total);
1000}