1use std::cell::RefCell;
2use std::collections::hash_map::Entry;
3
4use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
5use rustc_middle::mir::{self, Body, MirPhase, RuntimePhase};
6use rustc_middle::ty::TyCtxt;
7use rustc_session::Session;
8use tracing::trace;
9
10use crate::lint::lint_body;
11use crate::{errors, validate};
12
13thread_local! {
14 static PASS_TO_PROFILER_NAMES: RefCell<FxHashMap<&'static str, &'static str>> = {
16 RefCell::new(FxHashMap::default())
17 };
18}
19
20fn to_profiler_name(type_name: &'static str) -> &'static str {
22 PASS_TO_PROFILER_NAMES.with(|names| match names.borrow_mut().entry(type_name) {
23 Entry::Occupied(e) => *e.get(),
24 Entry::Vacant(e) => {
25 let snake_case: String = type_name
26 .chars()
27 .flat_map(|c| {
28 if c.is_ascii_uppercase() {
29 vec!['_', c.to_ascii_lowercase()]
30 } else if c == '-' {
31 vec!['_']
32 } else {
33 vec![c]
34 }
35 })
36 .collect();
37 let result = &*String::leak(format!("mir_pass{}", snake_case));
38 e.insert(result);
39 result
40 }
41 })
42}
43
44const fn simplify_pass_type_name(name: &'static str) -> &'static str {
57 let bytes = name.as_bytes();
61 let mut i = bytes.len();
62 while i > 0 && bytes[i - 1] != b':' {
63 i -= 1;
64 }
65 let (_, bytes) = bytes.split_at(i);
66
67 let mut i = 0;
70 while i < bytes.len() && bytes[i] != b'<' {
71 i += 1;
72 }
73 let (bytes, _) = bytes.split_at(i);
74
75 match std::str::from_utf8(bytes) {
76 Ok(name) => name,
77 Err(_) => panic!(),
78 }
79}
80
81pub(super) trait MirPass<'tcx> {
85 fn name(&self) -> &'static str {
86 const { simplify_pass_type_name(std::any::type_name::<Self>()) }
87 }
88
89 fn profiler_name(&self) -> &'static str {
90 to_profiler_name(self.name())
91 }
92
93 fn is_enabled(&self, _sess: &Session) -> bool {
95 true
96 }
97
98 fn can_be_overridden(&self) -> bool {
101 true
102 }
103
104 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
105
106 fn is_mir_dump_enabled(&self) -> bool {
107 true
108 }
109
110 fn is_required(&self) -> bool;
114}
115
116pub(super) trait MirLint<'tcx> {
119 fn name(&self) -> &'static str {
120 const { simplify_pass_type_name(std::any::type_name::<Self>()) }
121 }
122
123 fn is_enabled(&self, _sess: &Session) -> bool {
124 true
125 }
126
127 fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>);
128}
129
130#[derive(Debug, Clone)]
132pub(super) struct Lint<T>(pub T);
133
134impl<'tcx, T> MirPass<'tcx> for Lint<T>
135where
136 T: MirLint<'tcx>,
137{
138 fn name(&self) -> &'static str {
139 self.0.name()
140 }
141
142 fn is_enabled(&self, sess: &Session) -> bool {
143 self.0.is_enabled(sess)
144 }
145
146 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
147 self.0.run_lint(tcx, body)
148 }
149
150 fn is_mir_dump_enabled(&self) -> bool {
151 false
152 }
153
154 fn is_required(&self) -> bool {
155 true
156 }
157}
158
159pub(super) struct WithMinOptLevel<T>(pub u32, pub T);
160
161impl<'tcx, T> MirPass<'tcx> for WithMinOptLevel<T>
162where
163 T: MirPass<'tcx>,
164{
165 fn name(&self) -> &'static str {
166 self.1.name()
167 }
168
169 fn is_enabled(&self, sess: &Session) -> bool {
170 sess.mir_opt_level() >= self.0 as usize
171 }
172
173 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
174 self.1.run_pass(tcx, body)
175 }
176
177 fn is_required(&self) -> bool {
178 self.1.is_required()
179 }
180}
181
182#[derive(Copy, Clone, Debug, PartialEq, Eq)]
186pub(crate) enum Optimizations {
187 Suppressed,
188 Allowed,
189}
190
191pub(super) fn run_passes_no_validate<'tcx>(
194 tcx: TyCtxt<'tcx>,
195 body: &mut Body<'tcx>,
196 passes: &[&dyn MirPass<'tcx>],
197 phase_change: Option<MirPhase>,
198) {
199 run_passes_inner(tcx, body, passes, phase_change, false, Optimizations::Allowed);
200}
201
202pub(super) fn run_passes<'tcx>(
204 tcx: TyCtxt<'tcx>,
205 body: &mut Body<'tcx>,
206 passes: &[&dyn MirPass<'tcx>],
207 phase_change: Option<MirPhase>,
208 optimizations: Optimizations,
209) {
210 run_passes_inner(tcx, body, passes, phase_change, true, optimizations);
211}
212
213pub(super) fn should_run_pass<'tcx, P>(
214 tcx: TyCtxt<'tcx>,
215 pass: &P,
216 optimizations: Optimizations,
217) -> bool
218where
219 P: MirPass<'tcx> + ?Sized,
220{
221 let name = pass.name();
222
223 if !pass.can_be_overridden() {
224 return pass.is_enabled(tcx.sess);
225 }
226
227 let overridden_passes = &tcx.sess.opts.unstable_opts.mir_enable_passes;
228 let overridden =
229 overridden_passes.iter().rev().find(|(s, _)| s == &*name).map(|(_name, polarity)| {
230 trace!(
231 pass = %name,
232 "{} as requested by flag",
233 if *polarity { "Running" } else { "Not running" },
234 );
235 *polarity
236 });
237 let suppressed = !pass.is_required() && matches!(optimizations, Optimizations::Suppressed);
238 overridden.unwrap_or_else(|| !suppressed && pass.is_enabled(tcx.sess))
239}
240
241fn run_passes_inner<'tcx>(
242 tcx: TyCtxt<'tcx>,
243 body: &mut Body<'tcx>,
244 passes: &[&dyn MirPass<'tcx>],
245 phase_change: Option<MirPhase>,
246 validate_each: bool,
247 optimizations: Optimizations,
248) {
249 let overridden_passes = &tcx.sess.opts.unstable_opts.mir_enable_passes;
250 trace!(?overridden_passes);
251
252 let named_passes: FxIndexSet<_> =
253 overridden_passes.iter().map(|(name, _)| name.as_str()).collect();
254
255 for &name in named_passes.difference(&*crate::PASS_NAMES) {
256 tcx.dcx().emit_warn(errors::UnknownPassName { name });
257 }
258
259 #[cfg(debug_assertions)]
261 #[allow(rustc::diagnostic_outside_of_impl)]
262 #[allow(rustc::untranslatable_diagnostic)]
263 {
264 let used_passes: FxIndexSet<_> = passes.iter().map(|p| p.name()).collect();
265
266 let undeclared = used_passes.difference(&*crate::PASS_NAMES).collect::<Vec<_>>();
267 if let Some((name, rest)) = undeclared.split_first() {
268 let mut err =
269 tcx.dcx().struct_bug(format!("pass `{name}` is not declared in `PASS_NAMES`"));
270 for name in rest {
271 err.note(format!("pass `{name}` is also not declared in `PASS_NAMES`"));
272 }
273 err.emit();
274 }
275 }
276
277 let prof_arg = tcx.sess.prof.enabled().then(|| format!("{:?}", body.source.def_id()));
278
279 if !body.should_skip() {
280 let validate = validate_each & tcx.sess.opts.unstable_opts.validate_mir;
281 let lint = tcx.sess.opts.unstable_opts.lint_mir;
282
283 for pass in passes {
284 let name = pass.name();
285
286 if !should_run_pass(tcx, *pass, optimizations) {
287 continue;
288 };
289
290 let dump_enabled = pass.is_mir_dump_enabled();
291
292 if dump_enabled {
293 dump_mir_for_pass(tcx, body, name, false);
294 }
295
296 if let Some(prof_arg) = &prof_arg {
297 tcx.sess
298 .prof
299 .generic_activity_with_arg(pass.profiler_name(), &**prof_arg)
300 .run(|| pass.run_pass(tcx, body));
301 } else {
302 pass.run_pass(tcx, body);
303 }
304
305 if dump_enabled {
306 dump_mir_for_pass(tcx, body, name, true);
307 }
308 if validate {
309 validate_body(tcx, body, format!("after pass {name}"));
310 }
311 if lint {
312 lint_body(tcx, body, format!("after pass {name}"));
313 }
314
315 body.pass_count += 1;
316 }
317 }
318
319 if let Some(new_phase) = phase_change {
320 if body.phase >= new_phase {
321 panic!("Invalid MIR phase transition from {:?} to {:?}", body.phase, new_phase);
322 }
323
324 body.phase = new_phase;
325 body.pass_count = 0;
326
327 dump_mir_for_phase_change(tcx, body);
328
329 let validate =
330 (validate_each & tcx.sess.opts.unstable_opts.validate_mir & !body.should_skip())
331 || new_phase == MirPhase::Runtime(RuntimePhase::Optimized);
332 let lint = tcx.sess.opts.unstable_opts.lint_mir & !body.should_skip();
333 if validate {
334 validate_body(tcx, body, format!("after phase change to {}", new_phase.name()));
335 }
336 if lint {
337 lint_body(tcx, body, format!("after phase change to {}", new_phase.name()));
338 }
339
340 body.pass_count = 1;
341 }
342}
343
344pub(super) fn validate_body<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, when: String) {
345 validate::Validator { when }.run_pass(tcx, body);
346}
347
348fn dump_mir_for_pass<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, pass_name: &str, is_after: bool) {
349 mir::dump_mir(
350 tcx,
351 true,
352 pass_name,
353 if is_after { &"after" } else { &"before" },
354 body,
355 |_, _| Ok(()),
356 );
357}
358
359pub(super) fn dump_mir_for_phase_change<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
360 assert_eq!(body.pass_count, 0);
361 mir::dump_mir(tcx, true, body.phase.name(), &"after", body, |_, _| Ok(()))
362}