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