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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
use rustc::hir;
use rustc::hir::CodegenFnAttrFlags;
use rustc::hir::def_id::DefId;
use rustc_data_structures::bitvec::BitVector;
use rustc_data_structures::indexed_vec::{Idx, IndexVec};
use rustc::mir::*;
use rustc::mir::visit::*;
use rustc::ty::{self, Instance, Ty, TyCtxt};
use rustc::ty::subst::{Subst,Substs};
use std::collections::VecDeque;
use std::iter;
use transform::{MirPass, MirSource};
use super::simplify::{remove_dead_blocks, CfgSimplifier};
use syntax::{attr};
use rustc_target::spec::abi::Abi;
const DEFAULT_THRESHOLD: usize = 50;
const HINT_THRESHOLD: usize = 100;
const INSTR_COST: usize = 5;
const CALL_PENALTY: usize = 25;
const UNKNOWN_SIZE_COST: usize = 10;
pub struct Inline;
#[derive(Copy, Clone, Debug)]
struct CallSite<'tcx> {
callee: DefId,
substs: &'tcx Substs<'tcx>,
bb: BasicBlock,
location: SourceInfo,
}
impl MirPass for Inline {
fn run_pass<'a, 'tcx>(&self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
source: MirSource,
mir: &mut Mir<'tcx>) {
if tcx.sess.opts.debugging_opts.mir_opt_level >= 2 {
Inliner { tcx, source }.run_pass(mir);
}
}
}
struct Inliner<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
source: MirSource,
}
impl<'a, 'tcx> Inliner<'a, 'tcx> {
fn run_pass(&self, caller_mir: &mut Mir<'tcx>) {
let mut callsites = VecDeque::new();
let param_env = self.tcx.param_env(self.source.def_id);
let id = self.tcx.hir.as_local_node_id(self.source.def_id).unwrap();
let body_owner_kind = self.tcx.hir.body_owner_kind(id);
if let (hir::BodyOwnerKind::Fn, None) = (body_owner_kind, self.source.promoted) {
for (bb, bb_data) in caller_mir.basic_blocks().iter_enumerated() {
if bb_data.is_cleanup { continue; }
let terminator = bb_data.terminator();
if let TerminatorKind::Call {
func: Operand::Constant(ref f), .. } = terminator.kind {
if let ty::TyFnDef(callee_def_id, substs) = f.ty.sty {
if let Some(instance) = Instance::resolve(self.tcx,
param_env,
callee_def_id,
substs) {
callsites.push_back(CallSite {
callee: instance.def_id(),
substs: instance.substs,
bb,
location: terminator.source_info
});
}
}
}
}
} else {
return;
}
let mut local_change;
let mut changed = false;
loop {
local_change = false;
while let Some(callsite) = callsites.pop_front() {
debug!("checking whether to inline callsite {:?}", callsite);
if !self.tcx.is_mir_available(callsite.callee) {
debug!("checking whether to inline callsite {:?} - MIR unavailable", callsite);
continue;
}
let callee_mir = match self.tcx.try_optimized_mir(callsite.location.span,
callsite.callee) {
Ok(callee_mir) if self.should_inline(callsite, callee_mir) => {
self.tcx.subst_and_normalize_erasing_regions(
&callsite.substs,
param_env,
callee_mir,
)
}
Ok(_) => continue,
Err(mut bug) => {
bug.cancel();
continue
}
};
let start = caller_mir.basic_blocks().len();
debug!("attempting to inline callsite {:?} - mir={:?}", callsite, callee_mir);
if !self.inline_call(callsite, caller_mir, callee_mir) {
debug!("attempting to inline callsite {:?} - failure", callsite);
continue;
}
debug!("attempting to inline callsite {:?} - success", callsite);
for (bb, bb_data) in caller_mir.basic_blocks().iter_enumerated().skip(start) {
let terminator = bb_data.terminator();
if let TerminatorKind::Call {
func: Operand::Constant(ref f), .. } = terminator.kind {
if let ty::TyFnDef(callee_def_id, substs) = f.ty.sty {
if callsite.callee != callee_def_id {
callsites.push_back(CallSite {
callee: callee_def_id,
substs,
bb,
location: terminator.source_info
});
}
}
}
}
local_change = true;
changed = true;
}
if !local_change {
break;
}
}
if changed {
debug!("Running simplify cfg on {:?}", self.source);
CfgSimplifier::new(caller_mir).simplify();
remove_dead_blocks(caller_mir);
}
}
fn should_inline(&self,
callsite: CallSite<'tcx>,
callee_mir: &Mir<'tcx>)
-> bool
{
debug!("should_inline({:?})", callsite);
let tcx = self.tcx;
if callee_mir.upvar_decls.len() > 0 {
debug!(" upvar decls present - not inlining");
return false;
}
if callee_mir.yield_ty.is_some() {
debug!(" yield ty present - not inlining");
return false;
}
if tcx.is_binop_lang_item(callsite.callee).is_some() {
debug!(" not inlining 128bit integer lang item");
return false;
}
let codegen_fn_attrs = tcx.codegen_fn_attrs(callsite.callee);
let hinted = match codegen_fn_attrs.inline {
attr::InlineAttr::Always => true,
attr::InlineAttr::Never => {
debug!("#[inline(never)] present - not inlining");
return false
}
attr::InlineAttr::Hint => true,
attr::InlineAttr::None => false,
};
if callsite.callee.is_local() {
if callsite.substs.types().count() == 0 && !hinted {
debug!(" callee is an exported function - not inlining");
return false;
}
}
let mut threshold = if hinted {
HINT_THRESHOLD
} else {
DEFAULT_THRESHOLD
};
if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
threshold /= 5;
}
if callee_mir.basic_blocks().len() <= 3 {
threshold += threshold / 4;
}
debug!(" final inline threshold = {}", threshold);
let param_env = tcx.param_env(self.source.def_id);
let mut first_block = true;
let mut cost = 0;
let mut work_list = vec![START_BLOCK];
let mut visited = BitVector::new(callee_mir.basic_blocks().len());
while let Some(bb) = work_list.pop() {
if !visited.insert(bb.index()) { continue; }
let blk = &callee_mir.basic_blocks()[bb];
for stmt in &blk.statements {
match stmt.kind {
StatementKind::StorageLive(_) |
StatementKind::StorageDead(_) |
StatementKind::Nop => {}
_ => cost += INSTR_COST
}
}
let term = blk.terminator();
let mut is_drop = false;
match term.kind {
TerminatorKind::Drop { ref location, target, unwind } |
TerminatorKind::DropAndReplace { ref location, target, unwind, .. } => {
is_drop = true;
work_list.push(target);
let ty = location.ty(callee_mir, tcx).subst(tcx, callsite.substs);
let ty = ty.to_ty(tcx);
if ty.needs_drop(tcx, param_env) {
cost += CALL_PENALTY;
if let Some(unwind) = unwind {
work_list.push(unwind);
}
} else {
cost += INSTR_COST;
}
}
TerminatorKind::Unreachable |
TerminatorKind::Call { destination: None, .. } if first_block => {
threshold = 0;
}
TerminatorKind::Call {func: Operand::Constant(ref f), .. } => {
if let ty::TyFnDef(def_id, _) = f.ty.sty {
let f = tcx.fn_sig(def_id);
if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
cost += INSTR_COST;
} else {
cost += CALL_PENALTY;
}
}
}
TerminatorKind::Assert { .. } => cost += CALL_PENALTY,
_ => cost += INSTR_COST
}
if !is_drop {
for &succ in term.successors() {
work_list.push(succ);
}
}
first_block = false;
}
let ptr_size = tcx.data_layout.pointer_size.bytes();
for v in callee_mir.vars_and_temps_iter() {
let v = &callee_mir.local_decls[v];
let ty = v.ty.subst(tcx, callsite.substs);
if let Some(size) = type_size_of(tcx, param_env.clone(), ty) {
cost += (size / ptr_size) as usize;
} else {
cost += UNKNOWN_SIZE_COST;
}
}
if let attr::InlineAttr::Always = codegen_fn_attrs.inline {
debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
true
} else {
if cost <= threshold {
debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
true
} else {
debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
false
}
}
}
fn inline_call(&self,
callsite: CallSite<'tcx>,
caller_mir: &mut Mir<'tcx>,
mut callee_mir: Mir<'tcx>) -> bool {
let terminator = caller_mir[callsite.bb].terminator.take().unwrap();
match terminator.kind {
TerminatorKind::Call { args, destination: Some(destination), cleanup, .. } => {
debug!("Inlined {:?} into {:?}", callsite.callee, self.source);
let mut local_map = IndexVec::with_capacity(callee_mir.local_decls.len());
let mut scope_map = IndexVec::with_capacity(callee_mir.source_scopes.len());
let mut promoted_map = IndexVec::with_capacity(callee_mir.promoted.len());
for mut scope in callee_mir.source_scopes.iter().cloned() {
if scope.parent_scope.is_none() {
scope.parent_scope = Some(callsite.location.scope);
scope.span = callee_mir.span;
}
scope.span = callsite.location.span;
let idx = caller_mir.source_scopes.push(scope);
scope_map.push(idx);
}
for loc in callee_mir.vars_and_temps_iter() {
let mut local = callee_mir.local_decls[loc].clone();
local.source_info.scope =
scope_map[local.source_info.scope];
local.source_info.span = callsite.location.span;
local.visibility_scope = scope_map[local.visibility_scope];
let idx = caller_mir.local_decls.push(local);
local_map.push(idx);
}
promoted_map.extend(
callee_mir.promoted.iter().cloned().map(|p| caller_mir.promoted.push(p))
);
fn dest_needs_borrow(place: &Place) -> bool {
match *place {
Place::Projection(ref p) => {
match p.elem {
ProjectionElem::Deref |
ProjectionElem::Index(_) => true,
_ => dest_needs_borrow(&p.base)
}
}
Place::Static(_) => true,
_ => false
}
}
let dest = if dest_needs_borrow(&destination.0) {
debug!("Creating temp for return destination");
let dest = Rvalue::Ref(
self.tcx.types.re_erased,
BorrowKind::Mut { allow_two_phase_borrow: false },
destination.0);
let ty = dest.ty(caller_mir, self.tcx);
let temp = LocalDecl::new_temp(ty, callsite.location.span);
let tmp = caller_mir.local_decls.push(temp);
let tmp = Place::Local(tmp);
let stmt = Statement {
source_info: callsite.location,
kind: StatementKind::Assign(tmp.clone(), dest)
};
caller_mir[callsite.bb]
.statements.push(stmt);
tmp.deref()
} else {
destination.0
};
let return_block = destination.1;
let args: Vec<_> = self.make_call_args(args, &callsite, caller_mir);
let bb_len = caller_mir.basic_blocks().len();
let mut integrator = Integrator {
block_idx: bb_len,
args: &args,
local_map,
scope_map,
promoted_map,
_callsite: callsite,
destination: dest,
return_block,
cleanup_block: cleanup,
in_cleanup_block: false
};
for (bb, mut block) in callee_mir.basic_blocks_mut().drain_enumerated(..) {
integrator.visit_basic_block_data(bb, &mut block);
caller_mir.basic_blocks_mut().push(block);
}
let terminator = Terminator {
source_info: callsite.location,
kind: TerminatorKind::Goto { target: BasicBlock::new(bb_len) }
};
caller_mir[callsite.bb].terminator = Some(terminator);
true
}
kind => {
caller_mir[callsite.bb].terminator = Some(Terminator {
source_info: terminator.source_info,
kind,
});
false
}
}
}
fn make_call_args(
&self,
args: Vec<Operand<'tcx>>,
callsite: &CallSite<'tcx>,
caller_mir: &mut Mir<'tcx>,
) -> Vec<Local> {
let tcx = self.tcx;
if tcx.is_closure(callsite.callee) {
let mut args = args.into_iter();
let self_ = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_mir);
let tuple = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_mir);
assert!(args.next().is_none());
let tuple = Place::Local(tuple);
let tuple_tys = if let ty::TyTuple(s) = tuple.ty(caller_mir, tcx).to_ty(tcx).sty {
s
} else {
bug!("Closure arguments are not passed as a tuple");
};
let closure_ref_arg = iter::once(self_);
let tuple_tmp_args =
tuple_tys.iter().enumerate().map(|(i, ty)| {
let tuple_field = Operand::Move(tuple.clone().field(Field::new(i), ty));
self.create_temp_if_necessary(tuple_field, callsite, caller_mir)
});
closure_ref_arg.chain(tuple_tmp_args).collect()
} else {
args.into_iter()
.map(|a| self.create_temp_if_necessary(a, callsite, caller_mir))
.collect()
}
}
fn create_temp_if_necessary(
&self,
arg: Operand<'tcx>,
callsite: &CallSite<'tcx>,
caller_mir: &mut Mir<'tcx>,
) -> Local {
if let Operand::Move(Place::Local(local)) = arg {
if caller_mir.local_kind(local) == LocalKind::Temp {
return local;
}
}
debug!("Creating temp for argument {:?}", arg);
let arg = Rvalue::Use(arg);
let ty = arg.ty(caller_mir, self.tcx);
let arg_tmp = LocalDecl::new_temp(ty, callsite.location.span);
let arg_tmp = caller_mir.local_decls.push(arg_tmp);
let stmt = Statement {
source_info: callsite.location,
kind: StatementKind::Assign(Place::Local(arg_tmp), arg),
};
caller_mir[callsite.bb].statements.push(stmt);
arg_tmp
}
}
fn type_size_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>) -> Option<u64> {
tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
}
struct Integrator<'a, 'tcx: 'a> {
block_idx: usize,
args: &'a [Local],
local_map: IndexVec<Local, Local>,
scope_map: IndexVec<SourceScope, SourceScope>,
promoted_map: IndexVec<Promoted, Promoted>,
_callsite: CallSite<'tcx>,
destination: Place<'tcx>,
return_block: BasicBlock,
cleanup_block: Option<BasicBlock>,
in_cleanup_block: bool,
}
impl<'a, 'tcx> Integrator<'a, 'tcx> {
fn update_target(&self, tgt: BasicBlock) -> BasicBlock {
let new = BasicBlock::new(tgt.index() + self.block_idx);
debug!("Updating target `{:?}`, new: `{:?}`", tgt, new);
new
}
}
impl<'a, 'tcx> MutVisitor<'tcx> for Integrator<'a, 'tcx> {
fn visit_local(&mut self,
local: &mut Local,
_ctxt: PlaceContext<'tcx>,
_location: Location) {
if *local == RETURN_PLACE {
match self.destination {
Place::Local(l) => {
*local = l;
return;
},
ref place => bug!("Return place is {:?}, not local", place)
}
}
let idx = local.index() - 1;
if idx < self.args.len() {
*local = self.args[idx];
return;
}
*local = self.local_map[Local::new(idx - self.args.len())];
}
fn visit_place(&mut self,
place: &mut Place<'tcx>,
_ctxt: PlaceContext<'tcx>,
_location: Location) {
match place {
Place::Local(RETURN_PLACE) => {
*place = self.destination.clone();
},
Place::Promoted(ref mut promoted) => {
if let Some(p) = self.promoted_map.get(promoted.0).cloned() {
promoted.0 = p;
}
},
_ => self.super_place(place, _ctxt, _location),
}
}
fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
self.in_cleanup_block = data.is_cleanup;
self.super_basic_block_data(block, data);
self.in_cleanup_block = false;
}
fn visit_terminator_kind(&mut self, block: BasicBlock,
kind: &mut TerminatorKind<'tcx>, loc: Location) {
self.super_terminator_kind(block, kind, loc);
match *kind {
TerminatorKind::GeneratorDrop |
TerminatorKind::Yield { .. } => bug!(),
TerminatorKind::Goto { ref mut target} => {
*target = self.update_target(*target);
}
TerminatorKind::SwitchInt { ref mut targets, .. } => {
for tgt in targets {
*tgt = self.update_target(*tgt);
}
}
TerminatorKind::Drop { ref mut target, ref mut unwind, .. } |
TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
*target = self.update_target(*target);
if let Some(tgt) = *unwind {
*unwind = Some(self.update_target(tgt));
} else if !self.in_cleanup_block {
*unwind = self.cleanup_block;
}
}
TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
if let Some((_, ref mut tgt)) = *destination {
*tgt = self.update_target(*tgt);
}
if let Some(tgt) = *cleanup {
*cleanup = Some(self.update_target(tgt));
} else if !self.in_cleanup_block {
*cleanup = self.cleanup_block;
}
}
TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
*target = self.update_target(*target);
if let Some(tgt) = *cleanup {
*cleanup = Some(self.update_target(tgt));
} else if !self.in_cleanup_block {
*cleanup = self.cleanup_block;
}
}
TerminatorKind::Return => {
*kind = TerminatorKind::Goto { target: self.return_block };
}
TerminatorKind::Resume => {
if let Some(tgt) = self.cleanup_block {
*kind = TerminatorKind::Goto { target: tgt }
}
}
TerminatorKind::Abort => { }
TerminatorKind::Unreachable => { }
TerminatorKind::FalseEdges { ref mut real_target, ref mut imaginary_targets } => {
*real_target = self.update_target(*real_target);
for target in imaginary_targets {
*target = self.update_target(*target);
}
}
TerminatorKind::FalseUnwind { real_target: _ , unwind: _ } =>
bug!("False unwinds should have been removed before inlining")
}
}
fn visit_source_scope(&mut self, scope: &mut SourceScope) {
*scope = self.scope_map[*scope];
}
}