]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_session/src/session.rs
Update upstream source from tag 'upstream/1.53.0+dfsg1'
[rustc.git] / compiler / rustc_session / src / session.rs
1 use crate::cgu_reuse_tracker::CguReuseTracker;
2 use crate::code_stats::CodeStats;
3 pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
4 use crate::config::{self, CrateType, OutputType, PrintRequest, SwitchWithOptPath};
5 use crate::filesearch;
6 use crate::lint::{self, LintId};
7 use crate::parse::ParseSess;
8 use crate::search_paths::{PathKind, SearchPath};
9
10 pub use rustc_ast::attr::MarkedAttrs;
11 pub use rustc_ast::Attribute;
12 use rustc_data_structures::flock;
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_data_structures::jobserver::{self, Client};
15 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
16 use rustc_data_structures::sync::{
17 self, AtomicU64, AtomicUsize, Lock, Lrc, OnceCell, OneThread, Ordering, Ordering::SeqCst,
18 };
19 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
20 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
21 use rustc_errors::json::JsonEmitter;
22 use rustc_errors::registry::Registry;
23 use rustc_errors::{Diagnostic, DiagnosticBuilder, DiagnosticId, ErrorReported};
24 use rustc_lint_defs::FutureBreakage;
25 pub use rustc_span::crate_disambiguator::CrateDisambiguator;
26 use rustc_span::edition::Edition;
27 use rustc_span::source_map::{FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
28 use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};
29 use rustc_target::asm::InlineAsmArch;
30 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
31 use rustc_target::spec::{SanitizerSet, SplitDebuginfo, Target, TargetTriple, TlsModel};
32
33 use std::cell::{self, RefCell};
34 use std::env;
35 use std::fmt;
36 use std::io::Write;
37 use std::num::NonZeroU32;
38 use std::ops::{Div, Mul};
39 use std::path::PathBuf;
40 use std::str::FromStr;
41 use std::sync::Arc;
42 use std::time::Duration;
43
44 pub trait SessionLintStore: sync::Send + sync::Sync {
45 fn name_to_lint(&self, lint_name: &str) -> LintId;
46 }
47
48 pub struct OptimizationFuel {
49 /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
50 remaining: u64,
51 /// We're rejecting all further optimizations.
52 out_of_fuel: bool,
53 }
54
55 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
56 #[derive(Clone, Copy)]
57 pub enum CtfeBacktrace {
58 /// Do nothing special, return the error as usual without a backtrace.
59 Disabled,
60 /// Capture a backtrace at the point the error is created and return it in the error
61 /// (to be printed later if/when the error ever actually gets shown to the user).
62 Capture,
63 /// Capture a backtrace at the point the error is created and immediately print it out.
64 Immediate,
65 }
66
67 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
68 /// limits are consistent throughout the compiler.
69 #[derive(Clone, Copy, Debug)]
70 pub struct Limit(pub usize);
71
72 impl Limit {
73 /// Create a new limit from a `usize`.
74 pub fn new(value: usize) -> Self {
75 Limit(value)
76 }
77
78 /// Check that `value` is within the limit. Ensures that the same comparisons are used
79 /// throughout the compiler, as mismatches can cause ICEs, see #72540.
80 #[inline]
81 pub fn value_within_limit(&self, value: usize) -> bool {
82 value <= self.0
83 }
84 }
85
86 impl From<usize> for Limit {
87 fn from(value: usize) -> Self {
88 Self::new(value)
89 }
90 }
91
92 impl fmt::Display for Limit {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 write!(f, "{}", self.0)
95 }
96 }
97
98 impl Div<usize> for Limit {
99 type Output = Limit;
100
101 fn div(self, rhs: usize) -> Self::Output {
102 Limit::new(self.0 / rhs)
103 }
104 }
105
106 impl Mul<usize> for Limit {
107 type Output = Limit;
108
109 fn mul(self, rhs: usize) -> Self::Output {
110 Limit::new(self.0 * rhs)
111 }
112 }
113
114 /// Represents the data associated with a compilation
115 /// session for a single crate.
116 pub struct Session {
117 pub target: Target,
118 pub host: Target,
119 pub opts: config::Options,
120 pub host_tlib_path: SearchPath,
121 /// `None` if the host and target are the same.
122 pub target_tlib_path: Option<SearchPath>,
123 pub parse_sess: ParseSess,
124 pub sysroot: PathBuf,
125 /// The name of the root source file of the crate, in the local file system.
126 /// `None` means that there is no source file.
127 pub local_crate_source_file: Option<PathBuf>,
128 /// The directory the compiler has been executed in plus a flag indicating
129 /// if the value stored here has been affected by path remapping.
130 pub working_dir: (PathBuf, bool),
131
132 /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
133 /// (sub)diagnostics that have been set once, but should not be set again,
134 /// in order to avoid redundantly verbose output (Issue #24690, #44953).
135 pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
136 crate_types: OnceCell<Vec<CrateType>>,
137 /// The `crate_disambiguator` is constructed out of all the `-C metadata`
138 /// arguments passed to the compiler. Its value together with the crate-name
139 /// forms a unique global identifier for the crate. It is used to allow
140 /// multiple crates with the same name to coexist. See the
141 /// `rustc_codegen_llvm::back::symbol_names` module for more information.
142 pub crate_disambiguator: OnceCell<CrateDisambiguator>,
143
144 features: OnceCell<rustc_feature::Features>,
145
146 lint_store: OnceCell<Lrc<dyn SessionLintStore>>,
147
148 /// The maximum recursion limit for potentially infinitely recursive
149 /// operations such as auto-dereference and monomorphization.
150 pub recursion_limit: OnceCell<Limit>,
151
152 /// The size at which the `large_assignments` lint starts
153 /// being emitted.
154 pub move_size_limit: OnceCell<usize>,
155
156 /// The maximum length of types during monomorphization.
157 pub type_length_limit: OnceCell<Limit>,
158
159 /// The maximum blocks a const expression can evaluate.
160 pub const_eval_limit: OnceCell<Limit>,
161
162 incr_comp_session: OneThread<RefCell<IncrCompSession>>,
163 /// Used for incremental compilation tests. Will only be populated if
164 /// `-Zquery-dep-graph` is specified.
165 pub cgu_reuse_tracker: CguReuseTracker,
166
167 /// Used by `-Z self-profile`.
168 pub prof: SelfProfilerRef,
169
170 /// Some measurements that are being gathered during compilation.
171 pub perf_stats: PerfStats,
172
173 /// Data about code being compiled, gathered during compilation.
174 pub code_stats: CodeStats,
175
176 /// If `-zfuel=crate=n` is specified, `Some(crate)`.
177 optimization_fuel_crate: Option<String>,
178
179 /// Tracks fuel info if `-zfuel=crate=n` is specified.
180 optimization_fuel: Lock<OptimizationFuel>,
181
182 // The next two are public because the driver needs to read them.
183 /// If `-zprint-fuel=crate`, `Some(crate)`.
184 pub print_fuel_crate: Option<String>,
185 /// Always set to zero and incremented so that we can print fuel expended by a crate.
186 pub print_fuel: AtomicU64,
187
188 /// Loaded up early on in the initialization of this `Session` to avoid
189 /// false positives about a job server in our environment.
190 pub jobserver: Client,
191
192 /// Cap lint level specified by a driver specifically.
193 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
194
195 /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
196 pub trait_methods_not_found: Lock<FxHashSet<Span>>,
197
198 /// Mapping from ident span to path span for paths that don't exist as written, but that
199 /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
200 pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
201
202 /// Path for libraries that will take preference over libraries shipped by Rust.
203 /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
204 pub system_library_path: OneThread<RefCell<Option<Option<PathBuf>>>>,
205
206 /// Tracks the current behavior of the CTFE engine when an error occurs.
207 /// Options range from returning the error without a backtrace to returning an error
208 /// and immediately printing the backtrace to stderr.
209 pub ctfe_backtrace: Lock<CtfeBacktrace>,
210
211 /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
212 /// const check, optionally with the relevant feature gate. We use this to
213 /// warn about unleashing, but with a single diagnostic instead of dozens that
214 /// drown everything else in noise.
215 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
216
217 /// Architecture to use for interpreting asm!.
218 pub asm_arch: Option<InlineAsmArch>,
219
220 /// Set of enabled features for the current target.
221 pub target_features: FxHashSet<Symbol>,
222
223 known_attrs: Lock<MarkedAttrs>,
224 used_attrs: Lock<MarkedAttrs>,
225
226 /// `Span`s for `if` conditions that we have suggested turning into `if let`.
227 pub if_let_suggestions: Lock<FxHashSet<Span>>,
228 }
229
230 pub struct PerfStats {
231 /// The accumulated time spent on computing symbol hashes.
232 pub symbol_hash_time: Lock<Duration>,
233 /// Total number of values canonicalized queries constructed.
234 pub queries_canonicalized: AtomicUsize,
235 /// Number of times this query is invoked.
236 pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
237 /// Number of times this query is invoked.
238 pub normalize_projection_ty: AtomicUsize,
239 }
240
241 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
242 enum DiagnosticBuilderMethod {
243 Note,
244 SpanNote,
245 // Add more variants as needed to support one-time diagnostics.
246 }
247
248 /// Trait implemented by error types. This should not be implemented manually. Instead, use
249 /// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic].
250 pub trait SessionDiagnostic<'a> {
251 /// Write out as a diagnostic out of `sess`.
252 #[must_use]
253 fn into_diagnostic(self, sess: &'a Session) -> DiagnosticBuilder<'a>;
254 }
255
256 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
257 /// emitting the same message more than once.
258 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
259 pub enum DiagnosticMessageId {
260 ErrorId(u16), // EXXXX error code as integer
261 LintId(lint::LintId),
262 StabilityId(Option<NonZeroU32>), // issue number
263 }
264
265 impl From<&'static lint::Lint> for DiagnosticMessageId {
266 fn from(lint: &'static lint::Lint) -> Self {
267 DiagnosticMessageId::LintId(lint::LintId::of(lint))
268 }
269 }
270
271 impl Session {
272 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
273 self.miri_unleashed_features.lock().push((span, feature_gate));
274 }
275
276 fn check_miri_unleashed_features(&self) {
277 let unleashed_features = self.miri_unleashed_features.lock();
278 if !unleashed_features.is_empty() {
279 let mut must_err = false;
280 // Create a diagnostic pointing at where things got unleashed.
281 let mut diag = self.struct_warn("skipping const checks");
282 for &(span, feature_gate) in unleashed_features.iter() {
283 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
284 if let Some(feature_gate) = feature_gate {
285 diag.span_help(span, &format!("skipping check for `{}` feature", feature_gate));
286 // The unleash flag must *not* be used to just "hack around" feature gates.
287 must_err = true;
288 } else {
289 diag.span_help(span, "skipping check that does not even have a feature gate");
290 }
291 }
292 diag.emit();
293 // If we should err, make sure we did.
294 if must_err && !self.has_errors() {
295 // We have skipped a feature gate, and not run into other errors... reject.
296 self.err(
297 "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
298 gates, except when testing error paths in the CTFE engine",
299 );
300 }
301 }
302 }
303
304 /// Invoked all the way at the end to finish off diagnostics printing.
305 pub fn finish_diagnostics(&self, registry: &Registry) {
306 self.check_miri_unleashed_features();
307 self.diagnostic().print_error_count(registry);
308 self.emit_future_breakage();
309 }
310
311 fn emit_future_breakage(&self) {
312 if !self.opts.debugging_opts.emit_future_incompat_report {
313 return;
314 }
315
316 let diags = self.diagnostic().take_future_breakage_diagnostics();
317 if diags.is_empty() {
318 return;
319 }
320 // If any future-breakage lints were registered, this lint store
321 // should be available
322 let lint_store = self.lint_store.get().expect("`lint_store` not initialized!");
323 let diags_and_breakage: Vec<(FutureBreakage, Diagnostic)> = diags
324 .into_iter()
325 .map(|diag| {
326 let lint_name = match &diag.code {
327 Some(DiagnosticId::Lint { name, has_future_breakage: true }) => name,
328 _ => panic!("Unexpected code in diagnostic {:?}", diag),
329 };
330 let lint = lint_store.name_to_lint(&lint_name);
331 let future_breakage =
332 lint.lint.future_incompatible.unwrap().future_breakage.unwrap();
333 (future_breakage, diag)
334 })
335 .collect();
336 self.parse_sess.span_diagnostic.emit_future_breakage_report(diags_and_breakage);
337 }
338
339 pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
340 self.crate_disambiguator.get().copied().unwrap()
341 }
342
343 pub fn crate_types(&self) -> &[CrateType] {
344 self.crate_types.get().unwrap().as_slice()
345 }
346
347 pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
348 self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
349 }
350
351 #[inline]
352 pub fn recursion_limit(&self) -> Limit {
353 self.recursion_limit.get().copied().unwrap()
354 }
355
356 #[inline]
357 pub fn move_size_limit(&self) -> usize {
358 self.move_size_limit.get().copied().unwrap()
359 }
360
361 #[inline]
362 pub fn type_length_limit(&self) -> Limit {
363 self.type_length_limit.get().copied().unwrap()
364 }
365
366 pub fn const_eval_limit(&self) -> Limit {
367 self.const_eval_limit.get().copied().unwrap()
368 }
369
370 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
371 self.diagnostic().struct_span_warn(sp, msg)
372 }
373 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
374 &self,
375 sp: S,
376 msg: &str,
377 code: DiagnosticId,
378 ) -> DiagnosticBuilder<'_> {
379 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
380 }
381 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
382 self.diagnostic().struct_warn(msg)
383 }
384 pub fn struct_span_allow<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
385 self.diagnostic().struct_span_allow(sp, msg)
386 }
387 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
388 self.diagnostic().struct_allow(msg)
389 }
390 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
391 self.diagnostic().struct_span_err(sp, msg)
392 }
393 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
394 &self,
395 sp: S,
396 msg: &str,
397 code: DiagnosticId,
398 ) -> DiagnosticBuilder<'_> {
399 self.diagnostic().struct_span_err_with_code(sp, msg, code)
400 }
401 // FIXME: This method should be removed (every error should have an associated error code).
402 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
403 self.diagnostic().struct_err(msg)
404 }
405 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
406 self.diagnostic().struct_err_with_code(msg, code)
407 }
408 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
409 self.diagnostic().struct_span_fatal(sp, msg)
410 }
411 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
412 &self,
413 sp: S,
414 msg: &str,
415 code: DiagnosticId,
416 ) -> DiagnosticBuilder<'_> {
417 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
418 }
419 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
420 self.diagnostic().struct_fatal(msg)
421 }
422
423 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
424 self.diagnostic().span_fatal(sp, msg).raise()
425 }
426 pub fn span_fatal_with_code<S: Into<MultiSpan>>(
427 &self,
428 sp: S,
429 msg: &str,
430 code: DiagnosticId,
431 ) -> ! {
432 self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
433 }
434 pub fn fatal(&self, msg: &str) -> ! {
435 self.diagnostic().fatal(msg).raise()
436 }
437 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
438 if is_warning {
439 self.span_warn(sp, msg);
440 } else {
441 self.span_err(sp, msg);
442 }
443 }
444 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
445 self.diagnostic().span_err(sp, msg)
446 }
447 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
448 self.diagnostic().span_err_with_code(sp, &msg, code)
449 }
450 pub fn err(&self, msg: &str) {
451 self.diagnostic().err(msg)
452 }
453 pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) {
454 err.into_diagnostic(self).emit()
455 }
456 pub fn err_count(&self) -> usize {
457 self.diagnostic().err_count()
458 }
459 pub fn has_errors(&self) -> bool {
460 self.diagnostic().has_errors()
461 }
462 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
463 self.diagnostic().has_errors_or_delayed_span_bugs()
464 }
465 pub fn abort_if_errors(&self) {
466 self.diagnostic().abort_if_errors();
467 }
468 pub fn compile_status(&self) -> Result<(), ErrorReported> {
469 if self.has_errors() {
470 self.diagnostic().emit_stashed_diagnostics();
471 Err(ErrorReported)
472 } else {
473 Ok(())
474 }
475 }
476 // FIXME(matthewjasper) Remove this method, it should never be needed.
477 pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
478 where
479 F: FnOnce() -> T,
480 {
481 let old_count = self.err_count();
482 let result = f();
483 let errors = self.err_count() - old_count;
484 if errors == 0 { Ok(result) } else { Err(ErrorReported) }
485 }
486 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
487 self.diagnostic().span_warn(sp, msg)
488 }
489 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
490 self.diagnostic().span_warn_with_code(sp, msg, code)
491 }
492 pub fn warn(&self, msg: &str) {
493 self.diagnostic().warn(msg)
494 }
495 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
496 match opt_sp {
497 Some(sp) => self.span_warn(sp, msg),
498 None => self.warn(msg),
499 }
500 }
501 /// Delay a span_bug() call until abort_if_errors()
502 #[track_caller]
503 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
504 self.diagnostic().delay_span_bug(sp, msg)
505 }
506
507 /// Used for code paths of expensive computations that should only take place when
508 /// warnings or errors are emitted. If no messages are emitted ("good path"), then
509 /// it's likely a bug.
510 pub fn delay_good_path_bug(&self, msg: &str) {
511 if self.opts.debugging_opts.print_type_sizes
512 || self.opts.debugging_opts.query_dep_graph
513 || self.opts.debugging_opts.dump_mir.is_some()
514 || self.opts.debugging_opts.unpretty.is_some()
515 || self.opts.output_types.contains_key(&OutputType::Mir)
516 || std::env::var_os("RUSTC_LOG").is_some()
517 {
518 return;
519 }
520
521 self.diagnostic().delay_good_path_bug(msg)
522 }
523
524 pub fn note_without_error(&self, msg: &str) {
525 self.diagnostic().note_without_error(msg)
526 }
527 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
528 self.diagnostic().span_note_without_error(sp, msg)
529 }
530 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
531 self.diagnostic().struct_note_without_error(msg)
532 }
533
534 pub fn diagnostic(&self) -> &rustc_errors::Handler {
535 &self.parse_sess.span_diagnostic
536 }
537
538 /// Analogous to calling methods on the given `DiagnosticBuilder`, but
539 /// deduplicates on lint ID, span (if any), and message for this `Session`
540 fn diag_once<'a, 'b>(
541 &'a self,
542 diag_builder: &'b mut DiagnosticBuilder<'a>,
543 method: DiagnosticBuilderMethod,
544 msg_id: DiagnosticMessageId,
545 message: &str,
546 span_maybe: Option<Span>,
547 ) {
548 let id_span_message = (msg_id, span_maybe, message.to_owned());
549 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
550 if fresh {
551 match method {
552 DiagnosticBuilderMethod::Note => {
553 diag_builder.note(message);
554 }
555 DiagnosticBuilderMethod::SpanNote => {
556 let span = span_maybe.expect("`span_note` needs a span");
557 diag_builder.span_note(span, message);
558 }
559 }
560 }
561 }
562
563 pub fn diag_span_note_once<'a, 'b>(
564 &'a self,
565 diag_builder: &'b mut DiagnosticBuilder<'a>,
566 msg_id: DiagnosticMessageId,
567 span: Span,
568 message: &str,
569 ) {
570 self.diag_once(
571 diag_builder,
572 DiagnosticBuilderMethod::SpanNote,
573 msg_id,
574 message,
575 Some(span),
576 );
577 }
578
579 pub fn diag_note_once<'a, 'b>(
580 &'a self,
581 diag_builder: &'b mut DiagnosticBuilder<'a>,
582 msg_id: DiagnosticMessageId,
583 message: &str,
584 ) {
585 self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
586 }
587
588 #[inline]
589 pub fn source_map(&self) -> &SourceMap {
590 self.parse_sess.source_map()
591 }
592 pub fn verbose(&self) -> bool {
593 self.opts.debugging_opts.verbose
594 }
595 pub fn time_passes(&self) -> bool {
596 self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
597 }
598 pub fn instrument_mcount(&self) -> bool {
599 self.opts.debugging_opts.instrument_mcount
600 }
601 pub fn time_llvm_passes(&self) -> bool {
602 self.opts.debugging_opts.time_llvm_passes
603 }
604 pub fn meta_stats(&self) -> bool {
605 self.opts.debugging_opts.meta_stats
606 }
607 pub fn asm_comments(&self) -> bool {
608 self.opts.debugging_opts.asm_comments
609 }
610 pub fn verify_llvm_ir(&self) -> bool {
611 self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
612 }
613 pub fn print_llvm_passes(&self) -> bool {
614 self.opts.debugging_opts.print_llvm_passes
615 }
616 pub fn binary_dep_depinfo(&self) -> bool {
617 self.opts.debugging_opts.binary_dep_depinfo
618 }
619 pub fn mir_opt_level(&self) -> usize {
620 self.opts
621 .debugging_opts
622 .mir_opt_level
623 .unwrap_or_else(|| if self.opts.optimize != config::OptLevel::No { 2 } else { 1 })
624 }
625
626 /// Gets the features enabled for the current compilation session.
627 /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
628 /// dependency tracking. Use tcx.features() instead.
629 #[inline]
630 pub fn features_untracked(&self) -> &rustc_feature::Features {
631 self.features.get().unwrap()
632 }
633
634 pub fn init_features(&self, features: rustc_feature::Features) {
635 match self.features.set(features) {
636 Ok(()) => {}
637 Err(_) => panic!("`features` was initialized twice"),
638 }
639 }
640
641 pub fn init_lint_store(&self, lint_store: Lrc<dyn SessionLintStore>) {
642 self.lint_store
643 .set(lint_store)
644 .map_err(|_| ())
645 .expect("`lint_store` was initialized twice");
646 }
647
648 /// Calculates the flavor of LTO to use for this compilation.
649 pub fn lto(&self) -> config::Lto {
650 // If our target has codegen requirements ignore the command line
651 if self.target.requires_lto {
652 return config::Lto::Fat;
653 }
654
655 // If the user specified something, return that. If they only said `-C
656 // lto` and we've for whatever reason forced off ThinLTO via the CLI,
657 // then ensure we can't use a ThinLTO.
658 match self.opts.cg.lto {
659 config::LtoCli::Unspecified => {
660 // The compiler was invoked without the `-Clto` flag. Fall
661 // through to the default handling
662 }
663 config::LtoCli::No => {
664 // The user explicitly opted out of any kind of LTO
665 return config::Lto::No;
666 }
667 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
668 // All of these mean fat LTO
669 return config::Lto::Fat;
670 }
671 config::LtoCli::Thin => {
672 return if self.opts.cli_forced_thinlto_off {
673 config::Lto::Fat
674 } else {
675 config::Lto::Thin
676 };
677 }
678 }
679
680 // Ok at this point the target doesn't require anything and the user
681 // hasn't asked for anything. Our next decision is whether or not
682 // we enable "auto" ThinLTO where we use multiple codegen units and
683 // then do ThinLTO over those codegen units. The logic below will
684 // either return `No` or `ThinLocal`.
685
686 // If processing command line options determined that we're incompatible
687 // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
688 if self.opts.cli_forced_thinlto_off {
689 return config::Lto::No;
690 }
691
692 // If `-Z thinlto` specified process that, but note that this is mostly
693 // a deprecated option now that `-C lto=thin` exists.
694 if let Some(enabled) = self.opts.debugging_opts.thinlto {
695 if enabled {
696 return config::Lto::ThinLocal;
697 } else {
698 return config::Lto::No;
699 }
700 }
701
702 // If there's only one codegen unit and LTO isn't enabled then there's
703 // no need for ThinLTO so just return false.
704 if self.codegen_units() == 1 {
705 return config::Lto::No;
706 }
707
708 // Now we're in "defaults" territory. By default we enable ThinLTO for
709 // optimized compiles (anything greater than O0).
710 match self.opts.optimize {
711 config::OptLevel::No => config::Lto::No,
712 _ => config::Lto::ThinLocal,
713 }
714 }
715
716 /// Returns the panic strategy for this compile session. If the user explicitly selected one
717 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
718 pub fn panic_strategy(&self) -> PanicStrategy {
719 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
720 }
721 pub fn fewer_names(&self) -> bool {
722 if let Some(fewer_names) = self.opts.debugging_opts.fewer_names {
723 fewer_names
724 } else {
725 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
726 || self.opts.output_types.contains_key(&OutputType::Bitcode)
727 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
728 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
729 !more_names
730 }
731 }
732
733 pub fn unstable_options(&self) -> bool {
734 self.opts.debugging_opts.unstable_options
735 }
736 pub fn is_nightly_build(&self) -> bool {
737 self.opts.unstable_features.is_nightly_build()
738 }
739 pub fn overflow_checks(&self) -> bool {
740 self.opts
741 .cg
742 .overflow_checks
743 .or(self.opts.debugging_opts.force_overflow_checks)
744 .unwrap_or(self.opts.debug_assertions)
745 }
746
747 /// Check whether this compile session and crate type use static crt.
748 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
749 if !self.target.crt_static_respected {
750 // If the target does not opt in to crt-static support, use its default.
751 return self.target.crt_static_default;
752 }
753
754 let requested_features = self.opts.cg.target_feature.split(',');
755 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
756 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
757
758 if found_positive || found_negative {
759 found_positive
760 } else if crate_type == Some(CrateType::ProcMacro)
761 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
762 {
763 // FIXME: When crate_type is not available,
764 // we use compiler options to determine the crate_type.
765 // We can't check `#![crate_type = "proc-macro"]` here.
766 false
767 } else {
768 self.target.crt_static_default
769 }
770 }
771
772 pub fn relocation_model(&self) -> RelocModel {
773 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
774 }
775
776 pub fn code_model(&self) -> Option<CodeModel> {
777 self.opts.cg.code_model.or(self.target.code_model)
778 }
779
780 pub fn tls_model(&self) -> TlsModel {
781 self.opts.debugging_opts.tls_model.unwrap_or(self.target.tls_model)
782 }
783
784 pub fn is_wasi_reactor(&self) -> bool {
785 self.target.options.os == "wasi"
786 && matches!(
787 self.opts.debugging_opts.wasi_exec_model,
788 Some(config::WasiExecModel::Reactor)
789 )
790 }
791
792 pub fn split_debuginfo(&self) -> SplitDebuginfo {
793 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
794 }
795
796 pub fn target_can_use_split_dwarf(&self) -> bool {
797 !self.target.is_like_windows && !self.target.is_like_osx
798 }
799
800 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
801 // "mcount" function relies on stack pointer.
802 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
803 if self.instrument_mcount() {
804 true
805 } else if let Some(x) = self.opts.cg.force_frame_pointers {
806 x
807 } else {
808 !self.target.eliminate_frame_pointer
809 }
810 }
811
812 pub fn must_emit_unwind_tables(&self) -> bool {
813 // This is used to control the emission of the `uwtable` attribute on
814 // LLVM functions.
815 //
816 // Unwind tables are needed when compiling with `-C panic=unwind`, but
817 // LLVM won't omit unwind tables unless the function is also marked as
818 // `nounwind`, so users are allowed to disable `uwtable` emission.
819 // Historically rustc always emits `uwtable` attributes by default, so
820 // even they can be disabled, they're still emitted by default.
821 //
822 // On some targets (including windows), however, exceptions include
823 // other events such as illegal instructions, segfaults, etc. This means
824 // that on Windows we end up still needing unwind tables even if the `-C
825 // panic=abort` flag is passed.
826 //
827 // You can also find more info on why Windows needs unwind tables in:
828 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
829 //
830 // If a target requires unwind tables, then they must be emitted.
831 // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
832 // value, if it is provided, or disable them, if not.
833 self.target.requires_uwtable
834 || self.opts.cg.force_unwind_tables.unwrap_or(
835 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
836 )
837 }
838
839 /// Returns the symbol name for the registrar function,
840 /// given the crate `Svh` and the function `DefIndex`.
841 pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
842 format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
843 }
844
845 pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
846 format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
847 }
848
849 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
850 filesearch::FileSearch::new(
851 &self.sysroot,
852 self.opts.target_triple.triple(),
853 &self.opts.search_paths,
854 // `target_tlib_path == None` means it's the same as `host_tlib_path`.
855 self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
856 kind,
857 )
858 }
859 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
860 filesearch::FileSearch::new(
861 &self.sysroot,
862 config::host_triple(),
863 &self.opts.search_paths,
864 &self.host_tlib_path,
865 kind,
866 )
867 }
868
869 pub fn init_incr_comp_session(
870 &self,
871 session_dir: PathBuf,
872 lock_file: flock::Lock,
873 load_dep_graph: bool,
874 ) {
875 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
876
877 if let IncrCompSession::NotInitialized = *incr_comp_session {
878 } else {
879 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
880 }
881
882 *incr_comp_session =
883 IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
884 }
885
886 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
887 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
888
889 if let IncrCompSession::Active { .. } = *incr_comp_session {
890 } else {
891 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
892 }
893
894 // Note: this will also drop the lock file, thus unlocking the directory.
895 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
896 }
897
898 pub fn mark_incr_comp_session_as_invalid(&self) {
899 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
900
901 let session_directory = match *incr_comp_session {
902 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
903 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
904 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
905 };
906
907 // Note: this will also drop the lock file, thus unlocking the directory.
908 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
909 }
910
911 pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
912 let incr_comp_session = self.incr_comp_session.borrow();
913 cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
914 IncrCompSession::NotInitialized => panic!(
915 "trying to get session directory from `IncrCompSession`: {:?}",
916 *incr_comp_session,
917 ),
918 IncrCompSession::Active { ref session_directory, .. }
919 | IncrCompSession::Finalized { ref session_directory }
920 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
921 session_directory
922 }
923 })
924 }
925
926 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
927 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
928 }
929
930 pub fn print_perf_stats(&self) {
931 eprintln!(
932 "Total time spent computing symbol hashes: {}",
933 duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
934 );
935 eprintln!(
936 "Total queries canonicalized: {}",
937 self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
938 );
939 eprintln!(
940 "normalize_generic_arg_after_erasing_regions: {}",
941 self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
942 );
943 eprintln!(
944 "normalize_projection_ty: {}",
945 self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
946 );
947 }
948
949 /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
950 /// This expends fuel if applicable, and records fuel if applicable.
951 pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
952 let mut ret = true;
953 if let Some(ref c) = self.optimization_fuel_crate {
954 if c == crate_name {
955 assert_eq!(self.threads(), 1);
956 let mut fuel = self.optimization_fuel.lock();
957 ret = fuel.remaining != 0;
958 if fuel.remaining == 0 && !fuel.out_of_fuel {
959 self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
960 fuel.out_of_fuel = true;
961 } else if fuel.remaining > 0 {
962 fuel.remaining -= 1;
963 }
964 }
965 }
966 if let Some(ref c) = self.print_fuel_crate {
967 if c == crate_name {
968 assert_eq!(self.threads(), 1);
969 self.print_fuel.fetch_add(1, SeqCst);
970 }
971 }
972 ret
973 }
974
975 /// Returns the number of query threads that should be used for this
976 /// compilation
977 pub fn threads(&self) -> usize {
978 self.opts.debugging_opts.threads
979 }
980
981 /// Returns the number of codegen units that should be used for this
982 /// compilation
983 pub fn codegen_units(&self) -> usize {
984 if let Some(n) = self.opts.cli_forced_codegen_units {
985 return n;
986 }
987 if let Some(n) = self.target.default_codegen_units {
988 return n as usize;
989 }
990
991 // If incremental compilation is turned on, we default to a high number
992 // codegen units in order to reduce the "collateral damage" small
993 // changes cause.
994 if self.opts.incremental.is_some() {
995 return 256;
996 }
997
998 // Why is 16 codegen units the default all the time?
999 //
1000 // The main reason for enabling multiple codegen units by default is to
1001 // leverage the ability for the codegen backend to do codegen and
1002 // optimization in parallel. This allows us, especially for large crates, to
1003 // make good use of all available resources on the machine once we've
1004 // hit that stage of compilation. Large crates especially then often
1005 // take a long time in codegen/optimization and this helps us amortize that
1006 // cost.
1007 //
1008 // Note that a high number here doesn't mean that we'll be spawning a
1009 // large number of threads in parallel. The backend of rustc contains
1010 // global rate limiting through the `jobserver` crate so we'll never
1011 // overload the system with too much work, but rather we'll only be
1012 // optimizing when we're otherwise cooperating with other instances of
1013 // rustc.
1014 //
1015 // Rather a high number here means that we should be able to keep a lot
1016 // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1017 // to build we'll be guaranteed that all cpus will finish pretty closely
1018 // to one another and we should make relatively optimal use of system
1019 // resources
1020 //
1021 // Note that the main cost of codegen units is that it prevents LLVM
1022 // from inlining across codegen units. Users in general don't have a lot
1023 // of control over how codegen units are split up so it's our job in the
1024 // compiler to ensure that undue performance isn't lost when using
1025 // codegen units (aka we can't require everyone to slap `#[inline]` on
1026 // everything).
1027 //
1028 // If we're compiling at `-O0` then the number doesn't really matter too
1029 // much because performance doesn't matter and inlining is ok to lose.
1030 // In debug mode we just want to try to guarantee that no cpu is stuck
1031 // doing work that could otherwise be farmed to others.
1032 //
1033 // In release mode, however (O1 and above) performance does indeed
1034 // matter! To recover the loss in performance due to inlining we'll be
1035 // enabling ThinLTO by default (the function for which is just below).
1036 // This will ensure that we recover any inlining wins we otherwise lost
1037 // through codegen unit partitioning.
1038 //
1039 // ---
1040 //
1041 // Ok that's a lot of words but the basic tl;dr; is that we want a high
1042 // number here -- but not too high. Additionally we're "safe" to have it
1043 // always at the same number at all optimization levels.
1044 //
1045 // As a result 16 was chosen here! Mostly because it was a power of 2
1046 // and most benchmarks agreed it was roughly a local optimum. Not very
1047 // scientific.
1048 16
1049 }
1050
1051 pub fn teach(&self, code: &DiagnosticId) -> bool {
1052 self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
1053 }
1054
1055 pub fn rust_2015(&self) -> bool {
1056 self.opts.edition == Edition::Edition2015
1057 }
1058
1059 /// Are we allowed to use features from the Rust 2018 edition?
1060 pub fn rust_2018(&self) -> bool {
1061 self.opts.edition >= Edition::Edition2018
1062 }
1063
1064 /// Are we allowed to use features from the Rust 2021 edition?
1065 pub fn rust_2021(&self) -> bool {
1066 self.opts.edition >= Edition::Edition2021
1067 }
1068
1069 pub fn edition(&self) -> Edition {
1070 self.opts.edition
1071 }
1072
1073 /// Returns `true` if we cannot skip the PLT for shared library calls.
1074 pub fn needs_plt(&self) -> bool {
1075 // Check if the current target usually needs PLT to be enabled.
1076 // The user can use the command line flag to override it.
1077 let needs_plt = self.target.needs_plt;
1078
1079 let dbg_opts = &self.opts.debugging_opts;
1080
1081 let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
1082
1083 // Only enable this optimization by default if full relro is also enabled.
1084 // In this case, lazy binding was already unavailable, so nothing is lost.
1085 // This also ensures `-Wl,-z,now` is supported by the linker.
1086 let full_relro = RelroLevel::Full == relro_level;
1087
1088 // If user didn't explicitly forced us to use / skip the PLT,
1089 // then try to skip it where possible.
1090 dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1091 }
1092
1093 /// Checks if LLVM lifetime markers should be emitted.
1094 pub fn emit_lifetime_markers(&self) -> bool {
1095 self.opts.optimize != config::OptLevel::No
1096 // AddressSanitizer uses lifetimes to detect use after scope bugs.
1097 // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1098 // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
1099 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
1100 }
1101
1102 pub fn link_dead_code(&self) -> bool {
1103 self.opts.cg.link_dead_code.unwrap_or(false)
1104 }
1105
1106 pub fn instrument_coverage(&self) -> bool {
1107 self.opts.debugging_opts.instrument_coverage.unwrap_or(config::InstrumentCoverage::Off)
1108 != config::InstrumentCoverage::Off
1109 }
1110
1111 pub fn instrument_coverage_except_unused_generics(&self) -> bool {
1112 self.opts.debugging_opts.instrument_coverage.unwrap_or(config::InstrumentCoverage::Off)
1113 == config::InstrumentCoverage::ExceptUnusedGenerics
1114 }
1115
1116 pub fn instrument_coverage_except_unused_functions(&self) -> bool {
1117 self.opts.debugging_opts.instrument_coverage.unwrap_or(config::InstrumentCoverage::Off)
1118 == config::InstrumentCoverage::ExceptUnusedFunctions
1119 }
1120
1121 pub fn mark_attr_known(&self, attr: &Attribute) {
1122 self.known_attrs.lock().mark(attr)
1123 }
1124
1125 pub fn is_attr_known(&self, attr: &Attribute) -> bool {
1126 self.known_attrs.lock().is_marked(attr)
1127 }
1128
1129 pub fn mark_attr_used(&self, attr: &Attribute) {
1130 self.used_attrs.lock().mark(attr)
1131 }
1132
1133 pub fn is_attr_used(&self, attr: &Attribute) -> bool {
1134 self.used_attrs.lock().is_marked(attr)
1135 }
1136
1137 /// Returns `true` if the attribute's path matches the argument. If it
1138 /// matches, then the attribute is marked as used.
1139 ///
1140 /// This method should only be used by rustc, other tools can use
1141 /// `Attribute::has_name` instead, because only rustc is supposed to report
1142 /// the `unused_attributes` lint. (`MetaItem` and `NestedMetaItem` are
1143 /// produced by lowering an `Attribute` and don't have identity, so they
1144 /// only have the `has_name` method, and you need to mark the original
1145 /// `Attribute` as used when necessary.)
1146 pub fn check_name(&self, attr: &Attribute, name: Symbol) -> bool {
1147 let matches = attr.has_name(name);
1148 if matches {
1149 self.mark_attr_used(attr);
1150 }
1151 matches
1152 }
1153
1154 pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
1155 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
1156 .iter()
1157 .any(|kind| self.check_name(attr, *kind))
1158 }
1159
1160 pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
1161 attrs.iter().any(|item| self.check_name(item, name))
1162 }
1163
1164 pub fn find_by_name<'a>(
1165 &'a self,
1166 attrs: &'a [Attribute],
1167 name: Symbol,
1168 ) -> Option<&'a Attribute> {
1169 attrs.iter().find(|attr| self.check_name(attr, name))
1170 }
1171
1172 pub fn filter_by_name<'a>(
1173 &'a self,
1174 attrs: &'a [Attribute],
1175 name: Symbol,
1176 ) -> impl Iterator<Item = &'a Attribute> {
1177 attrs.iter().filter(move |attr| self.check_name(attr, name))
1178 }
1179
1180 pub fn first_attr_value_str_by_name(
1181 &self,
1182 attrs: &[Attribute],
1183 name: Symbol,
1184 ) -> Option<Symbol> {
1185 attrs.iter().find(|at| self.check_name(at, name)).and_then(|at| at.value_str())
1186 }
1187 }
1188
1189 fn default_emitter(
1190 sopts: &config::Options,
1191 registry: rustc_errors::registry::Registry,
1192 source_map: Lrc<SourceMap>,
1193 emitter_dest: Option<Box<dyn Write + Send>>,
1194 ) -> Box<dyn Emitter + sync::Send> {
1195 let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1196 match (sopts.error_format, emitter_dest) {
1197 (config::ErrorOutputType::HumanReadable(kind), dst) => {
1198 let (short, color_config) = kind.unzip();
1199
1200 if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1201 let emitter =
1202 AnnotateSnippetEmitterWriter::new(Some(source_map), short, macro_backtrace);
1203 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1204 } else {
1205 let emitter = match dst {
1206 None => EmitterWriter::stderr(
1207 color_config,
1208 Some(source_map),
1209 short,
1210 sopts.debugging_opts.teach,
1211 sopts.debugging_opts.terminal_width,
1212 macro_backtrace,
1213 ),
1214 Some(dst) => EmitterWriter::new(
1215 dst,
1216 Some(source_map),
1217 short,
1218 false, // no teach messages when writing to a buffer
1219 false, // no colors when writing to a buffer
1220 None, // no terminal width
1221 macro_backtrace,
1222 ),
1223 };
1224 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1225 }
1226 }
1227 (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1228 JsonEmitter::stderr(
1229 Some(registry),
1230 source_map,
1231 pretty,
1232 json_rendered,
1233 sopts.debugging_opts.terminal_width,
1234 macro_backtrace,
1235 )
1236 .ui_testing(sopts.debugging_opts.ui_testing),
1237 ),
1238 (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1239 JsonEmitter::new(
1240 dst,
1241 Some(registry),
1242 source_map,
1243 pretty,
1244 json_rendered,
1245 sopts.debugging_opts.terminal_width,
1246 macro_backtrace,
1247 )
1248 .ui_testing(sopts.debugging_opts.ui_testing),
1249 ),
1250 }
1251 }
1252
1253 pub enum DiagnosticOutput {
1254 Default,
1255 Raw(Box<dyn Write + Send>),
1256 }
1257
1258 pub fn build_session(
1259 sopts: config::Options,
1260 local_crate_source_file: Option<PathBuf>,
1261 registry: rustc_errors::registry::Registry,
1262 diagnostics_output: DiagnosticOutput,
1263 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1264 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1265 target_override: Option<Target>,
1266 ) -> Session {
1267 // FIXME: This is not general enough to make the warning lint completely override
1268 // normal diagnostic warnings, since the warning lint can also be denied and changed
1269 // later via the source code.
1270 let warnings_allow = sopts
1271 .lint_opts
1272 .iter()
1273 .filter(|&&(ref key, _)| *key == "warnings")
1274 .map(|&(_, ref level)| *level == lint::Allow)
1275 .last()
1276 .unwrap_or(false);
1277 let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1278 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1279
1280 let write_dest = match diagnostics_output {
1281 DiagnosticOutput::Default => None,
1282 DiagnosticOutput::Raw(write) => Some(write),
1283 };
1284
1285 let target_cfg = config::build_target_config(&sopts, target_override);
1286 let host_triple = TargetTriple::from_triple(config::host_triple());
1287 let host = Target::search(&host_triple).unwrap_or_else(|e| {
1288 early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1289 });
1290
1291 let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1292 let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1293 if target_cfg.is_like_msvc {
1294 SourceFileHashAlgorithm::Sha1
1295 } else {
1296 SourceFileHashAlgorithm::Md5
1297 }
1298 });
1299 let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1300 loader,
1301 sopts.file_path_mapping(),
1302 hash_kind,
1303 ));
1304 let emitter = default_emitter(&sopts, registry, source_map.clone(), write_dest);
1305
1306 let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1307 emitter,
1308 sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1309 );
1310
1311 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1312 {
1313 let directory =
1314 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1315
1316 let profiler = SelfProfiler::new(
1317 directory,
1318 sopts.crate_name.as_deref(),
1319 &sopts.debugging_opts.self_profile_events,
1320 );
1321 match profiler {
1322 Ok(profiler) => Some(Arc::new(profiler)),
1323 Err(e) => {
1324 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1325 None
1326 }
1327 }
1328 } else {
1329 None
1330 };
1331
1332 let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1333 parse_sess.assume_incomplete_release = sopts.debugging_opts.assume_incomplete_release;
1334 let sysroot = match &sopts.maybe_sysroot {
1335 Some(sysroot) => sysroot.clone(),
1336 None => filesearch::get_or_default_sysroot(),
1337 };
1338
1339 let host_triple = config::host_triple();
1340 let target_triple = sopts.target_triple.triple();
1341 let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1342 let target_tlib_path = if host_triple == target_triple {
1343 None
1344 } else {
1345 Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1346 };
1347
1348 let file_path_mapping = sopts.file_path_mapping();
1349
1350 let local_crate_source_file =
1351 local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1352
1353 let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1354 let optimization_fuel = Lock::new(OptimizationFuel {
1355 remaining: sopts.debugging_opts.fuel.as_ref().map_or(0, |i| i.1),
1356 out_of_fuel: false,
1357 });
1358 let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1359 let print_fuel = AtomicU64::new(0);
1360
1361 let working_dir = env::current_dir().unwrap_or_else(|e| {
1362 parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1363 });
1364 let working_dir = file_path_mapping.map_prefix(working_dir);
1365
1366 let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1367 CguReuseTracker::new()
1368 } else {
1369 CguReuseTracker::new_disabled()
1370 };
1371
1372 let prof = SelfProfilerRef::new(
1373 self_profiler,
1374 sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1375 sopts.debugging_opts.time_passes,
1376 );
1377
1378 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1379 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1380 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1381 _ => CtfeBacktrace::Disabled,
1382 });
1383
1384 let asm_arch =
1385 if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1386
1387 let sess = Session {
1388 target: target_cfg,
1389 host,
1390 opts: sopts,
1391 host_tlib_path,
1392 target_tlib_path,
1393 parse_sess,
1394 sysroot,
1395 local_crate_source_file,
1396 working_dir,
1397 one_time_diagnostics: Default::default(),
1398 crate_types: OnceCell::new(),
1399 crate_disambiguator: OnceCell::new(),
1400 features: OnceCell::new(),
1401 lint_store: OnceCell::new(),
1402 recursion_limit: OnceCell::new(),
1403 move_size_limit: OnceCell::new(),
1404 type_length_limit: OnceCell::new(),
1405 const_eval_limit: OnceCell::new(),
1406 incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1407 cgu_reuse_tracker,
1408 prof,
1409 perf_stats: PerfStats {
1410 symbol_hash_time: Lock::new(Duration::from_secs(0)),
1411 queries_canonicalized: AtomicUsize::new(0),
1412 normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1413 normalize_projection_ty: AtomicUsize::new(0),
1414 },
1415 code_stats: Default::default(),
1416 optimization_fuel_crate,
1417 optimization_fuel,
1418 print_fuel_crate,
1419 print_fuel,
1420 jobserver: jobserver::client(),
1421 driver_lint_caps,
1422 trait_methods_not_found: Lock::new(Default::default()),
1423 confused_type_with_std_module: Lock::new(Default::default()),
1424 system_library_path: OneThread::new(RefCell::new(Default::default())),
1425 ctfe_backtrace,
1426 miri_unleashed_features: Lock::new(Default::default()),
1427 asm_arch,
1428 target_features: FxHashSet::default(),
1429 known_attrs: Lock::new(MarkedAttrs::new()),
1430 used_attrs: Lock::new(MarkedAttrs::new()),
1431 if_let_suggestions: Default::default(),
1432 };
1433
1434 validate_commandline_args_with_session_available(&sess);
1435
1436 sess
1437 }
1438
1439 // If it is useful to have a Session available already for validating a
1440 // commandline argument, you can do so here.
1441 fn validate_commandline_args_with_session_available(sess: &Session) {
1442 // Since we don't know if code in an rlib will be linked to statically or
1443 // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1444 // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1445 // these manually generated symbols confuse LLD when it tries to merge
1446 // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1447 // when compiling for LLD ThinLTO. This way we can validly just not generate
1448 // the `dllimport` attributes and `__imp_` symbols in that case.
1449 if sess.opts.cg.linker_plugin_lto.enabled()
1450 && sess.opts.cg.prefer_dynamic
1451 && sess.target.is_like_windows
1452 {
1453 sess.err(
1454 "Linker plugin based LTO is not supported together with \
1455 `-C prefer-dynamic` when targeting Windows-like targets",
1456 );
1457 }
1458
1459 // Make sure that any given profiling data actually exists so LLVM can't
1460 // decide to silently skip PGO.
1461 if let Some(ref path) = sess.opts.cg.profile_use {
1462 if !path.exists() {
1463 sess.err(&format!(
1464 "File `{}` passed to `-C profile-use` does not exist.",
1465 path.display()
1466 ));
1467 }
1468 }
1469
1470 // Unwind tables cannot be disabled if the target requires them.
1471 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1472 if sess.target.requires_uwtable && !include_uwtables {
1473 sess.err(
1474 "target requires unwind tables, they cannot be disabled with \
1475 `-C force-unwind-tables=no`.",
1476 );
1477 }
1478 }
1479
1480 // PGO does not work reliably with panic=unwind on Windows. Let's make it
1481 // an error to combine the two for now. It always runs into an assertions
1482 // if LLVM is built with assertions, but without assertions it sometimes
1483 // does not crash and will probably generate a corrupted binary.
1484 // We should only display this error if we're actually going to run PGO.
1485 // If we're just supposed to print out some data, don't show the error (#61002).
1486 if sess.opts.cg.profile_generate.enabled()
1487 && sess.target.is_like_msvc
1488 && sess.panic_strategy() == PanicStrategy::Unwind
1489 && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1490 {
1491 sess.err(
1492 "Profile-guided optimization does not yet work in conjunction \
1493 with `-Cpanic=unwind` on Windows when targeting MSVC. \
1494 See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1495 for more information.",
1496 );
1497 }
1498
1499 // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1500 let supported_sanitizers = sess.target.options.supported_sanitizers;
1501 let unsupported_sanitizers = sess.opts.debugging_opts.sanitizer - supported_sanitizers;
1502 match unsupported_sanitizers.into_iter().count() {
1503 0 => {}
1504 1 => sess
1505 .err(&format!("{} sanitizer is not supported for this target", unsupported_sanitizers)),
1506 _ => sess.err(&format!(
1507 "{} sanitizers are not supported for this target",
1508 unsupported_sanitizers
1509 )),
1510 }
1511 // Cannot mix and match sanitizers.
1512 let mut sanitizer_iter = sess.opts.debugging_opts.sanitizer.into_iter();
1513 if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
1514 sess.err(&format!("`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`", first, second));
1515 }
1516 }
1517
1518 /// Holds data on the current incremental compilation session, if there is one.
1519 #[derive(Debug)]
1520 pub enum IncrCompSession {
1521 /// This is the state the session will be in until the incr. comp. dir is
1522 /// needed.
1523 NotInitialized,
1524 /// This is the state during which the session directory is private and can
1525 /// be modified.
1526 Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1527 /// This is the state after the session directory has been finalized. In this
1528 /// state, the contents of the directory must not be modified any more.
1529 Finalized { session_directory: PathBuf },
1530 /// This is an error state that is reached when some compilation error has
1531 /// occurred. It indicates that the contents of the session directory must
1532 /// not be used, since they might be invalid.
1533 InvalidBecauseOfErrors { session_directory: PathBuf },
1534 }
1535
1536 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1537 let emitter: Box<dyn Emitter + sync::Send> = match output {
1538 config::ErrorOutputType::HumanReadable(kind) => {
1539 let (short, color_config) = kind.unzip();
1540 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1541 }
1542 config::ErrorOutputType::Json { pretty, json_rendered } => {
1543 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1544 }
1545 };
1546 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1547 handler.struct_fatal(msg).emit();
1548 rustc_errors::FatalError.raise();
1549 }
1550
1551 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1552 let emitter: Box<dyn Emitter + sync::Send> = match output {
1553 config::ErrorOutputType::HumanReadable(kind) => {
1554 let (short, color_config) = kind.unzip();
1555 Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1556 }
1557 config::ErrorOutputType::Json { pretty, json_rendered } => {
1558 Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1559 }
1560 };
1561 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1562 handler.struct_warn(msg).emit();
1563 }