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
15 use rustc_const_math::{ConstMathErr, Op};
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_data_structures::indexed_vec::Idx;
19 use build::{BlockAnd, BlockAndExtension, Builder};
20 use build::expr::category::{Category, RvalueFunc};
22 use rustc_const_math::{ConstInt, ConstIsize};
23 use rustc::middle::const_val::ConstVal;
24 use rustc::middle::region::CodeExtent;
30 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
31 /// See comment on `as_local_operand`
32 pub fn as_local_rvalue<M>(&mut self, block: BasicBlock, expr: M)
33 -> BlockAnd<Rvalue<'tcx>>
34 where M: Mirror<'tcx, Output = Expr<'tcx>>
36 let local_scope = self.local_scope();
37 self.as_rvalue(block, local_scope, expr)
40 /// Compile `expr`, yielding an rvalue.
41 pub fn as_rvalue<M>(&mut self, block: BasicBlock, scope: Option<CodeExtent>, expr: M)
42 -> BlockAnd<Rvalue<'tcx>>
43 where M: Mirror<'tcx, Output = Expr<'tcx>>
45 let expr = self.hir.mirror(expr);
46 self.expr_as_rvalue(block, scope, expr)
49 fn expr_as_rvalue(&mut self,
50 mut block: BasicBlock,
51 scope: Option<CodeExtent>,
53 -> BlockAnd<Rvalue<'tcx>> {
54 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
57 let expr_span = expr.span;
58 let source_info = this.source_info(expr_span);
61 ExprKind::Scope { extent, value } => {
62 this.in_scope(extent, block, |this| this.as_rvalue(block, scope, value))
64 ExprKind::Repeat { value, count } => {
65 let value_operand = unpack!(block = this.as_operand(block, scope, value));
66 block.and(Rvalue::Repeat(value_operand, count))
68 ExprKind::Borrow { region, borrow_kind, arg } => {
69 let arg_lvalue = unpack!(block = this.as_lvalue(block, arg));
70 block.and(Rvalue::Ref(region, borrow_kind, arg_lvalue))
72 ExprKind::Binary { op, lhs, rhs } => {
73 let lhs = unpack!(block = this.as_operand(block, scope, lhs));
74 let rhs = unpack!(block = this.as_operand(block, scope, rhs));
75 this.build_binary_op(block, op, expr_span, expr.ty,
78 ExprKind::Unary { op, arg } => {
79 let arg = unpack!(block = this.as_operand(block, scope, arg));
80 // Check for -MIN on signed integers
81 if this.hir.check_overflow() && op == UnOp::Neg && expr.ty.is_signed() {
82 let bool_ty = this.hir.bool_ty();
84 let minval = this.minval_literal(expr_span, expr.ty);
85 let is_min = this.temp(bool_ty, expr_span);
87 this.cfg.push_assign(block, source_info, &is_min,
88 Rvalue::BinaryOp(BinOp::Eq, arg.clone(), minval));
90 let err = ConstMathErr::Overflow(Op::Neg);
91 block = this.assert(block, Operand::Consume(is_min), false,
92 AssertMessage::Math(err), expr_span);
94 block.and(Rvalue::UnaryOp(op, arg))
96 ExprKind::Box { value, value_extents } => {
97 let value = this.hir.mirror(value);
98 let result = this.temp(expr.ty, expr_span);
99 // to start, malloc some memory of suitable type (thus far, uninitialized):
100 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
101 this.cfg.push_assign(block, source_info, &result, box_);
102 this.in_scope(value_extents, block, |this| {
103 // schedule a shallow free of that memory, lest we unwind:
104 this.schedule_box_free(expr_span, value_extents, &result, value.ty);
105 // initialize the box contents:
106 unpack!(block = this.into(&result.clone().deref(), block, value));
107 block.and(Rvalue::Use(Operand::Consume(result)))
110 ExprKind::Cast { source } => {
111 let source = this.hir.mirror(source);
113 let source = unpack!(block = this.as_operand(block, scope, source));
114 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
116 ExprKind::Use { source } => {
117 let source = unpack!(block = this.as_operand(block, scope, source));
118 block.and(Rvalue::Use(source))
120 ExprKind::ReifyFnPointer { source } => {
121 let source = unpack!(block = this.as_operand(block, scope, source));
122 block.and(Rvalue::Cast(CastKind::ReifyFnPointer, source, expr.ty))
124 ExprKind::UnsafeFnPointer { source } => {
125 let source = unpack!(block = this.as_operand(block, scope, source));
126 block.and(Rvalue::Cast(CastKind::UnsafeFnPointer, source, expr.ty))
128 ExprKind::ClosureFnPointer { source } => {
129 let source = unpack!(block = this.as_operand(block, scope, source));
130 block.and(Rvalue::Cast(CastKind::ClosureFnPointer, source, expr.ty))
132 ExprKind::Unsize { source } => {
133 let source = unpack!(block = this.as_operand(block, scope, source));
134 block.and(Rvalue::Cast(CastKind::Unsize, source, expr.ty))
136 ExprKind::Array { fields } => {
137 // (*) We would (maybe) be closer to trans if we
138 // handled this and other aggregate cases via
139 // `into()`, not `as_rvalue` -- in that case, instead
144 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
146 // we could just generate
151 // The problem is that then we would need to:
153 // (a) have a more complex mechanism for handling
155 // (b) distinguish the case where the type `Foo` has a
156 // destructor, in which case creating an instance
157 // as a whole "arms" the destructor, and you can't
158 // write individual fields; and,
159 // (c) handle the case where the type Foo has no
160 // fields. We don't want `let x: ();` to compile
161 // to the same MIR as `let x = ();`.
163 // first process the set of fields
164 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
167 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
170 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
172 ExprKind::Tuple { fields } => { // see (*) above
173 // first process the set of fields
176 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
179 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
181 ExprKind::Closure { closure_id, substs, upvars } => { // see (*) above
184 .map(|upvar| unpack!(block = this.as_operand(block, scope, upvar)))
186 block.and(Rvalue::Aggregate(box AggregateKind::Closure(closure_id, substs), upvars))
189 adt_def, variant_index, substs, fields, base
190 } => { // see (*) above
191 let is_union = adt_def.is_union();
192 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
194 // first process the set of fields that were provided
195 // (evaluating them in order given by user)
196 let fields_map: FxHashMap<_, _> = fields.into_iter()
197 .map(|f| (f.name, unpack!(block = this.as_operand(block, scope, f.expr))))
200 let field_names = this.hir.all_fields(adt_def, variant_index);
202 let fields = if let Some(FruInfo { base, field_types }) = base {
203 let base = unpack!(block = this.as_lvalue(block, base));
205 // MIR does not natively support FRU, so for each
206 // base-supplied field, generate an operand that
207 // reads it from the base.
208 field_names.into_iter()
209 .zip(field_types.into_iter())
210 .map(|(n, ty)| match fields_map.get(&n) {
211 Some(v) => v.clone(),
212 None => Operand::Consume(base.clone().field(n, ty))
216 field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
220 box AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
221 block.and(Rvalue::Aggregate(adt, fields))
223 ExprKind::Assign { .. } |
224 ExprKind::AssignOp { .. } => {
225 block = unpack!(this.stmt_expr(block, expr));
226 block.and(this.unit_rvalue())
228 ExprKind::Literal { .. } |
229 ExprKind::Block { .. } |
230 ExprKind::Match { .. } |
231 ExprKind::If { .. } |
232 ExprKind::NeverToAny { .. } |
233 ExprKind::Loop { .. } |
234 ExprKind::LogicalOp { .. } |
235 ExprKind::Call { .. } |
236 ExprKind::Field { .. } |
237 ExprKind::Deref { .. } |
238 ExprKind::Index { .. } |
239 ExprKind::VarRef { .. } |
241 ExprKind::Break { .. } |
242 ExprKind::Continue { .. } |
243 ExprKind::Return { .. } |
244 ExprKind::InlineAsm { .. } |
245 ExprKind::StaticRef { .. } => {
246 // these do not have corresponding `Rvalue` variants,
247 // so make an operand and then return that
248 debug_assert!(match Category::of(&expr.kind) {
249 Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
252 let operand = unpack!(block = this.as_operand(block, scope, expr));
253 block.and(Rvalue::Use(operand))
258 pub fn build_binary_op(&mut self, mut block: BasicBlock,
259 op: BinOp, span: Span, ty: ty::Ty<'tcx>,
260 lhs: Operand<'tcx>, rhs: Operand<'tcx>) -> BlockAnd<Rvalue<'tcx>> {
261 let source_info = self.source_info(span);
262 let bool_ty = self.hir.bool_ty();
263 if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
264 let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty], false);
265 let result_value = self.temp(result_tup, span);
267 self.cfg.push_assign(block, source_info,
268 &result_value, Rvalue::CheckedBinaryOp(op,
271 let val_fld = Field::new(0);
272 let of_fld = Field::new(1);
274 let val = result_value.clone().field(val_fld, ty);
275 let of = result_value.field(of_fld, bool_ty);
277 let err = ConstMathErr::Overflow(match op {
278 BinOp::Add => Op::Add,
279 BinOp::Sub => Op::Sub,
280 BinOp::Mul => Op::Mul,
281 BinOp::Shl => Op::Shl,
282 BinOp::Shr => Op::Shr,
284 bug!("MIR build_binary_op: {:?} is not checkable", op)
288 block = self.assert(block, Operand::Consume(of), false,
289 AssertMessage::Math(err), span);
291 block.and(Rvalue::Use(Operand::Consume(val)))
293 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
294 // Checking division and remainder is more complex, since we 1. always check
295 // and 2. there are two possible failure cases, divide-by-zero and overflow.
297 let (zero_err, overflow_err) = if op == BinOp::Div {
298 (ConstMathErr::DivisionByZero,
299 ConstMathErr::Overflow(Op::Div))
301 (ConstMathErr::RemainderByZero,
302 ConstMathErr::Overflow(Op::Rem))
306 let is_zero = self.temp(bool_ty, span);
307 let zero = self.zero_literal(span, ty);
308 self.cfg.push_assign(block, source_info, &is_zero,
309 Rvalue::BinaryOp(BinOp::Eq, rhs.clone(), zero));
311 block = self.assert(block, Operand::Consume(is_zero), false,
312 AssertMessage::Math(zero_err), span);
314 // We only need to check for the overflow in one case:
315 // MIN / -1, and only for signed values.
317 let neg_1 = self.neg_1_literal(span, ty);
318 let min = self.minval_literal(span, ty);
320 let is_neg_1 = self.temp(bool_ty, span);
321 let is_min = self.temp(bool_ty, span);
322 let of = self.temp(bool_ty, span);
324 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
326 self.cfg.push_assign(block, source_info, &is_neg_1,
327 Rvalue::BinaryOp(BinOp::Eq, rhs.clone(), neg_1));
328 self.cfg.push_assign(block, source_info, &is_min,
329 Rvalue::BinaryOp(BinOp::Eq, lhs.clone(), min));
331 let is_neg_1 = Operand::Consume(is_neg_1);
332 let is_min = Operand::Consume(is_min);
333 self.cfg.push_assign(block, source_info, &of,
334 Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min));
336 block = self.assert(block, Operand::Consume(of), false,
337 AssertMessage::Math(overflow_err), span);
341 block.and(Rvalue::BinaryOp(op, lhs, rhs))
345 // Helper to get a `-1` value of the appropriate type
346 fn neg_1_literal(&mut self, span: Span, ty: ty::Ty<'tcx>) -> Operand<'tcx> {
347 let literal = match ty.sty {
349 let val = match ity {
350 ast::IntTy::I8 => ConstInt::I8(-1),
351 ast::IntTy::I16 => ConstInt::I16(-1),
352 ast::IntTy::I32 => ConstInt::I32(-1),
353 ast::IntTy::I64 => ConstInt::I64(-1),
354 ast::IntTy::I128 => ConstInt::I128(-1),
356 let int_ty = self.hir.tcx().sess.target.int_type;
357 let val = ConstIsize::new(-1, int_ty).unwrap();
362 Literal::Value { value: ConstVal::Integral(val) }
365 span_bug!(span, "Invalid type for neg_1_literal: `{:?}`", ty)
369 self.literal_operand(span, ty, literal)
372 // Helper to get the minimum value of the appropriate type
373 fn minval_literal(&mut self, span: Span, ty: ty::Ty<'tcx>) -> Operand<'tcx> {
374 let literal = match ty.sty {
376 let val = match ity {
377 ast::IntTy::I8 => ConstInt::I8(i8::min_value()),
378 ast::IntTy::I16 => ConstInt::I16(i16::min_value()),
379 ast::IntTy::I32 => ConstInt::I32(i32::min_value()),
380 ast::IntTy::I64 => ConstInt::I64(i64::min_value()),
381 ast::IntTy::I128 => ConstInt::I128(i128::min_value()),
383 let int_ty = self.hir.tcx().sess.target.int_type;
384 let min = match int_ty {
385 ast::IntTy::I16 => std::i16::MIN as i64,
386 ast::IntTy::I32 => std::i32::MIN as i64,
387 ast::IntTy::I64 => std::i64::MIN,
390 let val = ConstIsize::new(min, int_ty).unwrap();
395 Literal::Value { value: ConstVal::Integral(val) }
398 span_bug!(span, "Invalid type for minval_literal: `{:?}`", ty)
402 self.literal_operand(span, ty, literal)