3 use crate::early_error;
5 use crate::search_paths::SearchPath;
6 use crate::utils::NativeLib;
7 use rustc_errors::LanguageIdentifier;
8 use rustc_target::spec::{CodeModel, LinkerFlavorCli, MergeFunctions, PanicStrategy, SanitizerSet};
9 use rustc_target::spec::{
10 RelocModel, RelroLevel, SplitDebuginfo, StackProtector, TargetTriple, TlsModel,
13 use rustc_feature::UnstableFeatures;
14 use rustc_span::edition::Edition;
15 use rustc_span::RealFileName;
16 use rustc_span::SourceFileHashAlgorithm;
18 use std::collections::BTreeMap;
20 use std::collections::hash_map::DefaultHasher;
21 use std::hash::Hasher;
22 use std::num::NonZeroUsize;
23 use std::path::PathBuf;
27 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr) => {
29 .insert(stringify!($opt_name), $opt_expr as &dyn dep_tracking::DepTrackingHash)
32 panic!("duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
37 macro_rules! hash_opt {
38 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [UNTRACKED]) => {{}};
39 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [TRACKED]) => {{ insert!($opt_name, $opt_expr, $sub_hashes) }};
40 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $for_crate_hash: ident, [TRACKED_NO_CRATE_HASH]) => {{
42 insert!($opt_name, $opt_expr, $sub_hashes)
45 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, $_for_crate_hash: ident, [SUBSTRUCT]) => {{}};
48 macro_rules! hash_substruct {
49 ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [UNTRACKED]) => {{}};
50 ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [TRACKED]) => {{}};
51 ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [TRACKED_NO_CRATE_HASH]) => {{}};
52 ($opt_name:ident, $opt_expr:expr, $error_format:expr, $for_crate_hash:expr, $hasher:expr, [SUBSTRUCT]) => {
53 use crate::config::dep_tracking::DepTrackingHash;
54 $opt_expr.dep_tracking_hash($for_crate_hash, $error_format).hash(
62 macro_rules! top_level_options {
63 ( $( #[$top_level_attr:meta] )* pub struct Options { $(
65 $opt:ident : $t:ty [$dep_tracking_marker:ident],
68 $( #[$top_level_attr] )*
77 pub fn dep_tracking_hash(&self, for_crate_hash: bool) -> u64 {
78 let mut sub_hashes = BTreeMap::new();
84 [$dep_tracking_marker]);
86 let mut hasher = DefaultHasher::new();
87 dep_tracking::stable_hash(sub_hashes,
97 [$dep_tracking_marker]);
106 /// The top-level command-line options struct.
108 /// For each option, one has to specify how it behaves with regard to the
109 /// dependency tracking system of incremental compilation. This is done via the
110 /// square-bracketed directive after the field type. The options are:
113 /// A change in the given field will cause the compiler to completely clear the
114 /// incremental compilation cache before proceeding.
116 /// - `[TRACKED_NO_CRATE_HASH]`
117 /// Same as `[TRACKED]`, but will not affect the crate hash. This is useful for options that only
118 /// affect the incremental cache.
121 /// Incremental compilation is not influenced by this option.
124 /// Second-level sub-structs containing more options.
126 /// If you add a new option to this struct or one of the sub-structs like
127 /// `CodegenOptions`, think about how it influences incremental compilation. If in
128 /// doubt, specify `[TRACKED]`, which is always "correct" but might lead to
129 /// unnecessary re-compilation.
132 /// The crate config requested for the session, which may be combined
133 /// with additional crate configurations during the compile process.
134 #[rustc_lint_opt_deny_field_access("use `Session::crate_types` instead of this field")]
135 crate_types: Vec<CrateType> [TRACKED],
136 optimize: OptLevel [TRACKED],
137 /// Include the `debug_assertions` flag in dependency tracking, since it
138 /// can influence whether overflow checks are done or not.
139 debug_assertions: bool [TRACKED],
140 debuginfo: DebugInfo [TRACKED],
141 lint_opts: Vec<(String, lint::Level)> [TRACKED_NO_CRATE_HASH],
142 lint_cap: Option<lint::Level> [TRACKED_NO_CRATE_HASH],
143 describe_lints: bool [UNTRACKED],
144 output_types: OutputTypes [TRACKED],
145 search_paths: Vec<SearchPath> [UNTRACKED],
146 libs: Vec<NativeLib> [TRACKED],
147 maybe_sysroot: Option<PathBuf> [UNTRACKED],
149 target_triple: TargetTriple [TRACKED],
151 test: bool [TRACKED],
152 error_format: ErrorOutputType [UNTRACKED],
153 diagnostic_width: Option<usize> [UNTRACKED],
155 /// If `Some`, enable incremental compilation, using the given
156 /// directory to store intermediate results.
157 incremental: Option<PathBuf> [UNTRACKED],
158 assert_incr_state: Option<IncrementalStateAssertion> [UNTRACKED],
160 unstable_opts: UnstableOptions [SUBSTRUCT],
161 prints: Vec<PrintRequest> [UNTRACKED],
162 cg: CodegenOptions [SUBSTRUCT],
163 externs: Externs [UNTRACKED],
164 crate_name: Option<String> [TRACKED],
165 /// Indicates how the compiler should treat unstable features.
166 unstable_features: UnstableFeatures [TRACKED],
168 /// Indicates whether this run of the compiler is actually rustdoc. This
169 /// is currently just a hack and will be removed eventually, so please
170 /// try to not rely on this too much.
171 actually_rustdoc: bool [TRACKED],
173 /// Control path trimming.
174 trimmed_def_paths: TrimmedDefPaths [TRACKED],
176 /// Specifications of codegen units / ThinLTO which are forced as a
177 /// result of parsing command line options. These are not necessarily
178 /// what rustc was invoked with, but massaged a bit to agree with
179 /// commands like `--emit llvm-ir` which they're often incompatible with
180 /// if we otherwise use the defaults of rustc.
181 #[rustc_lint_opt_deny_field_access("use `Session::codegen_units` instead of this field")]
182 cli_forced_codegen_units: Option<usize> [UNTRACKED],
183 #[rustc_lint_opt_deny_field_access("use `Session::lto` instead of this field")]
184 cli_forced_local_thinlto_off: bool [UNTRACKED],
186 /// Remap source path prefixes in all output (messages, object files, debug, etc.).
187 remap_path_prefix: Vec<(PathBuf, PathBuf)> [TRACKED_NO_CRATE_HASH],
188 /// Base directory containing the `src/` for the Rust standard library, and
189 /// potentially `rustc` as well, if we can find it. Right now it's always
190 /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
192 /// This directory is what the virtual `/rustc/$hash` is translated back to,
193 /// if Rust was built with path remapping to `/rustc/$hash` enabled
194 /// (the `rust.remap-debuginfo` option in `config.toml`).
195 real_rust_source_base_dir: Option<PathBuf> [TRACKED_NO_CRATE_HASH],
197 edition: Edition [TRACKED],
199 /// `true` if we're emitting JSON blobs about each artifact produced
201 json_artifact_notifications: bool [TRACKED],
203 /// `true` if we're emitting a JSON blob containing the unused externs
204 json_unused_externs: JsonUnusedExterns [UNTRACKED],
206 /// `true` if we're emitting a JSON job containing a future-incompat report for lints
207 json_future_incompat: bool [TRACKED],
209 pretty: Option<PpMode> [UNTRACKED],
211 /// The (potentially remapped) working directory
212 working_dir: RealFileName [TRACKED],
216 /// Defines all `CodegenOptions`/`DebuggingOptions` fields and parsers all at once. The goal of this
217 /// macro is to define an interface that can be programmatically used by the option parser
218 /// to initialize the struct without hardcoding field names all over the place.
220 /// The goal is to invoke this macro once with the correct fields, and then this macro generates all
221 /// necessary code. The main gotcha of this macro is the `cgsetters` module which is a bunch of
222 /// generated code to parse an option into its respective field in the struct. There are a few
223 /// hand-written parsers for parsing specific types of values in this module.
224 macro_rules! options {
225 ($struct_name:ident, $stat:ident, $optmod:ident, $prefix:expr, $outputname:expr,
226 $($( #[$attr:meta] )* $opt:ident : $t:ty = (
229 [$dep_tracking_marker:ident],
235 pub struct $struct_name { $( $( #[$attr] )* pub $opt: $t),* }
237 impl Default for $struct_name {
238 fn default() -> $struct_name {
239 $struct_name { $($opt: $init),* }
245 matches: &getopts::Matches,
246 error_format: ErrorOutputType,
248 build_options(matches, $stat, $prefix, $outputname, error_format)
251 fn dep_tracking_hash(&self, for_crate_hash: bool, error_format: ErrorOutputType) -> u64 {
252 let mut sub_hashes = BTreeMap::new();
258 [$dep_tracking_marker]);
260 let mut hasher = DefaultHasher::new();
261 dep_tracking::stable_hash(sub_hashes,
270 pub const $stat: OptionDescrs<$struct_name> =
271 &[ $( (stringify!($opt), $optmod::$opt, desc::$parse, $desc) ),* ];
275 pub(super) fn $opt(cg: &mut super::$struct_name, v: Option<&str>) -> bool {
276 super::parse::$parse(&mut redirect_field!(cg.$opt), v)
283 impl CodegenOptions {
284 // JUSTIFICATION: defn of the suggested wrapper fn
285 #[allow(rustc::bad_opt_access)]
286 pub fn instrument_coverage(&self) -> InstrumentCoverage {
287 self.instrument_coverage.unwrap_or(InstrumentCoverage::Off)
291 // Sometimes different options need to build a common structure.
292 // That structure can be kept in one of the options' fields, the others become dummy.
293 macro_rules! redirect_field {
294 ($cg:ident.link_arg) => {
297 ($cg:ident.pre_link_arg) => {
300 ($cg:ident.$field:ident) => {
305 type OptionSetter<O> = fn(&mut O, v: Option<&str>) -> bool;
306 type OptionDescrs<O> = &'static [(&'static str, OptionSetter<O>, &'static str, &'static str)];
308 fn build_options<O: Default>(
309 matches: &getopts::Matches,
310 descrs: OptionDescrs<O>,
313 error_format: ErrorOutputType,
315 let mut op = O::default();
316 for option in matches.opt_strs(prefix) {
317 let (key, value) = match option.split_once('=') {
318 None => (option, None),
319 Some((k, v)) => (k.to_string(), Some(v)),
322 let option_to_lookup = key.replace('-', "_");
323 match descrs.iter().find(|(name, ..)| *name == option_to_lookup) {
324 Some((_, setter, type_desc, _)) => {
325 if !setter(&mut op, value) {
330 "{0} option `{1}` requires {2} ({3} {1}=<value>)",
331 outputname, key, type_desc, prefix
334 Some(value) => early_error(
337 "incorrect value `{value}` for {outputname} option `{key}` - {type_desc} was expected"
343 None => early_error(error_format, &format!("unknown {outputname} option: `{key}`")),
349 #[allow(non_upper_case_globals)]
351 pub const parse_no_flag: &str = "no value";
352 pub const parse_bool: &str = "one of: `y`, `yes`, `on`, `n`, `no`, or `off`";
353 pub const parse_opt_bool: &str = parse_bool;
354 pub const parse_string: &str = "a string";
355 pub const parse_opt_string: &str = parse_string;
356 pub const parse_string_push: &str = parse_string;
357 pub const parse_opt_langid: &str = "a language identifier";
358 pub const parse_opt_pathbuf: &str = "a path";
359 pub const parse_list: &str = "a space-separated list of strings";
360 pub const parse_list_with_polarity: &str =
361 "a comma-separated list of strings, with elements beginning with + or -";
362 pub const parse_opt_comma_list: &str = "a comma-separated list of strings";
363 pub const parse_number: &str = "a number";
364 pub const parse_opt_number: &str = parse_number;
365 pub const parse_threads: &str = parse_number;
366 pub const parse_passes: &str = "a space-separated list of passes, or `all`";
367 pub const parse_panic_strategy: &str = "either `unwind` or `abort`";
368 pub const parse_opt_panic_strategy: &str = parse_panic_strategy;
369 pub const parse_oom_strategy: &str = "either `panic` or `abort`";
370 pub const parse_relro_level: &str = "one of: `full`, `partial`, or `off`";
371 pub const parse_sanitizers: &str = "comma separated list of sanitizers: `address`, `cfi`, `hwaddress`, `kcfi`, `leak`, `memory`, `memtag`, `shadow-call-stack`, or `thread`";
372 pub const parse_sanitizer_memory_track_origins: &str = "0, 1, or 2";
373 pub const parse_cfguard: &str =
374 "either a boolean (`yes`, `no`, `on`, `off`, etc), `checks`, or `nochecks`";
375 pub const parse_cfprotection: &str = "`none`|`no`|`n` (default), `branch`, `return`, or `full`|`yes`|`y` (equivalent to `branch` and `return`)";
376 pub const parse_strip: &str = "either `none`, `debuginfo`, or `symbols`";
377 pub const parse_linker_flavor: &str = ::rustc_target::spec::LinkerFlavorCli::one_of();
378 pub const parse_optimization_fuel: &str = "crate=integer";
379 pub const parse_mir_spanview: &str = "`statement` (default), `terminator`, or `block`";
380 pub const parse_instrument_coverage: &str =
381 "`all` (default), `except-unused-generics`, `except-unused-functions`, or `off`";
382 pub const parse_unpretty: &str = "`string` or `string=string`";
383 pub const parse_treat_err_as_bug: &str = "either no value or a number bigger than 0";
384 pub const parse_lto: &str =
385 "either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, `fat`, or omitted";
386 pub const parse_linker_plugin_lto: &str =
387 "either a boolean (`yes`, `no`, `on`, `off`, etc), or the path to the linker plugin";
388 pub const parse_location_detail: &str = "either `none`, or a comma separated list of location details to track: `file`, `line`, or `column`";
389 pub const parse_switch_with_opt_path: &str =
390 "an optional path to the profiling data output directory";
391 pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`";
392 pub const parse_symbol_mangling_version: &str = "either `legacy` or `v0` (RFC 2603)";
393 pub const parse_src_file_hash: &str = "either `md5` or `sha1`";
394 pub const parse_relocation_model: &str =
395 "one of supported relocation models (`rustc --print relocation-models`)";
396 pub const parse_code_model: &str = "one of supported code models (`rustc --print code-models`)";
397 pub const parse_tls_model: &str = "one of supported TLS models (`rustc --print tls-models`)";
398 pub const parse_target_feature: &str = parse_string;
399 pub const parse_wasi_exec_model: &str = "either `command` or `reactor`";
400 pub const parse_split_debuginfo: &str =
401 "one of supported split-debuginfo modes (`off`, `packed`, or `unpacked`)";
402 pub const parse_split_dwarf_kind: &str =
403 "one of supported split dwarf modes (`split` or `single`)";
404 pub const parse_gcc_ld: &str = "one of: no value, `lld`";
405 pub const parse_stack_protector: &str =
406 "one of (`none` (default), `basic`, `strong`, or `all`)";
407 pub const parse_branch_protection: &str =
408 "a `,` separated combination of `bti`, `b-key`, `pac-ret`, or `leaf`";
409 pub const parse_proc_macro_execution_strategy: &str =
410 "one of supported execution strategies (`same-thread`, or `cross-thread`)";
414 pub(crate) use super::*;
415 use std::str::FromStr;
417 /// This is for boolean options that don't take a value and start with
418 /// `no-`. This style of option is deprecated.
419 pub(crate) fn parse_no_flag(slot: &mut bool, v: Option<&str>) -> bool {
429 /// Use this for any boolean option that has a static default.
430 pub(crate) fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
432 Some("y") | Some("yes") | Some("on") | None => {
436 Some("n") | Some("no") | Some("off") => {
444 /// Use this for any boolean option that lacks a static default. (The
445 /// actions taken when such an option is not specified will depend on
446 /// other factors, such as other options, or target options.)
447 pub(crate) fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
449 Some("y") | Some("yes") | Some("on") | None => {
453 Some("n") | Some("no") | Some("off") => {
461 /// Use this for any string option that has a static default.
462 pub(crate) fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
465 *slot = s.to_string();
472 /// Use this for any string option that lacks a static default.
473 pub(crate) fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
476 *slot = Some(s.to_string());
483 /// Parse an optional language identifier, e.g. `en-US` or `zh-CN`.
484 pub(crate) fn parse_opt_langid(slot: &mut Option<LanguageIdentifier>, v: Option<&str>) -> bool {
487 *slot = rustc_errors::LanguageIdentifier::from_str(s).ok();
494 pub(crate) fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
497 *slot = Some(PathBuf::from(s));
504 pub(crate) fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
507 slot.push(s.to_string());
514 pub(crate) fn parse_list(slot: &mut Vec<String>, v: Option<&str>) -> bool {
517 slot.extend(s.split_whitespace().map(|s| s.to_string()));
524 pub(crate) fn parse_list_with_polarity(
525 slot: &mut Vec<(String, bool)>,
530 for s in s.split(',') {
531 let Some(pass_name) = s.strip_prefix(&['+', '-'][..]) else { return false };
532 slot.push((pass_name.to_string(), &s[..1] == "+"));
540 pub(crate) fn parse_location_detail(ld: &mut LocationDetail, v: Option<&str>) -> bool {
548 for s in v.split(',') {
550 "file" => ld.file = true,
551 "line" => ld.line = true,
552 "column" => ld.column = true,
562 pub(crate) fn parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>) -> bool {
565 let mut v: Vec<_> = s.split(',').map(|s| s.to_string()).collect();
574 pub(crate) fn parse_threads(slot: &mut usize, v: Option<&str>) -> bool {
575 match v.and_then(|s| s.parse().ok()) {
577 *slot = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
588 /// Use this for any numeric option that has a static default.
589 pub(crate) fn parse_number<T: Copy + FromStr>(slot: &mut T, v: Option<&str>) -> bool {
590 match v.and_then(|s| s.parse().ok()) {
599 /// Use this for any numeric option that lacks a static default.
600 pub(crate) fn parse_opt_number<T: Copy + FromStr>(
601 slot: &mut Option<T>,
606 *slot = s.parse().ok();
613 pub(crate) fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
620 let mut passes = vec![];
621 if parse_list(&mut passes, v) {
631 pub(crate) fn parse_opt_panic_strategy(
632 slot: &mut Option<PanicStrategy>,
636 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
637 Some("abort") => *slot = Some(PanicStrategy::Abort),
643 pub(crate) fn parse_panic_strategy(slot: &mut PanicStrategy, v: Option<&str>) -> bool {
645 Some("unwind") => *slot = PanicStrategy::Unwind,
646 Some("abort") => *slot = PanicStrategy::Abort,
652 pub(crate) fn parse_oom_strategy(slot: &mut OomStrategy, v: Option<&str>) -> bool {
654 Some("panic") => *slot = OomStrategy::Panic,
655 Some("abort") => *slot = OomStrategy::Abort,
661 pub(crate) fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
663 Some(s) => match s.parse::<RelroLevel>() {
664 Ok(level) => *slot = Some(level),
672 pub(crate) fn parse_sanitizers(slot: &mut SanitizerSet, v: Option<&str>) -> bool {
674 for s in v.split(',') {
676 "address" => SanitizerSet::ADDRESS,
677 "cfi" => SanitizerSet::CFI,
678 "kcfi" => SanitizerSet::KCFI,
679 "leak" => SanitizerSet::LEAK,
680 "memory" => SanitizerSet::MEMORY,
681 "memtag" => SanitizerSet::MEMTAG,
682 "shadow-call-stack" => SanitizerSet::SHADOWCALLSTACK,
683 "thread" => SanitizerSet::THREAD,
684 "hwaddress" => SanitizerSet::HWADDRESS,
694 pub(crate) fn parse_sanitizer_memory_track_origins(slot: &mut usize, v: Option<&str>) -> bool {
696 Some("2") | None => {
712 pub(crate) fn parse_strip(slot: &mut Strip, v: Option<&str>) -> bool {
714 Some("none") => *slot = Strip::None,
715 Some("debuginfo") => *slot = Strip::Debuginfo,
716 Some("symbols") => *slot = Strip::Symbols,
722 pub(crate) fn parse_cfguard(slot: &mut CFGuard, v: Option<&str>) -> bool {
724 let mut bool_arg = None;
725 if parse_opt_bool(&mut bool_arg, v) {
726 *slot = if bool_arg.unwrap() { CFGuard::Checks } else { CFGuard::Disabled };
732 None => CFGuard::Checks,
733 Some("checks") => CFGuard::Checks,
734 Some("nochecks") => CFGuard::NoChecks,
735 Some(_) => return false,
740 pub(crate) fn parse_cfprotection(slot: &mut CFProtection, v: Option<&str>) -> bool {
742 let mut bool_arg = None;
743 if parse_opt_bool(&mut bool_arg, v) {
744 *slot = if bool_arg.unwrap() { CFProtection::Full } else { CFProtection::None };
750 None | Some("none") => CFProtection::None,
751 Some("branch") => CFProtection::Branch,
752 Some("return") => CFProtection::Return,
753 Some("full") => CFProtection::Full,
754 Some(_) => return false,
759 pub(crate) fn parse_linker_flavor(slot: &mut Option<LinkerFlavorCli>, v: Option<&str>) -> bool {
760 match v.and_then(LinkerFlavorCli::from_str) {
761 Some(lf) => *slot = Some(lf),
767 pub(crate) fn parse_optimization_fuel(
768 slot: &mut Option<(String, u64)>,
774 let parts = s.split('=').collect::<Vec<_>>();
775 if parts.len() != 2 {
778 let crate_name = parts[0].to_string();
779 let fuel = parts[1].parse::<u64>();
783 *slot = Some((crate_name, fuel.unwrap()));
789 pub(crate) fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
792 Some(s) if s.split('=').count() <= 2 => {
793 *slot = Some(s.to_string());
800 pub(crate) fn parse_mir_spanview(slot: &mut Option<MirSpanview>, v: Option<&str>) -> bool {
802 let mut bool_arg = None;
803 if parse_opt_bool(&mut bool_arg, v) {
804 *slot = if bool_arg.unwrap() { Some(MirSpanview::Statement) } else { None };
809 let Some(v) = v else {
810 *slot = Some(MirSpanview::Statement);
814 *slot = Some(match v.trim_end_matches('s') {
815 "statement" | "stmt" => MirSpanview::Statement,
816 "terminator" | "term" => MirSpanview::Terminator,
817 "block" | "basicblock" => MirSpanview::Block,
823 pub(crate) fn parse_instrument_coverage(
824 slot: &mut Option<InstrumentCoverage>,
828 let mut bool_arg = None;
829 if parse_opt_bool(&mut bool_arg, v) {
830 *slot = if bool_arg.unwrap() { Some(InstrumentCoverage::All) } else { None };
835 let Some(v) = v else {
836 *slot = Some(InstrumentCoverage::All);
840 *slot = Some(match v {
841 "all" => InstrumentCoverage::All,
842 "except-unused-generics" | "except_unused_generics" => {
843 InstrumentCoverage::ExceptUnusedGenerics
845 "except-unused-functions" | "except_unused_functions" => {
846 InstrumentCoverage::ExceptUnusedFunctions
848 "off" | "no" | "n" | "false" | "0" => InstrumentCoverage::Off,
854 pub(crate) fn parse_treat_err_as_bug(slot: &mut Option<NonZeroUsize>, v: Option<&str>) -> bool {
857 *slot = s.parse().ok();
861 *slot = NonZeroUsize::new(1);
867 pub(crate) fn parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool {
869 let mut bool_arg = None;
870 if parse_opt_bool(&mut bool_arg, v) {
871 *slot = if bool_arg.unwrap() { LtoCli::Yes } else { LtoCli::No };
877 None => LtoCli::NoParam,
878 Some("thin") => LtoCli::Thin,
879 Some("fat") => LtoCli::Fat,
880 Some(_) => return false,
885 pub(crate) fn parse_linker_plugin_lto(slot: &mut LinkerPluginLto, v: Option<&str>) -> bool {
887 let mut bool_arg = None;
888 if parse_opt_bool(&mut bool_arg, v) {
889 *slot = if bool_arg.unwrap() {
890 LinkerPluginLto::LinkerPluginAuto
892 LinkerPluginLto::Disabled
899 None => LinkerPluginLto::LinkerPluginAuto,
900 Some(path) => LinkerPluginLto::LinkerPlugin(PathBuf::from(path)),
905 pub(crate) fn parse_switch_with_opt_path(
906 slot: &mut SwitchWithOptPath,
910 None => SwitchWithOptPath::Enabled(None),
911 Some(path) => SwitchWithOptPath::Enabled(Some(PathBuf::from(path))),
916 pub(crate) fn parse_merge_functions(
917 slot: &mut Option<MergeFunctions>,
920 match v.and_then(|s| MergeFunctions::from_str(s).ok()) {
921 Some(mergefunc) => *slot = Some(mergefunc),
927 pub(crate) fn parse_relocation_model(slot: &mut Option<RelocModel>, v: Option<&str>) -> bool {
928 match v.and_then(|s| RelocModel::from_str(s).ok()) {
929 Some(relocation_model) => *slot = Some(relocation_model),
930 None if v == Some("default") => *slot = None,
936 pub(crate) fn parse_code_model(slot: &mut Option<CodeModel>, v: Option<&str>) -> bool {
937 match v.and_then(|s| CodeModel::from_str(s).ok()) {
938 Some(code_model) => *slot = Some(code_model),
944 pub(crate) fn parse_tls_model(slot: &mut Option<TlsModel>, v: Option<&str>) -> bool {
945 match v.and_then(|s| TlsModel::from_str(s).ok()) {
946 Some(tls_model) => *slot = Some(tls_model),
952 pub(crate) fn parse_symbol_mangling_version(
953 slot: &mut Option<SymbolManglingVersion>,
957 Some("legacy") => Some(SymbolManglingVersion::Legacy),
958 Some("v0") => Some(SymbolManglingVersion::V0),
964 pub(crate) fn parse_src_file_hash(
965 slot: &mut Option<SourceFileHashAlgorithm>,
968 match v.and_then(|s| SourceFileHashAlgorithm::from_str(s).ok()) {
969 Some(hash_kind) => *slot = Some(hash_kind),
975 pub(crate) fn parse_target_feature(slot: &mut String, v: Option<&str>) -> bool {
978 if !slot.is_empty() {
988 pub(crate) fn parse_wasi_exec_model(slot: &mut Option<WasiExecModel>, v: Option<&str>) -> bool {
990 Some("command") => *slot = Some(WasiExecModel::Command),
991 Some("reactor") => *slot = Some(WasiExecModel::Reactor),
997 pub(crate) fn parse_split_debuginfo(
998 slot: &mut Option<SplitDebuginfo>,
1001 match v.and_then(|s| SplitDebuginfo::from_str(s).ok()) {
1002 Some(e) => *slot = Some(e),
1008 pub(crate) fn parse_split_dwarf_kind(slot: &mut SplitDwarfKind, v: Option<&str>) -> bool {
1009 match v.and_then(|s| SplitDwarfKind::from_str(s).ok()) {
1010 Some(e) => *slot = e,
1016 pub(crate) fn parse_gcc_ld(slot: &mut Option<LdImpl>, v: Option<&str>) -> bool {
1018 None => *slot = None,
1019 Some("lld") => *slot = Some(LdImpl::Lld),
1025 pub(crate) fn parse_stack_protector(slot: &mut StackProtector, v: Option<&str>) -> bool {
1026 match v.and_then(|s| StackProtector::from_str(s).ok()) {
1027 Some(ssp) => *slot = ssp,
1033 pub(crate) fn parse_branch_protection(
1034 slot: &mut Option<BranchProtection>,
1039 let slot = slot.get_or_insert_default();
1040 for opt in s.split(',') {
1042 "bti" => slot.bti = true,
1043 "pac-ret" if slot.pac_ret.is_none() => {
1044 slot.pac_ret = Some(PacRet { leaf: false, key: PAuthKey::A })
1046 "leaf" => match slot.pac_ret.as_mut() {
1047 Some(pac) => pac.leaf = true,
1050 "b-key" => match slot.pac_ret.as_mut() {
1051 Some(pac) => pac.key = PAuthKey::B,
1063 pub(crate) fn parse_proc_macro_execution_strategy(
1064 slot: &mut ProcMacroExecutionStrategy,
1068 Some("same-thread") => ProcMacroExecutionStrategy::SameThread,
1069 Some("cross-thread") => ProcMacroExecutionStrategy::CrossThread,
1077 CodegenOptions, CG_OPTIONS, cgopts, "C", "codegen",
1079 // If you add a new option, please update:
1080 // - compiler/rustc_interface/src/tests.rs
1081 // - src/doc/rustc/src/codegen-options/index.md
1083 // tidy-alphabetical-start
1084 ar: String = (String::new(), parse_string, [UNTRACKED],
1085 "this option is deprecated and does nothing"),
1086 #[rustc_lint_opt_deny_field_access("use `Session::code_model` instead of this field")]
1087 code_model: Option<CodeModel> = (None, parse_code_model, [TRACKED],
1088 "choose the code model to use (`rustc --print code-models` for details)"),
1089 codegen_units: Option<usize> = (None, parse_opt_number, [UNTRACKED],
1090 "divide crate into N units to optimize in parallel"),
1091 control_flow_guard: CFGuard = (CFGuard::Disabled, parse_cfguard, [TRACKED],
1092 "use Windows Control Flow Guard (default: no)"),
1093 debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1094 "explicitly enable the `cfg(debug_assertions)` directive"),
1095 debuginfo: usize = (0, parse_number, [TRACKED],
1096 "debug info emission level (0 = no debug info, 1 = line tables only, \
1097 2 = full debug info with variable and type information; default: 0)"),
1098 default_linker_libraries: bool = (false, parse_bool, [UNTRACKED],
1099 "allow the linker to link its default libraries (default: no)"),
1100 embed_bitcode: bool = (true, parse_bool, [TRACKED],
1101 "emit bitcode in rlibs (default: yes)"),
1102 extra_filename: String = (String::new(), parse_string, [UNTRACKED],
1103 "extra data to put in each output filename"),
1104 force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1105 "force use of the frame pointers"),
1106 #[rustc_lint_opt_deny_field_access("use `Session::must_emit_unwind_tables` instead of this field")]
1107 force_unwind_tables: Option<bool> = (None, parse_opt_bool, [TRACKED],
1108 "force use of unwind tables"),
1109 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1110 "enable incremental compilation"),
1111 inline_threshold: Option<u32> = (None, parse_opt_number, [TRACKED],
1112 "set the threshold for inlining a function"),
1113 #[rustc_lint_opt_deny_field_access("use `Session::instrument_coverage` instead of this field")]
1114 instrument_coverage: Option<InstrumentCoverage> = (None, parse_instrument_coverage, [TRACKED],
1115 "instrument the generated code to support LLVM source-based code coverage \
1116 reports (note, the compiler build config must include `profiler = true`); \
1117 implies `-C symbol-mangling-version=v0`. Optional values are:
1118 `=all` (implicit value)
1119 `=except-unused-generics`
1120 `=except-unused-functions`
1122 link_arg: (/* redirected to link_args */) = ((), parse_string_push, [UNTRACKED],
1123 "a single extra argument to append to the linker invocation (can be used several times)"),
1124 link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
1125 "extra arguments to append to the linker invocation (space separated)"),
1126 #[rustc_lint_opt_deny_field_access("use `Session::link_dead_code` instead of this field")]
1127 link_dead_code: Option<bool> = (None, parse_opt_bool, [TRACKED],
1128 "keep dead code at link time (useful for code coverage) (default: no)"),
1129 link_self_contained: Option<bool> = (None, parse_opt_bool, [UNTRACKED],
1130 "control whether to link Rust provided C objects/libraries or rely
1131 on C toolchain installed in the system"),
1132 linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1133 "system linker to link outputs with"),
1134 linker_flavor: Option<LinkerFlavorCli> = (None, parse_linker_flavor, [UNTRACKED],
1136 linker_plugin_lto: LinkerPluginLto = (LinkerPluginLto::Disabled,
1137 parse_linker_plugin_lto, [TRACKED],
1138 "generate build artifacts that are compatible with linker-based LTO"),
1139 llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1140 "a list of arguments to pass to LLVM (space separated)"),
1141 #[rustc_lint_opt_deny_field_access("use `Session::lto` instead of this field")]
1142 lto: LtoCli = (LtoCli::Unspecified, parse_lto, [TRACKED],
1143 "perform LLVM link-time optimizations"),
1144 metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1145 "metadata to mangle symbol names with"),
1146 no_prepopulate_passes: bool = (false, parse_no_flag, [TRACKED],
1147 "give an empty list of passes to the pass manager"),
1148 no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1149 "disable the use of the redzone"),
1150 no_stack_check: bool = (false, parse_no_flag, [UNTRACKED],
1151 "this option is deprecated and does nothing"),
1152 no_vectorize_loops: bool = (false, parse_no_flag, [TRACKED],
1153 "disable loop vectorization optimization passes"),
1154 no_vectorize_slp: bool = (false, parse_no_flag, [TRACKED],
1155 "disable LLVM's SLP vectorization pass"),
1156 opt_level: String = ("0".to_string(), parse_string, [TRACKED],
1157 "optimization level (0-3, s, or z; default: 0)"),
1158 #[rustc_lint_opt_deny_field_access("use `Session::overflow_checks` instead of this field")]
1159 overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1160 "use overflow checks for integer arithmetic"),
1161 #[rustc_lint_opt_deny_field_access("use `Session::panic_strategy` instead of this field")]
1162 panic: Option<PanicStrategy> = (None, parse_opt_panic_strategy, [TRACKED],
1163 "panic strategy to compile crate with"),
1164 passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1165 "a list of extra LLVM passes to run (space separated)"),
1166 prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1167 "prefer dynamic linking to static linking (default: no)"),
1168 profile_generate: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1169 parse_switch_with_opt_path, [TRACKED],
1170 "compile the program with profiling instrumentation"),
1171 profile_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1172 "use the given `.profdata` file for profile-guided optimization"),
1173 #[rustc_lint_opt_deny_field_access("use `Session::relocation_model` instead of this field")]
1174 relocation_model: Option<RelocModel> = (None, parse_relocation_model, [TRACKED],
1175 "control generation of position-independent code (PIC) \
1176 (`rustc --print relocation-models` for details)"),
1177 remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
1178 "print remarks for these optimization passes (space separated, or \"all\")"),
1179 rpath: bool = (false, parse_bool, [UNTRACKED],
1180 "set rpath values in libs/exes (default: no)"),
1181 save_temps: bool = (false, parse_bool, [UNTRACKED],
1182 "save all temporary output files during compilation (default: no)"),
1183 soft_float: bool = (false, parse_bool, [TRACKED],
1184 "use soft float ABI (*eabihf targets only) (default: no)"),
1185 #[rustc_lint_opt_deny_field_access("use `Session::split_debuginfo` instead of this field")]
1186 split_debuginfo: Option<SplitDebuginfo> = (None, parse_split_debuginfo, [TRACKED],
1187 "how to handle split-debuginfo, a platform-specific option"),
1188 strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
1189 "tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"),
1190 symbol_mangling_version: Option<SymbolManglingVersion> = (None,
1191 parse_symbol_mangling_version, [TRACKED],
1192 "which mangling version to use for symbol names ('legacy' (default) or 'v0')"),
1193 target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1194 "select target processor (`rustc --print target-cpus` for details)"),
1195 target_feature: String = (String::new(), parse_target_feature, [TRACKED],
1196 "target specific attributes. (`rustc --print target-features` for details). \
1197 This feature is unsafe."),
1198 // tidy-alphabetical-end
1200 // If you add a new option, please update:
1201 // - compiler/rustc_interface/src/tests.rs
1202 // - src/doc/rustc/src/codegen-options/index.md
1206 UnstableOptions, Z_OPTIONS, dbopts, "Z", "unstable",
1208 // If you add a new option, please update:
1209 // - compiler/rustc_interface/src/tests.rs
1210 // - src/doc/unstable-book/src/compiler-flags
1212 // tidy-alphabetical-start
1213 allow_features: Option<Vec<String>> = (None, parse_opt_comma_list, [TRACKED],
1214 "only allow the listed language features to be enabled in code (space separated)"),
1215 always_encode_mir: bool = (false, parse_bool, [TRACKED],
1216 "encode MIR of all functions into the crate metadata (default: no)"),
1217 #[rustc_lint_opt_deny_field_access("use `Session::asm_comments` instead of this field")]
1218 asm_comments: bool = (false, parse_bool, [TRACKED],
1219 "generate comments into the assembly (may change behavior) (default: no)"),
1220 assert_incr_state: Option<String> = (None, parse_opt_string, [UNTRACKED],
1221 "assert that the incremental cache is in given state: \
1222 either `loaded` or `not-loaded`."),
1223 assume_incomplete_release: bool = (false, parse_bool, [TRACKED],
1224 "make cfg(version) treat the current version as incomplete (default: no)"),
1225 #[rustc_lint_opt_deny_field_access("use `Session::binary_dep_depinfo` instead of this field")]
1226 binary_dep_depinfo: bool = (false, parse_bool, [TRACKED],
1227 "include artifacts (sysroot, crate dependencies) used during compilation in dep-info \
1229 box_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
1230 "emit noalias metadata for box (default: yes)"),
1231 branch_protection: Option<BranchProtection> = (None, parse_branch_protection, [TRACKED],
1232 "set options for branch target identification and pointer authentication on AArch64"),
1233 cf_protection: CFProtection = (CFProtection::None, parse_cfprotection, [TRACKED],
1234 "instrument control-flow architecture protection"),
1235 cgu_partitioning_strategy: Option<String> = (None, parse_opt_string, [TRACKED],
1236 "the codegen unit partitioning strategy to use"),
1237 chalk: bool = (false, parse_bool, [TRACKED],
1238 "enable the experimental Chalk-based trait solving engine"),
1239 codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1240 "the backend to use"),
1241 combine_cgu: bool = (false, parse_bool, [TRACKED],
1242 "combine CGUs into a single one"),
1243 crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
1244 "inject the given attribute in the crate"),
1245 debug_info_for_profiling: bool = (false, parse_bool, [TRACKED],
1246 "emit discriminators and other data necessary for AutoFDO"),
1247 debug_macros: bool = (false, parse_bool, [TRACKED],
1248 "emit line numbers debug info inside macros (default: no)"),
1249 deduplicate_diagnostics: bool = (true, parse_bool, [UNTRACKED],
1250 "deduplicate identical diagnostics (default: yes)"),
1251 dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1252 "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1253 themselves (default: no)"),
1254 dep_tasks: bool = (false, parse_bool, [UNTRACKED],
1255 "print tasks that execute and the color their dep node gets (requires debug build) \
1257 diagnostic_width: Option<usize> = (None, parse_opt_number, [UNTRACKED],
1258 "set the current output width for diagnostic truncation"),
1259 dlltool: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1260 "import library generation tool (windows-gnu only)"),
1261 dont_buffer_diagnostics: bool = (false, parse_bool, [UNTRACKED],
1262 "emit diagnostics rather than buffering (breaks NLL error downgrading, sorting) \
1264 drop_tracking: bool = (false, parse_bool, [TRACKED],
1265 "enables drop tracking in generators (default: no)"),
1266 dual_proc_macros: bool = (false, parse_bool, [TRACKED],
1267 "load proc macros for both target and host, but only link to the target (default: no)"),
1268 dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1269 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv) \
1271 dump_drop_tracking_cfg: Option<String> = (None, parse_opt_string, [UNTRACKED],
1272 "dump drop-tracking control-flow graph as a `.dot` file (default: no)"),
1273 dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1274 "dump MIR state to file.
1275 `val` is used to select which passes and functions to dump. For example:
1276 `all` matches all passes and functions,
1277 `foo` matches all passes for functions whose name contains 'foo',
1278 `foo & ConstProp` only the 'ConstProp' pass for function names containing 'foo',
1279 `foo | bar` all passes for function names containing 'foo' or 'bar'."),
1280 dump_mir_dataflow: bool = (false, parse_bool, [UNTRACKED],
1281 "in addition to `.mir` files, create graphviz `.dot` files with dataflow results \
1283 dump_mir_dir: String = ("mir_dump".to_string(), parse_string, [UNTRACKED],
1284 "the directory the MIR is dumped into (default: `mir_dump`)"),
1285 dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1286 "exclude the pass number when dumping MIR (used in tests) (default: no)"),
1287 dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1288 "in addition to `.mir` files, create graphviz `.dot` files (and with \
1289 `-Z instrument-coverage`, also create a `.dot` file for the MIR-derived \
1290 coverage graph) (default: no)"),
1291 dump_mir_spanview: Option<MirSpanview> = (None, parse_mir_spanview, [UNTRACKED],
1292 "in addition to `.mir` files, create `.html` files to view spans for \
1293 all `statement`s (including terminators), only `terminator` spans, or \
1294 computed `block` spans (one span encompassing a block's terminator and \
1295 all statements). If `-Z instrument-coverage` is also enabled, create \
1296 an additional `.html` file showing the computed coverage spans."),
1297 dwarf_version: Option<u32> = (None, parse_opt_number, [TRACKED],
1298 "version of DWARF debug information to emit (default: 2 or 4, depending on platform)"),
1299 dylib_lto: bool = (false, parse_bool, [UNTRACKED],
1300 "enables LTO for dylib crate type"),
1301 emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
1302 "emit a section containing stack size metadata (default: no)"),
1303 emit_thin_lto: bool = (true, parse_bool, [TRACKED],
1304 "emit the bc module with thin LTO info (default: yes)"),
1305 export_executable_symbols: bool = (false, parse_bool, [TRACKED],
1306 "export symbols from executables, as if they were dynamic libraries"),
1307 extra_const_ub_checks: bool = (false, parse_bool, [TRACKED],
1308 "turns on more checks to detect const UB, which can be slow (default: no)"),
1309 #[rustc_lint_opt_deny_field_access("use `Session::fewer_names` instead of this field")]
1310 fewer_names: Option<bool> = (None, parse_opt_bool, [TRACKED],
1311 "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR) \
1313 force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1314 "force all crates to be `rustc_private` unstable (default: no)"),
1315 fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1316 "set the optimization fuel quota for a crate"),
1317 function_sections: Option<bool> = (None, parse_opt_bool, [TRACKED],
1318 "whether each function should go in its own section"),
1319 future_incompat_test: bool = (false, parse_bool, [UNTRACKED],
1320 "forces all lints to be future incompatible, used for internal testing (default: no)"),
1321 gcc_ld: Option<LdImpl> = (None, parse_gcc_ld, [TRACKED], "implementation of ld used by cc"),
1322 graphviz_dark_mode: bool = (false, parse_bool, [UNTRACKED],
1323 "use dark-themed colors in graphviz output (default: no)"),
1324 graphviz_font: String = ("Courier, monospace".to_string(), parse_string, [UNTRACKED],
1325 "use the given `fontname` in graphviz output; can be overridden by setting \
1326 environment variable `RUSTC_GRAPHVIZ_FONT` (default: `Courier, monospace`)"),
1327 hir_stats: bool = (false, parse_bool, [UNTRACKED],
1328 "print some statistics about AST and HIR (default: no)"),
1329 human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1330 "generate human-readable, predictable names for codegen units (default: no)"),
1331 identify_regions: bool = (false, parse_bool, [UNTRACKED],
1332 "display unnamed regions as `'<id>`, using a non-ident unique id (default: no)"),
1333 incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1334 "ignore spans during ICH computation -- used for testing (default: no)"),
1335 incremental_info: bool = (false, parse_bool, [UNTRACKED],
1336 "print high-level information about incremental reuse (or the lack thereof) \
1338 incremental_relative_spans: bool = (false, parse_bool, [TRACKED],
1339 "hash spans relative to their parent item for incr. comp. (default: no)"),
1340 incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1341 "verify incr. comp. hashes of green query instances (default: no)"),
1342 inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1343 "control whether `#[inline]` functions are in all CGUs"),
1344 inline_llvm: bool = (true, parse_bool, [TRACKED],
1345 "enable LLVM inlining (default: yes)"),
1346 inline_mir: Option<bool> = (None, parse_opt_bool, [TRACKED],
1347 "enable MIR inlining (default: no)"),
1348 inline_mir_hint_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
1349 "inlining threshold for functions with inline hint (default: 100)"),
1350 inline_mir_threshold: Option<usize> = (None, parse_opt_number, [TRACKED],
1351 "a default MIR inlining threshold (default: 50)"),
1352 input_stats: bool = (false, parse_bool, [UNTRACKED],
1353 "gather statistics about the input (default: no)"),
1354 #[rustc_lint_opt_deny_field_access("use `Session::instrument_coverage` instead of this field")]
1355 instrument_coverage: Option<InstrumentCoverage> = (None, parse_instrument_coverage, [TRACKED],
1356 "instrument the generated code to support LLVM source-based code coverage \
1357 reports (note, the compiler build config must include `profiler = true`); \
1358 implies `-C symbol-mangling-version=v0`. Optional values are:
1359 `=all` (implicit value)
1360 `=except-unused-generics`
1361 `=except-unused-functions`
1363 #[rustc_lint_opt_deny_field_access("use `Session::instrument_mcount` instead of this field")]
1364 instrument_mcount: bool = (false, parse_bool, [TRACKED],
1365 "insert function instrument code for mcount-based tracing (default: no)"),
1366 keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1367 "keep hygiene data after analysis (default: no)"),
1368 layout_seed: Option<u64> = (None, parse_opt_number, [TRACKED],
1369 "seed layout randomization"),
1370 link_native_libraries: bool = (true, parse_bool, [UNTRACKED],
1371 "link native libraries in the linker invocation (default: yes)"),
1372 link_only: bool = (false, parse_bool, [TRACKED],
1373 "link the `.rlink` file generated by `-Z no-link` (default: no)"),
1374 llvm_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1375 "a list LLVM plugins to enable (space separated)"),
1376 llvm_time_trace: bool = (false, parse_bool, [UNTRACKED],
1377 "generate JSON tracing data file from LLVM data (default: no)"),
1378 location_detail: LocationDetail = (LocationDetail::all(), parse_location_detail, [TRACKED],
1379 "what location details should be tracked when using caller_location, either \
1380 `none`, or a comma separated list of location details, for which \
1381 valid options are `file`, `line`, and `column` (default: `file,line,column`)"),
1382 ls: bool = (false, parse_bool, [UNTRACKED],
1383 "list the symbols defined by a library crate (default: no)"),
1384 macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1385 "show macro backtraces (default: no)"),
1386 maximal_hir_to_mir_coverage: bool = (false, parse_bool, [TRACKED],
1387 "save as much information as possible about the correspondence between MIR and HIR \
1388 as source scopes (default: no)"),
1389 merge_functions: Option<MergeFunctions> = (None, parse_merge_functions, [TRACKED],
1390 "control the operation of the MergeFunctions LLVM pass, taking \
1391 the same values as the target option of the same name"),
1392 #[rustc_lint_opt_deny_field_access("use `Session::meta_stats` instead of this field")]
1393 meta_stats: bool = (false, parse_bool, [UNTRACKED],
1394 "gather metadata statistics (default: no)"),
1395 mir_emit_retag: bool = (false, parse_bool, [TRACKED],
1396 "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 \
1398 mir_enable_passes: Vec<(String, bool)> = (Vec::new(), parse_list_with_polarity, [TRACKED],
1399 "use like `-Zmir-enable-passes=+DestProp,-InstCombine`. Forces the specified passes to be \
1400 enabled, overriding all other checks. Passes that are not specified are enabled or \
1401 disabled by other flags as usual."),
1402 #[rustc_lint_opt_deny_field_access("use `Session::mir_opt_level` instead of this field")]
1403 mir_opt_level: Option<usize> = (None, parse_opt_number, [TRACKED],
1404 "MIR optimization level (0-4; default: 1 in non optimized builds and 2 in optimized builds)"),
1405 mir_pretty_relative_line_numbers: bool = (false, parse_bool, [UNTRACKED],
1406 "use line numbers relative to the function in mir pretty printing"),
1407 move_size_limit: Option<usize> = (None, parse_opt_number, [TRACKED],
1408 "the size at which the `large_assignments` lint starts to be emitted"),
1409 mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
1410 "emit noalias metadata for mutable references (default: yes)"),
1411 nll_facts: bool = (false, parse_bool, [UNTRACKED],
1412 "dump facts from NLL analysis into side files (default: no)"),
1413 nll_facts_dir: String = ("nll-facts".to_string(), parse_string, [UNTRACKED],
1414 "the directory the NLL facts are dumped into (default: `nll-facts`)"),
1415 no_analysis: bool = (false, parse_no_flag, [UNTRACKED],
1416 "parse and expand the source, but run no analysis"),
1417 no_codegen: bool = (false, parse_no_flag, [TRACKED_NO_CRATE_HASH],
1418 "run all passes except codegen; no output"),
1419 no_generate_arange_section: bool = (false, parse_no_flag, [TRACKED],
1420 "omit DWARF address ranges that give faster lookups"),
1421 no_leak_check: bool = (false, parse_no_flag, [UNTRACKED],
1422 "disable the 'leak check' for subtyping; unsound, but useful for tests"),
1423 no_link: bool = (false, parse_no_flag, [TRACKED],
1424 "compile without linking"),
1425 no_parallel_llvm: bool = (false, parse_no_flag, [UNTRACKED],
1426 "run LLVM in non-parallel mode (while keeping codegen-units and ThinLTO)"),
1427 no_profiler_runtime: bool = (false, parse_no_flag, [TRACKED],
1428 "prevent automatic injection of the profiler_builtins crate"),
1429 no_unique_section_names: bool = (false, parse_bool, [TRACKED],
1430 "do not use unique names for text and data sections when -Z function-sections is used"),
1431 normalize_docs: bool = (false, parse_bool, [TRACKED],
1432 "normalize associated items in rustdoc when generating documentation"),
1433 oom: OomStrategy = (OomStrategy::Abort, parse_oom_strategy, [TRACKED],
1434 "panic strategy for out-of-memory handling"),
1435 osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1436 "pass `-install_name @rpath/...` to the macOS linker (default: no)"),
1437 packed_bundled_libs: bool = (false, parse_bool, [TRACKED],
1438 "change rlib format to store native libraries as archives"),
1439 panic_abort_tests: bool = (false, parse_bool, [TRACKED],
1440 "support compiling tests with panic=abort (default: no)"),
1441 panic_in_drop: PanicStrategy = (PanicStrategy::Unwind, parse_panic_strategy, [TRACKED],
1442 "panic strategy for panics in drops"),
1443 parse_only: bool = (false, parse_bool, [UNTRACKED],
1444 "parse only; do not compile, assemble, or link (default: no)"),
1445 perf_stats: bool = (false, parse_bool, [UNTRACKED],
1446 "print some performance-related statistics (default: no)"),
1447 pick_stable_methods_before_any_unstable: bool = (true, parse_bool, [TRACKED],
1448 "try to pick stable methods first before picking any unstable methods (default: yes)"),
1449 plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
1450 "whether to use the PLT when calling into shared libraries;
1451 only has effect for PIC code on systems with ELF binaries
1452 (default: PLT is disabled if full relro is enabled)"),
1453 polonius: bool = (false, parse_bool, [TRACKED],
1454 "enable polonius-based borrow-checker (default: no)"),
1455 polymorphize: bool = (false, parse_bool, [TRACKED],
1456 "perform polymorphization analysis"),
1457 pre_link_arg: (/* redirected to pre_link_args */) = ((), parse_string_push, [UNTRACKED],
1458 "a single extra argument to prepend the linker invocation (can be used several times)"),
1459 pre_link_args: Vec<String> = (Vec::new(), parse_list, [UNTRACKED],
1460 "extra arguments to prepend to the linker invocation (space separated)"),
1461 precise_enum_drop_elaboration: bool = (true, parse_bool, [TRACKED],
1462 "use a more precise version of drop elaboration for matches on enums (default: yes). \
1463 This results in better codegen, but has caused miscompilations on some tier 2 platforms. \
1464 See #77382 and #74551."),
1465 print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1466 "make rustc print the total optimization fuel used by a crate"),
1467 #[rustc_lint_opt_deny_field_access("use `Session::print_llvm_passes` instead of this field")]
1468 print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1469 "print the LLVM optimization passes being run (default: no)"),
1470 print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1471 "print the result of the monomorphization collection pass"),
1472 print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1473 "print layout information for each type encountered (default: no)"),
1474 proc_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1475 "show backtraces for panics during proc-macro execution (default: no)"),
1476 proc_macro_execution_strategy: ProcMacroExecutionStrategy = (ProcMacroExecutionStrategy::SameThread,
1477 parse_proc_macro_execution_strategy, [UNTRACKED],
1478 "how to run proc-macro code (default: same-thread)"),
1479 profile: bool = (false, parse_bool, [TRACKED],
1480 "insert profiling code (default: no)"),
1481 profile_closures: bool = (false, parse_no_flag, [UNTRACKED],
1482 "profile size of closures"),
1483 profile_emit: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1484 "file path to emit profiling data at runtime when using 'profile' \
1485 (default based on relative source path)"),
1486 profile_sample_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1487 "use the given `.prof` file for sampled profile-guided optimization (also known as AutoFDO)"),
1488 profiler_runtime: String = (String::from("profiler_builtins"), parse_string, [TRACKED],
1489 "name of the profiler runtime crate to automatically inject (default: `profiler_builtins`)"),
1490 query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1491 "enable queries of the dependency graph for regression testing (default: no)"),
1492 randomize_layout: bool = (false, parse_bool, [TRACKED],
1493 "randomize the layout of types (default: no)"),
1494 relax_elf_relocations: Option<bool> = (None, parse_opt_bool, [TRACKED],
1495 "whether ELF relocations can be relaxed"),
1496 relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1497 "choose which RELRO level to use"),
1498 remap_cwd_prefix: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1499 "remap paths under the current working directory to this path prefix"),
1500 report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
1501 "immediately print bugs registered with `delay_span_bug` (default: no)"),
1502 sanitizer: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED],
1504 sanitizer_memory_track_origins: usize = (0, parse_sanitizer_memory_track_origins, [TRACKED],
1505 "enable origins tracking in MemorySanitizer"),
1506 sanitizer_recover: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED],
1507 "enable recovery for selected sanitizers"),
1508 saturating_float_casts: Option<bool> = (None, parse_opt_bool, [TRACKED],
1509 "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1510 the max/min integer respectively, and NaN is mapped to 0 (default: yes)"),
1511 save_analysis: bool = (false, parse_bool, [UNTRACKED],
1512 "write syntax and type analysis (in JSON format) information, in \
1513 addition to normal output (default: no)"),
1514 self_profile: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1515 parse_switch_with_opt_path, [UNTRACKED],
1516 "run the self profiler and output the raw event data"),
1517 self_profile_counter: String = ("wall-time".to_string(), parse_string, [UNTRACKED],
1518 "counter used by the self profiler (default: `wall-time`), one of:
1519 `wall-time` (monotonic clock, i.e. `std::time::Instant`)
1520 `instructions:u` (retired instructions, userspace-only)
1521 `instructions-minus-irqs:u` (subtracting hardware interrupt counts for extra accuracy)"
1523 /// keep this in sync with the event filter names in librustc_data_structures/profiling.rs
1524 self_profile_events: Option<Vec<String>> = (None, parse_opt_comma_list, [UNTRACKED],
1525 "specify the events recorded by the self profiler;
1526 for example: `-Z self-profile-events=default,query-keys`
1527 all options: none, all, default, generic-activity, query-provider, query-cache-hit
1528 query-blocked, incr-cache-load, incr-result-hashing, query-keys, function-args, args, llvm, artifact-sizes"),
1529 share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
1530 "make the current crate share its generic instantiations"),
1531 show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1532 "show spans for compiler debugging (expr|pat|ty)"),
1533 simulate_remapped_rust_src_base: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1534 "simulate the effect of remap-debuginfo = true at bootstrapping by remapping path \
1535 to rust's source base directory. only meant for testing purposes"),
1536 span_debug: bool = (false, parse_bool, [UNTRACKED],
1537 "forward proc_macro::Span's `Debug` impl to `Span`"),
1538 /// o/w tests have closure@path
1539 span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1540 "exclude spans when debug-printing compiler state (default: no)"),
1541 split_dwarf_inlining: bool = (true, parse_bool, [TRACKED],
1542 "provide minimal debug info in the object/executable to facilitate online \
1543 symbolication/stack traces in the absence of .dwo/.dwp files when using Split DWARF"),
1544 split_dwarf_kind: SplitDwarfKind = (SplitDwarfKind::Split, parse_split_dwarf_kind, [TRACKED],
1545 "split dwarf variant (only if -Csplit-debuginfo is enabled and on relevant platform)
1548 `split`: sections which do not require relocation are written into a DWARF object (`.dwo`)
1549 file which is ignored by the linker
1550 `single`: sections which do not require relocation are written into object file but ignored
1552 src_hash_algorithm: Option<SourceFileHashAlgorithm> = (None, parse_src_file_hash, [TRACKED],
1553 "hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`)"),
1554 #[rustc_lint_opt_deny_field_access("use `Session::stack_protector` instead of this field")]
1555 stack_protector: StackProtector = (StackProtector::None, parse_stack_protector, [TRACKED],
1556 "control stack smash protection strategy (`rustc --print stack-protector-strategies` for details)"),
1557 strict_init_checks: bool = (false, parse_bool, [TRACKED],
1558 "control if mem::uninitialized and mem::zeroed panic on more UB"),
1559 strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
1560 "tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"),
1561 symbol_mangling_version: Option<SymbolManglingVersion> = (None,
1562 parse_symbol_mangling_version, [TRACKED],
1563 "which mangling version to use for symbol names ('legacy' (default) or 'v0')"),
1564 #[rustc_lint_opt_deny_field_access("use `Session::teach` instead of this field")]
1565 teach: bool = (false, parse_bool, [TRACKED],
1566 "show extended diagnostic help (default: no)"),
1567 temps_dir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1568 "the directory the intermediate files are written to"),
1569 #[rustc_lint_opt_deny_field_access("use `Session::lto` instead of this field")]
1570 thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1571 "enable ThinLTO when possible"),
1572 thir_unsafeck: bool = (false, parse_bool, [TRACKED],
1573 "use the THIR unsafety checker (default: no)"),
1574 /// We default to 1 here since we want to behave like
1575 /// a sequential compiler for now. This'll likely be adjusted
1576 /// in the future. Note that -Zthreads=0 is the way to get
1577 /// the num_cpus behavior.
1578 #[rustc_lint_opt_deny_field_access("use `Session::threads` instead of this field")]
1579 threads: usize = (1, parse_threads, [UNTRACKED],
1580 "use a thread pool with N threads"),
1581 #[rustc_lint_opt_deny_field_access("use `Session::time_llvm_passes` instead of this field")]
1582 time_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1583 "measure time of each LLVM pass (default: no)"),
1584 #[rustc_lint_opt_deny_field_access("use `Session::time_passes` instead of this field")]
1585 time_passes: bool = (false, parse_bool, [UNTRACKED],
1586 "measure time of each rustc pass (default: no)"),
1587 #[rustc_lint_opt_deny_field_access("use `Session::tls_model` instead of this field")]
1588 tls_model: Option<TlsModel> = (None, parse_tls_model, [TRACKED],
1589 "choose the TLS model to use (`rustc --print tls-models` for details)"),
1590 trace_macros: bool = (false, parse_bool, [UNTRACKED],
1591 "for every macro invocation, print its name and arguments (default: no)"),
1592 track_diagnostics: bool = (false, parse_bool, [UNTRACKED],
1593 "tracks where in rustc a diagnostic was emitted"),
1594 // Diagnostics are considered side-effects of a query (see `QuerySideEffects`) and are saved
1595 // alongside query results and changes to translation options can affect diagnostics - so
1596 // translation options should be tracked.
1597 translate_additional_ftl: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1598 "additional fluent translation to preferentially use (for testing translation)"),
1599 translate_directionality_markers: bool = (false, parse_bool, [TRACKED],
1600 "emit directionality isolation markers in translated diagnostics"),
1601 translate_lang: Option<LanguageIdentifier> = (None, parse_opt_langid, [TRACKED],
1602 "language identifier for diagnostic output"),
1603 translate_remapped_path_to_local_path: bool = (true, parse_bool, [TRACKED],
1604 "translate remapped paths into local paths when possible (default: yes)"),
1605 trap_unreachable: Option<bool> = (None, parse_opt_bool, [TRACKED],
1606 "generate trap instructions for unreachable intrinsics (default: use target setting, usually yes)"),
1607 treat_err_as_bug: Option<NonZeroUsize> = (None, parse_treat_err_as_bug, [TRACKED],
1608 "treat error number `val` that occurs as bug"),
1609 trim_diagnostic_paths: bool = (true, parse_bool, [UNTRACKED],
1610 "in diagnostics, use heuristics to shorten paths referring to items"),
1611 tune_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1612 "select processor to schedule for (`rustc --print target-cpus` for details)"),
1613 ui_testing: bool = (false, parse_bool, [UNTRACKED],
1614 "emit compiler diagnostics in a form suitable for UI testing (default: no)"),
1615 uninit_const_chunk_threshold: usize = (16, parse_number, [TRACKED],
1616 "allow generating const initializers with mixed init/uninit chunks, \
1617 and set the maximum number of chunks for which this is allowed (default: 16)"),
1618 unleash_the_miri_inside_of_you: bool = (false, parse_bool, [TRACKED],
1619 "take the brakes off const evaluation. NOTE: this is unsound (default: no)"),
1620 unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1621 "present the input source, unstable (and less-pretty) variants;
1622 `normal`, `identified`,
1623 `expanded`, `expanded,identified`,
1624 `expanded,hygiene` (with internal representations),
1625 `ast-tree` (raw AST before expansion),
1626 `ast-tree,expanded` (raw AST after expansion),
1627 `hir` (the HIR), `hir,identified`,
1628 `hir,typed` (HIR with types for each node),
1629 `hir-tree` (dump the raw HIR),
1630 `mir` (the MIR), or `mir-cfg` (graphviz formatted MIR)"),
1631 unsound_mir_opts: bool = (false, parse_bool, [TRACKED],
1632 "enable unsound and buggy MIR optimizations (default: no)"),
1633 /// This name is kind of confusing: Most unstable options enable something themselves, while
1634 /// this just allows "normal" options to be feature-gated.
1635 #[rustc_lint_opt_deny_field_access("use `Session::unstable_options` instead of this field")]
1636 unstable_options: bool = (false, parse_bool, [UNTRACKED],
1637 "adds unstable command line options to rustc interface (default: no)"),
1638 use_ctors_section: Option<bool> = (None, parse_opt_bool, [TRACKED],
1639 "use legacy .ctors section for initializers rather than .init_array"),
1640 validate_mir: bool = (false, parse_bool, [UNTRACKED],
1641 "validate MIR after each transformation"),
1642 #[rustc_lint_opt_deny_field_access("use `Session::verbose` instead of this field")]
1643 verbose: bool = (false, parse_bool, [UNTRACKED],
1644 "in general, enable more debug printouts (default: no)"),
1645 #[rustc_lint_opt_deny_field_access("use `Session::verify_llvm_ir` instead of this field")]
1646 verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
1647 "verify LLVM IR (default: no)"),
1648 virtual_function_elimination: bool = (false, parse_bool, [TRACKED],
1649 "enables dead virtual function elimination optimization. \
1650 Requires `-Clto[=[fat,yes]]`"),
1651 wasi_exec_model: Option<WasiExecModel> = (None, parse_wasi_exec_model, [TRACKED],
1652 "whether to build a wasi command or reactor"),
1653 // tidy-alphabetical-end
1655 // If you add a new option, please update:
1656 // - compiler/rustc_interface/src/tests.rs
1659 #[derive(Clone, Hash, PartialEq, Eq, Debug)]
1660 pub enum WasiExecModel {
1665 #[derive(Clone, Copy, Hash)]