1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
use rustc::hir;
use rustc::hir::def_id::{DefId, LOCAL_CRATE};
use rustc::mir::*;
use rustc::mir::visit::Visitor;
use rustc::ty::{self, TyCtxt};
use rustc::ty::item_path;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::indexed_vec::Idx;
use std::fmt::Display;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use super::graphviz::write_mir_fn_graphviz;
use transform::MirSource;
const INDENT: &'static str = " ";
pub(crate) const ALIGN: usize = 40;
pub enum PassWhere {
BeforeCFG,
AfterCFG,
BeforeBlock(BasicBlock),
BeforeLocation(Location),
AfterLocation(Location),
}
pub fn dump_mir<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
pass_num: Option<&dyn Display>,
pass_name: &str,
disambiguator: &dyn Display,
source: MirSource,
mir: &Mir<'tcx>,
extra_data: F,
) where
F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
{
if !dump_enabled(tcx, pass_name, source) {
return;
}
let node_path = item_path::with_forced_impl_filename_line(|| {
tcx.item_path_str(source.def_id)
});
dump_matched_mir_node(
tcx,
pass_num,
pass_name,
&node_path,
disambiguator,
source,
mir,
extra_data,
);
}
pub fn dump_enabled<'a, 'gcx, 'tcx>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
pass_name: &str,
source: MirSource,
) -> bool {
let filters = match tcx.sess.opts.debugging_opts.dump_mir {
None => return false,
Some(ref filters) => filters,
};
let node_path = item_path::with_forced_impl_filename_line(|| {
tcx.item_path_str(source.def_id)
});
filters.split("|").any(|or_filter| {
or_filter.split("&").all(|and_filter| {
and_filter == "all" || pass_name.contains(and_filter) || node_path.contains(and_filter)
})
})
}
fn dump_matched_mir_node<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
pass_num: Option<&dyn Display>,
pass_name: &str,
node_path: &str,
disambiguator: &dyn Display,
source: MirSource,
mir: &Mir<'tcx>,
mut extra_data: F,
) where
F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
{
let _: io::Result<()> = do catch {
let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, source)?;
writeln!(file, "// MIR for `{}`", node_path)?;
writeln!(file, "// source = {:?}", source)?;
writeln!(file, "// pass_name = {}", pass_name)?;
writeln!(file, "// disambiguator = {}", disambiguator)?;
if let Some(ref layout) = mir.generator_layout {
writeln!(file, "// generator_layout = {:?}", layout)?;
}
writeln!(file, "")?;
extra_data(PassWhere::BeforeCFG, &mut file)?;
write_mir_fn(tcx, source, mir, &mut extra_data, &mut file)?;
extra_data(PassWhere::AfterCFG, &mut file)?;
Ok(())
};
if tcx.sess.opts.debugging_opts.dump_mir_graphviz {
let _: io::Result<()> = do catch {
let mut file =
create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, source)?;
write_mir_fn_graphviz(tcx, source.def_id, mir, &mut file)?;
Ok(())
};
}
}
fn dump_path(
tcx: TyCtxt<'_, '_, '_>,
extension: &str,
pass_num: Option<&dyn Display>,
pass_name: &str,
disambiguator: &dyn Display,
source: MirSource,
) -> PathBuf {
let promotion_id = match source.promoted {
Some(id) => format!("-{:?}", id),
None => String::new(),
};
let pass_num = if tcx.sess.opts.debugging_opts.dump_mir_exclude_pass_number {
format!("")
} else {
match pass_num {
None => format!(".-------"),
Some(pass_num) => format!(".{}", pass_num),
}
};
let mut file_path = PathBuf::new();
file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
let item_name = tcx.hir
.def_path(source.def_id)
.to_filename_friendly_no_crate();
let file_name = format!(
"rustc.{}{}{}.{}.{}.{}",
item_name,
promotion_id,
pass_num,
pass_name,
disambiguator,
extension,
);
file_path.push(&file_name);
file_path
}
pub(crate) fn create_dump_file(
tcx: TyCtxt<'_, '_, '_>,
extension: &str,
pass_num: Option<&dyn Display>,
pass_name: &str,
disambiguator: &dyn Display,
source: MirSource,
) -> io::Result<fs::File> {
let file_path = dump_path(tcx, extension, pass_num, pass_name, disambiguator, source);
if let Some(parent) = file_path.parent() {
fs::create_dir_all(parent)?;
}
fs::File::create(&file_path)
}
pub fn write_mir_pretty<'a, 'gcx, 'tcx>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
single: Option<DefId>,
w: &mut dyn Write,
) -> io::Result<()> {
writeln!(
w,
"// WARNING: This output format is intended for human consumers only"
)?;
writeln!(
w,
"// and is subject to change without notice. Knock yourself out."
)?;
let mut first = true;
for def_id in dump_mir_def_ids(tcx, single) {
let mir = &tcx.optimized_mir(def_id);
if first {
first = false;
} else {
writeln!(w, "")?;
}
write_mir_fn(tcx, MirSource::item(def_id), mir, &mut |_, _| Ok(()), w)?;
for (i, mir) in mir.promoted.iter_enumerated() {
writeln!(w, "")?;
let src = MirSource {
def_id,
promoted: Some(i),
};
write_mir_fn(tcx, src, mir, &mut |_, _| Ok(()), w)?;
}
}
Ok(())
}
pub fn write_mir_fn<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
src: MirSource,
mir: &Mir<'tcx>,
extra_data: &mut F,
w: &mut dyn Write,
) -> io::Result<()>
where
F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
{
write_mir_intro(tcx, src, mir, w)?;
for block in mir.basic_blocks().indices() {
extra_data(PassWhere::BeforeBlock(block), w)?;
write_basic_block(tcx, block, mir, extra_data, w)?;
if block.index() + 1 != mir.basic_blocks().len() {
writeln!(w, "")?;
}
}
writeln!(w, "}}")?;
Ok(())
}
pub fn write_basic_block<'cx, 'gcx, 'tcx, F>(
tcx: TyCtxt<'cx, 'gcx, 'tcx>,
block: BasicBlock,
mir: &Mir<'tcx>,
extra_data: &mut F,
w: &mut dyn Write,
) -> io::Result<()>
where
F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
{
let data = &mir[block];
let cleanup_text = if data.is_cleanup { " // cleanup" } else { "" };
let lbl = format!("{}{:?}: {{", INDENT, block);
writeln!(w, "{0:1$}{2}", lbl, ALIGN, cleanup_text)?;
let mut current_location = Location {
block: block,
statement_index: 0,
};
for statement in &data.statements {
extra_data(PassWhere::BeforeLocation(current_location), w)?;
let indented_mir = format!("{0}{0}{1:?};", INDENT, statement);
writeln!(
w,
"{:A$} // {:?}: {}",
indented_mir,
current_location,
comment(tcx, statement.source_info),
A = ALIGN,
)?;
write_extra(tcx, w, |visitor| {
visitor.visit_statement(current_location.block, statement, current_location);
})?;
extra_data(PassWhere::AfterLocation(current_location), w)?;
current_location.statement_index += 1;
}
extra_data(PassWhere::BeforeLocation(current_location), w)?;
let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
writeln!(
w,
"{:A$} // {:?}: {}",
indented_terminator,
current_location,
comment(tcx, data.terminator().source_info),
A = ALIGN,
)?;
write_extra(tcx, w, |visitor| {
visitor.visit_terminator(current_location.block, data.terminator(), current_location);
})?;
extra_data(PassWhere::AfterLocation(current_location), w)?;
writeln!(w, "{}}}", INDENT)
}
fn write_extra<'cx, 'gcx, 'tcx, F>(
tcx: TyCtxt<'cx, 'gcx, 'tcx>,
write: &mut dyn Write,
mut visit_op: F,
) -> io::Result<()>
where
F: FnMut(&mut ExtraComments<'cx, 'gcx, 'tcx>),
{
let mut extra_comments = ExtraComments {
_tcx: tcx,
comments: vec![],
};
visit_op(&mut extra_comments);
for comment in extra_comments.comments {
writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
}
Ok(())
}
struct ExtraComments<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
_tcx: TyCtxt<'cx, 'gcx, 'tcx>,
comments: Vec<String>,
}
impl<'cx, 'gcx, 'tcx> ExtraComments<'cx, 'gcx, 'tcx> {
fn push(&mut self, lines: &str) {
for line in lines.split("\n") {
self.comments.push(line.to_string());
}
}
}
impl<'cx, 'gcx, 'tcx> Visitor<'tcx> for ExtraComments<'cx, 'gcx, 'tcx> {
fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
self.super_constant(constant, location);
let Constant { span, ty, literal } = constant;
self.push(&format!("mir::Constant"));
self.push(&format!("+ span: {:?}", span));
self.push(&format!("+ ty: {:?}", ty));
self.push(&format!("+ literal: {:?}", literal));
}
fn visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, _: Location) {
self.super_const(constant);
let ty::Const { ty, val } = constant;
self.push(&format!("ty::Const"));
self.push(&format!("+ ty: {:?}", ty));
self.push(&format!("+ val: {:?}", val));
}
fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
self.super_rvalue(rvalue, location);
match rvalue {
Rvalue::Aggregate(kind, _) => match **kind {
AggregateKind::Closure(def_id, substs) => {
self.push(&format!("closure"));
self.push(&format!("+ def_id: {:?}", def_id));
self.push(&format!("+ substs: {:#?}", substs));
}
AggregateKind::Generator(def_id, substs, interior) => {
self.push(&format!("generator"));
self.push(&format!("+ def_id: {:?}", def_id));
self.push(&format!("+ substs: {:#?}", substs));
self.push(&format!("+ interior: {:?}", interior));
}
_ => {}
},
_ => {}
}
}
}
fn comment(tcx: TyCtxt, SourceInfo { span, scope }: SourceInfo) -> String {
format!(
"scope {} at {}",
scope.index(),
tcx.sess.codemap().span_to_string(span)
)
}
fn write_scope_tree(
tcx: TyCtxt,
mir: &Mir,
scope_tree: &FxHashMap<VisibilityScope, Vec<VisibilityScope>>,
w: &mut dyn Write,
parent: VisibilityScope,
depth: usize,
) -> io::Result<()> {
let indent = depth * INDENT.len();
let children = match scope_tree.get(&parent) {
Some(childs) => childs,
None => return Ok(()),
};
for &child in children {
let data = &mir.visibility_scopes[child];
assert_eq!(data.parent_scope, Some(parent));
writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;
for local in mir.vars_iter() {
let var = &mir.local_decls[local];
let (name, source_info) = if var.source_info.scope == child {
(var.name.unwrap(), var.source_info)
} else {
continue;
};
let mut_str = if var.mutability == Mutability::Mut {
"mut "
} else {
""
};
let indent = indent + INDENT.len();
let indented_var = format!(
"{0:1$}let {2}{3:?}: {4:?};",
INDENT,
indent,
mut_str,
local,
var.ty
);
writeln!(
w,
"{0:1$} // \"{2}\" in {3}",
indented_var,
ALIGN,
name,
comment(tcx, source_info)
)?;
}
write_scope_tree(tcx, mir, scope_tree, w, child, depth + 1)?;
writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
}
Ok(())
}
pub fn write_mir_intro<'a, 'gcx, 'tcx>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
src: MirSource,
mir: &Mir,
w: &mut dyn Write,
) -> io::Result<()> {
write_mir_sig(tcx, src, mir, w)?;
writeln!(w, "{{")?;
let mut scope_tree: FxHashMap<VisibilityScope, Vec<VisibilityScope>> = FxHashMap();
for (index, scope_data) in mir.visibility_scopes.iter().enumerate() {
if let Some(parent) = scope_data.parent_scope {
scope_tree
.entry(parent)
.or_insert(vec![])
.push(VisibilityScope::new(index));
} else {
assert_eq!(index, ARGUMENT_VISIBILITY_SCOPE.index());
}
}
let indented_retptr = format!("{}let mut {:?}: {};",
INDENT,
RETURN_PLACE,
mir.local_decls[RETURN_PLACE].ty);
writeln!(w, "{0:1$} // return place",
indented_retptr,
ALIGN)?;
write_scope_tree(tcx, mir, &scope_tree, w, ARGUMENT_VISIBILITY_SCOPE, 1)?;
write_temp_decls(mir, w)?;
writeln!(w, "")?;
Ok(())
}
fn write_mir_sig(tcx: TyCtxt, src: MirSource, mir: &Mir, w: &mut dyn Write) -> io::Result<()> {
let id = tcx.hir.as_local_node_id(src.def_id).unwrap();
let body_owner_kind = tcx.hir.body_owner_kind(id);
match (body_owner_kind, src.promoted) {
(_, Some(i)) => write!(w, "{:?} in", i)?,
(hir::BodyOwnerKind::Fn, _) => write!(w, "fn")?,
(hir::BodyOwnerKind::Const, _) => write!(w, "const")?,
(hir::BodyOwnerKind::Static(hir::MutImmutable), _) => write!(w, "static")?,
(hir::BodyOwnerKind::Static(hir::MutMutable), _) => write!(w, "static mut")?,
}
item_path::with_forced_impl_filename_line(|| {
write!(w, " {}", tcx.item_path_str(src.def_id))
})?;
match (body_owner_kind, src.promoted) {
(hir::BodyOwnerKind::Fn, None) => {
write!(w, "(")?;
for (i, arg) in mir.args_iter().enumerate() {
if i != 0 {
write!(w, ", ")?;
}
write!(w, "{:?}: {}", Place::Local(arg), mir.local_decls[arg].ty)?;
}
write!(w, ") -> {}", mir.return_ty())?;
}
(hir::BodyOwnerKind::Const, _) | (hir::BodyOwnerKind::Static(_), _) | (_, Some(_)) => {
assert_eq!(mir.arg_count, 0);
write!(w, ": {} =", mir.return_ty())?;
}
}
if let Some(yield_ty) = mir.yield_ty {
writeln!(w)?;
writeln!(w, "yields {}", yield_ty)?;
}
Ok(())
}
fn write_temp_decls(mir: &Mir, w: &mut dyn Write) -> io::Result<()> {
for temp in mir.temps_iter() {
writeln!(
w,
"{}let mut {:?}: {};",
INDENT,
temp,
mir.local_decls[temp].ty
)?;
}
Ok(())
}
pub fn dump_mir_def_ids(tcx: TyCtxt, single: Option<DefId>) -> Vec<DefId> {
if let Some(i) = single {
vec![i]
} else {
tcx.mir_keys(LOCAL_CRATE).iter().cloned().collect()
}
}