]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/expr/as_rvalue.rs
Auto merge of #42264 - GuillaumeGomez:new-error-codes, r=Susurrus
[rust.git] / src / librustc_mir / build / expr / as_rvalue.rs
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.
4 //
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.
10
11 //! See docs in build/expr/mod.rs
12
13 use std;
14
15 use rustc_const_math::{ConstMathErr, Op};
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_data_structures::indexed_vec::Idx;
18
19 use build::{BlockAnd, BlockAndExtension, Builder};
20 use build::expr::category::{Category, RvalueFunc};
21 use hair::*;
22 use rustc_const_math::{ConstInt, ConstIsize};
23 use rustc::middle::const_val::ConstVal;
24 use rustc::middle::region::CodeExtent;
25 use rustc::ty;
26 use rustc::mir::*;
27 use syntax::ast;
28 use syntax_pos::Span;
29
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>>
35     {
36         let local_scope = self.local_scope();
37         self.as_rvalue(block, local_scope, expr)
38     }
39
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>>
44     {
45         let expr = self.hir.mirror(expr);
46         self.expr_as_rvalue(block, scope, expr)
47     }
48
49     fn expr_as_rvalue(&mut self,
50                       mut block: BasicBlock,
51                       scope: Option<CodeExtent>,
52                       expr: Expr<'tcx>)
53                       -> BlockAnd<Rvalue<'tcx>> {
54         debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
55
56         let this = self;
57         let expr_span = expr.span;
58         let source_info = this.source_info(expr_span);
59
60         match expr.kind {
61             ExprKind::Scope { extent, value } => {
62                 this.in_scope(extent, block, |this| this.as_rvalue(block, scope, value))
63             }
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))
67             }
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))
71             }
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,
76                                      lhs, rhs)
77             }
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();
83
84                     let minval = this.minval_literal(expr_span, expr.ty);
85                     let is_min = this.temp(bool_ty, expr_span);
86
87                     this.cfg.push_assign(block, source_info, &is_min,
88                                          Rvalue::BinaryOp(BinOp::Eq, arg.clone(), minval));
89
90                     let err = ConstMathErr::Overflow(Op::Neg);
91                     block = this.assert(block, Operand::Consume(is_min), false,
92                                         AssertMessage::Math(err), expr_span);
93                 }
94                 block.and(Rvalue::UnaryOp(op, arg))
95             }
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)))
108                 })
109             }
110             ExprKind::Cast { source } => {
111                 let source = this.hir.mirror(source);
112
113                 let source = unpack!(block = this.as_operand(block, scope, source));
114                 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
115             }
116             ExprKind::Use { source } => {
117                 let source = unpack!(block = this.as_operand(block, scope, source));
118                 block.and(Rvalue::Use(source))
119             }
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))
123             }
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))
127             }
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))
131             }
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))
135             }
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
140                 // of generating
141                 //
142                 //     let tmp1 = ...1;
143                 //     let tmp2 = ...2;
144                 //     dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
145                 //
146                 // we could just generate
147                 //
148                 //     dest.f = ...1;
149                 //     dest.g = ...2;
150                 //
151                 // The problem is that then we would need to:
152                 //
153                 // (a) have a more complex mechanism for handling
154                 //     partial cleanup;
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 = ();`.
162
163                 // first process the set of fields
164                 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
165                 let fields: Vec<_> =
166                     fields.into_iter()
167                           .map(|f| unpack!(block = this.as_operand(block, scope, f)))
168                           .collect();
169
170                 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
171             }
172             ExprKind::Tuple { fields } => { // see (*) above
173                 // first process the set of fields
174                 let fields: Vec<_> =
175                     fields.into_iter()
176                           .map(|f| unpack!(block = this.as_operand(block, scope, f)))
177                           .collect();
178
179                 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
180             }
181             ExprKind::Closure { closure_id, substs, upvars } => { // see (*) above
182                 let upvars =
183                     upvars.into_iter()
184                           .map(|upvar| unpack!(block = this.as_operand(block, scope, upvar)))
185                           .collect();
186                 block.and(Rvalue::Aggregate(box AggregateKind::Closure(closure_id, substs), upvars))
187             }
188             ExprKind::Adt {
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 };
193
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))))
198                     .collect();
199
200                 let field_names = this.hir.all_fields(adt_def, variant_index);
201
202                 let fields = if let Some(FruInfo { base, field_types }) = base {
203                     let base = unpack!(block = this.as_lvalue(block, base));
204
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))
213                         })
214                         .collect()
215                 } else {
216                     field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
217                 };
218
219                 let adt =
220                     box AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
221                 block.and(Rvalue::Aggregate(adt, fields))
222             }
223             ExprKind::Assign { .. } |
224             ExprKind::AssignOp { .. } => {
225                 block = unpack!(this.stmt_expr(block, expr));
226                 block.and(this.unit_rvalue())
227             }
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 { .. } |
240             ExprKind::SelfRef |
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,
250                     _ => true,
251                 });
252                 let operand = unpack!(block = this.as_operand(block, scope, expr));
253                 block.and(Rvalue::Use(operand))
254             }
255         }
256     }
257
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);
266
267             self.cfg.push_assign(block, source_info,
268                                  &result_value, Rvalue::CheckedBinaryOp(op,
269                                                                         lhs,
270                                                                         rhs));
271             let val_fld = Field::new(0);
272             let of_fld = Field::new(1);
273
274             let val = result_value.clone().field(val_fld, ty);
275             let of = result_value.field(of_fld, bool_ty);
276
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,
283                 _ => {
284                     bug!("MIR build_binary_op: {:?} is not checkable", op)
285                 }
286             });
287
288             block = self.assert(block, Operand::Consume(of), false,
289                                 AssertMessage::Math(err), span);
290
291             block.and(Rvalue::Use(Operand::Consume(val)))
292         } else {
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.
296
297                 let (zero_err, overflow_err) = if op == BinOp::Div {
298                     (ConstMathErr::DivisionByZero,
299                      ConstMathErr::Overflow(Op::Div))
300                 } else {
301                     (ConstMathErr::RemainderByZero,
302                      ConstMathErr::Overflow(Op::Rem))
303                 };
304
305                 // Check for / 0
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));
310
311                 block = self.assert(block, Operand::Consume(is_zero), false,
312                                     AssertMessage::Math(zero_err), span);
313
314                 // We only need to check for the overflow in one case:
315                 // MIN / -1, and only for signed values.
316                 if ty.is_signed() {
317                     let neg_1 = self.neg_1_literal(span, ty);
318                     let min = self.minval_literal(span, ty);
319
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);
323
324                     // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
325
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));
330
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));
335
336                     block = self.assert(block, Operand::Consume(of), false,
337                                         AssertMessage::Math(overflow_err), span);
338                 }
339             }
340
341             block.and(Rvalue::BinaryOp(op, lhs, rhs))
342         }
343     }
344
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 {
348             ty::TyInt(ity) => {
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),
355                     ast::IntTy::Is => {
356                         let int_ty = self.hir.tcx().sess.target.int_type;
357                         let val = ConstIsize::new(-1, int_ty).unwrap();
358                         ConstInt::Isize(val)
359                     }
360                 };
361
362                 Literal::Value { value: ConstVal::Integral(val) }
363             }
364             _ => {
365                 span_bug!(span, "Invalid type for neg_1_literal: `{:?}`", ty)
366             }
367         };
368
369         self.literal_operand(span, ty, literal)
370     }
371
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 {
375             ty::TyInt(ity) => {
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()),
382                     ast::IntTy::Is => {
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,
388                             _ => unreachable!()
389                         };
390                         let val = ConstIsize::new(min, int_ty).unwrap();
391                         ConstInt::Isize(val)
392                     }
393                 };
394
395                 Literal::Value { value: ConstVal::Integral(val) }
396             }
397             _ => {
398                 span_bug!(span, "Invalid type for minval_literal: `{:?}`", ty)
399             }
400         };
401
402         self.literal_operand(span, ty, literal)
403     }
404 }