]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/back/write.rs
Auto merge of #67831 - mati865:ci-images-upgrade, r=pietroalbini
[rust.git] / src / librustc_codegen_llvm / back / write.rs
1 use crate::attributes;
2 use crate::back::bytecode;
3 use crate::back::lto::ThinBuffer;
4 use crate::base;
5 use crate::common;
6 use crate::consts;
7 use crate::context::{get_reloc_model, is_pie_binary};
8 use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
9 use crate::llvm_util;
10 use crate::type_::Type;
11 use crate::LlvmCodegenBackend;
12 use crate::ModuleLlvm;
13 use log::debug;
14 use rustc::bug;
15 use rustc::session::config::{self, Lto, OutputType, Passes, Sanitizer, SwitchWithOptPath};
16 use rustc::session::Session;
17 use rustc::ty::TyCtxt;
18 use rustc_codegen_ssa::back::write::{run_assembler, CodegenContext, ModuleConfig};
19 use rustc_codegen_ssa::traits::*;
20 use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, RLIB_BYTECODE_EXTENSION};
21 use rustc_data_structures::small_c_str::SmallCStr;
22 use rustc_errors::{FatalError, Handler};
23 use rustc_fs_util::{link_or_copy, path_to_c_string};
24 use rustc_hir::def_id::LOCAL_CRATE;
25
26 use libc::{c_char, c_int, c_uint, c_void, size_t};
27 use std::ffi::CString;
28 use std::fs;
29 use std::io::{self, Write};
30 use std::path::{Path, PathBuf};
31 use std::slice;
32 use std::str;
33 use std::sync::Arc;
34
35 pub const RELOC_MODEL_ARGS: [(&str, llvm::RelocMode); 7] = [
36     ("pic", llvm::RelocMode::PIC),
37     ("static", llvm::RelocMode::Static),
38     ("default", llvm::RelocMode::Default),
39     ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
40     ("ropi", llvm::RelocMode::ROPI),
41     ("rwpi", llvm::RelocMode::RWPI),
42     ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
43 ];
44
45 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
46     ("small", llvm::CodeModel::Small),
47     ("kernel", llvm::CodeModel::Kernel),
48     ("medium", llvm::CodeModel::Medium),
49     ("large", llvm::CodeModel::Large),
50 ];
51
52 pub const TLS_MODEL_ARGS: [(&str, llvm::ThreadLocalMode); 4] = [
53     ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
54     ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
55     ("initial-exec", llvm::ThreadLocalMode::InitialExec),
56     ("local-exec", llvm::ThreadLocalMode::LocalExec),
57 ];
58
59 pub fn llvm_err(handler: &rustc_errors::Handler, msg: &str) -> FatalError {
60     match llvm::last_error() {
61         Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
62         None => handler.fatal(&msg),
63     }
64 }
65
66 pub fn write_output_file(
67     handler: &rustc_errors::Handler,
68     target: &'ll llvm::TargetMachine,
69     pm: &llvm::PassManager<'ll>,
70     m: &'ll llvm::Module,
71     output: &Path,
72     file_type: llvm::FileType,
73 ) -> Result<(), FatalError> {
74     unsafe {
75         let output_c = path_to_c_string(output);
76         let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
77         result.into_result().map_err(|()| {
78             let msg = format!("could not write output to {}", output.display());
79             llvm_err(handler, &msg)
80         })
81     }
82 }
83
84 pub fn create_informational_target_machine(
85     sess: &Session,
86     find_features: bool,
87 ) -> &'static mut llvm::TargetMachine {
88     target_machine_factory(sess, config::OptLevel::No, find_features)()
89         .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
90 }
91
92 pub fn create_target_machine(
93     tcx: TyCtxt<'_>,
94     find_features: bool,
95 ) -> &'static mut llvm::TargetMachine {
96     target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE), find_features)()
97         .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
98 }
99
100 pub fn to_llvm_opt_settings(
101     cfg: config::OptLevel,
102 ) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
103     use self::config::OptLevel::*;
104     match cfg {
105         No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
106         Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
107         Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
108         Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
109         Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
110         SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
111     }
112 }
113
114 // If find_features is true this won't access `sess.crate_types` by assuming
115 // that `is_pie_binary` is false. When we discover LLVM target features
116 // `sess.crate_types` is uninitialized so we cannot access it.
117 pub fn target_machine_factory(
118     sess: &Session,
119     optlvl: config::OptLevel,
120     find_features: bool,
121 ) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
122     let reloc_model = get_reloc_model(sess);
123
124     let (opt_level, _) = to_llvm_opt_settings(optlvl);
125     let use_softfp = sess.opts.cg.soft_float;
126
127     let ffunction_sections = sess.target.target.options.function_sections;
128     let fdata_sections = ffunction_sections;
129
130     let code_model_arg =
131         sess.opts.cg.code_model.as_ref().or(sess.target.target.options.code_model.as_ref());
132
133     let code_model = match code_model_arg {
134         Some(s) => match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
135             Some(x) => x.1,
136             _ => {
137                 sess.err(&format!("{:?} is not a valid code model", code_model_arg));
138                 sess.abort_if_errors();
139                 bug!();
140             }
141         },
142         None => llvm::CodeModel::None,
143     };
144
145     let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
146     let mut singlethread = sess.target.target.options.singlethread;
147
148     // On the wasm target once the `atomics` feature is enabled that means that
149     // we're no longer single-threaded, or otherwise we don't want LLVM to
150     // lower atomic operations to single-threaded operations.
151     if singlethread
152         && sess.target.target.llvm_target.contains("wasm32")
153         && features.iter().any(|s| *s == "+atomics")
154     {
155         singlethread = false;
156     }
157
158     let triple = SmallCStr::new(&sess.target.target.llvm_target);
159     let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
160     let features = features.join(",");
161     let features = CString::new(features).unwrap();
162     let abi = SmallCStr::new(&sess.target.target.options.llvm_abiname);
163     let is_pie_binary = !find_features && is_pie_binary(sess);
164     let trap_unreachable = sess.target.target.options.trap_unreachable;
165     let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
166
167     let asm_comments = sess.asm_comments();
168     let relax_elf_relocations = sess.target.target.options.relax_elf_relocations;
169     Arc::new(move || {
170         let tm = unsafe {
171             llvm::LLVMRustCreateTargetMachine(
172                 triple.as_ptr(),
173                 cpu.as_ptr(),
174                 features.as_ptr(),
175                 abi.as_ptr(),
176                 code_model,
177                 reloc_model,
178                 opt_level,
179                 use_softfp,
180                 is_pie_binary,
181                 ffunction_sections,
182                 fdata_sections,
183                 trap_unreachable,
184                 singlethread,
185                 asm_comments,
186                 emit_stack_size_section,
187                 relax_elf_relocations,
188             )
189         };
190
191         tm.ok_or_else(|| {
192             format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
193         })
194     })
195 }
196
197 pub(crate) fn save_temp_bitcode(
198     cgcx: &CodegenContext<LlvmCodegenBackend>,
199     module: &ModuleCodegen<ModuleLlvm>,
200     name: &str,
201 ) {
202     if !cgcx.save_temps {
203         return;
204     }
205     unsafe {
206         let ext = format!("{}.bc", name);
207         let cgu = Some(&module.name[..]);
208         let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
209         let cstr = path_to_c_string(&path);
210         let llmod = module.module_llvm.llmod();
211         llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
212     }
213 }
214
215 pub struct DiagnosticHandlers<'a> {
216     data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
217     llcx: &'a llvm::Context,
218 }
219
220 impl<'a> DiagnosticHandlers<'a> {
221     pub fn new(
222         cgcx: &'a CodegenContext<LlvmCodegenBackend>,
223         handler: &'a Handler,
224         llcx: &'a llvm::Context,
225     ) -> Self {
226         let data = Box::into_raw(Box::new((cgcx, handler)));
227         unsafe {
228             llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data.cast());
229             llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data.cast());
230         }
231         DiagnosticHandlers { data, llcx }
232     }
233 }
234
235 impl<'a> Drop for DiagnosticHandlers<'a> {
236     fn drop(&mut self) {
237         use std::ptr::null_mut;
238         unsafe {
239             llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
240             llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
241             drop(Box::from_raw(self.data));
242         }
243     }
244 }
245
246 unsafe extern "C" fn report_inline_asm(
247     cgcx: &CodegenContext<LlvmCodegenBackend>,
248     msg: &str,
249     cookie: c_uint,
250 ) {
251     cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
252 }
253
254 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, user: *const c_void, cookie: c_uint) {
255     if user.is_null() {
256         return;
257     }
258     let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
259
260     let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
261         .expect("non-UTF8 SMDiagnostic");
262
263     report_inline_asm(cgcx, &msg, cookie);
264 }
265
266 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
267     if user.is_null() {
268         return;
269     }
270     let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
271
272     match llvm::diagnostic::Diagnostic::unpack(info) {
273         llvm::diagnostic::InlineAsm(inline) => {
274             report_inline_asm(cgcx, &llvm::twine_to_string(inline.message), inline.cookie);
275         }
276
277         llvm::diagnostic::Optimization(opt) => {
278             let enabled = match cgcx.remark {
279                 Passes::All => true,
280                 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
281             };
282
283             if enabled {
284                 diag_handler.note_without_error(&format!(
285                     "optimization {} for {} at {}:{}:{}: {}",
286                     opt.kind.describe(),
287                     opt.pass_name,
288                     opt.filename,
289                     opt.line,
290                     opt.column,
291                     opt.message
292                 ));
293             }
294         }
295         llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
296             let msg = llvm::build_string(|s| {
297                 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
298             })
299             .expect("non-UTF8 diagnostic");
300             diag_handler.warn(&msg);
301         }
302         llvm::diagnostic::UnknownDiagnostic(..) => {}
303     }
304 }
305
306 // Unsafe due to LLVM calls.
307 pub(crate) unsafe fn optimize(
308     cgcx: &CodegenContext<LlvmCodegenBackend>,
309     diag_handler: &Handler,
310     module: &ModuleCodegen<ModuleLlvm>,
311     config: &ModuleConfig,
312 ) -> Result<(), FatalError> {
313     let _timer = cgcx.prof.generic_activity("LLVM_module_optimize");
314
315     let llmod = module.module_llvm.llmod();
316     let llcx = &*module.module_llvm.llcx;
317     let tm = &*module.module_llvm.tm;
318     let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
319
320     let module_name = module.name.clone();
321     let module_name = Some(&module_name[..]);
322
323     if config.emit_no_opt_bc {
324         let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
325         let out = path_to_c_string(&out);
326         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
327     }
328
329     if let Some(opt_level) = config.opt_level {
330         // Create the two optimizing pass managers. These mirror what clang
331         // does, and are by populated by LLVM's default PassManagerBuilder.
332         // Each manager has a different set of passes, but they also share
333         // some common passes.
334         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
335         let mpm = llvm::LLVMCreatePassManager();
336
337         {
338             let find_pass = |pass_name: &str| {
339                 let pass_name = SmallCStr::new(pass_name);
340                 llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr())
341             };
342
343             if config.verify_llvm_ir {
344                 // Verification should run as the very first pass.
345                 llvm::LLVMRustAddPass(fpm, find_pass("verify").unwrap());
346             }
347
348             let mut extra_passes = Vec::new();
349             let mut have_name_anon_globals_pass = false;
350
351             for pass_name in &config.passes {
352                 if pass_name == "lint" {
353                     // Linting should also be performed early, directly on the generated IR.
354                     llvm::LLVMRustAddPass(fpm, find_pass("lint").unwrap());
355                     continue;
356                 }
357
358                 if let Some(pass) = find_pass(pass_name) {
359                     extra_passes.push(pass);
360                 } else {
361                     diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass_name));
362                 }
363
364                 if pass_name == "name-anon-globals" {
365                     have_name_anon_globals_pass = true;
366                 }
367             }
368
369             add_sanitizer_passes(config, &mut extra_passes);
370
371             // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
372             // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
373             // we'll get errors in LLVM.
374             let using_thin_buffers = config.bitcode_needed();
375             if !config.no_prepopulate_passes {
376                 llvm::LLVMAddAnalysisPasses(tm, fpm);
377                 llvm::LLVMAddAnalysisPasses(tm, mpm);
378                 let opt_level = to_llvm_opt_settings(opt_level).0;
379                 let prepare_for_thin_lto = cgcx.lto == Lto::Thin
380                     || cgcx.lto == Lto::ThinLocal
381                     || (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
382                 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
383                     llvm::LLVMRustAddLastExtensionPasses(
384                         b,
385                         extra_passes.as_ptr(),
386                         extra_passes.len() as size_t,
387                     );
388                     llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
389                     llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
390                 });
391
392                 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
393                 if using_thin_buffers && !prepare_for_thin_lto {
394                     llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
395                     have_name_anon_globals_pass = true;
396                 }
397             } else {
398                 // If we don't use the standard pipeline, directly populate the MPM
399                 // with the extra passes.
400                 for pass in extra_passes {
401                     llvm::LLVMRustAddPass(mpm, pass);
402                 }
403             }
404
405             if using_thin_buffers && !have_name_anon_globals_pass {
406                 // As described above, this will probably cause an error in LLVM
407                 if config.no_prepopulate_passes {
408                     diag_handler.err(
409                         "The current compilation is going to use thin LTO buffers \
410                                       without running LLVM's NameAnonGlobals pass. \
411                                       This will likely cause errors in LLVM. Consider adding \
412                                       -C passes=name-anon-globals to the compiler command line.",
413                     );
414                 } else {
415                     bug!(
416                         "We are using thin LTO buffers without running the NameAnonGlobals pass. \
417                           This will likely cause errors in LLVM and should never happen."
418                     );
419                 }
420             }
421         }
422
423         diag_handler.abort_if_errors();
424
425         // Finally, run the actual optimization passes
426         {
427             let _timer = cgcx.prof.generic_activity("LLVM_module_optimize_function_passes");
428             let desc = &format!("llvm function passes [{}]", module_name.unwrap());
429             let _timer = if config.time_module {
430                 Some(cgcx.prof.extra_verbose_generic_activity(desc))
431             } else {
432                 None
433             };
434             llvm::LLVMRustRunFunctionPassManager(fpm, llmod);
435         }
436         {
437             let _timer = cgcx.prof.generic_activity("LLVM_module_optimize_module_passes");
438             let desc = &format!("llvm module passes [{}]", module_name.unwrap());
439             let _timer = if config.time_module {
440                 Some(cgcx.prof.extra_verbose_generic_activity(desc))
441             } else {
442                 None
443             };
444             llvm::LLVMRunPassManager(mpm, llmod);
445         }
446
447         // Deallocate managers that we're now done with
448         llvm::LLVMDisposePassManager(fpm);
449         llvm::LLVMDisposePassManager(mpm);
450     }
451     Ok(())
452 }
453
454 unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) {
455     let sanitizer = match &config.sanitizer {
456         None => return,
457         Some(s) => s,
458     };
459
460     let recover = config.sanitizer_recover.contains(sanitizer);
461     match sanitizer {
462         Sanitizer::Address => {
463             passes.push(llvm::LLVMRustCreateAddressSanitizerFunctionPass(recover));
464             passes.push(llvm::LLVMRustCreateModuleAddressSanitizerPass(recover));
465         }
466         Sanitizer::Memory => {
467             let track_origins = config.sanitizer_memory_track_origins as c_int;
468             passes.push(llvm::LLVMRustCreateMemorySanitizerPass(track_origins, recover));
469         }
470         Sanitizer::Thread => {
471             passes.push(llvm::LLVMRustCreateThreadSanitizerPass());
472         }
473         Sanitizer::Leak => {}
474     }
475 }
476
477 pub(crate) unsafe fn codegen(
478     cgcx: &CodegenContext<LlvmCodegenBackend>,
479     diag_handler: &Handler,
480     module: ModuleCodegen<ModuleLlvm>,
481     config: &ModuleConfig,
482 ) -> Result<CompiledModule, FatalError> {
483     let _timer = cgcx.prof.generic_activity("LLVM_module_codegen");
484     {
485         let llmod = module.module_llvm.llmod();
486         let llcx = &*module.module_llvm.llcx;
487         let tm = &*module.module_llvm.tm;
488         let module_name = module.name.clone();
489         let module_name = Some(&module_name[..]);
490         let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
491
492         if cgcx.msvc_imps_needed {
493             create_msvc_imps(cgcx, llcx, llmod);
494         }
495
496         // A codegen-specific pass manager is used to generate object
497         // files for an LLVM module.
498         //
499         // Apparently each of these pass managers is a one-shot kind of
500         // thing, so we create a new one for each type of output. The
501         // pass manager passed to the closure should be ensured to not
502         // escape the closure itself, and the manager should only be
503         // used once.
504         unsafe fn with_codegen<'ll, F, R>(
505             tm: &'ll llvm::TargetMachine,
506             llmod: &'ll llvm::Module,
507             no_builtins: bool,
508             f: F,
509         ) -> R
510         where
511             F: FnOnce(&'ll mut PassManager<'ll>) -> R,
512         {
513             let cpm = llvm::LLVMCreatePassManager();
514             llvm::LLVMAddAnalysisPasses(tm, cpm);
515             llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
516             f(cpm)
517         }
518
519         // If we don't have the integrated assembler, then we need to emit asm
520         // from LLVM and use `gcc` to create the object file.
521         let asm_to_obj = config.emit_obj && config.no_integrated_as;
522
523         // Change what we write and cleanup based on whether obj files are
524         // just llvm bitcode. In that case write bitcode, and possibly
525         // delete the bitcode if it wasn't requested. Don't generate the
526         // machine code, instead copy the .o file from the .bc
527         let write_bc = config.emit_bc || config.obj_is_bitcode;
528         let rm_bc = !config.emit_bc && config.obj_is_bitcode;
529         let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
530         let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
531
532         let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
533         let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
534
535         if write_bc || config.emit_bc_compressed || config.embed_bitcode {
536             let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_make_bitcode");
537             let thin = ThinBuffer::new(llmod);
538             let data = thin.data();
539
540             if write_bc {
541                 let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_emit_bitcode");
542                 if let Err(e) = fs::write(&bc_out, data) {
543                     let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
544                     diag_handler.err(&msg);
545                 }
546             }
547
548             if config.embed_bitcode {
549                 let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_embed_bitcode");
550                 embed_bitcode(cgcx, llcx, llmod, Some(data));
551             }
552
553             if config.emit_bc_compressed {
554                 let _timer =
555                     cgcx.prof.generic_activity("LLVM_module_codegen_emit_compressed_bitcode");
556                 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
557                 let data = bytecode::encode(&module.name, data);
558                 if let Err(e) = fs::write(&dst, data) {
559                     let msg = format!("failed to write bytecode to {}: {}", dst.display(), e);
560                     diag_handler.err(&msg);
561                 }
562             }
563         } else if config.embed_bitcode_marker {
564             embed_bitcode(cgcx, llcx, llmod, None);
565         }
566
567         {
568             let desc = &format!("codegen passes [{}]", module_name.unwrap());
569             let _timer = if config.time_module {
570                 Some(cgcx.prof.extra_verbose_generic_activity(desc))
571             } else {
572                 None
573             };
574
575             if config.emit_ir {
576                 let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_emit_ir");
577                 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
578                 let out_c = path_to_c_string(&out);
579
580                 extern "C" fn demangle_callback(
581                     input_ptr: *const c_char,
582                     input_len: size_t,
583                     output_ptr: *mut c_char,
584                     output_len: size_t,
585                 ) -> size_t {
586                     let input = unsafe {
587                         slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
588                     };
589
590                     let input = match str::from_utf8(input) {
591                         Ok(s) => s,
592                         Err(_) => return 0,
593                     };
594
595                     let output = unsafe {
596                         slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
597                     };
598                     let mut cursor = io::Cursor::new(output);
599
600                     let demangled = match rustc_demangle::try_demangle(input) {
601                         Ok(d) => d,
602                         Err(_) => return 0,
603                     };
604
605                     if let Err(_) = write!(cursor, "{:#}", demangled) {
606                         // Possible only if provided buffer is not big enough
607                         return 0;
608                     }
609
610                     cursor.position() as size_t
611                 }
612
613                 let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
614                 result.into_result().map_err(|()| {
615                     let msg = format!("failed to write LLVM IR to {}", out.display());
616                     llvm_err(diag_handler, &msg)
617                 })?;
618             }
619
620             if config.emit_asm || asm_to_obj {
621                 let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_emit_asm");
622                 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
623
624                 // We can't use the same module for asm and binary output, because that triggers
625                 // various errors like invalid IR or broken binaries, so we might have to clone the
626                 // module to produce the asm output
627                 let llmod = if config.emit_obj { llvm::LLVMCloneModule(llmod) } else { llmod };
628                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
629                     write_output_file(
630                         diag_handler,
631                         tm,
632                         cpm,
633                         llmod,
634                         &path,
635                         llvm::FileType::AssemblyFile,
636                     )
637                 })?;
638             }
639
640             if write_obj {
641                 let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_emit_obj");
642                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
643                     write_output_file(
644                         diag_handler,
645                         tm,
646                         cpm,
647                         llmod,
648                         &obj_out,
649                         llvm::FileType::ObjectFile,
650                     )
651                 })?;
652             } else if asm_to_obj {
653                 let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_asm_to_obj");
654                 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
655                 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
656
657                 if !config.emit_asm && !cgcx.save_temps {
658                     drop(fs::remove_file(&assembly));
659                 }
660             }
661         }
662
663         if copy_bc_to_obj {
664             debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
665             if let Err(e) = link_or_copy(&bc_out, &obj_out) {
666                 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
667             }
668         }
669
670         if rm_bc {
671             debug!("removing_bitcode {:?}", bc_out);
672             if let Err(e) = fs::remove_file(&bc_out) {
673                 diag_handler.err(&format!("failed to remove bitcode: {}", e));
674             }
675         }
676
677         drop(handlers);
678     }
679     Ok(module.into_compiled_module(
680         config.emit_obj,
681         config.emit_bc,
682         config.emit_bc_compressed,
683         &cgcx.output_filenames,
684     ))
685 }
686
687 /// Embed the bitcode of an LLVM module in the LLVM module itself.
688 ///
689 /// This is done primarily for iOS where it appears to be standard to compile C
690 /// code at least with `-fembed-bitcode` which creates two sections in the
691 /// executable:
692 ///
693 /// * __LLVM,__bitcode
694 /// * __LLVM,__cmdline
695 ///
696 /// It appears *both* of these sections are necessary to get the linker to
697 /// recognize what's going on. For us though we just always throw in an empty
698 /// cmdline section.
699 ///
700 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
701 /// embed an empty section.
702 ///
703 /// Basically all of this is us attempting to follow in the footsteps of clang
704 /// on iOS. See #35968 for lots more info.
705 unsafe fn embed_bitcode(
706     cgcx: &CodegenContext<LlvmCodegenBackend>,
707     llcx: &llvm::Context,
708     llmod: &llvm::Module,
709     bitcode: Option<&[u8]>,
710 ) {
711     let llconst = common::bytes_in_context(llcx, bitcode.unwrap_or(&[]));
712     let llglobal = llvm::LLVMAddGlobal(
713         llmod,
714         common::val_ty(llconst),
715         "rustc.embedded.module\0".as_ptr().cast(),
716     );
717     llvm::LLVMSetInitializer(llglobal, llconst);
718
719     let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
720         || cgcx.opts.target_triple.triple().contains("-darwin");
721
722     let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
723     llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
724     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
725     llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
726
727     let llconst = common::bytes_in_context(llcx, &[]);
728     let llglobal = llvm::LLVMAddGlobal(
729         llmod,
730         common::val_ty(llconst),
731         "rustc.embedded.cmdline\0".as_ptr().cast(),
732     );
733     llvm::LLVMSetInitializer(llglobal, llconst);
734     let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
735     llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
736     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
737 }
738
739 pub unsafe fn with_llvm_pmb(
740     llmod: &llvm::Module,
741     config: &ModuleConfig,
742     opt_level: llvm::CodeGenOptLevel,
743     prepare_for_thin_lto: bool,
744     f: &mut dyn FnMut(&llvm::PassManagerBuilder),
745 ) {
746     use std::ptr;
747
748     // Create the PassManagerBuilder for LLVM. We configure it with
749     // reasonable defaults and prepare it to actually populate the pass
750     // manager.
751     let builder = llvm::LLVMPassManagerBuilderCreate();
752     let opt_size =
753         config.opt_size.map(|x| to_llvm_opt_settings(x).1).unwrap_or(llvm::CodeGenOptSizeNone);
754     let inline_threshold = config.inline_threshold;
755
756     let pgo_gen_path = match config.pgo_gen {
757         SwitchWithOptPath::Enabled(ref opt_dir_path) => {
758             let path = if let Some(dir_path) = opt_dir_path {
759                 dir_path.join("default_%m.profraw")
760             } else {
761                 PathBuf::from("default_%m.profraw")
762             };
763
764             Some(CString::new(format!("{}", path.display())).unwrap())
765         }
766         SwitchWithOptPath::Disabled => None,
767     };
768
769     let pgo_use_path = config
770         .pgo_use
771         .as_ref()
772         .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap());
773
774     llvm::LLVMRustConfigurePassManagerBuilder(
775         builder,
776         opt_level,
777         config.merge_functions,
778         config.vectorize_slp,
779         config.vectorize_loop,
780         prepare_for_thin_lto,
781         pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
782         pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
783     );
784
785     llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
786
787     if opt_size != llvm::CodeGenOptSizeNone {
788         llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
789     }
790
791     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
792
793     // Here we match what clang does (kinda). For O0 we only inline
794     // always-inline functions (but don't add lifetime intrinsics), at O1 we
795     // inline with lifetime intrinsics, and O2+ we add an inliner with a
796     // thresholds copied from clang.
797     match (opt_level, opt_size, inline_threshold) {
798         (.., Some(t)) => {
799             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
800         }
801         (llvm::CodeGenOptLevel::Aggressive, ..) => {
802             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
803         }
804         (_, llvm::CodeGenOptSizeDefault, _) => {
805             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
806         }
807         (_, llvm::CodeGenOptSizeAggressive, _) => {
808             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
809         }
810         (llvm::CodeGenOptLevel::None, ..) => {
811             llvm::LLVMRustAddAlwaysInlinePass(builder, false);
812         }
813         (llvm::CodeGenOptLevel::Less, ..) => {
814             llvm::LLVMRustAddAlwaysInlinePass(builder, true);
815         }
816         (llvm::CodeGenOptLevel::Default, ..) => {
817             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
818         }
819         (llvm::CodeGenOptLevel::Other, ..) => bug!("CodeGenOptLevel::Other selected"),
820     }
821
822     f(builder);
823     llvm::LLVMPassManagerBuilderDispose(builder);
824 }
825
826 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
827 // This is required to satisfy `dllimport` references to static data in .rlibs
828 // when using MSVC linker.  We do this only for data, as linker can fix up
829 // code references on its own.
830 // See #26591, #27438
831 fn create_msvc_imps(
832     cgcx: &CodegenContext<LlvmCodegenBackend>,
833     llcx: &llvm::Context,
834     llmod: &llvm::Module,
835 ) {
836     if !cgcx.msvc_imps_needed {
837         return;
838     }
839     // The x86 ABI seems to require that leading underscores are added to symbol
840     // names, so we need an extra underscore on x86. There's also a leading
841     // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
842     // underscores added in front).
843     let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
844
845     unsafe {
846         let i8p_ty = Type::i8p_llcx(llcx);
847         let globals = base::iter_globals(llmod)
848             .filter(|&val| {
849                 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
850                     && llvm::LLVMIsDeclaration(val) == 0
851             })
852             .filter_map(|val| {
853                 // Exclude some symbols that we know are not Rust symbols.
854                 let name = llvm::get_value_name(val);
855                 if ignored(name) { None } else { Some((val, name)) }
856             })
857             .map(move |(val, name)| {
858                 let mut imp_name = prefix.as_bytes().to_vec();
859                 imp_name.extend(name);
860                 let imp_name = CString::new(imp_name).unwrap();
861                 (imp_name, val)
862             })
863             .collect::<Vec<_>>();
864
865         for (imp_name, val) in globals {
866             let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
867             llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
868             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
869         }
870     }
871
872     // Use this function to exclude certain symbols from `__imp` generation.
873     fn ignored(symbol_name: &[u8]) -> bool {
874         // These are symbols generated by LLVM's profiling instrumentation
875         symbol_name.starts_with(b"__llvm_profile_")
876     }
877 }