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