]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_codegen_ssa/src/back/write.rs
New upstream version 1.64.0+dfsg1
[rustc.git] / compiler / rustc_codegen_ssa / src / back / write.rs
CommitLineData
6a06907d 1use super::link::{self, ensure_removed};
a1dfa0c6 2use super::lto::{self, SerializedModule};
dfeec247
XL
3use super::symbol_export::symbol_name_for_instance_in_crate;
4
5use crate::{
6 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
dfeec247 7};
a1dfa0c6 8
9fa01778 9use crate::traits::*;
dfeec247 10use jobserver::{Acquired, Client};
dfeec247 11use rustc_data_structures::fx::FxHashMap;
cdc7bbd5 12use rustc_data_structures::memmap::Mmap;
60c5eb7d 13use rustc_data_structures::profiling::SelfProfilerRef;
74b04a01 14use rustc_data_structures::profiling::TimingGuard;
dfeec247 15use rustc_data_structures::profiling::VerboseTimingGuard;
e74abb32 16use rustc_data_structures::sync::Lrc;
dfeec247
XL
17use rustc_errors::emitter::Emitter;
18use rustc_errors::{DiagnosticId, FatalError, Handler, Level};
19use rustc_fs_util::link_or_copy;
20use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
21use rustc_incremental::{
f9f354fc 22 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
dfeec247 23};
c295e0f8 24use rustc_metadata::EncodedMetadata;
f9f354fc 25use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
04454e1e 26use rustc_middle::middle::exported_symbols::SymbolExportInfo;
ba9703b0 27use rustc_middle::ty::TyCtxt;
dfeec247 28use rustc_session::cgu_reuse_tracker::CguReuseTracker;
f9f354fc 29use rustc_session::config::{self, CrateType, Lto, OutputFilenames, OutputType};
cdc7bbd5 30use rustc_session::config::{Passes, SwitchWithOptPath};
ba9703b0 31use rustc_session::Session;
dfeec247 32use rustc_span::source_map::SourceMap;
17df50a5 33use rustc_span::symbol::sym;
f9f354fc 34use rustc_span::{BytePos, FileName, InnerSpan, Pos, Span};
5099ac24 35use rustc_target::spec::{MergeFunctions, SanitizerSet};
a1dfa0c6
XL
36
37use std::any::Any;
38use std::fs;
39use std::io;
064997fb 40use std::marker::PhantomData;
a1dfa0c6
XL
41use std::mem;
42use std::path::{Path, PathBuf};
43use std::str;
dfeec247 44use std::sync::mpsc::{channel, Receiver, Sender};
a1dfa0c6 45use std::sync::Arc;
a1dfa0c6
XL
46use std::thread;
47
9fa01778 48const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
a1dfa0c6 49
ba9703b0
XL
50/// What kind of object file to emit.
51#[derive(Clone, Copy, PartialEq)]
52pub enum EmitObj {
53 // No object file.
54 None,
55
56 // Just uncompressed llvm bitcode. Provides easy compatibility with
57 // emscripten's ecc compiler, when used as the linker.
58 Bitcode,
59
60 // Object code, possibly augmented with a bitcode section.
61 ObjectCode(BitcodeSection),
62}
63
64/// What kind of llvm bitcode section to embed in an object file.
65#[derive(Clone, Copy, PartialEq)]
66pub enum BitcodeSection {
67 // No bitcode section.
68 None,
69
ba9703b0
XL
70 // A full, uncompressed bitcode section.
71 Full,
72}
73
a1dfa0c6
XL
74/// Module-specific configuration for `optimize_and_codegen`.
75pub struct ModuleConfig {
76 /// Names of additional optimization passes to run.
77 pub passes: Vec<String>,
78 /// Some(level) to optimize at a certain level, or None to run
79 /// absolutely no optimizations (used for the metadata module).
80 pub opt_level: Option<config::OptLevel>,
81
82 /// Some(level) to optimize binary size, or None to not affect program size.
83 pub opt_size: Option<config::OptLevel>,
84
dc9dc135
XL
85 pub pgo_gen: SwitchWithOptPath,
86 pub pgo_use: Option<PathBuf>,
c295e0f8
XL
87 pub pgo_sample_use: Option<PathBuf>,
88 pub debug_info_for_profiling: bool,
17df50a5
XL
89 pub instrument_coverage: bool,
90 pub instrument_gcov: bool,
a1dfa0c6 91
f035d41b
XL
92 pub sanitizer: SanitizerSet,
93 pub sanitizer_recover: SanitizerSet,
60c5eb7d
XL
94 pub sanitizer_memory_track_origins: usize,
95
a1dfa0c6 96 // Flags indicating which outputs to produce.
9fa01778 97 pub emit_pre_lto_bc: bool,
a1dfa0c6
XL
98 pub emit_no_opt_bc: bool,
99 pub emit_bc: bool,
a1dfa0c6
XL
100 pub emit_ir: bool,
101 pub emit_asm: bool,
ba9703b0 102 pub emit_obj: EmitObj,
064997fb 103 pub emit_thin_lto: bool,
f9f354fc 104 pub bc_cmdline: String,
ba9703b0 105
a1dfa0c6
XL
106 // Miscellaneous flags. These are mostly copied from command-line
107 // options.
108 pub verify_llvm_ir: bool,
109 pub no_prepopulate_passes: bool,
110 pub no_builtins: bool,
dfeec247 111 pub time_module: bool,
a1dfa0c6
XL
112 pub vectorize_loop: bool,
113 pub vectorize_slp: bool,
114 pub merge_functions: bool,
cdc7bbd5 115 pub inline_threshold: Option<u32>,
17df50a5 116 pub new_llvm_pass_manager: Option<bool>,
f9f354fc 117 pub emit_lifetime_markers: bool,
a2a8927a 118 pub llvm_plugins: Vec<String>,
a1dfa0c6
XL
119}
120
121impl ModuleConfig {
f9f354fc
XL
122 fn new(
123 kind: ModuleKind,
124 sess: &Session,
125 no_builtins: bool,
126 is_compiler_builtins: bool,
127 ) -> ModuleConfig {
ba9703b0
XL
128 // If it's a regular module, use `$regular`, otherwise use `$other`.
129 // `$regular` and `$other` are evaluated lazily.
130 macro_rules! if_regular {
131 ($regular: expr, $other: expr) => {
132 if let ModuleKind::Regular = kind { $regular } else { $other }
133 };
a1dfa0c6 134 }
a1dfa0c6 135
ba9703b0
XL
136 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
137
138 let save_temps = sess.opts.cg.save_temps;
139
140 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
141 || match kind {
142 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
143 ModuleKind::Allocator => false,
144 ModuleKind::Metadata => sess.opts.output_types.contains_key(&OutputType::Metadata),
145 };
146
147 let emit_obj = if !should_emit_obj {
148 EmitObj::None
29967ef6 149 } else if sess.target.obj_is_bitcode
f9f354fc 150 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
ba9703b0 151 {
f9f354fc
XL
152 // This case is selected if the target uses objects as bitcode, or
153 // if linker plugin LTO is enabled. In the linker plugin LTO case
154 // the assumption is that the final link-step will read the bitcode
155 // and convert it to object code. This may be done by either the
156 // native linker or rustc itself.
157 //
158 // Note, however, that the linker-plugin-lto requested here is
159 // explicitly ignored for `#![no_builtins]` crates. These crates are
160 // specifically ignored by rustc's LTO passes and wouldn't work if
161 // loaded into the linker. These crates define symbols that LLVM
162 // lowers intrinsics to, and these symbol dependencies aren't known
163 // until after codegen. As a result any crate marked
164 // `#![no_builtins]` is assumed to not participate in LTO and
165 // instead goes on to generate object code.
ba9703b0 166 EmitObj::Bitcode
f9f354fc
XL
167 } else if need_bitcode_in_object(sess) {
168 EmitObj::ObjectCode(BitcodeSection::Full)
ba9703b0
XL
169 } else {
170 EmitObj::ObjectCode(BitcodeSection::None)
9fa01778 171 };
ba9703b0
XL
172
173 ModuleConfig {
17df50a5 174 passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
ba9703b0
XL
175
176 opt_level: opt_level_and_size,
177 opt_size: opt_level_and_size,
178
179 pgo_gen: if_regular!(
180 sess.opts.cg.profile_generate.clone(),
181 SwitchWithOptPath::Disabled
182 ),
183 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
064997fb
FG
184 pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
185 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
17df50a5
XL
186 instrument_coverage: if_regular!(sess.instrument_coverage(), false),
187 instrument_gcov: if_regular!(
188 // compiler_builtins overrides the codegen-units settings,
189 // which is incompatible with -Zprofile which requires that
190 // only a single codegen unit is used per crate.
064997fb 191 sess.opts.unstable_opts.profile && !is_compiler_builtins,
17df50a5
XL
192 false
193 ),
ba9703b0 194
064997fb 195 sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
ba9703b0 196 sanitizer_recover: if_regular!(
064997fb 197 sess.opts.unstable_opts.sanitizer_recover,
f035d41b 198 SanitizerSet::empty()
ba9703b0
XL
199 ),
200 sanitizer_memory_track_origins: if_regular!(
064997fb 201 sess.opts.unstable_opts.sanitizer_memory_track_origins,
ba9703b0
XL
202 0
203 ),
204
205 emit_pre_lto_bc: if_regular!(
206 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
207 false
208 ),
209 emit_no_opt_bc: if_regular!(save_temps, false),
210 emit_bc: if_regular!(
211 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
212 save_temps
213 ),
ba9703b0
XL
214 emit_ir: if_regular!(
215 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
216 false
217 ),
218 emit_asm: if_regular!(
219 sess.opts.output_types.contains_key(&OutputType::Assembly),
220 false
221 ),
222 emit_obj,
064997fb 223 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto,
5e7ed085 224 bc_cmdline: sess.target.bitcode_llvm_cmdline.to_string(),
ba9703b0
XL
225
226 verify_llvm_ir: sess.verify_llvm_ir(),
227 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
29967ef6 228 no_builtins: no_builtins || sess.target.no_builtins,
ba9703b0
XL
229
230 // Exclude metadata and allocator modules from time_passes output,
231 // since they throw off the "LLVM passes" measurement.
232 time_module: if_regular!(true, false),
233
234 // Copy what clang does by turning on loop vectorization at O2 and
235 // slp vectorization at O3.
236 vectorize_loop: !sess.opts.cg.no_vectorize_loops
237 && (sess.opts.optimize == config::OptLevel::Default
238 || sess.opts.optimize == config::OptLevel::Aggressive),
239 vectorize_slp: !sess.opts.cg.no_vectorize_slp
240 && sess.opts.optimize == config::OptLevel::Aggressive,
241
242 // Some targets (namely, NVPTX) interact badly with the
243 // MergeFunctions pass. This is because MergeFunctions can generate
244 // new function calls which may interfere with the target calling
245 // convention; e.g. for the NVPTX target, PTX kernels should not
246 // call other PTX kernels. MergeFunctions can also be configured to
247 // generate aliases instead, but aliases are not supported by some
248 // backends (again, NVPTX). Therefore, allow targets to opt out of
249 // the MergeFunctions pass, but otherwise keep the pass enabled (at
250 // O2 and O3) since it can be useful for reducing code size.
251 merge_functions: match sess
252 .opts
064997fb 253 .unstable_opts
ba9703b0 254 .merge_functions
29967ef6 255 .unwrap_or(sess.target.merge_functions)
ba9703b0
XL
256 {
257 MergeFunctions::Disabled => false,
258 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
259 sess.opts.optimize == config::OptLevel::Default
260 || sess.opts.optimize == config::OptLevel::Aggressive
261 }
262 },
263
264 inline_threshold: sess.opts.cg.inline_threshold,
064997fb 265 new_llvm_pass_manager: sess.opts.unstable_opts.new_llvm_pass_manager,
f9f354fc 266 emit_lifetime_markers: sess.emit_lifetime_markers(),
064997fb 267 llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
ba9703b0 268 }
a1dfa0c6
XL
269 }
270
271 pub fn bitcode_needed(&self) -> bool {
ba9703b0 272 self.emit_bc
ba9703b0
XL
273 || self.emit_obj == EmitObj::Bitcode
274 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
a1dfa0c6
XL
275 }
276}
277
fc512014
XL
278/// Configuration passed to the function returned by the `target_machine_factory`.
279pub struct TargetMachineFactoryConfig {
280 /// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
281 /// so the path to the dwarf object has to be provided when we create the target machine.
282 /// This can be ignored by backends which do not need it for their Split DWARF support.
283 pub split_dwarf_file: Option<PathBuf>,
a1dfa0c6
XL
284}
285
5869c6ff
XL
286impl TargetMachineFactoryConfig {
287 pub fn new(
288 cgcx: &CodegenContext<impl WriteBackendMethods>,
289 module_name: &str,
290 ) -> TargetMachineFactoryConfig {
291 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
a2a8927a
XL
292 cgcx.output_filenames.split_dwarf_path(
293 cgcx.split_debuginfo,
294 cgcx.split_dwarf_kind,
295 Some(module_name),
296 )
5869c6ff
XL
297 } else {
298 None
299 };
300 TargetMachineFactoryConfig { split_dwarf_file }
301 }
302}
303
fc512014
XL
304pub type TargetMachineFactoryFn<B> = Arc<
305 dyn Fn(TargetMachineFactoryConfig) -> Result<<B as WriteBackendMethods>::TargetMachine, String>
306 + Send
307 + Sync,
308>;
309
04454e1e 310pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportInfo)>>>;
dfeec247 311
a1dfa0c6
XL
312/// Additional resources used by optimize_and_codegen (not module specific)
313#[derive(Clone)]
314pub struct CodegenContext<B: WriteBackendMethods> {
315 // Resources needed when running LTO
316 pub backend: B,
e74abb32 317 pub prof: SelfProfilerRef,
a1dfa0c6 318 pub lto: Lto,
a1dfa0c6
XL
319 pub save_temps: bool,
320 pub fewer_names: bool,
3c0e092e 321 pub time_trace: bool,
a1dfa0c6
XL
322 pub exported_symbols: Option<Arc<ExportedSymbols>>,
323 pub opts: Arc<config::Options>,
f9f354fc 324 pub crate_types: Vec<CrateType>,
a1dfa0c6
XL
325 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
326 pub output_filenames: Arc<OutputFilenames>,
327 pub regular_module_config: Arc<ModuleConfig>,
328 pub metadata_module_config: Arc<ModuleConfig>,
329 pub allocator_module_config: Arc<ModuleConfig>,
fc512014 330 pub tm_factory: TargetMachineFactoryFn<B>,
a1dfa0c6 331 pub msvc_imps_needed: bool,
fc512014 332 pub is_pe_coff: bool,
5869c6ff 333 pub target_can_use_split_dwarf: bool,
29967ef6 334 pub target_pointer_width: u32,
48663c56 335 pub target_arch: String,
a1dfa0c6 336 pub debuginfo: config::DebugInfo,
5869c6ff 337 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
a2a8927a 338 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
a1dfa0c6
XL
339
340 // Number of cgus excluding the allocator/metadata modules
341 pub total_cgus: usize,
342 // Handler to use for diagnostics produced during codegen.
343 pub diag_emitter: SharedEmitter,
a1dfa0c6
XL
344 // LLVM optimizations for which we want to print remarks.
345 pub remark: Passes,
346 // Worker thread number
347 pub worker: usize,
348 // The incremental compilation session directory, or None if we are not
349 // compiling incrementally
350 pub incr_comp_session_dir: Option<PathBuf>,
351 // Used to update CGU re-use information during the thinlto phase.
352 pub cgu_reuse_tracker: CguReuseTracker,
353 // Channel back to the main control thread to send messages to
354 pub coordinator_send: Sender<Box<dyn Any + Send>>,
a1dfa0c6
XL
355}
356
357impl<B: WriteBackendMethods> CodegenContext<B> {
358 pub fn create_diag_handler(&self) -> Handler {
532ac7d7 359 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
a1dfa0c6
XL
360 }
361
362 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
363 match kind {
364 ModuleKind::Regular => &self.regular_module_config,
365 ModuleKind::Metadata => &self.metadata_module_config,
366 ModuleKind::Allocator => &self.allocator_module_config,
367 }
368 }
369}
370
371fn generate_lto_work<B: ExtraBackendMethods>(
372 cgcx: &CodegenContext<B>,
9fa01778 373 needs_fat_lto: Vec<FatLTOInput<B>>,
0731742a 374 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
dfeec247 375 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
a1dfa0c6 376) -> Vec<(WorkItem<B>, u64)> {
e74abb32 377 let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
a1dfa0c6 378
0731742a
XL
379 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
380 assert!(needs_thin_lto.is_empty());
dfeec247
XL
381 let lto_module =
382 B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
0731742a
XL
383 (vec![lto_module], vec![])
384 } else {
385 assert!(needs_fat_lto.is_empty());
dfeec247 386 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise())
0731742a
XL
387 };
388
ba9703b0 389 lto_modules
dfeec247
XL
390 .into_iter()
391 .map(|module| {
392 let cost = module.cost();
393 (WorkItem::LTO(module), cost)
394 })
395 .chain(copy_jobs.into_iter().map(|wp| {
396 (
397 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
398 name: wp.cgu_name.clone(),
399 source: wp,
400 }),
401 0,
402 )
403 }))
ba9703b0 404 .collect()
a1dfa0c6
XL
405}
406
407pub struct CompiledModules {
408 pub modules: Vec<CompiledModule>,
a1dfa0c6
XL
409 pub allocator_module: Option<CompiledModule>,
410}
411
f9f354fc
XL
412fn need_bitcode_in_object(sess: &Session) -> bool {
413 let requested_for_rlib = sess.opts.cg.embed_bitcode
414 && sess.crate_types().contains(&CrateType::Rlib)
415 && sess.opts.output_types.contains_key(&OutputType::Exe);
29967ef6 416 let forced_by_target = sess.target.forces_embed_bitcode;
f9f354fc 417 requested_for_rlib || forced_by_target
a1dfa0c6
XL
418}
419
9fa01778 420fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
a1dfa0c6 421 if sess.opts.incremental.is_none() {
dfeec247 422 return false;
a1dfa0c6
XL
423 }
424
425 match sess.lto() {
a1dfa0c6 426 Lto::No => false,
dfeec247 427 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
a1dfa0c6
XL
428 }
429}
430
431pub fn start_async_codegen<B: ExtraBackendMethods>(
432 backend: B,
dc9dc135 433 tcx: TyCtxt<'_>,
17df50a5 434 target_cpu: String,
a1dfa0c6 435 metadata: EncodedMetadata,
a2a8927a 436 metadata_module: Option<CompiledModule>,
dc9dc135 437 total_cgus: usize,
a1dfa0c6 438) -> OngoingCodegen<B> {
e74abb32 439 let (coordinator_send, coordinator_receive) = channel();
a1dfa0c6 440 let sess = tcx.sess;
e74abb32 441
6a06907d
XL
442 let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
443 let no_builtins = tcx.sess.contains_name(crate_attrs, sym::no_builtins);
444 let is_compiler_builtins = tcx.sess.contains_name(crate_attrs, sym::compiler_builtins);
a1dfa0c6 445
136023e0 446 let crate_info = CrateInfo::new(tcx, target_cpu);
a1dfa0c6 447
f9f354fc
XL
448 let regular_config =
449 ModuleConfig::new(ModuleKind::Regular, sess, no_builtins, is_compiler_builtins);
450 let metadata_config =
451 ModuleConfig::new(ModuleKind::Metadata, sess, no_builtins, is_compiler_builtins);
452 let allocator_config =
453 ModuleConfig::new(ModuleKind::Allocator, sess, no_builtins, is_compiler_builtins);
a1dfa0c6
XL
454
455 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
456 let (codegen_worker_send, codegen_worker_receive) = channel();
457
dfeec247
XL
458 let coordinator_thread = start_executing_work(
459 backend.clone(),
460 tcx,
461 &crate_info,
462 shared_emitter,
463 codegen_worker_send,
464 coordinator_receive,
465 total_cgus,
466 sess.jobserver.clone(),
ba9703b0 467 Arc::new(regular_config),
dfeec247
XL
468 Arc::new(metadata_config),
469 Arc::new(allocator_config),
470 coordinator_send.clone(),
471 );
a1dfa0c6
XL
472
473 OngoingCodegen {
474 backend,
a1dfa0c6 475 metadata,
a2a8927a 476 metadata_module,
a1dfa0c6
XL
477 crate_info,
478
a1dfa0c6
XL
479 codegen_worker_receive,
480 shared_emitter_main,
064997fb
FG
481 coordinator: Coordinator {
482 sender: coordinator_send,
483 future: Some(coordinator_thread),
484 phantom: PhantomData,
485 },
5099ac24 486 output_filenames: tcx.output_filenames(()).clone(),
a1dfa0c6
XL
487 }
488}
489
490fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
491 sess: &Session,
492 compiled_modules: &CompiledModules,
493) -> FxHashMap<WorkProductId, WorkProduct> {
494 let mut work_products = FxHashMap::default();
495
496 if sess.opts.incremental.is_none() {
497 return work_products;
498 }
499
f9f354fc 500 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
dfeec247 501
a1dfa0c6 502 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
064997fb
FG
503 let mut files = Vec::new();
504 if let Some(object_file_path) = &module.object {
505 files.push(("o", object_file_path.as_path()));
506 }
507 if let Some(dwarf_object_file_path) = &module.dwarf_object {
508 files.push(("dwo", dwarf_object_file_path.as_path()));
509 }
510
511 if let Some((id, product)) =
512 copy_cgu_workproduct_to_incr_comp_cache_dir(sess, &module.name, files.as_slice())
513 {
514 work_products.insert(id, product);
a1dfa0c6
XL
515 }
516 }
517
518 work_products
519}
520
dfeec247
XL
521fn produce_final_output_artifacts(
522 sess: &Session,
523 compiled_modules: &CompiledModules,
524 crate_output: &OutputFilenames,
525) {
a1dfa0c6
XL
526 let mut user_wants_bitcode = false;
527 let mut user_wants_objects = false;
528
529 // Produce final compile outputs.
530 let copy_gracefully = |from: &Path, to: &Path| {
531 if let Err(e) = fs::copy(from, to) {
532 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
533 }
534 };
535
dfeec247 536 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
a1dfa0c6
XL
537 if compiled_modules.modules.len() == 1 {
538 // 1) Only one codegen unit. In this case it's no difficulty
539 // to copy `foo.0.x` to `foo.x`.
540 let module_name = Some(&compiled_modules.modules[0].name[..]);
541 let path = crate_output.temp_path(output_type, module_name);
dfeec247 542 copy_gracefully(&path, &crate_output.path(output_type));
a1dfa0c6
XL
543 if !sess.opts.cg.save_temps && !keep_numbered {
544 // The user just wants `foo.x`, not `foo.#module-name#.x`.
6a06907d 545 ensure_removed(sess.diagnostic(), &path);
a1dfa0c6
XL
546 }
547 } else {
dfeec247
XL
548 let ext = crate_output
549 .temp_path(output_type, None)
550 .extension()
551 .unwrap()
552 .to_str()
553 .unwrap()
554 .to_owned();
a1dfa0c6
XL
555
556 if crate_output.outputs.contains_key(&output_type) {
557 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
558 // no good solution for this case, so warn the user.
dfeec247
XL
559 sess.warn(&format!(
560 "ignoring emit path because multiple .{} files \
561 were produced",
562 ext
563 ));
a1dfa0c6
XL
564 } else if crate_output.single_output_file.is_some() {
565 // 3) Multiple codegen units, with `-o some_name`. We have
566 // no good solution for this case, so warn the user.
dfeec247
XL
567 sess.warn(&format!(
568 "ignoring -o because multiple .{} files \
569 were produced",
570 ext
571 ));
a1dfa0c6
XL
572 } else {
573 // 4) Multiple codegen units, but no explicit name. We
574 // just leave the `foo.0.x` files in place.
575 // (We don't have to do any work in this case.)
576 }
577 }
578 };
579
580 // Flag to indicate whether the user explicitly requested bitcode.
581 // Otherwise, we produced it only as a temporary output, and will need
582 // to get rid of it.
583 for output_type in crate_output.outputs.keys() {
584 match *output_type {
585 OutputType::Bitcode => {
586 user_wants_bitcode = true;
587 // Copy to .bc, but always keep the .0.bc. There is a later
588 // check to figure out if we should delete .0.bc files, or keep
589 // them for making an rlib.
590 copy_if_one_unit(OutputType::Bitcode, true);
591 }
592 OutputType::LlvmAssembly => {
593 copy_if_one_unit(OutputType::LlvmAssembly, false);
594 }
595 OutputType::Assembly => {
596 copy_if_one_unit(OutputType::Assembly, false);
597 }
598 OutputType::Object => {
599 user_wants_objects = true;
600 copy_if_one_unit(OutputType::Object, true);
601 }
dfeec247 602 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
a1dfa0c6
XL
603 }
604 }
605
606 // Clean up unwanted temporary files.
607
608 // We create the following files by default:
609 // - #crate#.#module-name#.bc
610 // - #crate#.#module-name#.o
611 // - #crate#.crate.metadata.bc
612 // - #crate#.crate.metadata.o
613 // - #crate#.o (linked from crate.##.o)
614 // - #crate#.bc (copied from crate.##.bc)
615 // We may create additional files if requested by the user (through
616 // `-C save-temps` or `--emit=` flags).
617
618 if !sess.opts.cg.save_temps {
619 // Remove the temporary .#module-name#.o objects. If the user didn't
620 // explicitly request bitcode (with --emit=bc), and the bitcode is not
621 // needed for building an rlib, then we must remove .#module-name#.bc as
622 // well.
623
624 // Specific rules for keeping .#module-name#.bc:
625 // - If the user requested bitcode (`user_wants_bitcode`), and
626 // codegen_units > 1, then keep it.
627 // - If the user requested bitcode but codegen_units == 1, then we
628 // can toss .#module-name#.bc because we copied it to .bc earlier.
629 // - If we're not building an rlib and the user didn't request
630 // bitcode, then delete .#module-name#.bc.
631 // If you change how this works, also update back::link::link_rlib,
632 // where .#module-name#.bc files are (maybe) deleted after making an
633 // rlib.
634 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
635
636 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
637
dfeec247
XL
638 let keep_numbered_objects =
639 needs_crate_object || (user_wants_objects && sess.codegen_units() > 1);
a1dfa0c6
XL
640
641 for module in compiled_modules.modules.iter() {
642 if let Some(ref path) = module.object {
643 if !keep_numbered_objects {
6a06907d 644 ensure_removed(sess.diagnostic(), path);
a1dfa0c6
XL
645 }
646 }
647
fc512014
XL
648 if let Some(ref path) = module.dwarf_object {
649 if !keep_numbered_objects {
6a06907d 650 ensure_removed(sess.diagnostic(), path);
fc512014
XL
651 }
652 }
653
a1dfa0c6
XL
654 if let Some(ref path) = module.bytecode {
655 if !keep_numbered_bitcode {
6a06907d 656 ensure_removed(sess.diagnostic(), path);
a1dfa0c6
XL
657 }
658 }
659 }
660
661 if !user_wants_bitcode {
a1dfa0c6
XL
662 if let Some(ref allocator_module) = compiled_modules.allocator_module {
663 if let Some(ref path) = allocator_module.bytecode {
6a06907d 664 ensure_removed(sess.diagnostic(), path);
a1dfa0c6
XL
665 }
666 }
667 }
668 }
669
670 // We leave the following files around by default:
671 // - #crate#.o
672 // - #crate#.crate.metadata.o
673 // - #crate#.bc
674 // These are used in linking steps and will be cleaned up afterward.
675}
676
a1dfa0c6
XL
677pub enum WorkItem<B: WriteBackendMethods> {
678 /// Optimize a newly codegened, totally unoptimized module.
679 Optimize(ModuleCodegen<B::Module>),
680 /// Copy the post-LTO artifacts from the incremental cache to the output
681 /// directory.
682 CopyPostLtoArtifacts(CachedModuleCodegen),
9fa01778 683 /// Performs (Thin)LTO on the given module.
a1dfa0c6
XL
684 LTO(lto::LtoModuleCodegen<B>),
685}
686
687impl<B: WriteBackendMethods> WorkItem<B> {
688 pub fn module_kind(&self) -> ModuleKind {
689 match *self {
690 WorkItem::Optimize(ref m) => m.kind,
dfeec247 691 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
a1dfa0c6
XL
692 }
693 }
694
74b04a01 695 fn start_profiling<'a>(&self, cgcx: &'a CodegenContext<B>) -> TimingGuard<'a> {
a1dfa0c6 696 match *self {
74b04a01 697 WorkItem::Optimize(ref m) => {
a2a8927a 698 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name)
74b04a01
XL
699 }
700 WorkItem::CopyPostLtoArtifacts(ref m) => cgcx
701 .prof
a2a8927a 702 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*m.name),
74b04a01
XL
703 WorkItem::LTO(ref m) => {
704 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name())
705 }
a1dfa0c6
XL
706 }
707 }
6a06907d
XL
708
709 /// Generate a short description of this work item suitable for use as a thread name.
710 fn short_description(&self) -> String {
711 // `pthread_setname()` on *nix is limited to 15 characters and longer names are ignored.
712 // Use very short descriptions in this case to maximize the space available for the module name.
713 // Windows does not have that limitation so use slightly more descriptive names there.
714 match self {
715 WorkItem::Optimize(m) => {
716 #[cfg(windows)]
717 return format!("optimize module {}", m.name);
718 #[cfg(not(windows))]
719 return format!("opt {}", m.name);
720 }
721 WorkItem::CopyPostLtoArtifacts(m) => {
722 #[cfg(windows)]
723 return format!("copy LTO artifacts for {}", m.name);
724 #[cfg(not(windows))]
725 return format!("copy {}", m.name);
726 }
727 WorkItem::LTO(m) => {
728 #[cfg(windows)]
729 return format!("LTO module {}", m.name());
730 #[cfg(not(windows))]
731 return format!("LTO {}", m.name());
732 }
733 }
734 }
a1dfa0c6
XL
735}
736
0731742a 737enum WorkItemResult<B: WriteBackendMethods> {
a1dfa0c6 738 Compiled(CompiledModule),
1b1a35ee 739 NeedsLink(ModuleCodegen<B::Module>),
9fa01778 740 NeedsFatLTO(FatLTOInput<B>),
0731742a 741 NeedsThinLTO(String, B::ThinBuffer),
a1dfa0c6
XL
742}
743
9fa01778 744pub enum FatLTOInput<B: WriteBackendMethods> {
dfeec247 745 Serialized { name: String, buffer: B::ModuleBuffer },
9fa01778
XL
746 InMemory(ModuleCodegen<B::Module>),
747}
748
a1dfa0c6
XL
749fn execute_work_item<B: ExtraBackendMethods>(
750 cgcx: &CodegenContext<B>,
751 work_item: WorkItem<B>,
0731742a 752) -> Result<WorkItemResult<B>, FatalError> {
a1dfa0c6
XL
753 let module_config = cgcx.config(work_item.module_kind());
754
755 match work_item {
dfeec247 756 WorkItem::Optimize(module) => execute_optimize_work_item(cgcx, module, module_config),
a1dfa0c6 757 WorkItem::CopyPostLtoArtifacts(module) => {
6a06907d 758 Ok(execute_copy_from_cache_work_item(cgcx, module, module_config))
a1dfa0c6 759 }
dfeec247 760 WorkItem::LTO(module) => execute_lto_work_item(cgcx, module, module_config),
a1dfa0c6
XL
761 }
762}
763
74b04a01 764// Actual LTO type we end up choosing based on multiple factors.
f9f354fc 765pub enum ComputedLtoType {
0731742a
XL
766 No,
767 Thin,
768 Fat,
769}
770
f9f354fc
XL
771pub fn compute_per_cgu_lto_type(
772 sess_lto: &Lto,
773 opts: &config::Options,
774 sess_crate_types: &[CrateType],
775 module_kind: ModuleKind,
776) -> ComputedLtoType {
777 // Metadata modules never participate in LTO regardless of the lto
778 // settings.
779 if module_kind == ModuleKind::Metadata {
780 return ComputedLtoType::No;
a1dfa0c6
XL
781 }
782
0731742a
XL
783 // If the linker does LTO, we don't have to do it. Note that we
784 // keep doing full LTO, if it is requested, as not to break the
785 // assumption that the output will be a single module.
f9f354fc 786 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
a1dfa0c6 787
0731742a
XL
788 // When we're automatically doing ThinLTO for multi-codegen-unit
789 // builds we don't actually want to LTO the allocator modules if
790 // it shows up. This is due to various linker shenanigans that
791 // we'll encounter later.
f9f354fc 792 let is_allocator = module_kind == ModuleKind::Allocator;
a1dfa0c6 793
5e7ed085 794 // We ignore a request for full crate graph LTO if the crate type
0731742a
XL
795 // is only an rlib, as there is no full crate graph to process,
796 // that'll happen later.
797 //
798 // This use case currently comes up primarily for targets that
799 // require LTO so the request for LTO is always unconditionally
800 // passed down to the backend, but we don't actually want to do
801 // anything about it yet until we've got a final product.
f9f354fc 802 let is_rlib = sess_crate_types.len() == 1 && sess_crate_types[0] == CrateType::Rlib;
a1dfa0c6 803
f9f354fc
XL
804 match sess_lto {
805 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
806 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
807 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
808 _ => ComputedLtoType::No,
809 }
810}
811
812fn execute_optimize_work_item<B: ExtraBackendMethods>(
813 cgcx: &CodegenContext<B>,
814 module: ModuleCodegen<B::Module>,
815 module_config: &ModuleConfig,
816) -> Result<WorkItemResult<B>, FatalError> {
817 let diag_handler = cgcx.create_diag_handler();
818
819 unsafe {
820 B::optimize(cgcx, &diag_handler, &module, module_config)?;
821 }
822
823 // After we've done the initial round of optimizations we need to
824 // decide whether to synchronously codegen this module or ship it
825 // back to the coordinator thread for further LTO processing (which
826 // has to wait for all the initial modules to be optimized).
827
828 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
0731742a 829
9fa01778
XL
830 // If we're doing some form of incremental LTO then we need to be sure to
831 // save our module to disk first.
832 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
833 let filename = pre_lto_bitcode_filename(&module.name);
834 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
835 } else {
836 None
837 };
838
1b1a35ee
XL
839 match lto_type {
840 ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config),
0731742a 841 ComputedLtoType::Thin => {
9fa01778
XL
842 let (name, thin_buffer) = B::prepare_thin(module);
843 if let Some(path) = bitcode {
844 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
dfeec247 845 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
9fa01778
XL
846 });
847 }
1b1a35ee 848 Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))
0731742a 849 }
dfeec247
XL
850 ComputedLtoType::Fat => match bitcode {
851 Some(path) => {
852 let (name, buffer) = B::serialize_module(module);
853 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
854 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
855 });
1b1a35ee 856 Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer }))
9fa01778 857 }
1b1a35ee 858 None => Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module))),
dfeec247 859 },
1b1a35ee 860 }
a1dfa0c6
XL
861}
862
863fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
864 cgcx: &CodegenContext<B>,
865 module: CachedModuleCodegen,
866 module_config: &ModuleConfig,
6a06907d 867) -> WorkItemResult<B> {
923072b8
FG
868 assert!(module_config.emit_obj != EmitObj::None);
869
dfeec247 870 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
064997fb
FG
871
872 let load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
873 let source_file = in_incr_comp_dir(&incr_comp_session_dir, saved_path);
874 debug!(
875 "copying pre-existing module `{}` from {:?} to {}",
876 module.name,
877 source_file,
878 output_path.display()
879 );
880 match link_or_copy(&source_file, &output_path) {
881 Ok(_) => Some(output_path),
882 Err(err) => {
883 let diag_handler = cgcx.create_diag_handler();
884 diag_handler.err(&format!(
885 "unable to copy {} to {}: {}",
886 source_file.display(),
887 output_path.display(),
888 err
889 ));
890 None
891 }
892 }
893 };
894
895 let object = load_from_incr_comp_dir(
896 cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name)),
897 &module.source.saved_files.get("o").expect("no saved object file in work product"),
923072b8 898 );
064997fb
FG
899 let dwarf_object =
900 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
901 let dwarf_obj_out = cgcx
902 .output_filenames
903 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, Some(&module.name))
904 .expect(
905 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
906 );
907 load_from_incr_comp_dir(dwarf_obj_out, &saved_dwarf_object_file)
908 });
a1dfa0c6 909
6a06907d 910 WorkItemResult::Compiled(CompiledModule {
a1dfa0c6
XL
911 name: module.name,
912 kind: ModuleKind::Regular,
064997fb
FG
913 object,
914 dwarf_object,
f9f354fc 915 bytecode: None,
6a06907d 916 })
a1dfa0c6
XL
917}
918
919fn execute_lto_work_item<B: ExtraBackendMethods>(
920 cgcx: &CodegenContext<B>,
04454e1e 921 module: lto::LtoModuleCodegen<B>,
a1dfa0c6 922 module_config: &ModuleConfig,
1b1a35ee
XL
923) -> Result<WorkItemResult<B>, FatalError> {
924 let module = unsafe { module.optimize(cgcx)? };
925 finish_intra_module_work(cgcx, module, module_config)
926}
927
928fn finish_intra_module_work<B: ExtraBackendMethods>(
929 cgcx: &CodegenContext<B>,
930 module: ModuleCodegen<B::Module>,
931 module_config: &ModuleConfig,
0731742a 932) -> Result<WorkItemResult<B>, FatalError> {
a1dfa0c6
XL
933 let diag_handler = cgcx.create_diag_handler();
934
064997fb 935 if !cgcx.opts.unstable_opts.combine_cgu
1b1a35ee
XL
936 || module.kind == ModuleKind::Metadata
937 || module.kind == ModuleKind::Allocator
938 {
939 let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? };
a1dfa0c6 940 Ok(WorkItemResult::Compiled(module))
1b1a35ee
XL
941 } else {
942 Ok(WorkItemResult::NeedsLink(module))
a1dfa0c6
XL
943 }
944}
945
946pub enum Message<B: WriteBackendMethods> {
947 Token(io::Result<Acquired>),
0731742a 948 NeedsFatLTO {
9fa01778 949 result: FatLTOInput<B>,
a1dfa0c6
XL
950 worker_id: usize,
951 },
0731742a
XL
952 NeedsThinLTO {
953 name: String,
954 thin_buffer: B::ThinBuffer,
955 worker_id: usize,
956 },
1b1a35ee
XL
957 NeedsLink {
958 module: ModuleCodegen<B::Module>,
959 worker_id: usize,
960 },
a1dfa0c6 961 Done {
dfeec247 962 result: Result<CompiledModule, Option<WorkerFatalError>>,
a1dfa0c6
XL
963 worker_id: usize,
964 },
965 CodegenDone {
966 llvm_work_item: WorkItem<B>,
967 cost: u64,
968 },
969 AddImportOnlyModule {
970 module_data: SerializedModule<B::ModuleBuffer>,
971 work_product: WorkProduct,
972 },
973 CodegenComplete,
974 CodegenItem,
975 CodegenAborted,
976}
977
978struct Diagnostic {
979 msg: String,
980 code: Option<DiagnosticId>,
981 lvl: Level,
982}
983
984#[derive(PartialEq, Clone, Copy, Debug)]
985enum MainThreadWorkerState {
986 Idle,
987 Codegenning,
988 LLVMing,
989}
990
991fn start_executing_work<B: ExtraBackendMethods>(
992 backend: B,
dc9dc135 993 tcx: TyCtxt<'_>,
a1dfa0c6
XL
994 crate_info: &CrateInfo,
995 shared_emitter: SharedEmitter,
996 codegen_worker_send: Sender<Message<B>>,
997 coordinator_receive: Receiver<Box<dyn Any + Send>>,
998 total_cgus: usize,
999 jobserver: Client,
ba9703b0 1000 regular_config: Arc<ModuleConfig>,
a1dfa0c6 1001 metadata_config: Arc<ModuleConfig>,
dc9dc135 1002 allocator_config: Arc<ModuleConfig>,
e74abb32 1003 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
a1dfa0c6 1004) -> thread::JoinHandle<Result<CompiledModules, ()>> {
e74abb32 1005 let coordinator_send = tx_to_llvm_workers;
a1dfa0c6
XL
1006 let sess = tcx.sess;
1007
1008 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1009 let exported_symbols = {
1010 let mut exported_symbols = FxHashMap::default();
1011
1012 let copy_symbols = |cnum| {
dfeec247
XL
1013 let symbols = tcx
1014 .exported_symbols(cnum)
1015 .iter()
1016 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
1017 .collect();
a1dfa0c6
XL
1018 Arc::new(symbols)
1019 };
1020
1021 match sess.lto() {
1022 Lto::No => None,
1023 Lto::ThinLocal => {
1024 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1025 Some(Arc::new(exported_symbols))
1026 }
1027 Lto::Fat | Lto::Thin => {
1028 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
136023e0 1029 for &cnum in tcx.crates(()).iter() {
a1dfa0c6
XL
1030 exported_symbols.insert(cnum, copy_symbols(cnum));
1031 }
1032 Some(Arc::new(exported_symbols))
1033 }
1034 }
1035 };
1036
1037 // First up, convert our jobserver into a helper thread so we can use normal
1038 // mpsc channels to manage our messages and such.
1039 // After we've requested tokens then we'll, when we can,
1040 // get tokens on `coordinator_receive` which will
1041 // get managed in the main loop below.
1042 let coordinator_send2 = coordinator_send.clone();
dfeec247
XL
1043 let helper = jobserver
1044 .into_helper_thread(move |token| {
1045 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1046 })
1047 .expect("failed to spawn helper thread");
a1dfa0c6
XL
1048
1049 let mut each_linked_rlib_for_lto = Vec::new();
e74abb32 1050 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
a1dfa0c6 1051 if link::ignored_for_lto(sess, crate_info, cnum) {
dfeec247 1052 return;
a1dfa0c6
XL
1053 }
1054 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1055 }));
1056
064997fb
FG
1057 let ol =
1058 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1059 // If we know that we won’t be doing codegen, create target machines without optimisation.
1060 config::OptLevel::No
1061 } else {
1062 tcx.backend_optimization_level(())
1063 };
5e7ed085 1064 let backend_features = tcx.global_backend_features(());
a1dfa0c6
XL
1065 let cgcx = CodegenContext::<B> {
1066 backend: backend.clone(),
f9f354fc 1067 crate_types: sess.crate_types().to_vec(),
a1dfa0c6
XL
1068 each_linked_rlib_for_lto,
1069 lto: sess.lto(),
a1dfa0c6
XL
1070 fewer_names: sess.fewer_names(),
1071 save_temps: sess.opts.cg.save_temps,
064997fb 1072 time_trace: sess.opts.unstable_opts.llvm_time_trace,
a1dfa0c6 1073 opts: Arc::new(sess.opts.clone()),
e74abb32 1074 prof: sess.prof.clone(),
a1dfa0c6 1075 exported_symbols,
a1dfa0c6
XL
1076 remark: sess.opts.cg.remark.clone(),
1077 worker: 0,
1078 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1079 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1080 coordinator_send,
1081 diag_emitter: shared_emitter.clone(),
5099ac24 1082 output_filenames: tcx.output_filenames(()).clone(),
ba9703b0 1083 regular_module_config: regular_config,
a1dfa0c6
XL
1084 metadata_module_config: metadata_config,
1085 allocator_module_config: allocator_config,
5e7ed085 1086 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
a1dfa0c6
XL
1087 total_cgus,
1088 msvc_imps_needed: msvc_imps_needed(tcx),
fc512014 1089 is_pe_coff: tcx.sess.target.is_like_windows,
5869c6ff 1090 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
29967ef6 1091 target_pointer_width: tcx.sess.target.pointer_width,
5e7ed085 1092 target_arch: tcx.sess.target.arch.to_string(),
a1dfa0c6 1093 debuginfo: tcx.sess.opts.debuginfo,
5869c6ff 1094 split_debuginfo: tcx.sess.split_debuginfo(),
064997fb 1095 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
a1dfa0c6
XL
1096 };
1097
1098 // This is the "main loop" of parallel work happening for parallel codegen.
1099 // It's here that we manage parallelism, schedule work, and work with
1100 // messages coming from clients.
1101 //
1102 // There are a few environmental pre-conditions that shape how the system
1103 // is set up:
1104 //
1105 // - Error reporting only can happen on the main thread because that's the
1106 // only place where we have access to the compiler `Session`.
1107 // - LLVM work can be done on any thread.
1108 // - Codegen can only happen on the main thread.
cdc7bbd5 1109 // - Each thread doing substantial work must be in possession of a `Token`
a1dfa0c6
XL
1110 // from the `Jobserver`.
1111 // - The compiler process always holds one `Token`. Any additional `Tokens`
1112 // have to be requested from the `Jobserver`.
1113 //
1114 // Error Reporting
1115 // ===============
1116 // The error reporting restriction is handled separately from the rest: We
1117 // set up a `SharedEmitter` the holds an open channel to the main thread.
1118 // When an error occurs on any thread, the shared emitter will send the
1119 // error message to the receiver main thread (`SharedEmitterMain`). The
1120 // main thread will periodically query this error message queue and emit
1121 // any error messages it has received. It might even abort compilation if
1122 // has received a fatal error. In this case we rely on all other threads
1123 // being torn down automatically with the main thread.
1124 // Since the main thread will often be busy doing codegen work, error
1125 // reporting will be somewhat delayed, since the message queue can only be
1126 // checked in between to work packages.
1127 //
1128 // Work Processing Infrastructure
1129 // ==============================
1130 // The work processing infrastructure knows three major actors:
1131 //
1132 // - the coordinator thread,
1133 // - the main thread, and
1134 // - LLVM worker threads
1135 //
1136 // The coordinator thread is running a message loop. It instructs the main
1137 // thread about what work to do when, and it will spawn off LLVM worker
1138 // threads as open LLVM WorkItems become available.
1139 //
1140 // The job of the main thread is to codegen CGUs into LLVM work package
1141 // (since the main thread is the only thread that can do this). The main
1142 // thread will block until it receives a message from the coordinator, upon
1143 // which it will codegen one CGU, send it to the coordinator and block
1144 // again. This way the coordinator can control what the main thread is
1145 // doing.
1146 //
1147 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1148 // available, it will spawn off a new LLVM worker thread and let it process
1149 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1150 // it will just shut down, which also frees all resources associated with
1151 // the given LLVM module, and sends a message to the coordinator that the
1152 // has been completed.
1153 //
1154 // Work Scheduling
1155 // ===============
1156 // The scheduler's goal is to minimize the time it takes to complete all
1157 // work there is, however, we also want to keep memory consumption low
1158 // if possible. These two goals are at odds with each other: If memory
1159 // consumption were not an issue, we could just let the main thread produce
1160 // LLVM WorkItems at full speed, assuring maximal utilization of
cdc7bbd5 1161 // Tokens/LLVM worker threads. However, since codegen is usually faster
a1dfa0c6
XL
1162 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1163 // WorkItem potentially holds on to a substantial amount of memory.
1164 //
1165 // So the actual goal is to always produce just enough LLVM WorkItems as
1166 // not to starve our LLVM worker threads. That means, once we have enough
1167 // WorkItems in our queue, we can block the main thread, so it does not
1168 // produce more until we need them.
1169 //
1170 // Doing LLVM Work on the Main Thread
1171 // ----------------------------------
1172 // Since the main thread owns the compiler processes implicit `Token`, it is
1173 // wasteful to keep it blocked without doing any work. Therefore, what we do
1174 // in this case is: We spawn off an additional LLVM worker thread that helps
1175 // reduce the queue. The work it is doing corresponds to the implicit
1176 // `Token`. The coordinator will mark the main thread as being busy with
1177 // LLVM work. (The actual work happens on another OS thread but we just care
1178 // about `Tokens`, not actual threads).
1179 //
1180 // When any LLVM worker thread finishes while the main thread is marked as
1181 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1182 // of the just finished thread to the LLVM worker thread that is working on
1183 // behalf of the main thread's implicit Token, thus freeing up the main
1184 // thread again. The coordinator can then again decide what the main thread
1185 // should do. This allows the coordinator to make decisions at more points
1186 // in time.
1187 //
1188 // Striking a Balance between Throughput and Memory Consumption
1189 // ------------------------------------------------------------
1190 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1191 // memory consumption as low as possible, are in conflict with each other,
1192 // we have to find a trade off between them. Right now, the goal is to keep
1193 // all workers busy, which means that no worker should find the queue empty
1194 // when it is ready to start.
1195 // How do we do achieve this? Good question :) We actually never know how
1196 // many `Tokens` are potentially available so it's hard to say how much to
1197 // fill up the queue before switching the main thread to LLVM work. Also we
1198 // currently don't have a means to estimate how long a running LLVM worker
1199 // will still be busy with it's current WorkItem. However, we know the
1200 // maximal count of available Tokens that makes sense (=the number of CPU
1201 // cores), so we can take a conservative guess. The heuristic we use here
1202 // is implemented in the `queue_full_enough()` function.
1203 //
1204 // Some Background on Jobservers
1205 // -----------------------------
1206 // It's worth also touching on the management of parallelism here. We don't
1207 // want to just spawn a thread per work item because while that's optimal
1208 // parallelism it may overload a system with too many threads or violate our
1209 // configuration for the maximum amount of cpu to use for this process. To
1210 // manage this we use the `jobserver` crate.
1211 //
1212 // Job servers are an artifact of GNU make and are used to manage
1213 // parallelism between processes. A jobserver is a glorified IPC semaphore
1214 // basically. Whenever we want to run some work we acquire the semaphore,
1215 // and whenever we're done with that work we release the semaphore. In this
1216 // manner we can ensure that the maximum number of parallel workers is
1217 // capped at any one point in time.
1218 //
1219 // LTO and the coordinator thread
1220 // ------------------------------
1221 //
1222 // The final job the coordinator thread is responsible for is managing LTO
1223 // and how that works. When LTO is requested what we'll to is collect all
1224 // optimized LLVM modules into a local vector on the coordinator. Once all
1225 // modules have been codegened and optimized we hand this to the `lto`
1226 // module for further optimization. The `lto` module will return back a list
1227 // of more modules to work on, which the coordinator will continue to spawn
1228 // work for.
1229 //
1230 // Each LLVM module is automatically sent back to the coordinator for LTO if
1231 // necessary. There's already optimizations in place to avoid sending work
1232 // back to the coordinator if LTO isn't requested.
3c0e092e 1233 return B::spawn_thread(cgcx.time_trace, move || {
a1dfa0c6
XL
1234 let mut worker_id_counter = 0;
1235 let mut free_worker_ids = Vec::new();
1236 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1237 if let Some(id) = free_worker_ids.pop() {
1238 id
1239 } else {
1240 let id = worker_id_counter;
1241 worker_id_counter += 1;
1242 id
1243 }
1244 };
1245
1246 // This is where we collect codegen units that have gone all the way
1247 // through codegen and LLVM.
1248 let mut compiled_modules = vec![];
a1dfa0c6 1249 let mut compiled_allocator_module = None;
1b1a35ee 1250 let mut needs_link = Vec::new();
0731742a
XL
1251 let mut needs_fat_lto = Vec::new();
1252 let mut needs_thin_lto = Vec::new();
a1dfa0c6
XL
1253 let mut lto_import_only_modules = Vec::new();
1254 let mut started_lto = false;
1255 let mut codegen_aborted = false;
1256
1257 // This flag tracks whether all items have gone through codegens
1258 let mut codegen_done = false;
1259
1260 // This is the queue of LLVM work items that still need processing.
1261 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1262
1263 // This are the Jobserver Tokens we currently hold. Does not include
1264 // the implicit Token the compiler process owns no matter what.
1265 let mut tokens = Vec::new();
1266
1267 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1268 let mut running = 0;
1269
dfeec247
XL
1270 let prof = &cgcx.prof;
1271 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
a1dfa0c6
XL
1272
1273 // Run the message loop while there's still anything that needs message
1274 // processing. Note that as soon as codegen is aborted we simply want to
1275 // wait for all existing work to finish, so many of the conditions here
1276 // only apply if codegen hasn't been aborted as they represent pending
1277 // work to be done.
dfeec247
XL
1278 while !codegen_done
1279 || running > 0
064997fb 1280 || main_thread_worker_state == MainThreadWorkerState::LLVMing
dfeec247 1281 || (!codegen_aborted
74b04a01
XL
1282 && !(work_items.is_empty()
1283 && needs_fat_lto.is_empty()
1284 && needs_thin_lto.is_empty()
1285 && lto_import_only_modules.is_empty()
1286 && main_thread_worker_state == MainThreadWorkerState::Idle))
a1dfa0c6 1287 {
a1dfa0c6
XL
1288 // While there are still CGUs to be codegened, the coordinator has
1289 // to decide how to utilize the compiler processes implicit Token:
1290 // For codegenning more CGU or for running them through LLVM.
1291 if !codegen_done {
1292 if main_thread_worker_state == MainThreadWorkerState::Idle {
6a06907d
XL
1293 // Compute the number of workers that will be running once we've taken as many
1294 // items from the work queue as we can, plus one for the main thread. It's not
1295 // critically important that we use this instead of just `running`, but it
1296 // prevents the `queue_full_enough` heuristic from fluctuating just because a
1297 // worker finished up and we decreased the `running` count, even though we're
1298 // just going to increase it right after this when we put a new worker to work.
1299 let extra_tokens = tokens.len().checked_sub(running).unwrap();
1300 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1301 let anticipated_running = running + additional_running + 1;
1302
1303 if !queue_full_enough(work_items.len(), anticipated_running) {
a1dfa0c6 1304 // The queue is not full enough, codegen more items:
74b04a01 1305 if codegen_worker_send.send(Message::CodegenItem).is_err() {
a1dfa0c6
XL
1306 panic!("Could not send Message::CodegenItem to main thread")
1307 }
1308 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1309 } else {
1310 // The queue is full enough to not let the worker
1311 // threads starve. Use the implicit Token to do some
1312 // LLVM work too.
dfeec247
XL
1313 let (item, _) =
1314 work_items.pop().expect("queue empty - queue_full_enough() broken?");
a1dfa0c6
XL
1315 let cgcx = CodegenContext {
1316 worker: get_worker_id(&mut free_worker_ids),
dfeec247 1317 ..cgcx.clone()
a1dfa0c6 1318 };
dfeec247
XL
1319 maybe_start_llvm_timer(
1320 prof,
1321 cgcx.config(item.module_kind()),
1322 &mut llvm_start_time,
1323 );
a1dfa0c6
XL
1324 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1325 spawn_work(cgcx, item);
1326 }
1327 }
1328 } else if codegen_aborted {
1329 // don't queue up any more work if codegen was aborted, we're
1330 // just waiting for our existing children to finish
1331 } else {
1332 // If we've finished everything related to normal codegen
1333 // then it must be the case that we've got some LTO work to do.
1334 // Perform the serial work here of figuring out what we're
1335 // going to LTO and then push a bunch of work items onto our
1336 // queue to do LTO
74b04a01 1337 if work_items.is_empty()
dfeec247
XL
1338 && running == 0
1339 && main_thread_worker_state == MainThreadWorkerState::Idle
1340 {
a1dfa0c6 1341 assert!(!started_lto);
a1dfa0c6 1342 started_lto = true;
0731742a 1343
416331ca
XL
1344 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1345 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1346 let import_only_modules = mem::take(&mut lto_import_only_modules);
0731742a 1347
dfeec247
XL
1348 for (work, cost) in
1349 generate_lto_work(&cgcx, needs_fat_lto, needs_thin_lto, import_only_modules)
1350 {
a1dfa0c6
XL
1351 let insertion_index = work_items
1352 .binary_search_by_key(&cost, |&(_, cost)| cost)
1353 .unwrap_or_else(|e| e);
1354 work_items.insert(insertion_index, (work, cost));
064997fb 1355 if !cgcx.opts.unstable_opts.no_parallel_llvm {
a1dfa0c6
XL
1356 helper.request_token();
1357 }
1358 }
1359 }
1360
1361 // In this branch, we know that everything has been codegened,
1362 // so it's just a matter of determining whether the implicit
1363 // Token is free to use for LLVM work.
1364 match main_thread_worker_state {
1365 MainThreadWorkerState::Idle => {
1366 if let Some((item, _)) = work_items.pop() {
1367 let cgcx = CodegenContext {
1368 worker: get_worker_id(&mut free_worker_ids),
dfeec247 1369 ..cgcx.clone()
a1dfa0c6 1370 };
dfeec247
XL
1371 maybe_start_llvm_timer(
1372 prof,
1373 cgcx.config(item.module_kind()),
1374 &mut llvm_start_time,
1375 );
a1dfa0c6
XL
1376 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1377 spawn_work(cgcx, item);
1378 } else {
1379 // There is no unstarted work, so let the main thread
1380 // take over for a running worker. Otherwise the
1381 // implicit token would just go to waste.
1382 // We reduce the `running` counter by one. The
1383 // `tokens.truncate()` below will take care of
1384 // giving the Token back.
1385 debug_assert!(running > 0);
1386 running -= 1;
1387 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1388 }
1389 }
dfeec247
XL
1390 MainThreadWorkerState::Codegenning => bug!(
1391 "codegen worker should not be codegenning after \
1392 codegen was already completed"
1393 ),
a1dfa0c6
XL
1394 MainThreadWorkerState::LLVMing => {
1395 // Already making good use of that token
1396 }
1397 }
1398 }
1399
1400 // Spin up what work we can, only doing this while we've got available
1401 // parallelism slots and work left to spawn.
74b04a01 1402 while !codegen_aborted && !work_items.is_empty() && running < tokens.len() {
a1dfa0c6
XL
1403 let (item, _) = work_items.pop().unwrap();
1404
dfeec247 1405 maybe_start_llvm_timer(prof, cgcx.config(item.module_kind()), &mut llvm_start_time);
a1dfa0c6 1406
dfeec247
XL
1407 let cgcx =
1408 CodegenContext { worker: get_worker_id(&mut free_worker_ids), ..cgcx.clone() };
a1dfa0c6
XL
1409
1410 spawn_work(cgcx, item);
1411 running += 1;
1412 }
1413
1414 // Relinquish accidentally acquired extra tokens
1415 tokens.truncate(running);
1416
0731742a
XL
1417 // If a thread exits successfully then we drop a token associated
1418 // with that worker and update our `running` count. We may later
1419 // re-acquire a token to continue running more work. We may also not
1420 // actually drop a token here if the worker was running with an
1421 // "ephemeral token"
1422 let mut free_worker = |worker_id| {
1423 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1424 main_thread_worker_state = MainThreadWorkerState::Idle;
1425 } else {
1426 running -= 1;
1427 }
1428
1429 free_worker_ids.push(worker_id);
1430 };
1431
a1dfa0c6
XL
1432 let msg = coordinator_receive.recv().unwrap();
1433 match *msg.downcast::<Message<B>>().ok().unwrap() {
1434 // Save the token locally and the next turn of the loop will use
1435 // this to spawn a new unit of work, or it may get dropped
1436 // immediately if we have no more work to spawn.
1437 Message::Token(token) => {
1438 match token {
1439 Ok(token) => {
1440 tokens.push(token);
1441
1442 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1443 // If the main thread token is used for LLVM work
1444 // at the moment, we turn that thread into a regular
1445 // LLVM worker thread, so the main thread is free
1446 // to react to codegen demand.
1447 main_thread_worker_state = MainThreadWorkerState::Idle;
1448 running += 1;
1449 }
1450 }
1451 Err(e) => {
1452 let msg = &format!("failed to acquire jobserver token: {}", e);
1453 shared_emitter.fatal(msg);
1454 // Exit the coordinator thread
1455 panic!("{}", msg)
1456 }
1457 }
1458 }
1459
1460 Message::CodegenDone { llvm_work_item, cost } => {
1461 // We keep the queue sorted by estimated processing cost,
1462 // so that more expensive items are processed earlier. This
1463 // is good for throughput as it gives the main thread more
1464 // time to fill up the queue and it avoids scheduling
1465 // expensive items to the end.
1466 // Note, however, that this is not ideal for memory
1467 // consumption, as LLVM module sizes are not evenly
1468 // distributed.
dfeec247 1469 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
a1dfa0c6 1470 let insertion_index = match insertion_index {
dfeec247 1471 Ok(idx) | Err(idx) => idx,
a1dfa0c6
XL
1472 };
1473 work_items.insert(insertion_index, (llvm_work_item, cost));
1474
064997fb 1475 if !cgcx.opts.unstable_opts.no_parallel_llvm {
a1dfa0c6
XL
1476 helper.request_token();
1477 }
dfeec247 1478 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
a1dfa0c6
XL
1479 main_thread_worker_state = MainThreadWorkerState::Idle;
1480 }
1481
1482 Message::CodegenComplete => {
1483 codegen_done = true;
dfeec247 1484 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
a1dfa0c6
XL
1485 main_thread_worker_state = MainThreadWorkerState::Idle;
1486 }
1487
1488 // If codegen is aborted that means translation was aborted due
1489 // to some normal-ish compiler error. In this situation we want
1490 // to exit as soon as possible, but we want to make sure all
1491 // existing work has finished. Flag codegen as being done, and
1492 // then conditions above will ensure no more work is spawned but
1493 // we'll keep executing this loop until `running` hits 0.
1494 Message::CodegenAborted => {
a1dfa0c6
XL
1495 codegen_done = true;
1496 codegen_aborted = true;
a1dfa0c6 1497 }
a1dfa0c6 1498 Message::Done { result: Ok(compiled_module), worker_id } => {
0731742a 1499 free_worker(worker_id);
a1dfa0c6
XL
1500 match compiled_module.kind {
1501 ModuleKind::Regular => {
1502 compiled_modules.push(compiled_module);
1503 }
a1dfa0c6
XL
1504 ModuleKind::Allocator => {
1505 assert!(compiled_allocator_module.is_none());
1506 compiled_allocator_module = Some(compiled_module);
1507 }
a2a8927a 1508 ModuleKind::Metadata => bug!("Should be handled separately"),
a1dfa0c6
XL
1509 }
1510 }
1b1a35ee
XL
1511 Message::NeedsLink { module, worker_id } => {
1512 free_worker(worker_id);
1513 needs_link.push(module);
1514 }
0731742a 1515 Message::NeedsFatLTO { result, worker_id } => {
a1dfa0c6 1516 assert!(!started_lto);
0731742a
XL
1517 free_worker(worker_id);
1518 needs_fat_lto.push(result);
1519 }
1520 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1521 assert!(!started_lto);
1522 free_worker(worker_id);
1523 needs_thin_lto.push((name, thin_buffer));
a1dfa0c6
XL
1524 }
1525 Message::AddImportOnlyModule { module_data, work_product } => {
1526 assert!(!started_lto);
1527 assert!(!codegen_done);
dfeec247 1528 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
a1dfa0c6
XL
1529 lto_import_only_modules.push((module_data, work_product));
1530 main_thread_worker_state = MainThreadWorkerState::Idle;
1531 }
0731742a 1532 // If the thread failed that means it panicked, so we abort immediately.
dfeec247 1533 Message::Done { result: Err(None), worker_id: _ } => {
a1dfa0c6
XL
1534 bug!("worker thread panicked");
1535 }
064997fb
FG
1536 Message::Done { result: Err(Some(WorkerFatalError)), worker_id } => {
1537 // Similar to CodegenAborted, wait for remaining work to finish.
1538 free_worker(worker_id);
1539 codegen_done = true;
1540 codegen_aborted = true;
a1dfa0c6 1541 }
dfeec247 1542 Message::CodegenItem => bug!("the coordinator should not receive codegen requests"),
a1dfa0c6
XL
1543 }
1544 }
1545
064997fb
FG
1546 if codegen_aborted {
1547 return Err(());
1548 }
1549
1b1a35ee
XL
1550 let needs_link = mem::take(&mut needs_link);
1551 if !needs_link.is_empty() {
1552 assert!(compiled_modules.is_empty());
1553 let diag_handler = cgcx.create_diag_handler();
1554 let module = B::run_link(&cgcx, &diag_handler, needs_link).map_err(|_| ())?;
1555 let module = unsafe {
1556 B::codegen(&cgcx, &diag_handler, module, cgcx.config(ModuleKind::Regular))
1557 .map_err(|_| ())?
1558 };
1559 compiled_modules.push(module);
1560 }
1561
dfeec247
XL
1562 // Drop to print timings
1563 drop(llvm_start_time);
a1dfa0c6
XL
1564
1565 // Regardless of what order these modules completed in, report them to
1566 // the backend in the same order every time to ensure that we're handing
1567 // out deterministic results.
1568 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1569
a1dfa0c6
XL
1570 Ok(CompiledModules {
1571 modules: compiled_modules,
a1dfa0c6
XL
1572 allocator_module: compiled_allocator_module,
1573 })
1574 });
1575
1576 // A heuristic that determines if we have enough LLVM WorkItems in the
1577 // queue so that the main thread can do LLVM work instead of codegen
6a06907d
XL
1578 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1579 // This heuristic scales ahead-of-time codegen according to available
1580 // concurrency, as measured by `workers_running`. The idea is that the
1581 // more concurrency we have available, the more demand there will be for
1582 // work items, and the fuller the queue should be kept to meet demand.
1583 // An important property of this approach is that we codegen ahead of
1584 // time only as much as necessary, so as to keep fewer LLVM modules in
1585 // memory at once, thereby reducing memory consumption.
1586 //
1587 // When the number of workers running is less than the max concurrency
1588 // available to us, this heuristic can cause us to instruct the main
1589 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1590 // of codegen, even though it seems like it *should* be codegenning so
1591 // that we can create more work items and spawn more LLVM workers.
1592 //
1593 // But this is not a problem. When the main thread is told to LLVM,
1594 // according to this heuristic and how work is scheduled, there is
1595 // always at least one item in the queue, and therefore at least one
1596 // pending jobserver token request. If there *is* more concurrency
1597 // available, we will immediately receive a token, which will upgrade
1598 // the main thread's LLVM worker to a real one (conceptually), and free
1599 // up the main thread to codegen if necessary. On the other hand, if
1600 // there isn't more concurrency, then the main thread working on an LLVM
1601 // item is appropriate, as long as the queue is full enough for demand.
1602 //
1603 // Speaking of which, how full should we keep the queue? Probably less
1604 // full than you'd think. A lot has to go wrong for the queue not to be
1605 // full enough and for that to have a negative effect on compile times.
1606 //
1607 // Workers are unlikely to finish at exactly the same time, so when one
1608 // finishes and takes another work item off the queue, we often have
1609 // ample time to codegen at that point before the next worker finishes.
1610 // But suppose that codegen takes so long that the workers exhaust the
1611 // queue, and we have one or more workers that have nothing to work on.
1612 // Well, it might not be so bad. Of all the LLVM modules we create and
1613 // optimize, one has to finish last. It's not necessarily the case that
1614 // by losing some concurrency for a moment, we delay the point at which
1615 // that last LLVM module is finished and the rest of compilation can
1616 // proceed. Also, when we can't take advantage of some concurrency, we
1617 // give tokens back to the job server. That enables some other rustc to
1618 // potentially make use of the available concurrency. That could even
1619 // *decrease* overall compile time if we're lucky. But yes, if no other
1620 // rustc can make use of the concurrency, then we've squandered it.
1621 //
1622 // However, keeping the queue full is also beneficial when we have a
1623 // surge in available concurrency. Then items can be taken from the
1624 // queue immediately, without having to wait for codegen.
1625 //
1626 // So, the heuristic below tries to keep one item in the queue for every
1627 // four running workers. Based on limited benchmarking, this appears to
1628 // be more than sufficient to avoid increasing compilation times.
1629 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1630 items_in_queue > 0 && items_in_queue >= quarter_of_workers
a1dfa0c6
XL
1631 }
1632
dfeec247
XL
1633 fn maybe_start_llvm_timer<'a>(
1634 prof: &'a SelfProfilerRef,
1635 config: &ModuleConfig,
1636 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1637 ) {
1638 if config.time_module && llvm_start_time.is_none() {
74b04a01 1639 *llvm_start_time = Some(prof.extra_verbose_generic_activity("LLVM_passes", "crate"));
a1dfa0c6
XL
1640 }
1641 }
1642}
1643
dfeec247
XL
1644/// `FatalError` is explicitly not `Send`.
1645#[must_use]
1646pub struct WorkerFatalError;
a1dfa0c6 1647
dfeec247 1648fn spawn_work<B: ExtraBackendMethods>(cgcx: CodegenContext<B>, work: WorkItem<B>) {
3c0e092e
XL
1649 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1650 // Set up a destructor which will fire off a message that we're done as
1651 // we exit.
1652 struct Bomb<B: ExtraBackendMethods> {
1653 coordinator_send: Sender<Box<dyn Any + Send>>,
1654 result: Option<Result<WorkItemResult<B>, FatalError>>,
1655 worker_id: usize,
1656 }
1657 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1658 fn drop(&mut self) {
1659 let worker_id = self.worker_id;
1660 let msg = match self.result.take() {
1661 Some(Ok(WorkItemResult::Compiled(m))) => {
1662 Message::Done::<B> { result: Ok(m), worker_id }
1663 }
1664 Some(Ok(WorkItemResult::NeedsLink(m))) => {
1665 Message::NeedsLink::<B> { module: m, worker_id }
1666 }
1667 Some(Ok(WorkItemResult::NeedsFatLTO(m))) => {
1668 Message::NeedsFatLTO::<B> { result: m, worker_id }
1669 }
1670 Some(Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))) => {
1671 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1672 }
1673 Some(Err(FatalError)) => {
1674 Message::Done::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1675 }
1676 None => Message::Done::<B> { result: Err(None), worker_id },
1677 };
1678 drop(self.coordinator_send.send(Box::new(msg)));
a1dfa0c6 1679 }
3c0e092e 1680 }
a1dfa0c6 1681
3c0e092e
XL
1682 let mut bomb = Bomb::<B> {
1683 coordinator_send: cgcx.coordinator_send.clone(),
1684 result: None,
1685 worker_id: cgcx.worker,
1686 };
a1dfa0c6 1687
3c0e092e
XL
1688 // Execute the work itself, and if it finishes successfully then flag
1689 // ourselves as a success as well.
1690 //
1691 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1692 // as a diagnostic was already sent off to the main thread - just
1693 // surface that there was an error in this worker.
1694 bomb.result = {
1695 let _prof_timer = work.start_profiling(&cgcx);
1696 Some(execute_work_item(&cgcx, work))
1697 };
1698 })
1699 .expect("failed to spawn thread");
a1dfa0c6
XL
1700}
1701
a1dfa0c6
XL
1702enum SharedEmitterMessage {
1703 Diagnostic(Diagnostic),
f035d41b 1704 InlineAsmError(u32, String, Level, Option<(String, Vec<InnerSpan>)>),
a1dfa0c6
XL
1705 AbortIfErrors,
1706 Fatal(String),
1707}
1708
1709#[derive(Clone)]
1710pub struct SharedEmitter {
1711 sender: Sender<SharedEmitterMessage>,
1712}
1713
1714pub struct SharedEmitterMain {
1715 receiver: Receiver<SharedEmitterMessage>,
1716}
1717
1718impl SharedEmitter {
1719 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1720 let (sender, receiver) = channel();
1721
1722 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1723 }
1724
f9f354fc
XL
1725 pub fn inline_asm_error(
1726 &self,
1727 cookie: u32,
1728 msg: String,
f035d41b 1729 level: Level,
f9f354fc
XL
1730 source: Option<(String, Vec<InnerSpan>)>,
1731 ) {
f035d41b 1732 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)));
a1dfa0c6
XL
1733 }
1734
1735 pub fn fatal(&self, msg: &str) {
1736 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1737 }
1738}
1739
1740impl Emitter for SharedEmitter {
e74abb32 1741 fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
04454e1e 1742 let fluent_args = self.to_fluent_args(diag.args());
a1dfa0c6 1743 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
04454e1e 1744 msg: self.translate_messages(&diag.message, &fluent_args).to_string(),
e74abb32 1745 code: diag.code.clone(),
5e7ed085 1746 lvl: diag.level(),
a1dfa0c6 1747 })));
e74abb32 1748 for child in &diag.children {
a1dfa0c6 1749 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
04454e1e 1750 msg: self.translate_messages(&child.message, &fluent_args).to_string(),
a1dfa0c6
XL
1751 code: None,
1752 lvl: child.level,
1753 })));
1754 }
1755 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1756 }
04454e1e 1757
60c5eb7d 1758 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
e74abb32
XL
1759 None
1760 }
04454e1e
FG
1761
1762 fn fluent_bundle(&self) -> Option<&Lrc<rustc_errors::FluentBundle>> {
1763 None
1764 }
1765
1766 fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle {
1767 panic!("shared emitter attempted to translate a diagnostic");
1768 }
a1dfa0c6
XL
1769}
1770
1771impl SharedEmitterMain {
1772 pub fn check(&self, sess: &Session, blocking: bool) {
1773 loop {
1774 let message = if blocking {
1775 match self.receiver.recv() {
1776 Ok(message) => Ok(message),
1777 Err(_) => Err(()),
1778 }
1779 } else {
1780 match self.receiver.try_recv() {
1781 Ok(message) => Ok(message),
1782 Err(_) => Err(()),
1783 }
1784 };
1785
1786 match message {
1787 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1788 let handler = sess.diagnostic();
e1599b0c
XL
1789 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1790 if let Some(code) = diag.code {
1791 d.code(code);
a1dfa0c6 1792 }
5e7ed085 1793 handler.emit_diagnostic(&mut d);
a1dfa0c6 1794 }
f035d41b 1795 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
f9f354fc
XL
1796 let msg = msg.strip_prefix("error: ").unwrap_or(&msg);
1797
f035d41b 1798 let mut err = match level {
04454e1e 1799 Level::Error { lint: false } => sess.struct_err(msg).forget_guarantee(),
923072b8 1800 Level::Warning(_) => sess.struct_warn(msg),
04454e1e 1801 Level::Note => sess.struct_note_without_error(msg),
f035d41b
XL
1802 _ => bug!("Invalid inline asm diagnostic level"),
1803 };
1804
f9f354fc 1805 // If the cookie is 0 then we don't have span information.
f035d41b 1806 if cookie != 0 {
f9f354fc
XL
1807 let pos = BytePos::from_u32(cookie);
1808 let span = Span::with_root_ctxt(pos, pos);
f035d41b 1809 err.set_span(span);
f9f354fc
XL
1810 };
1811
1812 // Point to the generated assembly if it is available.
1813 if let Some((buffer, spans)) = source {
1814 let source = sess
1815 .source_map()
1816 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1817 let source_span = Span::with_root_ctxt(source.start_pos, source.end_pos);
1818 let spans: Vec<_> =
1819 spans.iter().map(|sp| source_span.from_inner(*sp)).collect();
1820 err.span_note(spans, "instantiated into assembly here");
1821 }
1822
1823 err.emit();
a1dfa0c6
XL
1824 }
1825 Ok(SharedEmitterMessage::AbortIfErrors) => {
1826 sess.abort_if_errors();
1827 }
1828 Ok(SharedEmitterMessage::Fatal(msg)) => {
1829 sess.fatal(&msg);
1830 }
1831 Err(_) => {
1832 break;
1833 }
1834 }
a1dfa0c6
XL
1835 }
1836 }
1837}
1838
064997fb
FG
1839pub struct Coordinator<B: ExtraBackendMethods> {
1840 pub sender: Sender<Box<dyn Any + Send>>,
1841 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
1842 // Only used for the Message type.
1843 phantom: PhantomData<B>,
1844}
1845
1846impl<B: ExtraBackendMethods> Coordinator<B> {
1847 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
1848 self.future.take().unwrap().join()
1849 }
1850}
1851
1852impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
1853 fn drop(&mut self) {
1854 if let Some(future) = self.future.take() {
1855 // If we haven't joined yet, signal to the coordinator that it should spawn no more
1856 // work, and wait for worker threads to finish.
1857 drop(self.sender.send(Box::new(Message::CodegenAborted::<B>)));
1858 drop(future.join());
1859 }
1860 }
1861}
1862
a1dfa0c6
XL
1863pub struct OngoingCodegen<B: ExtraBackendMethods> {
1864 pub backend: B,
a1dfa0c6 1865 pub metadata: EncodedMetadata,
a2a8927a 1866 pub metadata_module: Option<CompiledModule>,
a1dfa0c6 1867 pub crate_info: CrateInfo,
a1dfa0c6
XL
1868 pub codegen_worker_receive: Receiver<Message<B>>,
1869 pub shared_emitter_main: SharedEmitterMain,
a1dfa0c6 1870 pub output_filenames: Arc<OutputFilenames>,
064997fb 1871 pub coordinator: Coordinator<B>,
a1dfa0c6
XL
1872}
1873
1874impl<B: ExtraBackendMethods> OngoingCodegen<B> {
dfeec247
XL
1875 pub fn join(self, sess: &Session) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1876 let _timer = sess.timer("finish_ongoing_codegen");
1877
a1dfa0c6 1878 self.shared_emitter_main.check(sess, true);
064997fb 1879 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
a1dfa0c6
XL
1880 Ok(Ok(compiled_modules)) => compiled_modules,
1881 Ok(Err(())) => {
1882 sess.abort_if_errors();
1883 panic!("expected abort due to worker thread errors")
dfeec247 1884 }
a1dfa0c6
XL
1885 Err(_) => {
1886 bug!("panic during codegen/LLVM phase");
1887 }
dfeec247 1888 });
a1dfa0c6 1889
60c5eb7d 1890 sess.cgu_reuse_tracker.check_expected_reuse(sess.diagnostic());
a1dfa0c6
XL
1891
1892 sess.abort_if_errors();
1893
a1dfa0c6 1894 let work_products =
dfeec247
XL
1895 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1896 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
a1dfa0c6
XL
1897
1898 // FIXME: time_llvm_passes support - does this use a global context or
1899 // something?
1900 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1901 self.backend.print_pass_timings()
1902 }
1903
dfeec247
XL
1904 (
1905 CodegenResults {
dfeec247 1906 metadata: self.metadata,
dfeec247
XL
1907 crate_info: self.crate_info,
1908
1909 modules: compiled_modules.modules,
1910 allocator_module: compiled_modules.allocator_module,
a2a8927a 1911 metadata_module: self.metadata_module,
dfeec247
XL
1912 },
1913 work_products,
1914 )
a1dfa0c6
XL
1915 }
1916
dc9dc135
XL
1917 pub fn submit_pre_codegened_module_to_llvm(
1918 &self,
1919 tcx: TyCtxt<'_>,
1920 module: ModuleCodegen<B::Module>,
1921 ) {
a1dfa0c6
XL
1922 self.wait_for_signal_to_codegen_item();
1923 self.check_for_errors(tcx.sess);
1924
48663c56 1925 // These are generally cheap and won't throw off scheduling.
a1dfa0c6 1926 let cost = 0;
064997fb 1927 submit_codegened_module_to_llvm(&self.backend, &self.coordinator.sender, module, cost);
a1dfa0c6
XL
1928 }
1929
dc9dc135 1930 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
a1dfa0c6
XL
1931 self.wait_for_signal_to_codegen_item();
1932 self.check_for_errors(tcx.sess);
064997fb 1933 drop(self.coordinator.sender.send(Box::new(Message::CodegenComplete::<B>)));
a1dfa0c6
XL
1934 }
1935
1936 pub fn check_for_errors(&self, sess: &Session) {
1937 self.shared_emitter_main.check(sess, false);
1938 }
1939
1940 pub fn wait_for_signal_to_codegen_item(&self) {
1941 match self.codegen_worker_receive.recv() {
1942 Ok(Message::CodegenItem) => {
1943 // Nothing to do
1944 }
1945 Ok(_) => panic!("unexpected message"),
1946 Err(_) => {
1947 // One of the LLVM threads must have panicked, fall through so
1948 // error handling can be reached.
1949 }
1950 }
1951 }
1952}
1953
1954pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1955 _backend: &B,
e74abb32 1956 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
a1dfa0c6 1957 module: ModuleCodegen<B::Module>,
dc9dc135 1958 cost: u64,
a1dfa0c6
XL
1959) {
1960 let llvm_work_item = WorkItem::Optimize(module);
dfeec247 1961 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
a1dfa0c6
XL
1962}
1963
1964pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1965 _backend: &B,
e74abb32 1966 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
dc9dc135 1967 module: CachedModuleCodegen,
a1dfa0c6
XL
1968) {
1969 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
dfeec247 1970 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
a1dfa0c6
XL
1971}
1972
1973pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1974 _backend: &B,
dc9dc135 1975 tcx: TyCtxt<'_>,
e74abb32 1976 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
dc9dc135 1977 module: CachedModuleCodegen,
a1dfa0c6
XL
1978) {
1979 let filename = pre_lto_bitcode_filename(&module.name);
1980 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
dfeec247
XL
1981 let file = fs::File::open(&bc_path)
1982 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
a1dfa0c6
XL
1983
1984 let mmap = unsafe {
cdc7bbd5 1985 Mmap::map(file).unwrap_or_else(|e| {
a1dfa0c6
XL
1986 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1987 })
1988 };
1989 // Schedule the module to be loaded
e74abb32 1990 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
a1dfa0c6
XL
1991 module_data: SerializedModule::FromUncompressedFile(mmap),
1992 work_product: module.source,
1993 })));
1994}
1995
1996pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
9fa01778 1997 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
a1dfa0c6
XL
1998}
1999
dc9dc135 2000fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
a1dfa0c6
XL
2001 // This should never be true (because it's not supported). If it is true,
2002 // something is wrong with commandline arg validation.
dfeec247
XL
2003 assert!(
2004 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
29967ef6 2005 && tcx.sess.target.is_like_windows
dfeec247
XL
2006 && tcx.sess.opts.cg.prefer_dynamic)
2007 );
a1dfa0c6 2008
29967ef6 2009 tcx.sess.target.is_like_windows &&
f9f354fc 2010 tcx.sess.crate_types().iter().any(|ct| *ct == CrateType::Rlib) &&
a1dfa0c6
XL
2011 // ThinLTO can't handle this workaround in all cases, so we don't
2012 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
9fa01778
XL
2013 // dynamic linking when linker plugin LTO is enabled.
2014 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
a1dfa0c6 2015}