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