1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! See docs in build/expr/mod.rs
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_data_structures::indexed_vec::Idx;
16 use build::{BlockAnd, BlockAndExtension, Builder};
17 use build::expr::category::{Category, RvalueFunc};
19 use rustc::middle::region;
20 use rustc::ty::{self, Ty, UpvarSubsts};
22 use rustc::mir::interpret::EvalErrorKind;
25 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
26 /// See comment on `as_local_operand`
27 pub fn as_local_rvalue<M>(&mut self, block: BasicBlock, expr: M)
28 -> BlockAnd<Rvalue<'tcx>>
29 where M: Mirror<'tcx, Output = Expr<'tcx>>
31 let local_scope = self.local_scope();
32 self.as_rvalue(block, local_scope, expr)
35 /// Compile `expr`, yielding an rvalue.
36 pub fn as_rvalue<M>(&mut self, block: BasicBlock, scope: Option<region::Scope>, expr: M)
37 -> BlockAnd<Rvalue<'tcx>>
38 where M: Mirror<'tcx, Output = Expr<'tcx>>
40 let expr = self.hir.mirror(expr);
41 self.expr_as_rvalue(block, scope, expr)
44 fn expr_as_rvalue(&mut self,
45 mut block: BasicBlock,
46 scope: Option<region::Scope>,
48 -> BlockAnd<Rvalue<'tcx>> {
49 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
52 let expr_span = expr.span;
53 let source_info = this.source_info(expr_span);
56 ExprKind::Scope { region_scope, lint_level, value } => {
57 let region_scope = (region_scope, source_info);
58 this.in_scope(region_scope, lint_level, block,
59 |this| this.as_rvalue(block, scope, value))
61 ExprKind::Repeat { value, count } => {
62 let value_operand = unpack!(block = this.as_operand(block, scope, value));
63 block.and(Rvalue::Repeat(value_operand, count))
65 ExprKind::Borrow { region, borrow_kind, arg } => {
66 let arg_place = unpack!(block = this.as_place(block, arg));
67 block.and(Rvalue::Ref(region, borrow_kind, arg_place))
69 ExprKind::Binary { op, lhs, rhs } => {
70 let lhs = unpack!(block = this.as_operand(block, scope, lhs));
71 let rhs = unpack!(block = this.as_operand(block, scope, rhs));
72 this.build_binary_op(block, op, expr_span, expr.ty,
75 ExprKind::Unary { op, arg } => {
76 let arg = unpack!(block = this.as_operand(block, scope, arg));
77 // Check for -MIN on signed integers
78 if this.hir.check_overflow() && op == UnOp::Neg && expr.ty.is_signed() {
79 let bool_ty = this.hir.bool_ty();
81 let minval = this.minval_literal(expr_span, expr.ty);
82 let is_min = this.temp(bool_ty, expr_span);
84 this.cfg.push_assign(block, source_info, &is_min,
85 Rvalue::BinaryOp(BinOp::Eq, arg.to_copy(), minval));
87 block = this.assert(block, Operand::Move(is_min), false,
88 EvalErrorKind::OverflowNeg, expr_span);
90 block.and(Rvalue::UnaryOp(op, arg))
92 ExprKind::Box { value } => {
93 let value = this.hir.mirror(value);
94 // The `Box<T>` temporary created here is not a part of the HIR,
95 // and therefore is not considered during generator OIBIT
96 // determination. See the comment about `box` at `yield_in_scope`.
97 let result = this.local_decls.push(
98 LocalDecl::new_internal(expr.ty, expr_span));
99 this.cfg.push(block, Statement {
101 kind: StatementKind::StorageLive(result)
103 if let Some(scope) = scope {
104 // schedule a shallow free of that memory, lest we unwind:
105 this.schedule_drop(expr_span, scope, &Place::Local(result), value.ty);
108 // malloc some memory of suitable type (thus far, uninitialized):
109 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
110 this.cfg.push_assign(block, source_info, &Place::Local(result), box_);
112 // initialize the box contents:
113 unpack!(block = this.into(&Place::Local(result).deref(), block, value));
114 block.and(Rvalue::Use(Operand::Move(Place::Local(result))))
116 ExprKind::Cast { source } => {
117 let source = this.hir.mirror(source);
119 let source = unpack!(block = this.as_operand(block, scope, source));
120 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
122 ExprKind::Use { source } => {
123 let source = unpack!(block = this.as_operand(block, scope, source));
124 block.and(Rvalue::Use(source))
126 ExprKind::ReifyFnPointer { source } => {
127 let source = unpack!(block = this.as_operand(block, scope, source));
128 block.and(Rvalue::Cast(CastKind::ReifyFnPointer, source, expr.ty))
130 ExprKind::UnsafeFnPointer { source } => {
131 let source = unpack!(block = this.as_operand(block, scope, source));
132 block.and(Rvalue::Cast(CastKind::UnsafeFnPointer, source, expr.ty))
134 ExprKind::ClosureFnPointer { source } => {
135 let source = unpack!(block = this.as_operand(block, scope, source));
136 block.and(Rvalue::Cast(CastKind::ClosureFnPointer, source, expr.ty))
138 ExprKind::Unsize { source } => {
139 let source = unpack!(block = this.as_operand(block, scope, source));
140 block.and(Rvalue::Cast(CastKind::Unsize, source, expr.ty))
142 ExprKind::Array { fields } => {
143 // (*) We would (maybe) be closer to codegen if we
144 // handled this and other aggregate cases via
145 // `into()`, not `as_rvalue` -- in that case, instead
150 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
152 // we could just generate
157 // The problem is that then we would need to:
159 // (a) have a more complex mechanism for handling
161 // (b) distinguish the case where the type `Foo` has a
162 // destructor, in which case creating an instance
163 // as a whole "arms" the destructor, and you can't
164 // write individual fields; and,
165 // (c) handle the case where the type Foo has no
166 // fields. We don't want `let x: ();` to compile
167 // to the same MIR as `let x = ();`.
169 // first process the set of fields
170 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
173 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
176 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
178 ExprKind::Tuple { fields } => { // see (*) above
179 // first process the set of fields
182 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
185 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
187 ExprKind::Closure { closure_id, substs, upvars, movability } => {
189 let mut operands: Vec<_> = upvars
192 let upvar = this.hir.mirror(upvar);
193 match Category::of(&upvar.kind) {
194 // Use as_place to avoid creating a temporary when
195 // moving a variable into a closure, so that
196 // borrowck knows which variables to mark as being
197 // used as mut. This is OK here because the upvar
198 // expressions have no side effects and act on
200 // This occurs when capturing by copy/move, while
201 // by reference captures use as_operand
202 Some(Category::Place) => {
203 let place = unpack!(block = this.as_place(block, upvar));
204 this.consume_by_copy_or_move(place)
207 unpack!(block = this.as_operand(block, scope, upvar))
212 let result = match substs {
213 UpvarSubsts::Generator(substs) => {
214 let movability = movability.unwrap();
215 // Add the state operand since it follows the upvars in the generator
216 // struct. See librustc_mir/transform/generator.rs for more details.
217 operands.push(Operand::Constant(box Constant {
219 ty: this.hir.tcx().types.u32,
220 literal: Literal::Value {
221 value: ty::Const::from_bits(
224 ty::ParamEnv::empty().and(this.hir.tcx().types.u32)),
227 box AggregateKind::Generator(closure_id, substs, movability)
229 UpvarSubsts::Closure(substs) => {
230 box AggregateKind::Closure(closure_id, substs)
233 block.and(Rvalue::Aggregate(result, operands))
236 adt_def, variant_index, substs, fields, base
237 } => { // see (*) above
238 let is_union = adt_def.is_union();
239 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
241 // first process the set of fields that were provided
242 // (evaluating them in order given by user)
243 let fields_map: FxHashMap<_, _> = fields.into_iter()
244 .map(|f| (f.name, unpack!(block = this.as_operand(block, scope, f.expr))))
247 let field_names = this.hir.all_fields(adt_def, variant_index);
249 let fields = if let Some(FruInfo { base, field_types }) = base {
250 let base = unpack!(block = this.as_place(block, base));
252 // MIR does not natively support FRU, so for each
253 // base-supplied field, generate an operand that
254 // reads it from the base.
255 field_names.into_iter()
256 .zip(field_types.into_iter())
257 .map(|(n, ty)| match fields_map.get(&n) {
258 Some(v) => v.clone(),
259 None => this.consume_by_copy_or_move(base.clone().field(n, ty))
263 field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
267 box AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
268 block.and(Rvalue::Aggregate(adt, fields))
270 ExprKind::Assign { .. } |
271 ExprKind::AssignOp { .. } => {
272 block = unpack!(this.stmt_expr(block, expr));
273 block.and(this.unit_rvalue())
275 ExprKind::Yield { value } => {
276 let value = unpack!(block = this.as_operand(block, scope, value));
277 let resume = this.cfg.start_new_block();
278 let cleanup = this.generator_drop_cleanup();
279 this.cfg.terminate(block, source_info, TerminatorKind::Yield {
284 resume.and(this.unit_rvalue())
286 ExprKind::Literal { .. } |
287 ExprKind::Block { .. } |
288 ExprKind::Match { .. } |
289 ExprKind::If { .. } |
290 ExprKind::NeverToAny { .. } |
291 ExprKind::Loop { .. } |
292 ExprKind::LogicalOp { .. } |
293 ExprKind::Call { .. } |
294 ExprKind::Field { .. } |
295 ExprKind::Deref { .. } |
296 ExprKind::Index { .. } |
297 ExprKind::VarRef { .. } |
299 ExprKind::Break { .. } |
300 ExprKind::Continue { .. } |
301 ExprKind::Return { .. } |
302 ExprKind::InlineAsm { .. } |
303 ExprKind::StaticRef { .. } => {
304 // these do not have corresponding `Rvalue` variants,
305 // so make an operand and then return that
306 debug_assert!(match Category::of(&expr.kind) {
307 Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
310 let operand = unpack!(block = this.as_operand(block, scope, expr));
311 block.and(Rvalue::Use(operand))
316 pub fn build_binary_op(&mut self, mut block: BasicBlock,
317 op: BinOp, span: Span, ty: Ty<'tcx>,
318 lhs: Operand<'tcx>, rhs: Operand<'tcx>) -> BlockAnd<Rvalue<'tcx>> {
319 let source_info = self.source_info(span);
320 let bool_ty = self.hir.bool_ty();
321 if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
322 let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
323 let result_value = self.temp(result_tup, span);
325 self.cfg.push_assign(block, source_info,
326 &result_value, Rvalue::CheckedBinaryOp(op,
329 let val_fld = Field::new(0);
330 let of_fld = Field::new(1);
332 let val = result_value.clone().field(val_fld, ty);
333 let of = result_value.field(of_fld, bool_ty);
335 let err = EvalErrorKind::Overflow(op);
337 block = self.assert(block, Operand::Move(of), false,
340 block.and(Rvalue::Use(Operand::Move(val)))
342 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
343 // Checking division and remainder is more complex, since we 1. always check
344 // and 2. there are two possible failure cases, divide-by-zero and overflow.
346 let (zero_err, overflow_err) = if op == BinOp::Div {
347 (EvalErrorKind::DivisionByZero,
348 EvalErrorKind::Overflow(op))
350 (EvalErrorKind::RemainderByZero,
351 EvalErrorKind::Overflow(op))
355 let is_zero = self.temp(bool_ty, span);
356 let zero = self.zero_literal(span, ty);
357 self.cfg.push_assign(block, source_info, &is_zero,
358 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero));
360 block = self.assert(block, Operand::Move(is_zero), false,
363 // We only need to check for the overflow in one case:
364 // MIN / -1, and only for signed values.
366 let neg_1 = self.neg_1_literal(span, ty);
367 let min = self.minval_literal(span, ty);
369 let is_neg_1 = self.temp(bool_ty, span);
370 let is_min = self.temp(bool_ty, span);
371 let of = self.temp(bool_ty, span);
373 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
375 self.cfg.push_assign(block, source_info, &is_neg_1,
376 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1));
377 self.cfg.push_assign(block, source_info, &is_min,
378 Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min));
380 let is_neg_1 = Operand::Move(is_neg_1);
381 let is_min = Operand::Move(is_min);
382 self.cfg.push_assign(block, source_info, &of,
383 Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min));
385 block = self.assert(block, Operand::Move(of), false,
390 block.and(Rvalue::BinaryOp(op, lhs, rhs))
394 // Helper to get a `-1` value of the appropriate type
395 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
396 let param_ty = ty::ParamEnv::empty().and(self.hir.tcx().lift_to_global(&ty).unwrap());
397 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
398 let n = (!0u128) >> (128 - bits);
399 let literal = Literal::Value {
400 value: ty::Const::from_bits(self.hir.tcx(), n, param_ty)
403 self.literal_operand(span, ty, literal)
406 // Helper to get the minimum value of the appropriate type
407 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
408 assert!(ty.is_signed());
409 let param_ty = ty::ParamEnv::empty().and(self.hir.tcx().lift_to_global(&ty).unwrap());
410 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
411 let n = 1 << (bits - 1);
412 let literal = Literal::Value {
413 value: ty::Const::from_bits(self.hir.tcx(), n, param_ty)
416 self.literal_operand(span, ty, literal)