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