]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/expr/as_rvalue.rs
Rollup merge of #41249 - GuillaumeGomez:rustdoc-render, r=steveklabnik,frewsxcv
[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 topmost_scope = self.topmost_scope(); // FIXME(#6393)
37         self.as_rvalue(block, Some(topmost_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={:?}, expr={:?})", block, 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                 this.cfg.push_assign(block, source_info, &result, Rvalue::Box(value.ty));
101                 this.in_scope(value_extents, block, |this| {
102                     // schedule a shallow free of that memory, lest we unwind:
103                     this.schedule_box_free(expr_span, value_extents, &result, value.ty);
104                     // initialize the box contents:
105                     unpack!(block = this.into(&result.clone().deref(), block, value));
106                     block.and(Rvalue::Use(Operand::Consume(result)))
107                 })
108             }
109             ExprKind::Cast { source } => {
110                 let source = this.hir.mirror(source);
111
112                 let source = unpack!(block = this.as_operand(block, scope, source));
113                 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
114             }
115             ExprKind::Use { source } => {
116                 let source = unpack!(block = this.as_operand(block, scope, source));
117                 block.and(Rvalue::Use(source))
118             }
119             ExprKind::ReifyFnPointer { source } => {
120                 let source = unpack!(block = this.as_operand(block, scope, source));
121                 block.and(Rvalue::Cast(CastKind::ReifyFnPointer, source, expr.ty))
122             }
123             ExprKind::UnsafeFnPointer { source } => {
124                 let source = unpack!(block = this.as_operand(block, scope, source));
125                 block.and(Rvalue::Cast(CastKind::UnsafeFnPointer, source, expr.ty))
126             }
127             ExprKind::ClosureFnPointer { source } => {
128                 let source = unpack!(block = this.as_operand(block, scope, source));
129                 block.and(Rvalue::Cast(CastKind::ClosureFnPointer, source, expr.ty))
130             }
131             ExprKind::Unsize { source } => {
132                 let source = unpack!(block = this.as_operand(block, scope, source));
133                 block.and(Rvalue::Cast(CastKind::Unsize, source, expr.ty))
134             }
135             ExprKind::Array { fields } => {
136                 // (*) We would (maybe) be closer to trans if we
137                 // handled this and other aggregate cases via
138                 // `into()`, not `as_rvalue` -- in that case, instead
139                 // of generating
140                 //
141                 //     let tmp1 = ...1;
142                 //     let tmp2 = ...2;
143                 //     dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
144                 //
145                 // we could just generate
146                 //
147                 //     dest.f = ...1;
148                 //     dest.g = ...2;
149                 //
150                 // The problem is that then we would need to:
151                 //
152                 // (a) have a more complex mechanism for handling
153                 //     partial cleanup;
154                 // (b) distinguish the case where the type `Foo` has a
155                 //     destructor, in which case creating an instance
156                 //     as a whole "arms" the destructor, and you can't
157                 //     write individual fields; and,
158                 // (c) handle the case where the type Foo has no
159                 //     fields. We don't want `let x: ();` to compile
160                 //     to the same MIR as `let x = ();`.
161
162                 // first process the set of fields
163                 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
164                 let fields: Vec<_> =
165                     fields.into_iter()
166                           .map(|f| unpack!(block = this.as_operand(block, scope, f)))
167                           .collect();
168
169                 block.and(Rvalue::Aggregate(AggregateKind::Array(el_ty), fields))
170             }
171             ExprKind::Tuple { fields } => { // see (*) above
172                 // first process the set of fields
173                 let fields: Vec<_> =
174                     fields.into_iter()
175                           .map(|f| unpack!(block = this.as_operand(block, scope, f)))
176                           .collect();
177
178                 block.and(Rvalue::Aggregate(AggregateKind::Tuple, fields))
179             }
180             ExprKind::Closure { closure_id, substs, upvars } => { // see (*) above
181                 let upvars =
182                     upvars.into_iter()
183                           .map(|upvar| unpack!(block = this.as_operand(block, scope, upvar)))
184                           .collect();
185                 block.and(Rvalue::Aggregate(AggregateKind::Closure(closure_id, substs), upvars))
186             }
187             ExprKind::Adt {
188                 adt_def, variant_index, substs, fields, base
189             } => { // see (*) above
190                 let is_union = adt_def.is_union();
191                 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
192
193                 // first process the set of fields that were provided
194                 // (evaluating them in order given by user)
195                 let fields_map: FxHashMap<_, _> = fields.into_iter()
196                     .map(|f| (f.name, unpack!(block = this.as_operand(block, scope, f.expr))))
197                     .collect();
198
199                 let field_names = this.hir.all_fields(adt_def, variant_index);
200
201                 let fields = if let Some(FruInfo { base, field_types }) = base {
202                     let base = unpack!(block = this.as_lvalue(block, base));
203
204                     // MIR does not natively support FRU, so for each
205                     // base-supplied field, generate an operand that
206                     // reads it from the base.
207                     field_names.into_iter()
208                         .zip(field_types.into_iter())
209                         .map(|(n, ty)| match fields_map.get(&n) {
210                             Some(v) => v.clone(),
211                             None => Operand::Consume(base.clone().field(n, ty))
212                         })
213                         .collect()
214                 } else {
215                     field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
216                 };
217
218                 let adt = AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
219                 block.and(Rvalue::Aggregate(adt, fields))
220             }
221             ExprKind::Assign { .. } |
222             ExprKind::AssignOp { .. } => {
223                 block = unpack!(this.stmt_expr(block, expr));
224                 block.and(this.unit_rvalue())
225             }
226             ExprKind::Literal { .. } |
227             ExprKind::Block { .. } |
228             ExprKind::Match { .. } |
229             ExprKind::If { .. } |
230             ExprKind::NeverToAny { .. } |
231             ExprKind::Loop { .. } |
232             ExprKind::LogicalOp { .. } |
233             ExprKind::Call { .. } |
234             ExprKind::Field { .. } |
235             ExprKind::Deref { .. } |
236             ExprKind::Index { .. } |
237             ExprKind::VarRef { .. } |
238             ExprKind::SelfRef |
239             ExprKind::Break { .. } |
240             ExprKind::Continue { .. } |
241             ExprKind::Return { .. } |
242             ExprKind::InlineAsm { .. } |
243             ExprKind::StaticRef { .. } => {
244                 // these do not have corresponding `Rvalue` variants,
245                 // so make an operand and then return that
246                 debug_assert!(match Category::of(&expr.kind) {
247                     Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
248                     _ => true,
249                 });
250                 let operand = unpack!(block = this.as_operand(block, scope, expr));
251                 block.and(Rvalue::Use(operand))
252             }
253         }
254     }
255
256     pub fn build_binary_op(&mut self, mut block: BasicBlock,
257                            op: BinOp, span: Span, ty: ty::Ty<'tcx>,
258                            lhs: Operand<'tcx>, rhs: Operand<'tcx>) -> BlockAnd<Rvalue<'tcx>> {
259         let source_info = self.source_info(span);
260         let bool_ty = self.hir.bool_ty();
261         if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
262             let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty], false);
263             let result_value = self.temp(result_tup, span);
264
265             self.cfg.push_assign(block, source_info,
266                                  &result_value, Rvalue::CheckedBinaryOp(op,
267                                                                         lhs,
268                                                                         rhs));
269             let val_fld = Field::new(0);
270             let of_fld = Field::new(1);
271
272             let val = result_value.clone().field(val_fld, ty);
273             let of = result_value.field(of_fld, bool_ty);
274
275             let err = ConstMathErr::Overflow(match op {
276                 BinOp::Add => Op::Add,
277                 BinOp::Sub => Op::Sub,
278                 BinOp::Mul => Op::Mul,
279                 BinOp::Shl => Op::Shl,
280                 BinOp::Shr => Op::Shr,
281                 _ => {
282                     bug!("MIR build_binary_op: {:?} is not checkable", op)
283                 }
284             });
285
286             block = self.assert(block, Operand::Consume(of), false,
287                                 AssertMessage::Math(err), span);
288
289             block.and(Rvalue::Use(Operand::Consume(val)))
290         } else {
291             if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
292                 // Checking division and remainder is more complex, since we 1. always check
293                 // and 2. there are two possible failure cases, divide-by-zero and overflow.
294
295                 let (zero_err, overflow_err) = if op == BinOp::Div {
296                     (ConstMathErr::DivisionByZero,
297                      ConstMathErr::Overflow(Op::Div))
298                 } else {
299                     (ConstMathErr::RemainderByZero,
300                      ConstMathErr::Overflow(Op::Rem))
301                 };
302
303                 // Check for / 0
304                 let is_zero = self.temp(bool_ty, span);
305                 let zero = self.zero_literal(span, ty);
306                 self.cfg.push_assign(block, source_info, &is_zero,
307                                      Rvalue::BinaryOp(BinOp::Eq, rhs.clone(), zero));
308
309                 block = self.assert(block, Operand::Consume(is_zero), false,
310                                     AssertMessage::Math(zero_err), span);
311
312                 // We only need to check for the overflow in one case:
313                 // MIN / -1, and only for signed values.
314                 if ty.is_signed() {
315                     let neg_1 = self.neg_1_literal(span, ty);
316                     let min = self.minval_literal(span, ty);
317
318                     let is_neg_1 = self.temp(bool_ty, span);
319                     let is_min   = self.temp(bool_ty, span);
320                     let of       = self.temp(bool_ty, span);
321
322                     // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
323
324                     self.cfg.push_assign(block, source_info, &is_neg_1,
325                                          Rvalue::BinaryOp(BinOp::Eq, rhs.clone(), neg_1));
326                     self.cfg.push_assign(block, source_info, &is_min,
327                                          Rvalue::BinaryOp(BinOp::Eq, lhs.clone(), min));
328
329                     let is_neg_1 = Operand::Consume(is_neg_1);
330                     let is_min = Operand::Consume(is_min);
331                     self.cfg.push_assign(block, source_info, &of,
332                                          Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min));
333
334                     block = self.assert(block, Operand::Consume(of), false,
335                                         AssertMessage::Math(overflow_err), span);
336                 }
337             }
338
339             block.and(Rvalue::BinaryOp(op, lhs, rhs))
340         }
341     }
342
343     // Helper to get a `-1` value of the appropriate type
344     fn neg_1_literal(&mut self, span: Span, ty: ty::Ty<'tcx>) -> Operand<'tcx> {
345         let literal = match ty.sty {
346             ty::TyInt(ity) => {
347                 let val = match ity {
348                     ast::IntTy::I8  => ConstInt::I8(-1),
349                     ast::IntTy::I16 => ConstInt::I16(-1),
350                     ast::IntTy::I32 => ConstInt::I32(-1),
351                     ast::IntTy::I64 => ConstInt::I64(-1),
352                     ast::IntTy::I128 => ConstInt::I128(-1),
353                     ast::IntTy::Is => {
354                         let int_ty = self.hir.tcx().sess.target.int_type;
355                         let val = ConstIsize::new(-1, int_ty).unwrap();
356                         ConstInt::Isize(val)
357                     }
358                 };
359
360                 Literal::Value { value: ConstVal::Integral(val) }
361             }
362             _ => {
363                 span_bug!(span, "Invalid type for neg_1_literal: `{:?}`", ty)
364             }
365         };
366
367         self.literal_operand(span, ty, literal)
368     }
369
370     // Helper to get the minimum value of the appropriate type
371     fn minval_literal(&mut self, span: Span, ty: ty::Ty<'tcx>) -> Operand<'tcx> {
372         let literal = match ty.sty {
373             ty::TyInt(ity) => {
374                 let val = match ity {
375                     ast::IntTy::I8  => ConstInt::I8(i8::min_value()),
376                     ast::IntTy::I16 => ConstInt::I16(i16::min_value()),
377                     ast::IntTy::I32 => ConstInt::I32(i32::min_value()),
378                     ast::IntTy::I64 => ConstInt::I64(i64::min_value()),
379                     ast::IntTy::I128 => ConstInt::I128(i128::min_value()),
380                     ast::IntTy::Is => {
381                         let int_ty = self.hir.tcx().sess.target.int_type;
382                         let min = match int_ty {
383                             ast::IntTy::I16 => std::i16::MIN as i64,
384                             ast::IntTy::I32 => std::i32::MIN as i64,
385                             ast::IntTy::I64 => std::i64::MIN,
386                             _ => unreachable!()
387                         };
388                         let val = ConstIsize::new(min, int_ty).unwrap();
389                         ConstInt::Isize(val)
390                     }
391                 };
392
393                 Literal::Value { value: ConstVal::Integral(val) }
394             }
395             _ => {
396                 span_bug!(span, "Invalid type for minval_literal: `{:?}`", ty)
397             }
398         };
399
400         self.literal_operand(span, ty, literal)
401     }
402 }