]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/back/write.rs
3902df8a7cac3d5d71e03d8233512432febda9c9
[rust.git] / compiler / rustc_codegen_llvm / src / back / write.rs
1 use crate::attributes;
2 use crate::back::lto::ThinBuffer;
3 use crate::back::profiling::{
4     selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler,
5 };
6 use crate::base;
7 use crate::common;
8 use crate::consts;
9 use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
10 use crate::llvm_util;
11 use crate::type_::Type;
12 use crate::LlvmCodegenBackend;
13 use crate::ModuleLlvm;
14 use rustc_codegen_ssa::back::write::{BitcodeSection, CodegenContext, EmitObj, ModuleConfig};
15 use rustc_codegen_ssa::traits::*;
16 use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
17 use rustc_data_structures::small_c_str::SmallCStr;
18 use rustc_errors::{FatalError, Handler, Level};
19 use rustc_fs_util::{link_or_copy, path_to_c_string};
20 use rustc_hir::def_id::LOCAL_CRATE;
21 use rustc_middle::bug;
22 use rustc_middle::ty::TyCtxt;
23 use rustc_session::config::{self, Lto, OutputType, Passes, SanitizerSet, SwitchWithOptPath};
24 use rustc_session::Session;
25 use rustc_span::symbol::sym;
26 use rustc_span::InnerSpan;
27 use rustc_target::spec::{CodeModel, RelocModel};
28 use tracing::debug;
29
30 use libc::{c_char, c_int, c_uint, c_void, size_t};
31 use std::ffi::CString;
32 use std::fs;
33 use std::io::{self, Write};
34 use std::path::{Path, PathBuf};
35 use std::slice;
36 use std::str;
37 use std::sync::Arc;
38
39 pub fn llvm_err(handler: &rustc_errors::Handler, msg: &str) -> FatalError {
40     match llvm::last_error() {
41         Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
42         None => handler.fatal(&msg),
43     }
44 }
45
46 pub fn write_output_file(
47     handler: &rustc_errors::Handler,
48     target: &'ll llvm::TargetMachine,
49     pm: &llvm::PassManager<'ll>,
50     m: &'ll llvm::Module,
51     output: &Path,
52     file_type: llvm::FileType,
53 ) -> Result<(), FatalError> {
54     unsafe {
55         let output_c = path_to_c_string(output);
56         let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
57         result.into_result().map_err(|()| {
58             let msg = format!("could not write output to {}", output.display());
59             llvm_err(handler, &msg)
60         })
61     }
62 }
63
64 pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
65     target_machine_factory(sess, config::OptLevel::No)()
66         .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
67 }
68
69 pub fn create_target_machine(tcx: TyCtxt<'_>) -> &'static mut llvm::TargetMachine {
70     target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE))()
71         .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
72 }
73
74 pub fn to_llvm_opt_settings(
75     cfg: config::OptLevel,
76 ) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
77     use self::config::OptLevel::*;
78     match cfg {
79         No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
80         Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
81         Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
82         Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
83         Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
84         SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
85     }
86 }
87
88 fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
89     use config::OptLevel::*;
90     match cfg {
91         No => llvm::PassBuilderOptLevel::O0,
92         Less => llvm::PassBuilderOptLevel::O1,
93         Default => llvm::PassBuilderOptLevel::O2,
94         Aggressive => llvm::PassBuilderOptLevel::O3,
95         Size => llvm::PassBuilderOptLevel::Os,
96         SizeMin => llvm::PassBuilderOptLevel::Oz,
97     }
98 }
99
100 fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
101     match relocation_model {
102         RelocModel::Static => llvm::RelocModel::Static,
103         RelocModel::Pic => llvm::RelocModel::PIC,
104         RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
105         RelocModel::Ropi => llvm::RelocModel::ROPI,
106         RelocModel::Rwpi => llvm::RelocModel::RWPI,
107         RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
108     }
109 }
110
111 fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
112     match code_model {
113         Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
114         Some(CodeModel::Small) => llvm::CodeModel::Small,
115         Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
116         Some(CodeModel::Medium) => llvm::CodeModel::Medium,
117         Some(CodeModel::Large) => llvm::CodeModel::Large,
118         None => llvm::CodeModel::None,
119     }
120 }
121
122 pub fn target_machine_factory(
123     sess: &Session,
124     optlvl: config::OptLevel,
125 ) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
126     let reloc_model = to_llvm_relocation_model(sess.relocation_model());
127
128     let (opt_level, _) = to_llvm_opt_settings(optlvl);
129     let use_softfp = sess.opts.cg.soft_float;
130
131     let ffunction_sections =
132         sess.opts.debugging_opts.function_sections.unwrap_or(sess.target.options.function_sections);
133     let fdata_sections = ffunction_sections;
134
135     let code_model = to_llvm_code_model(sess.code_model());
136
137     let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
138     let mut singlethread = sess.target.options.singlethread;
139
140     // On the wasm target once the `atomics` feature is enabled that means that
141     // we're no longer single-threaded, or otherwise we don't want LLVM to
142     // lower atomic operations to single-threaded operations.
143     if singlethread
144         && sess.target.llvm_target.contains("wasm32")
145         && sess.target_features.contains(&sym::atomics)
146     {
147         singlethread = false;
148     }
149
150     let triple = SmallCStr::new(&sess.target.llvm_target);
151     let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
152     let features = features.join(",");
153     let features = CString::new(features).unwrap();
154     let abi = SmallCStr::new(&sess.target.options.llvm_abiname);
155     let trap_unreachable = sess.target.options.trap_unreachable;
156     let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
157
158     let asm_comments = sess.asm_comments();
159     let relax_elf_relocations = sess.target.options.relax_elf_relocations;
160
161     let use_init_array = !sess
162         .opts
163         .debugging_opts
164         .use_ctors_section
165         .unwrap_or(sess.target.options.use_ctors_section);
166
167     Arc::new(move || {
168         let tm = unsafe {
169             llvm::LLVMRustCreateTargetMachine(
170                 triple.as_ptr(),
171                 cpu.as_ptr(),
172                 features.as_ptr(),
173                 abi.as_ptr(),
174                 code_model,
175                 reloc_model,
176                 opt_level,
177                 use_softfp,
178                 ffunction_sections,
179                 fdata_sections,
180                 trap_unreachable,
181                 singlethread,
182                 asm_comments,
183                 emit_stack_size_section,
184                 relax_elf_relocations,
185                 use_init_array,
186             )
187         };
188
189         tm.ok_or_else(|| {
190             format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
191         })
192     })
193 }
194
195 pub(crate) fn save_temp_bitcode(
196     cgcx: &CodegenContext<LlvmCodegenBackend>,
197     module: &ModuleCodegen<ModuleLlvm>,
198     name: &str,
199 ) {
200     if !cgcx.save_temps {
201         return;
202     }
203     unsafe {
204         let ext = format!("{}.bc", name);
205         let cgu = Some(&module.name[..]);
206         let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
207         let cstr = path_to_c_string(&path);
208         let llmod = module.module_llvm.llmod();
209         llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
210     }
211 }
212
213 pub struct DiagnosticHandlers<'a> {
214     data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
215     llcx: &'a llvm::Context,
216 }
217
218 impl<'a> DiagnosticHandlers<'a> {
219     pub fn new(
220         cgcx: &'a CodegenContext<LlvmCodegenBackend>,
221         handler: &'a Handler,
222         llcx: &'a llvm::Context,
223     ) -> Self {
224         let data = Box::into_raw(Box::new((cgcx, handler)));
225         unsafe {
226             llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data.cast());
227             llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data.cast());
228         }
229         DiagnosticHandlers { data, llcx }
230     }
231 }
232
233 impl<'a> Drop for DiagnosticHandlers<'a> {
234     fn drop(&mut self) {
235         use std::ptr::null_mut;
236         unsafe {
237             llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
238             llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
239             drop(Box::from_raw(self.data));
240         }
241     }
242 }
243
244 fn report_inline_asm(
245     cgcx: &CodegenContext<LlvmCodegenBackend>,
246     msg: String,
247     level: llvm::DiagnosticLevel,
248     mut cookie: c_uint,
249     source: Option<(String, Vec<InnerSpan>)>,
250 ) {
251     // In LTO build we may get srcloc values from other crates which are invalid
252     // since they use a different source map. To be safe we just suppress these
253     // in LTO builds.
254     if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
255         cookie = 0;
256     }
257     let level = match level {
258         llvm::DiagnosticLevel::Error => Level::Error,
259         llvm::DiagnosticLevel::Warning => Level::Warning,
260         llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
261     };
262     cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
263 }
264
265 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, user: *const c_void, cookie: c_uint) {
266     if user.is_null() {
267         return;
268     }
269     let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
270
271     // Recover the post-substitution assembly code from LLVM for better
272     // diagnostics.
273     let mut have_source = false;
274     let mut buffer = String::new();
275     let mut level = llvm::DiagnosticLevel::Error;
276     let mut loc = 0;
277     let mut ranges = [0; 8];
278     let mut num_ranges = ranges.len() / 2;
279     let msg = llvm::build_string(|msg| {
280         buffer = llvm::build_string(|buffer| {
281             have_source = llvm::LLVMRustUnpackSMDiagnostic(
282                 diag,
283                 msg,
284                 buffer,
285                 &mut level,
286                 &mut loc,
287                 ranges.as_mut_ptr(),
288                 &mut num_ranges,
289             );
290         })
291         .expect("non-UTF8 inline asm");
292     })
293     .expect("non-UTF8 SMDiagnostic");
294
295     let source = have_source.then(|| {
296         let mut spans = vec![InnerSpan::new(loc as usize, loc as usize)];
297         for i in 0..num_ranges {
298             spans.push(InnerSpan::new(ranges[i * 2] as usize, ranges[i * 2 + 1] as usize));
299         }
300         (buffer, spans)
301     });
302
303     report_inline_asm(cgcx, msg, level, cookie, source);
304 }
305
306 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
307     if user.is_null() {
308         return;
309     }
310     let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
311
312     match llvm::diagnostic::Diagnostic::unpack(info) {
313         llvm::diagnostic::InlineAsm(inline) => {
314             report_inline_asm(
315                 cgcx,
316                 llvm::twine_to_string(inline.message),
317                 inline.level,
318                 inline.cookie,
319                 None,
320             );
321         }
322
323         llvm::diagnostic::Optimization(opt) => {
324             let enabled = match cgcx.remark {
325                 Passes::All => true,
326                 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
327             };
328
329             if enabled {
330                 diag_handler.note_without_error(&format!(
331                     "optimization {} for {} at {}:{}:{}: {}",
332                     opt.kind.describe(),
333                     opt.pass_name,
334                     opt.filename,
335                     opt.line,
336                     opt.column,
337                     opt.message
338                 ));
339             }
340         }
341         llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
342             let msg = llvm::build_string(|s| {
343                 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
344             })
345             .expect("non-UTF8 diagnostic");
346             diag_handler.warn(&msg);
347         }
348         llvm::diagnostic::Unsupported(diagnostic_ref) => {
349             let msg = llvm::build_string(|s| {
350                 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
351             })
352             .expect("non-UTF8 diagnostic");
353             diag_handler.err(&msg);
354         }
355         llvm::diagnostic::UnknownDiagnostic(..) => {}
356     }
357 }
358
359 fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
360     match config.pgo_gen {
361         SwitchWithOptPath::Enabled(ref opt_dir_path) => {
362             let path = if let Some(dir_path) = opt_dir_path {
363                 dir_path.join("default_%m.profraw")
364             } else {
365                 PathBuf::from("default_%m.profraw")
366             };
367
368             Some(CString::new(format!("{}", path.display())).unwrap())
369         }
370         SwitchWithOptPath::Disabled => None,
371     }
372 }
373
374 fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
375     config
376         .pgo_use
377         .as_ref()
378         .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
379 }
380
381 pub(crate) fn should_use_new_llvm_pass_manager(config: &ModuleConfig) -> bool {
382     // We only support the new pass manager starting with LLVM 9.
383     if llvm_util::get_major_version() < 9 {
384         return false;
385     }
386
387     // The new pass manager is disabled by default.
388     config.new_llvm_pass_manager
389 }
390
391 pub(crate) unsafe fn optimize_with_new_llvm_pass_manager(
392     cgcx: &CodegenContext<LlvmCodegenBackend>,
393     module: &ModuleCodegen<ModuleLlvm>,
394     config: &ModuleConfig,
395     opt_level: config::OptLevel,
396     opt_stage: llvm::OptStage,
397 ) {
398     let unroll_loops =
399         opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
400     let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
401     let pgo_gen_path = get_pgo_gen_path(config);
402     let pgo_use_path = get_pgo_use_path(config);
403     let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
404     // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
405     let sanitizer_options = if !is_lto {
406         Some(llvm::SanitizerOptions {
407             sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
408             sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
409             sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
410             sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
411             sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
412             sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
413         })
414     } else {
415         None
416     };
417
418     let llvm_selfprofiler = if cgcx.prof.llvm_recording_enabled() {
419         let mut llvm_profiler = LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap());
420         &mut llvm_profiler as *mut _ as *mut c_void
421     } else {
422         std::ptr::null_mut()
423     };
424
425     // FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
426     // We would have to add upstream support for this first, before we can support
427     // config.inline_threshold and our more aggressive default thresholds.
428     // FIXME: NewPM uses an different and more explicit way to textually represent
429     // pass pipelines. It would probably make sense to expose this, but it would
430     // require a different format than the current -C passes.
431     llvm::LLVMRustOptimizeWithNewPassManager(
432         module.module_llvm.llmod(),
433         &*module.module_llvm.tm,
434         to_pass_builder_opt_level(opt_level),
435         opt_stage,
436         config.no_prepopulate_passes,
437         config.verify_llvm_ir,
438         using_thin_buffers,
439         config.merge_functions,
440         unroll_loops,
441         config.vectorize_slp,
442         config.vectorize_loop,
443         config.no_builtins,
444         config.emit_lifetime_markers,
445         sanitizer_options.as_ref(),
446         pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
447         pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
448         llvm_selfprofiler,
449         selfprofile_before_pass_callback,
450         selfprofile_after_pass_callback,
451     );
452 }
453
454 // Unsafe due to LLVM calls.
455 pub(crate) unsafe fn optimize(
456     cgcx: &CodegenContext<LlvmCodegenBackend>,
457     diag_handler: &Handler,
458     module: &ModuleCodegen<ModuleLlvm>,
459     config: &ModuleConfig,
460 ) -> Result<(), FatalError> {
461     let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &module.name[..]);
462
463     let llmod = module.module_llvm.llmod();
464     let llcx = &*module.module_llvm.llcx;
465     let tm = &*module.module_llvm.tm;
466     let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
467
468     let module_name = module.name.clone();
469     let module_name = Some(&module_name[..]);
470
471     if config.emit_no_opt_bc {
472         let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
473         let out = path_to_c_string(&out);
474         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
475     }
476
477     if let Some(opt_level) = config.opt_level {
478         if should_use_new_llvm_pass_manager(config) {
479             let opt_stage = match cgcx.lto {
480                 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
481                 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
482                 _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
483                 _ => llvm::OptStage::PreLinkNoLTO,
484             };
485             optimize_with_new_llvm_pass_manager(cgcx, module, config, opt_level, opt_stage);
486             return Ok(());
487         }
488
489         if cgcx.prof.llvm_recording_enabled() {
490             diag_handler
491                 .warn("`-Z self-profile-events = llvm` requires `-Z new-llvm-pass-manager`");
492         }
493
494         // Create the two optimizing pass managers. These mirror what clang
495         // does, and are by populated by LLVM's default PassManagerBuilder.
496         // Each manager has a different set of passes, but they also share
497         // some common passes.
498         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
499         let mpm = llvm::LLVMCreatePassManager();
500
501         {
502             let find_pass = |pass_name: &str| {
503                 let pass_name = SmallCStr::new(pass_name);
504                 llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr())
505             };
506
507             if config.verify_llvm_ir {
508                 // Verification should run as the very first pass.
509                 llvm::LLVMRustAddPass(fpm, find_pass("verify").unwrap());
510             }
511
512             let mut extra_passes = Vec::new();
513             let mut have_name_anon_globals_pass = false;
514
515             for pass_name in &config.passes {
516                 if pass_name == "lint" {
517                     // Linting should also be performed early, directly on the generated IR.
518                     llvm::LLVMRustAddPass(fpm, find_pass("lint").unwrap());
519                     continue;
520                 }
521
522                 if let Some(pass) = find_pass(pass_name) {
523                     extra_passes.push(pass);
524                 } else {
525                     diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass_name));
526                 }
527
528                 if pass_name == "name-anon-globals" {
529                     have_name_anon_globals_pass = true;
530                 }
531             }
532
533             add_sanitizer_passes(config, &mut extra_passes);
534
535             // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
536             // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
537             // we'll get errors in LLVM.
538             let using_thin_buffers = config.bitcode_needed();
539             if !config.no_prepopulate_passes {
540                 llvm::LLVMAddAnalysisPasses(tm, fpm);
541                 llvm::LLVMAddAnalysisPasses(tm, mpm);
542                 let opt_level = to_llvm_opt_settings(opt_level).0;
543                 let prepare_for_thin_lto = cgcx.lto == Lto::Thin
544                     || cgcx.lto == Lto::ThinLocal
545                     || (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
546                 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
547                     llvm::LLVMRustAddLastExtensionPasses(
548                         b,
549                         extra_passes.as_ptr(),
550                         extra_passes.len() as size_t,
551                     );
552                     llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
553                     llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
554                 });
555
556                 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
557                 if using_thin_buffers && !prepare_for_thin_lto {
558                     llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
559                     have_name_anon_globals_pass = true;
560                 }
561             } else {
562                 // If we don't use the standard pipeline, directly populate the MPM
563                 // with the extra passes.
564                 for pass in extra_passes {
565                     llvm::LLVMRustAddPass(mpm, pass);
566                 }
567             }
568
569             if using_thin_buffers && !have_name_anon_globals_pass {
570                 // As described above, this will probably cause an error in LLVM
571                 if config.no_prepopulate_passes {
572                     diag_handler.err(
573                         "The current compilation is going to use thin LTO buffers \
574                                       without running LLVM's NameAnonGlobals pass. \
575                                       This will likely cause errors in LLVM. Consider adding \
576                                       -C passes=name-anon-globals to the compiler command line.",
577                     );
578                 } else {
579                     bug!(
580                         "We are using thin LTO buffers without running the NameAnonGlobals pass. \
581                           This will likely cause errors in LLVM and should never happen."
582                     );
583                 }
584             }
585         }
586
587         diag_handler.abort_if_errors();
588
589         // Finally, run the actual optimization passes
590         {
591             let _timer = cgcx.prof.extra_verbose_generic_activity(
592                 "LLVM_module_optimize_function_passes",
593                 &module.name[..],
594             );
595             llvm::LLVMRustRunFunctionPassManager(fpm, llmod);
596         }
597         {
598             let _timer = cgcx.prof.extra_verbose_generic_activity(
599                 "LLVM_module_optimize_module_passes",
600                 &module.name[..],
601             );
602             llvm::LLVMRunPassManager(mpm, llmod);
603         }
604
605         // Deallocate managers that we're now done with
606         llvm::LLVMDisposePassManager(fpm);
607         llvm::LLVMDisposePassManager(mpm);
608     }
609     Ok(())
610 }
611
612 unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) {
613     if config.sanitizer.contains(SanitizerSet::ADDRESS) {
614         let recover = config.sanitizer_recover.contains(SanitizerSet::ADDRESS);
615         passes.push(llvm::LLVMRustCreateAddressSanitizerFunctionPass(recover));
616         passes.push(llvm::LLVMRustCreateModuleAddressSanitizerPass(recover));
617     }
618     if config.sanitizer.contains(SanitizerSet::MEMORY) {
619         let track_origins = config.sanitizer_memory_track_origins as c_int;
620         let recover = config.sanitizer_recover.contains(SanitizerSet::MEMORY);
621         passes.push(llvm::LLVMRustCreateMemorySanitizerPass(track_origins, recover));
622     }
623     if config.sanitizer.contains(SanitizerSet::THREAD) {
624         passes.push(llvm::LLVMRustCreateThreadSanitizerPass());
625     }
626 }
627
628 pub(crate) fn link(
629     cgcx: &CodegenContext<LlvmCodegenBackend>,
630     diag_handler: &Handler,
631     mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
632 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
633     use super::lto::{Linker, ModuleBuffer};
634     // Sort the modules by name to ensure to ensure deterministic behavior.
635     modules.sort_by(|a, b| a.name.cmp(&b.name));
636     let (first, elements) =
637         modules.split_first().expect("Bug! modules must contain at least one module.");
638
639     let mut linker = Linker::new(first.module_llvm.llmod());
640     for module in elements {
641         let _timer =
642             cgcx.prof.generic_activity_with_arg("LLVM_link_module", format!("{:?}", module.name));
643         let buffer = ModuleBuffer::new(module.module_llvm.llmod());
644         linker.add(&buffer.data()).map_err(|()| {
645             let msg = format!("failed to serialize module {:?}", module.name);
646             llvm_err(&diag_handler, &msg)
647         })?;
648     }
649     drop(linker);
650     Ok(modules.remove(0))
651 }
652
653 pub(crate) unsafe fn codegen(
654     cgcx: &CodegenContext<LlvmCodegenBackend>,
655     diag_handler: &Handler,
656     module: ModuleCodegen<ModuleLlvm>,
657     config: &ModuleConfig,
658 ) -> Result<CompiledModule, FatalError> {
659     let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &module.name[..]);
660     {
661         let llmod = module.module_llvm.llmod();
662         let llcx = &*module.module_llvm.llcx;
663         let tm = &*module.module_llvm.tm;
664         let module_name = module.name.clone();
665         let module_name = Some(&module_name[..]);
666         let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
667
668         if cgcx.msvc_imps_needed {
669             create_msvc_imps(cgcx, llcx, llmod);
670         }
671
672         // A codegen-specific pass manager is used to generate object
673         // files for an LLVM module.
674         //
675         // Apparently each of these pass managers is a one-shot kind of
676         // thing, so we create a new one for each type of output. The
677         // pass manager passed to the closure should be ensured to not
678         // escape the closure itself, and the manager should only be
679         // used once.
680         unsafe fn with_codegen<'ll, F, R>(
681             tm: &'ll llvm::TargetMachine,
682             llmod: &'ll llvm::Module,
683             no_builtins: bool,
684             f: F,
685         ) -> R
686         where
687             F: FnOnce(&'ll mut PassManager<'ll>) -> R,
688         {
689             let cpm = llvm::LLVMCreatePassManager();
690             llvm::LLVMAddAnalysisPasses(tm, cpm);
691             llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
692             f(cpm)
693         }
694
695         // Two things to note:
696         // - If object files are just LLVM bitcode we write bitcode, copy it to
697         //   the .o file, and delete the bitcode if it wasn't otherwise
698         //   requested.
699         // - If we don't have the integrated assembler then we need to emit
700         //   asm from LLVM and use `gcc` to create the object file.
701
702         let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
703         let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
704
705         if config.bitcode_needed() {
706             let _timer = cgcx
707                 .prof
708                 .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &module.name[..]);
709             let thin = ThinBuffer::new(llmod);
710             let data = thin.data();
711
712             if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
713                 let _timer = cgcx.prof.generic_activity_with_arg(
714                     "LLVM_module_codegen_emit_bitcode",
715                     &module.name[..],
716                 );
717                 if let Err(e) = fs::write(&bc_out, data) {
718                     let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
719                     diag_handler.err(&msg);
720                 }
721             }
722
723             if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
724                 let _timer = cgcx.prof.generic_activity_with_arg(
725                     "LLVM_module_codegen_embed_bitcode",
726                     &module.name[..],
727                 );
728                 embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
729             }
730         }
731
732         if config.emit_ir {
733             let _timer = cgcx
734                 .prof
735                 .generic_activity_with_arg("LLVM_module_codegen_emit_ir", &module.name[..]);
736             let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
737             let out_c = path_to_c_string(&out);
738
739             extern "C" fn demangle_callback(
740                 input_ptr: *const c_char,
741                 input_len: size_t,
742                 output_ptr: *mut c_char,
743                 output_len: size_t,
744             ) -> size_t {
745                 let input =
746                     unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
747
748                 let input = match str::from_utf8(input) {
749                     Ok(s) => s,
750                     Err(_) => return 0,
751                 };
752
753                 let output = unsafe {
754                     slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
755                 };
756                 let mut cursor = io::Cursor::new(output);
757
758                 let demangled = match rustc_demangle::try_demangle(input) {
759                     Ok(d) => d,
760                     Err(_) => return 0,
761                 };
762
763                 if write!(cursor, "{:#}", demangled).is_err() {
764                     // Possible only if provided buffer is not big enough
765                     return 0;
766                 }
767
768                 cursor.position() as size_t
769             }
770
771             let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
772             result.into_result().map_err(|()| {
773                 let msg = format!("failed to write LLVM IR to {}", out.display());
774                 llvm_err(diag_handler, &msg)
775             })?;
776         }
777
778         if config.emit_asm {
779             let _timer = cgcx
780                 .prof
781                 .generic_activity_with_arg("LLVM_module_codegen_emit_asm", &module.name[..]);
782             let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
783
784             // We can't use the same module for asm and object code output,
785             // because that triggers various errors like invalid IR or broken
786             // binaries. So we must clone the module to produce the asm output
787             // if we are also producing object code.
788             let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
789                 llvm::LLVMCloneModule(llmod)
790             } else {
791                 llmod
792             };
793             with_codegen(tm, llmod, config.no_builtins, |cpm| {
794                 write_output_file(diag_handler, tm, cpm, llmod, &path, llvm::FileType::AssemblyFile)
795             })?;
796         }
797
798         match config.emit_obj {
799             EmitObj::ObjectCode(_) => {
800                 let _timer = cgcx
801                     .prof
802                     .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &module.name[..]);
803                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
804                     write_output_file(
805                         diag_handler,
806                         tm,
807                         cpm,
808                         llmod,
809                         &obj_out,
810                         llvm::FileType::ObjectFile,
811                     )
812                 })?;
813             }
814
815             EmitObj::Bitcode => {
816                 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
817                 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
818                     diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
819                 }
820
821                 if !config.emit_bc {
822                     debug!("removing_bitcode {:?}", bc_out);
823                     if let Err(e) = fs::remove_file(&bc_out) {
824                         diag_handler.err(&format!("failed to remove bitcode: {}", e));
825                     }
826                 }
827             }
828
829             EmitObj::None => {}
830         }
831
832         drop(handlers);
833     }
834
835     Ok(module.into_compiled_module(
836         config.emit_obj != EmitObj::None,
837         config.emit_bc,
838         &cgcx.output_filenames,
839     ))
840 }
841
842 /// Embed the bitcode of an LLVM module in the LLVM module itself.
843 ///
844 /// This is done primarily for iOS where it appears to be standard to compile C
845 /// code at least with `-fembed-bitcode` which creates two sections in the
846 /// executable:
847 ///
848 /// * __LLVM,__bitcode
849 /// * __LLVM,__cmdline
850 ///
851 /// It appears *both* of these sections are necessary to get the linker to
852 /// recognize what's going on. A suitable cmdline value is taken from the
853 /// target spec.
854 ///
855 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
856 /// embed an empty section.
857 ///
858 /// Basically all of this is us attempting to follow in the footsteps of clang
859 /// on iOS. See #35968 for lots more info.
860 unsafe fn embed_bitcode(
861     cgcx: &CodegenContext<LlvmCodegenBackend>,
862     llcx: &llvm::Context,
863     llmod: &llvm::Module,
864     cmdline: &str,
865     bitcode: &[u8],
866 ) {
867     let llconst = common::bytes_in_context(llcx, bitcode);
868     let llglobal = llvm::LLVMAddGlobal(
869         llmod,
870         common::val_ty(llconst),
871         "rustc.embedded.module\0".as_ptr().cast(),
872     );
873     llvm::LLVMSetInitializer(llglobal, llconst);
874
875     let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
876         || cgcx.opts.target_triple.triple().contains("-darwin")
877         || cgcx.opts.target_triple.triple().contains("-tvos");
878
879     let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
880     llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
881     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
882     llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
883
884     let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
885     let llglobal = llvm::LLVMAddGlobal(
886         llmod,
887         common::val_ty(llconst),
888         "rustc.embedded.cmdline\0".as_ptr().cast(),
889     );
890     llvm::LLVMSetInitializer(llglobal, llconst);
891     let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
892     llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
893     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
894
895     // We're adding custom sections to the output object file, but we definitely
896     // do not want these custom sections to make their way into the final linked
897     // executable. The purpose of these custom sections is for tooling
898     // surrounding object files to work with the LLVM IR, if necessary. For
899     // example rustc's own LTO will look for LLVM IR inside of the object file
900     // in these sections by default.
901     //
902     // To handle this is a bit different depending on the object file format
903     // used by the backend, broken down into a few different categories:
904     //
905     // * Mach-O - this is for macOS. Inspecting the source code for the native
906     //   linker here shows that the `.llvmbc` and `.llvmcmd` sections are
907     //   automatically skipped by the linker. In that case there's nothing extra
908     //   that we need to do here.
909     //
910     // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
911     //   `.llvmcmd` sections, so there's nothing extra we need to do.
912     //
913     // * COFF - if we don't do anything the linker will by default copy all
914     //   these sections to the output artifact, not what we want! To subvert
915     //   this we want to flag the sections we inserted here as
916     //   `IMAGE_SCN_LNK_REMOVE`. Unfortunately though LLVM has no native way to
917     //   do this. Thankfully though we can do this with some inline assembly,
918     //   which is easy enough to add via module-level global inline asm.
919     //
920     // * ELF - this is very similar to COFF above. One difference is that these
921     //   sections are removed from the output linked artifact when
922     //   `--gc-sections` is passed, which we pass by default. If that flag isn't
923     //   passed though then these sections will show up in the final output.
924     //   Additionally the flag that we need to set here is `SHF_EXCLUDE`.
925     if is_apple
926         || cgcx.opts.target_triple.triple().starts_with("wasm")
927         || cgcx.opts.target_triple.triple().starts_with("asmjs")
928     {
929         // nothing to do here
930     } else if cgcx.opts.target_triple.triple().contains("windows")
931         || cgcx.opts.target_triple.triple().contains("uefi")
932     {
933         let asm = "
934             .section .llvmbc,\"n\"
935             .section .llvmcmd,\"n\"
936         ";
937         llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
938     } else {
939         let asm = "
940             .section .llvmbc,\"e\"
941             .section .llvmcmd,\"e\"
942         ";
943         llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
944     }
945 }
946
947 pub unsafe fn with_llvm_pmb(
948     llmod: &llvm::Module,
949     config: &ModuleConfig,
950     opt_level: llvm::CodeGenOptLevel,
951     prepare_for_thin_lto: bool,
952     f: &mut dyn FnMut(&llvm::PassManagerBuilder),
953 ) {
954     use std::ptr;
955
956     // Create the PassManagerBuilder for LLVM. We configure it with
957     // reasonable defaults and prepare it to actually populate the pass
958     // manager.
959     let builder = llvm::LLVMPassManagerBuilderCreate();
960     let opt_size =
961         config.opt_size.map(|x| to_llvm_opt_settings(x).1).unwrap_or(llvm::CodeGenOptSizeNone);
962     let inline_threshold = config.inline_threshold;
963     let pgo_gen_path = get_pgo_gen_path(config);
964     let pgo_use_path = get_pgo_use_path(config);
965
966     llvm::LLVMRustConfigurePassManagerBuilder(
967         builder,
968         opt_level,
969         config.merge_functions,
970         config.vectorize_slp,
971         config.vectorize_loop,
972         prepare_for_thin_lto,
973         pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
974         pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
975     );
976
977     llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
978
979     if opt_size != llvm::CodeGenOptSizeNone {
980         llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
981     }
982
983     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
984
985     // Here we match what clang does (kinda). For O0 we only inline
986     // always-inline functions (but don't add lifetime intrinsics), at O1 we
987     // inline with lifetime intrinsics, and O2+ we add an inliner with a
988     // thresholds copied from clang.
989     match (opt_level, opt_size, inline_threshold) {
990         (.., Some(t)) => {
991             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
992         }
993         (llvm::CodeGenOptLevel::Aggressive, ..) => {
994             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
995         }
996         (_, llvm::CodeGenOptSizeDefault, _) => {
997             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
998         }
999         (_, llvm::CodeGenOptSizeAggressive, _) => {
1000             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1001         }
1002         (llvm::CodeGenOptLevel::None, ..) => {
1003             llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1004         }
1005         (llvm::CodeGenOptLevel::Less, ..) => {
1006             llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1007         }
1008         (llvm::CodeGenOptLevel::Default, ..) => {
1009             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1010         }
1011     }
1012
1013     f(builder);
1014     llvm::LLVMPassManagerBuilderDispose(builder);
1015 }
1016
1017 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1018 // This is required to satisfy `dllimport` references to static data in .rlibs
1019 // when using MSVC linker.  We do this only for data, as linker can fix up
1020 // code references on its own.
1021 // See #26591, #27438
1022 fn create_msvc_imps(
1023     cgcx: &CodegenContext<LlvmCodegenBackend>,
1024     llcx: &llvm::Context,
1025     llmod: &llvm::Module,
1026 ) {
1027     if !cgcx.msvc_imps_needed {
1028         return;
1029     }
1030     // The x86 ABI seems to require that leading underscores are added to symbol
1031     // names, so we need an extra underscore on x86. There's also a leading
1032     // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1033     // underscores added in front).
1034     let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1035
1036     unsafe {
1037         let i8p_ty = Type::i8p_llcx(llcx);
1038         let globals = base::iter_globals(llmod)
1039             .filter(|&val| {
1040                 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
1041                     && llvm::LLVMIsDeclaration(val) == 0
1042             })
1043             .filter_map(|val| {
1044                 // Exclude some symbols that we know are not Rust symbols.
1045                 let name = llvm::get_value_name(val);
1046                 if ignored(name) { None } else { Some((val, name)) }
1047             })
1048             .map(move |(val, name)| {
1049                 let mut imp_name = prefix.as_bytes().to_vec();
1050                 imp_name.extend(name);
1051                 let imp_name = CString::new(imp_name).unwrap();
1052                 (imp_name, val)
1053             })
1054             .collect::<Vec<_>>();
1055
1056         for (imp_name, val) in globals {
1057             let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
1058             llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
1059             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1060         }
1061     }
1062
1063     // Use this function to exclude certain symbols from `__imp` generation.
1064     fn ignored(symbol_name: &[u8]) -> bool {
1065         // These are symbols generated by LLVM's profiling instrumentation
1066         symbol_name.starts_with(b"__llvm_profile_")
1067     }
1068 }