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
use rustc_hir::Mutability;
use rustc_index::bit_set::HybridBitSet;
use rustc_middle::mir::visit::{MutVisitor, NonUseContext, PlaceContext, Visitor};
use rustc_middle::mir::{self, BasicBlock, Local, Location};
use rustc_middle::ty::TyCtxt;
use crate::MirPass;
pub struct RenameReturnPlace;
impl<'tcx> MirPass<'tcx> for RenameReturnPlace {
fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
sess.mir_opt_level() > 0
}
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut mir::Body<'tcx>) {
let def_id = body.source.def_id();
let Some(returned_local) = local_eligible_for_nrvo(body) else {
debug!("`{:?}` was ineligible for NRVO", def_id);
return;
};
if !tcx.consider_optimizing(|| format!("RenameReturnPlace {:?}", def_id)) {
return;
}
debug!(
"`{:?}` was eligible for NRVO, making {:?} the return place",
def_id, returned_local
);
RenameToReturnPlace { tcx, to_rename: returned_local }.visit_body_preserves_cfg(body);
for block_data in body.basic_blocks.as_mut_preserves_cfg() {
block_data.statements.retain(|stmt| stmt.kind != mir::StatementKind::Nop);
}
let (renamed_decl, ret_decl) =
body.local_decls.pick2_mut(returned_local, mir::RETURN_PLACE);
debug!("_0: {:?} = {:?}: {:?}", ret_decl.ty, returned_local, renamed_decl.ty);
ret_decl.clone_from(renamed_decl);
ret_decl.mutability = Mutability::Mut;
}
}
fn local_eligible_for_nrvo(body: &mut mir::Body<'_>) -> Option<Local> {
if IsReturnPlaceRead::run(body) {
return None;
}
let mut copied_to_return_place = None;
for block in body.basic_blocks.indices() {
if !matches!(body[block].terminator().kind, mir::TerminatorKind::Return) {
continue;
}
let returned_local = find_local_assigned_to_return_place(block, body)?;
match body.local_kind(returned_local) {
mir::LocalKind::Arg => return None,
mir::LocalKind::ReturnPointer => bug!("Return place was assigned to itself?"),
mir::LocalKind::Var | mir::LocalKind::Temp => {}
}
if copied_to_return_place.map_or(false, |old| old != returned_local) {
return None;
}
copied_to_return_place = Some(returned_local);
}
copied_to_return_place
}
fn find_local_assigned_to_return_place(
start: BasicBlock,
body: &mut mir::Body<'_>,
) -> Option<Local> {
let mut block = start;
let mut seen = HybridBitSet::new_empty(body.basic_blocks.len());
while seen.insert(block) {
trace!("Looking for assignments to `_0` in {:?}", block);
let local = body[block].statements.iter().rev().find_map(as_local_assigned_to_return_place);
if local.is_some() {
return local;
}
match body.basic_blocks.predecessors()[block].as_slice() {
&[pred] => block = pred,
_ => return None,
}
}
None
}
fn as_local_assigned_to_return_place(stmt: &mir::Statement<'_>) -> Option<Local> {
if let mir::StatementKind::Assign(box (lhs, rhs)) = &stmt.kind {
if lhs.as_local() == Some(mir::RETURN_PLACE) {
if let mir::Rvalue::Use(mir::Operand::Copy(rhs) | mir::Operand::Move(rhs)) = rhs {
return rhs.as_local();
}
}
}
None
}
struct RenameToReturnPlace<'tcx> {
to_rename: Local,
tcx: TyCtxt<'tcx>,
}
impl<'tcx> MutVisitor<'tcx> for RenameToReturnPlace<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn visit_statement(&mut self, stmt: &mut mir::Statement<'tcx>, loc: Location) {
if as_local_assigned_to_return_place(stmt) == Some(self.to_rename) {
stmt.kind = mir::StatementKind::Nop;
return;
}
if let mir::StatementKind::StorageLive(local) | mir::StatementKind::StorageDead(local) =
stmt.kind
{
if local == self.to_rename {
stmt.kind = mir::StatementKind::Nop;
return;
}
}
self.super_statement(stmt, loc)
}
fn visit_terminator(&mut self, terminator: &mut mir::Terminator<'tcx>, loc: Location) {
if let mir::TerminatorKind::Return = terminator.kind {
return;
}
self.super_terminator(terminator, loc);
}
fn visit_local(&mut self, l: &mut Local, ctxt: PlaceContext, _: Location) {
if *l == mir::RETURN_PLACE {
assert_eq!(ctxt, PlaceContext::NonUse(NonUseContext::VarDebugInfo));
} else if *l == self.to_rename {
*l = mir::RETURN_PLACE;
}
}
}
struct IsReturnPlaceRead(bool);
impl IsReturnPlaceRead {
fn run(body: &mir::Body<'_>) -> bool {
let mut vis = IsReturnPlaceRead(false);
vis.visit_body(body);
vis.0
}
}
impl<'tcx> Visitor<'tcx> for IsReturnPlaceRead {
fn visit_local(&mut self, l: Local, ctxt: PlaceContext, _: Location) {
if l == mir::RETURN_PLACE && ctxt.is_use() && !ctxt.is_place_assignment() {
self.0 = true;
}
}
fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, loc: Location) {
if let mir::TerminatorKind::Return = terminator.kind {
return;
}
self.super_terminator(terminator, loc);
}
}