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