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