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