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