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