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<_> =
191 .map(|upvar| unpack!(block = this.as_operand(block, scope, upvar)))
193 let result = match substs {
194 UpvarSubsts::Generator(substs) => {
195 let movability = movability.unwrap();
196 // Add the state operand since it follows the upvars in the generator
197 // struct. See librustc_mir/transform/generator.rs for more details.
198 operands.push(Operand::Constant(box Constant {
200 ty: this.hir.tcx().types.u32,
201 literal: Literal::Value {
202 value: ty::Const::from_bits(
205 this.hir.tcx().types.u32),
208 box AggregateKind::Generator(closure_id, substs, movability)
210 UpvarSubsts::Closure(substs) => {
211 box AggregateKind::Closure(closure_id, substs)
214 block.and(Rvalue::Aggregate(result, operands))
217 adt_def, variant_index, substs, fields, base
218 } => { // see (*) above
219 let is_union = adt_def.is_union();
220 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
222 // first process the set of fields that were provided
223 // (evaluating them in order given by user)
224 let fields_map: FxHashMap<_, _> = fields.into_iter()
225 .map(|f| (f.name, unpack!(block = this.as_operand(block, scope, f.expr))))
228 let field_names = this.hir.all_fields(adt_def, variant_index);
230 let fields = if let Some(FruInfo { base, field_types }) = base {
231 let base = unpack!(block = this.as_place(block, base));
233 // MIR does not natively support FRU, so for each
234 // base-supplied field, generate an operand that
235 // reads it from the base.
236 field_names.into_iter()
237 .zip(field_types.into_iter())
238 .map(|(n, ty)| match fields_map.get(&n) {
239 Some(v) => v.clone(),
240 None => this.consume_by_copy_or_move(base.clone().field(n, ty))
244 field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
248 box AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
249 block.and(Rvalue::Aggregate(adt, fields))
251 ExprKind::Assign { .. } |
252 ExprKind::AssignOp { .. } => {
253 block = unpack!(this.stmt_expr(block, expr));
254 block.and(this.unit_rvalue())
256 ExprKind::Yield { value } => {
257 let value = unpack!(block = this.as_operand(block, scope, value));
258 let resume = this.cfg.start_new_block();
259 let cleanup = this.generator_drop_cleanup();
260 this.cfg.terminate(block, source_info, TerminatorKind::Yield {
265 resume.and(this.unit_rvalue())
267 ExprKind::Literal { .. } |
268 ExprKind::Block { .. } |
269 ExprKind::Match { .. } |
270 ExprKind::If { .. } |
271 ExprKind::NeverToAny { .. } |
272 ExprKind::Loop { .. } |
273 ExprKind::LogicalOp { .. } |
274 ExprKind::Call { .. } |
275 ExprKind::Field { .. } |
276 ExprKind::Deref { .. } |
277 ExprKind::Index { .. } |
278 ExprKind::VarRef { .. } |
280 ExprKind::Break { .. } |
281 ExprKind::Continue { .. } |
282 ExprKind::Return { .. } |
283 ExprKind::InlineAsm { .. } |
284 ExprKind::StaticRef { .. } => {
285 // these do not have corresponding `Rvalue` variants,
286 // so make an operand and then return that
287 debug_assert!(match Category::of(&expr.kind) {
288 Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
291 let operand = unpack!(block = this.as_operand(block, scope, expr));
292 block.and(Rvalue::Use(operand))
297 pub fn build_binary_op(&mut self, mut block: BasicBlock,
298 op: BinOp, span: Span, ty: Ty<'tcx>,
299 lhs: Operand<'tcx>, rhs: Operand<'tcx>) -> BlockAnd<Rvalue<'tcx>> {
300 let source_info = self.source_info(span);
301 let bool_ty = self.hir.bool_ty();
302 if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
303 let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
304 let result_value = self.temp(result_tup, span);
306 self.cfg.push_assign(block, source_info,
307 &result_value, Rvalue::CheckedBinaryOp(op,
310 let val_fld = Field::new(0);
311 let of_fld = Field::new(1);
313 let val = result_value.clone().field(val_fld, ty);
314 let of = result_value.field(of_fld, bool_ty);
316 let err = EvalErrorKind::Overflow(op);
318 block = self.assert(block, Operand::Move(of), false,
321 block.and(Rvalue::Use(Operand::Move(val)))
323 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
324 // Checking division and remainder is more complex, since we 1. always check
325 // and 2. there are two possible failure cases, divide-by-zero and overflow.
327 let (zero_err, overflow_err) = if op == BinOp::Div {
328 (EvalErrorKind::DivisionByZero,
329 EvalErrorKind::Overflow(op))
331 (EvalErrorKind::RemainderByZero,
332 EvalErrorKind::Overflow(op))
336 let is_zero = self.temp(bool_ty, span);
337 let zero = self.zero_literal(span, ty);
338 self.cfg.push_assign(block, source_info, &is_zero,
339 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero));
341 block = self.assert(block, Operand::Move(is_zero), false,
344 // We only need to check for the overflow in one case:
345 // MIN / -1, and only for signed values.
347 let neg_1 = self.neg_1_literal(span, ty);
348 let min = self.minval_literal(span, ty);
350 let is_neg_1 = self.temp(bool_ty, span);
351 let is_min = self.temp(bool_ty, span);
352 let of = self.temp(bool_ty, span);
354 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
356 self.cfg.push_assign(block, source_info, &is_neg_1,
357 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1));
358 self.cfg.push_assign(block, source_info, &is_min,
359 Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min));
361 let is_neg_1 = Operand::Move(is_neg_1);
362 let is_min = Operand::Move(is_min);
363 self.cfg.push_assign(block, source_info, &of,
364 Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min));
366 block = self.assert(block, Operand::Move(of), false,
371 block.and(Rvalue::BinaryOp(op, lhs, rhs))
375 // Helper to get a `-1` value of the appropriate type
376 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
377 let bits = ty.scalar_size(self.hir.tcx()).expect("neg_1_literal expects integers").bits();
378 let n = (!0u128) >> (128 - bits);
379 let literal = Literal::Value {
380 value: ty::Const::from_bits(self.hir.tcx(), n, ty)
383 self.literal_operand(span, ty, literal)
386 // Helper to get the minimum value of the appropriate type
387 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
388 assert!(ty.is_signed());
389 let bits = ty.scalar_size(self.hir.tcx()).expect("minval_literal expects integers").bits();
390 let n = 1 << (bits - 1);
391 let literal = Literal::Value {
392 value: ty::Const::from_bits(self.hir.tcx(), n, ty)
395 self.literal_operand(span, ty, literal)