Skip to content

Handle closures correctly in MIR inlining #45913

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 15, 2017
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/librustc/ty/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -621,9 +621,13 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
result
}

pub fn is_closure(self, def_id: DefId) -> bool {
self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr
}

pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
let mut def_id = def_id;
while self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr {
while self.is_closure(def_id) {
def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
bug!("closure {:?} has no parent", def_id);
});
Expand Down
11 changes: 5 additions & 6 deletions src/librustc_mir/transform/check_unsafety.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use rustc::ty::maps::Providers;
use rustc::ty::{self, TyCtxt};
use rustc::hir;
use rustc::hir::def_id::DefId;
use rustc::hir::map::DefPathData;
use rustc::lint::builtin::{SAFE_EXTERN_STATICS, UNUSED_UNSAFE};
use rustc::mir::*;
use rustc::mir::visit::{LvalueContext, Visitor};
Expand Down Expand Up @@ -362,11 +361,11 @@ fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet<ast::NodeId>, id: a

pub fn check_unsafety<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
debug!("check_unsafety({:?})", def_id);
match tcx.def_key(def_id).disambiguated_data.data {
// closures are handled by their parent fn.
DefPathData::ClosureExpr => return,
_ => {}
};

// closures are handled by their parent fn.
if tcx.is_closure(def_id) {
return;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice drive-by cleanup =)


let UnsafetyCheckResult {
violations,
Expand Down
83 changes: 61 additions & 22 deletions src/librustc_mir/transform/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -550,36 +550,75 @@ impl<'a, 'tcx> Inliner<'a, 'tcx> {
Operand::Consume(cast_tmp)
}

fn make_call_args(&self, args: Vec<Operand<'tcx>>,
callsite: &CallSite<'tcx>, caller_mir: &mut Mir<'tcx>) -> Vec<Operand<'tcx>> {
fn make_call_args(
&self,
args: Vec<Operand<'tcx>>,
callsite: &CallSite<'tcx>,
caller_mir: &mut Mir<'tcx>,
) -> Vec<Operand<'tcx>> {
let tcx = self.tcx;

// A closure is passed its self-type and a tuple like `(arg1, arg2, ...)`,
// hence mappings to tuple fields are needed.
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_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 mut res = Vec::with_capacity(1 + tuple_tys.len());
res.push(Operand::Consume(self_));
res.extend(tuple_tys.iter().enumerate().map(|(i, ty)| {
Operand::Consume(tuple.clone().field(Field::new(i), ty))
}));
res
} else {
args.into_iter()
.map(|a| Operand::Consume(self.create_temp_if_necessary(a, callsite, caller_mir)))
.collect()
}
}

/// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
/// temporary `T` and an instruction `T = arg`, and returns `T`.
fn create_temp_if_necessary(
&self,
arg: Operand<'tcx>,
callsite: &CallSite<'tcx>,
caller_mir: &mut Mir<'tcx>,
) -> Lvalue<'tcx> {
// FIXME: Analysis of the usage of the arguments to avoid
// unnecessary temporaries.
args.into_iter().map(|a| {
if let Operand::Consume(Lvalue::Local(local)) = a {
if caller_mir.local_kind(local) == LocalKind::Temp {
// Reuse the operand if it's a temporary already
return a;
}

if let Operand::Consume(Lvalue::Local(local)) = arg {
if caller_mir.local_kind(local) == LocalKind::Temp {
// Reuse the operand if it's a temporary already
return Lvalue::Local(local);
}
}

debug!("Creating temp for argument");
// Otherwise, create a temporary for the arg
let arg = Rvalue::Use(a);
debug!("Creating temp for argument {:?}", arg);
// Otherwise, create a temporary for the arg
let arg = Rvalue::Use(arg);

let ty = arg.ty(caller_mir, tcx);
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 arg_tmp = Lvalue::Local(arg_tmp);
let arg_tmp = LocalDecl::new_temp(ty, callsite.location.span);
let arg_tmp = caller_mir.local_decls.push(arg_tmp);
let arg_tmp = Lvalue::Local(arg_tmp);

let stmt = Statement {
source_info: callsite.location,
kind: StatementKind::Assign(arg_tmp.clone(), arg)
};
caller_mir[callsite.bb].statements.push(stmt);
Operand::Consume(arg_tmp)
}).collect()
let stmt = Statement {
source_info: callsite.location,
kind: StatementKind::Assign(arg_tmp.clone(), arg),
};
caller_mir[callsite.bb].statements.push(stmt);
arg_tmp
}
}

Expand Down
53 changes: 53 additions & 0 deletions src/test/mir-opt/inline-closure.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// compile-flags: -Z span_free_formats

// Tests that MIR inliner can handle closure arguments. (#45894)

fn main() {
println!("{}", foo(0, 14));
}

fn foo<T: Copy>(_t: T, q: i32) -> i32 {
let x = |_t, _q| _t;
x(q*2, q*3)
}

// END RUST SOURCE
// START rustc.foo.Inline.after.mir
// ...
// bb0: {
// StorageLive(_3);
// _3 = [closure@NodeId(28)];
// StorageLive(_4);
// _4 = &_3;
// StorageLive(_5);
// StorageLive(_6);
// StorageLive(_7);
// _7 = _2;
// _6 = Mul(_7, const 2i32);
Copy link
Member

@kennytm kennytm Nov 14, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked arithmetic strikes again! These are CheckedMul in debug build. Please change to a non-checked operator like q & 3 or maybe just write x(q, q).

[01:06:23] ---- [mir-opt] mir-opt/inline-closure.rs stdout ----
[01:06:23] 	thread '[mir-opt] mir-opt/inline-closure.rs' panicked at 'Did not find expected line, error: Mismatch in lines
[01:06:23] Currnt block: None
[01:06:23] Expected Line: "        _8 = CheckedMul(_7, const 2i32); // scope 1 at /checkout/src/test/mir-opt/inline-closure.rs:21:7: 21:10"
[01:06:23] Actual Line: "    _6 = Mul(_7, const 2i32);"
[01:06:23] Expected:
[01:06:23] ... (elided)
[01:06:23] ... (elided)
[01:06:23] bb0: {
[01:06:23]     StorageLive(_3);
[01:06:23]     _3 = [closure@NodeId(28)];
[01:06:23]     StorageLive(_4);
[01:06:23]     _4 = &_3;
[01:06:23]     StorageLive(_5);
[01:06:23]     StorageLive(_6);
[01:06:23]     StorageLive(_7);
[01:06:23]     _7 = _2;
[01:06:23]     _6 = Mul(_7, const 2i32);
[01:06:23]     StorageDead(_7);
[01:06:23]     StorageLive(_8);
[01:06:23]     StorageLive(_9);
[01:06:23]     _9 = _2;
[01:06:23]     _8 = Mul(_9, const 3i32);
[01:06:23]     StorageDead(_9);
[01:06:23]     _5 = (_6, _8);
[01:06:23]     _0 = (_5.0: i32);
[01:06:23]     StorageDead(_5);
[01:06:23]     StorageDead(_8);
[01:06:23]     StorageDead(_6);
[01:06:23]     StorageDead(_4);
[01:06:23]     StorageDead(_3);
[01:06:23]     return;
[01:06:23] }
[01:06:23] ... (elided)
[01:06:23] Actual:
[01:06:23] fn foo(_1: T, _2: i32) -> i32 {
[01:06:23]     let mut _0: i32;
[01:06:23]     scope 1 {
[01:06:23]         let _3: [closure@NodeId(28)];
[01:06:23]         scope 3 {
[01:06:23]         }
[01:06:23]     }
[01:06:23]     scope 2 {
[01:06:23]     }
[01:06:23]     let mut _4: &[closure@NodeId(28)];
[01:06:23]     let mut _5: (i32, i32);
[01:06:23]     let mut _6: i32;
[01:06:23]     let mut _7: i32;
[01:06:23]     let mut _8: (i32, bool);
[01:06:23]     let mut _9: i32;
[01:06:23]     let mut _10: i32;
[01:06:23]     let mut _11: (i32, bool);
[01:06:23]     bb0: {                              
[01:06:23]         StorageLive(_3);
[01:06:23]         _3 = [closure@NodeId(28)];
[01:06:23]         StorageLive(_4);
[01:06:23]         _4 = &_3;
[01:06:23]         StorageLive(_5);
[01:06:23]         StorageLive(_6);
[01:06:23]         StorageLive(_7);
[01:06:23]         _7 = _2;
[01:06:23]         _8 = CheckedMul(_7, const 2i32);
[01:06:23]         assert(!(_8.1: bool), "attempt to multiply with overflow") -> bb1;
[01:06:23]     }
[01:06:23]     bb1: {                              
[01:06:23]         _6 = (_8.0: i32);
[01:06:23]         StorageDead(_7);
[01:06:23]         StorageLive(_9);
[01:06:23]         StorageLive(_10);
[01:06:23]         _10 = _2;
[01:06:23]         _11 = CheckedMul(_10, const 3i32);
[01:06:23]         assert(!(_11.1: bool), "attempt to multiply with overflow") -> bb2;
[01:06:23]     }
[01:06:23]     bb2: {                              
[01:06:23]         _9 = (_11.0: i32);
[01:06:23]         StorageDead(_10);
[01:06:23]         _5 = (_6, _9);
[01:06:23]         _0 = (_5.0: i32);
[01:06:23]         StorageDead(_5);
[01:06:23]         StorageDead(_9);
[01:06:23]         StorageDead(_6);
[01:06:23]         StorageDead(_4);
[01:06:23]         StorageDead(_3);
[01:06:23]         return;
[01:06:23]     }
[01:06:23] }', /checkout/src/tools/compiletest/src/runtest.rs:2337:12
[01:06:23] note: Run with `RUST_BACKTRACE=1` for a backtrace.
[01:06:23] 
[01:06:23] 
[01:06:23] failures:
[01:06:23]     [mir-opt] mir-opt/inline-closure.rs
[01:06:23] 
[01:06:23] test result: �[31mFAILED�(B�[m. 44 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out

// StorageDead(_7);
// StorageLive(_8);
// StorageLive(_9);
// _9 = _2;
// _8 = Mul(_9, const 3i32);
// StorageDead(_9);
// _5 = (_6, _8);
// _0 = (_5.0: i32);
// StorageDead(_5);
// StorageDead(_8);
// StorageDead(_6);
// StorageDead(_4);
// StorageDead(_3);
// return;
// }
// ...
// END rustc.foo.Inline.after.mir