]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Rustup to rustc 1.35.0-nightly (e3428db7c 2019-03-31)
[rust.git] / src / base.rs
1 use crate::prelude::*;
2
3 struct PrintOnPanic<F: Fn() -> String>(F);
4 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
5     fn drop(&mut self) {
6         if ::std::thread::panicking() {
7             println!("{}", (self.0)());
8         }
9     }
10 }
11
12 pub fn trans_mono_item<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
13     cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
14     mono_item: MonoItem<'tcx>,
15     linkage: Linkage,
16 ) {
17     let tcx = cx.tcx;
18     match mono_item {
19         MonoItem::Fn(inst) => {
20             let _inst_guard =
21                 PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).as_str()));
22             debug_assert!(!inst.substs.needs_infer());
23             let _mir_guard = PrintOnPanic(|| {
24                 match inst.def {
25                     InstanceDef::Item(_)
26                     | InstanceDef::DropGlue(_, _)
27                     | InstanceDef::Virtual(_, _)
28                         if inst.def_id().krate == LOCAL_CRATE =>
29                     {
30                         let mut mir = ::std::io::Cursor::new(Vec::new());
31                         crate::rustc_mir::util::write_mir_pretty(
32                             tcx,
33                             Some(inst.def_id()),
34                             &mut mir,
35                         )
36                         .unwrap();
37                         String::from_utf8(mir.into_inner()).unwrap()
38                     }
39                     _ => {
40                         // FIXME fix write_mir_pretty for these instances
41                         format!("{:#?}", tcx.instance_mir(inst.def))
42                     }
43                 }
44             });
45
46             trans_fn(cx, inst, linkage);
47         }
48         MonoItem::Static(def_id) => {
49             crate::constant::codegen_static(&mut cx.ccx, def_id);
50         }
51         MonoItem::GlobalAsm(node_id) => tcx
52             .sess
53             .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
54     }
55 }
56
57 fn trans_fn<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
58     cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
59     instance: Instance<'tcx>,
60     linkage: Linkage,
61 ) {
62     let tcx = cx.tcx;
63
64     // Step 1. Get mir
65     let mir = tcx.instance_mir(instance.def);
66
67     // Step 2. Check fn sig for u128 and i128 and replace those functions with a trap.
68     {
69         // FIXME implement u128 and i128 support
70
71         // Step 2a. Check sig for u128 and i128
72         let fn_sig = tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &instance.fn_sig(tcx));
73
74         struct UI128Visitor<'a, 'tcx: 'a>(TyCtxt<'a, 'tcx, 'tcx>, bool);
75
76         impl<'a, 'tcx: 'a> rustc::ty::fold::TypeVisitor<'tcx> for UI128Visitor<'a, 'tcx> {
77             fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
78                 if t.sty == self.0.types.u128.sty || t.sty == self.0.types.i128.sty {
79                     self.1 = true;
80                     return false; // stop visiting
81                 }
82
83                 t.super_visit_with(self)
84             }
85         }
86
87         let mut visitor = UI128Visitor(tcx, false);
88         fn_sig.visit_with(&mut visitor);
89
90         // Step 2b. If found replace function with a trap.
91         if visitor.1 {
92             tcx.sess.warn("u128 and i128 are not yet supported. \
93             Functions using these as args will be replaced with a trap.");
94
95             // Step 2b1. Declare function with fake signature
96             let sig = Signature {
97                 params: vec![AbiParam::new(types::INVALID)],
98                 returns: vec![],
99                 call_conv: CallConv::Fast,
100             };
101             let name = tcx.symbol_name(instance).as_str();
102             let func_id = cx.module.declare_function(&*name, linkage, &sig).unwrap();
103
104             // Step 2b2. Create trapping function
105             let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
106             let mut func_ctx = FunctionBuilderContext::new();
107             let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
108             let start_ebb = bcx.create_ebb();
109             bcx.append_ebb_params_for_function_params(start_ebb);
110             bcx.switch_to_block(start_ebb);
111             crate::trap::trap_unreachable(&mut bcx);
112             bcx.seal_all_blocks();
113             bcx.finalize();
114
115             // Step 2b3. Define function
116             cx.caches.context.func = func;
117             cx.module
118                 .define_function(func_id, &mut cx.caches.context)
119                 .unwrap();
120             cx.caches.context.clear();
121             return;
122         }
123     }
124
125     // Step 3. Declare function
126     let (name, sig) = get_function_name_and_sig(tcx, instance, false);
127     let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
128     let mut debug_context = cx
129         .debug_context
130         .as_mut()
131         .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
132
133     // Step 4. Make FunctionBuilder
134     let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
135     let mut func_ctx = FunctionBuilderContext::new();
136     let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
137
138     // Step 5. Predefine ebb's
139     let start_ebb = bcx.create_ebb();
140     let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
141     for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
142         ebb_map.insert(bb, bcx.create_ebb());
143     }
144
145     // Step 6. Make FunctionCx
146     let pointer_type = cx.module.target_config().pointer_type();
147     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
148
149     let mut fx = FunctionCx {
150         tcx,
151         module: cx.module,
152         pointer_type,
153
154         instance,
155         mir,
156
157         bcx,
158         ebb_map,
159         local_map: HashMap::new(),
160
161         clif_comments,
162         constants: &mut cx.ccx,
163         caches: &mut cx.caches,
164         source_info_set: indexmap::IndexSet::new(),
165     };
166
167     // Step 7. Codegen function
168     with_unimpl_span(fx.mir.span, || {
169         crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
170         codegen_fn_content(&mut fx);
171     });
172     let source_info_set = fx.source_info_set.clone();
173
174     // Step 8. Write function to file for debugging
175     #[cfg(debug_assertions)]
176     fx.write_clif_file();
177
178     // Step 9. Verify function
179     verify_func(tcx, fx.clif_comments, &func);
180
181     // Step 10. Define function
182     cx.caches.context.func = func;
183     cx.module
184         .define_function(func_id, &mut cx.caches.context)
185         .unwrap();
186
187     // Step 11. Define debuginfo for function
188     let context = &cx.caches.context;
189     let isa = cx.module.isa();
190     debug_context
191         .as_mut()
192         .map(|x| x.define(tcx, context, isa, &source_info_set));
193
194     // Step 12. Clear context to make it usable for the next function
195     cx.caches.context.clear();
196 }
197
198 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
199     let flags = settings::Flags::new(settings::builder());
200     match ::cranelift::codegen::verify_function(&func, &flags) {
201         Ok(_) => {}
202         Err(err) => {
203             tcx.sess.err(&format!("{:?}", err));
204             let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
205                 &func,
206                 None,
207                 Some(Box::new(&writer)),
208                 err,
209             );
210             tcx.sess
211                 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
212         }
213     }
214 }
215
216 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
217     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
218         if bb_data.is_cleanup {
219             // Unwinding after panicking is not supported
220             continue;
221         }
222
223         let ebb = fx.get_ebb(bb);
224         fx.bcx.switch_to_block(ebb);
225
226         fx.bcx.ins().nop();
227         for stmt in &bb_data.statements {
228             fx.set_debug_loc(stmt.source_info);
229             trans_stmt(fx, ebb, stmt);
230         }
231
232         #[cfg(debug_assertions)]
233         {
234             let mut terminator_head = "\n".to_string();
235             bb_data
236                 .terminator()
237                 .kind
238                 .fmt_head(&mut terminator_head)
239                 .unwrap();
240             let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
241             fx.add_comment(inst, terminator_head);
242         }
243
244         fx.set_debug_loc(bb_data.terminator().source_info);
245
246         match &bb_data.terminator().kind {
247             TerminatorKind::Goto { target } => {
248                 let ebb = fx.get_ebb(*target);
249                 fx.bcx.ins().jump(ebb, &[]);
250             }
251             TerminatorKind::Return => {
252                 crate::abi::codegen_return(fx);
253             }
254             TerminatorKind::Assert {
255                 cond,
256                 expected,
257                 msg: _,
258                 target,
259                 cleanup: _,
260             } => {
261                 let cond = trans_operand(fx, cond).load_scalar(fx);
262                 // TODO HACK brz/brnz for i8/i16 is not yet implemented
263                 let cond = fx.bcx.ins().uextend(types::I32, cond);
264                 let target = fx.get_ebb(*target);
265                 if *expected {
266                     fx.bcx.ins().brnz(cond, target, &[]);
267                 } else {
268                     fx.bcx.ins().brz(cond, target, &[]);
269                 };
270                 trap_panic(&mut fx.bcx);
271             }
272
273             TerminatorKind::SwitchInt {
274                 discr,
275                 switch_ty: _,
276                 values,
277                 targets,
278             } => {
279                 let discr = trans_operand(fx, discr).load_scalar(fx);
280                 let mut switch = ::cranelift::frontend::Switch::new();
281                 for (i, value) in values.iter().enumerate() {
282                     let ebb = fx.get_ebb(targets[i]);
283                     switch.set_entry(*value as u64, ebb);
284                 }
285                 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
286                 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
287             }
288             TerminatorKind::Call {
289                 func,
290                 args,
291                 destination,
292                 cleanup: _,
293                 from_hir_call: _,
294             } => {
295                 crate::abi::codegen_terminator_call(fx, func, args, destination);
296             }
297             TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Unreachable => {
298                 trap_unreachable(&mut fx.bcx);
299             }
300             TerminatorKind::Yield { .. }
301             | TerminatorKind::FalseEdges { .. }
302             | TerminatorKind::FalseUnwind { .. }
303             | TerminatorKind::DropAndReplace { .. }
304             | TerminatorKind::GeneratorDrop => {
305                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
306             }
307             TerminatorKind::Drop {
308                 location,
309                 target,
310                 unwind: _,
311             } => {
312                 let ty = location.ty(fx.mir, fx.tcx).to_ty(fx.tcx);
313                 let ty = fx.monomorphize(&ty);
314                 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
315
316                 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
317                     // we don't actually need to drop anything
318                 } else {
319                     let drop_place = trans_place(fx, location);
320                     let drop_fn_ty = drop_fn.ty(fx.tcx);
321                     match ty.sty {
322                         ty::Dynamic(..) => {
323                             crate::abi::codegen_drop(fx, drop_place, drop_fn_ty);
324                         }
325                         _ => {
326                             let arg_place = CPlace::new_stack_slot(
327                                 fx,
328                                 fx.tcx.mk_ref(
329                                     &ty::RegionKind::ReErased,
330                                     TypeAndMut {
331                                         ty,
332                                         mutbl: crate::rustc::hir::Mutability::MutMutable,
333                                     },
334                                 ),
335                             );
336                             drop_place.write_place_ref(fx, arg_place);
337                             let arg_value = arg_place.to_cvalue(fx);
338                             crate::abi::codegen_call_inner(
339                                 fx,
340                                 None,
341                                 drop_fn_ty,
342                                 vec![arg_value],
343                                 None,
344                             );
345                         }
346                     }
347                 }
348
349                 let target_ebb = fx.get_ebb(*target);
350                 fx.bcx.ins().jump(target_ebb, &[]);
351             }
352         };
353     }
354
355     fx.bcx.seal_all_blocks();
356     fx.bcx.finalize();
357 }
358
359 fn trans_stmt<'a, 'tcx: 'a>(
360     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
361     cur_ebb: Ebb,
362     stmt: &Statement<'tcx>,
363 ) {
364     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
365
366     fx.set_debug_loc(stmt.source_info);
367
368     #[cfg(debug_assertions)]
369     match &stmt.kind {
370         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
371         _ => {
372             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
373             fx.add_comment(inst, format!("{:?}", stmt));
374         }
375     }
376
377     match &stmt.kind {
378         StatementKind::SetDiscriminant {
379             place,
380             variant_index,
381         } => {
382             let place = trans_place(fx, place);
383             let layout = place.layout();
384             if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
385                 return;
386             }
387             match layout.variants {
388                 layout::Variants::Single { index } => {
389                     assert_eq!(index, *variant_index);
390                 }
391                 layout::Variants::Multiple { discr_kind: layout::DiscriminantKind::Tag, .. } => {
392                     let ptr = place.place_field(fx, mir::Field::new(0));
393                     let to = layout
394                         .ty
395                         .ty_adt_def()
396                         .unwrap()
397                         .discriminant_for_variant(fx.tcx, *variant_index)
398                         .val;
399                     let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
400                     ptr.write_cvalue(fx, discr);
401                 }
402                 layout::Variants::Multiple {
403                     discr_kind: layout::DiscriminantKind::Niche {
404                         dataful_variant,
405                         ref niche_variants,
406                         niche_start,
407                     },
408                     ..
409                 } => {
410                     if *variant_index != dataful_variant {
411                         let niche = place.place_field(fx, mir::Field::new(0));
412                         //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
413                         let niche_value =
414                             ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
415                                 .wrapping_add(niche_start);
416                         // FIXME(eddyb) Check the actual primitive type here.
417                         let niche_llval = if niche_value == 0 {
418                             CValue::const_val(fx, niche.layout().ty, 0)
419                         } else {
420                             CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
421                         };
422                         niche.write_cvalue(fx, niche_llval);
423                     }
424                 }
425             }
426         }
427         StatementKind::Assign(to_place, rval) => {
428             let lval = trans_place(fx, to_place);
429             let dest_layout = lval.layout();
430             match &**rval {
431                 Rvalue::Use(operand) => {
432                     let val = trans_operand(fx, operand);
433                     lval.write_cvalue(fx, val);
434                 }
435                 Rvalue::Ref(_, _, place) => {
436                     let place = trans_place(fx, place);
437                     place.write_place_ref(fx, lval);
438                 }
439                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
440                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
441                     let lhs = trans_operand(fx, lhs);
442                     let rhs = trans_operand(fx, rhs);
443
444                     let res = match ty.sty {
445                         ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
446                         ty::Uint(_) => {
447                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
448                         }
449                         ty::Int(_) => {
450                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
451                         }
452                         ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
453                         ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
454                         ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
455                         ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
456                         _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
457                     };
458                     lval.write_cvalue(fx, res);
459                 }
460                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
461                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
462                     let lhs = trans_operand(fx, lhs);
463                     let rhs = trans_operand(fx, rhs);
464
465                     let res = match ty.sty {
466                         ty::Uint(_) => {
467                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
468                         }
469                         ty::Int(_) => {
470                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
471                         }
472                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
473                     };
474                     lval.write_cvalue(fx, res);
475                 }
476                 Rvalue::UnaryOp(un_op, operand) => {
477                     let operand = trans_operand(fx, operand);
478                     let layout = operand.layout();
479                     let val = operand.load_scalar(fx);
480                     let res = match un_op {
481                         UnOp::Not => {
482                             match layout.ty.sty {
483                                 ty::Bool => {
484                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
485                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
486                                     fx.bcx.ins().bint(types::I8, res)
487                                 }
488                                 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
489                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
490                             }
491                         }
492                         UnOp::Neg => match layout.ty.sty {
493                             ty::Int(_) => {
494                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
495                                 let zero = fx.bcx.ins().iconst(clif_ty, 0);
496                                 fx.bcx.ins().isub(zero, val)
497                             }
498                             ty::Float(_) => fx.bcx.ins().fneg(val),
499                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
500                         },
501                     };
502                     lval.write_cvalue(fx, CValue::ByVal(res, layout));
503                 }
504                 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
505                     let layout = fx.layout_of(ty);
506                     match fx
507                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
508                         .sty
509                     {
510                         ty::FnDef(def_id, substs) => {
511                             let func_ref = fx.get_function_ref(
512                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
513                                     .unwrap(),
514                             );
515                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
516                             lval.write_cvalue(fx, CValue::ByVal(func_addr, layout));
517                         }
518                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
519                     }
520                 }
521                 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty)
522                 | Rvalue::Cast(CastKind::MutToConstPointer, operand, ty) => {
523                     let operand = trans_operand(fx, operand);
524                     let layout = fx.layout_of(ty);
525                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
526                 }
527                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
528                     let operand = trans_operand(fx, operand);
529                     let from_ty = operand.layout().ty;
530
531                     fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
532                         ty
533                             .builtin_deref(true)
534                             .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
535                             .unwrap_or(false)
536                     }
537
538                     if is_fat_ptr(fx, from_ty) {
539                         if is_fat_ptr(fx, to_ty) {
540                             // fat-ptr -> fat-ptr
541                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
542                         } else {
543                             // fat-ptr -> thin-ptr
544                             let (ptr, _extra) = operand.load_scalar_pair(fx);
545                             lval.write_cvalue(fx, CValue::ByVal(ptr, dest_layout))
546                         }
547                     } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
548                         // enum -> discriminant value
549                         assert!(adt_def.is_enum());
550                         match to_ty.sty {
551                             ty::Uint(_) | ty::Int(_) => {},
552                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
553                         }
554
555                         // FIXME avoid forcing to stack
556                         let place =
557                             CPlace::Addr(operand.force_stack(fx), None, operand.layout());
558                         let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
559                         lval.write_cvalue(fx, discr);
560                     } else {
561                         let from_clif_ty = fx.clif_type(from_ty).unwrap();
562                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
563                         let from = operand.load_scalar(fx);
564
565                         let signed = match from_ty.sty {
566                             ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
567                             ty::Int(..) => true,
568                             ty::Float(..) => false, // `signed` is unused for floats
569                             _ => panic!("{}", from_ty),
570                         };
571
572                         let res = if from_clif_ty.is_int() && to_clif_ty.is_int() {
573                             // int-like -> int-like
574                             crate::common::clif_intcast(
575                                 fx,
576                                 from,
577                                 to_clif_ty,
578                                 signed,
579                             )
580                         } else if from_clif_ty.is_int() && to_clif_ty.is_float() {
581                             // int-like -> float
582                             // FIXME missing encoding for fcvt_from_sint.f32.i8
583                             let from = if from_clif_ty == types::I8 || from_clif_ty == types::I16 {
584                                 fx.bcx.ins().uextend(types::I32, from)
585                             } else {
586                                 from
587                             };
588                             if signed {
589                                 fx.bcx.ins().fcvt_from_sint(to_clif_ty, from)
590                             } else {
591                                 fx.bcx.ins().fcvt_from_uint(to_clif_ty, from)
592                             }
593                         } else if from_clif_ty.is_float() && to_clif_ty.is_int() {
594                             // float -> int-like
595                             let from = operand.load_scalar(fx);
596                             if signed {
597                                 fx.bcx.ins().fcvt_to_sint_sat(to_clif_ty, from)
598                             } else {
599                                 fx.bcx.ins().fcvt_to_uint_sat(to_clif_ty, from)
600                             }
601                         } else if from_clif_ty.is_float() && to_clif_ty.is_float() {
602                             // float -> float
603                             match (from_clif_ty, to_clif_ty) {
604                                 (types::F32, types::F64) => {
605                                     fx.bcx.ins().fpromote(types::F64, from)
606                                 }
607                                 (types::F64, types::F32) => {
608                                     fx.bcx.ins().fdemote(types::F32, from)
609                                 }
610                                 _ => from,
611                             }
612                         } else {
613                             unimpl!("rval misc {:?} {:?}", from_ty, to_ty)
614                         };
615                         lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
616                     }
617                 }
618                 Rvalue::Cast(CastKind::ClosureFnPointer(_), operand, _ty) => {
619                     let operand = trans_operand(fx, operand);
620                     match operand.layout().ty.sty {
621                         ty::Closure(def_id, substs) => {
622                             let instance = rustc_mir::monomorphize::resolve_closure(
623                                 fx.tcx,
624                                 def_id,
625                                 substs,
626                                 ty::ClosureKind::FnOnce,
627                             );
628                             let func_ref = fx.get_function_ref(instance);
629                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
630                             lval.write_cvalue(fx, CValue::ByVal(func_addr, lval.layout()));
631                         }
632                         _ => {
633                             bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
634                         }
635                     }
636                 }
637                 Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
638                     let operand = trans_operand(fx, operand);
639                     operand.unsize_value(fx, lval);
640                 }
641                 Rvalue::Discriminant(place) => {
642                     let place = trans_place(fx, place);
643                     let discr = trans_get_discriminant(fx, place, dest_layout);
644                     lval.write_cvalue(fx, discr);
645                 }
646                 Rvalue::Repeat(operand, times) => {
647                     let operand = trans_operand(fx, operand);
648                     for i in 0..*times {
649                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
650                         let to = lval.place_index(fx, index);
651                         to.write_cvalue(fx, operand);
652                     }
653                 }
654                 Rvalue::Len(place) => {
655                     let place = trans_place(fx, place);
656                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
657                     let len = codegen_array_len(fx, place);
658                     lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
659                 }
660                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
661                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
662
663                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
664                     let layout = fx.layout_of(content_ty);
665                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
666                     let llalign = fx
667                         .bcx
668                         .ins()
669                         .iconst(usize_type, layout.align.abi.bytes() as i64);
670                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
671
672                     // Allocate space:
673                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
674                         Ok(id) => id,
675                         Err(s) => {
676                             fx.tcx
677                                 .sess
678                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
679                         }
680                     };
681                     let instance = ty::Instance::mono(fx.tcx, def_id);
682                     let func_ref = fx.get_function_ref(instance);
683                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
684                     let ptr = fx.bcx.inst_results(call)[0];
685                     lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
686                 }
687                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
688                     assert!(lval
689                         .layout()
690                         .ty
691                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
692                     let ty_size = fx.layout_of(ty).size.bytes();
693                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
694                     lval.write_cvalue(fx, val);
695                 }
696                 Rvalue::Aggregate(kind, operands) => match **kind {
697                     AggregateKind::Array(_ty) => {
698                         for (i, operand) in operands.into_iter().enumerate() {
699                             let operand = trans_operand(fx, operand);
700                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
701                             let to = lval.place_index(fx, index);
702                             to.write_cvalue(fx, operand);
703                         }
704                     }
705                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
706                 },
707             }
708         }
709         StatementKind::StorageLive(_)
710         | StatementKind::StorageDead(_)
711         | StatementKind::Nop
712         | StatementKind::FakeRead(..)
713         | StatementKind::Retag { .. }
714         | StatementKind::AscribeUserType(..) => {}
715
716         StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
717     }
718 }
719
720 fn codegen_array_len<'a, 'tcx: 'a>(
721     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
722     place: CPlace<'tcx>,
723 ) -> Value {
724     match place.layout().ty.sty {
725         ty::Array(_elem_ty, len) => {
726             let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
727             fx.bcx.ins().iconst(fx.pointer_type, len)
728         }
729         ty::Slice(_elem_ty) => place
730             .to_addr_maybe_unsized(fx)
731             .1
732             .expect("Length metadata for slice place"),
733         _ => bug!("Rvalue::Len({:?})", place),
734     }
735 }
736
737 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
738     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
739     place: CPlace<'tcx>,
740     dest_layout: TyLayout<'tcx>,
741 ) -> CValue<'tcx> {
742     let layout = place.layout();
743
744     if layout.abi == layout::Abi::Uninhabited {
745         return trap_unreachable_ret_value(fx, dest_layout);
746     }
747
748     let (discr_scalar, discr_kind) = match &layout.variants {
749         layout::Variants::Single { index } => {
750             let discr_val = layout
751                 .ty
752                 .ty_adt_def()
753                 .map_or(index.as_u32() as u128, |def| {
754                     def.discriminant_for_variant(fx.tcx, *index).val
755                 });
756             return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
757         }
758         layout::Variants::Multiple { discr, discr_kind, variants: _ } => (discr, discr_kind),
759     };
760
761     let discr = place.place_field(fx, mir::Field::new(0)).to_cvalue(fx);
762     let discr_ty = discr.layout().ty;
763     let lldiscr = discr.load_scalar(fx);
764     match discr_kind {
765         layout::DiscriminantKind::Tag => {
766             let signed = match discr_scalar.value {
767                 layout::Int(_, signed) => signed,
768                 _ => false,
769             };
770             let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
771             return CValue::ByVal(val, dest_layout);
772         }
773         layout::DiscriminantKind::Niche {
774             dataful_variant,
775             ref niche_variants,
776             niche_start,
777         } => {
778             let niche_llty = fx.clif_type(discr_ty).unwrap();
779             let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
780             if niche_variants.start() == niche_variants.end() {
781                 let b = fx
782                     .bcx
783                     .ins()
784                     .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
785                 let if_true = fx
786                     .bcx
787                     .ins()
788                     .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
789                 let if_false = fx
790                     .bcx
791                     .ins()
792                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
793                 let val = fx.bcx.ins().select(b, if_true, if_false);
794                 return CValue::ByVal(val, dest_layout);
795             } else {
796                 // Rebase from niche values to discriminant values.
797                 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
798                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
799                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
800                 let b = fx.bcx.ins().icmp_imm(
801                     IntCC::UnsignedLessThanOrEqual,
802                     lldiscr,
803                     niche_variants.end().as_u32() as i64,
804                 );
805                 let if_true =
806                     clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
807                 let if_false = fx
808                     .bcx
809                     .ins()
810                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
811                 let val = fx.bcx.ins().select(b, if_true, if_false);
812                 return CValue::ByVal(val, dest_layout);
813             }
814         }
815     }
816 }
817
818 macro_rules! binop_match {
819     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
820         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
821     };
822     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
823         assert_eq!($fx.tcx.types.bool, $ret_ty);
824         let ret_layout = $fx.layout_of($ret_ty);
825
826         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
827         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
828     }};
829     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
830         assert_eq!($fx.tcx.types.bool, $ret_ty);
831         let ret_layout = $fx.layout_of($ret_ty);
832         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
833         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
834     }};
835     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
836         $body
837     }};
838     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
839         let ret_layout = $fx.layout_of($ret_ty);
840         CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
841     }};
842     (
843         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
844         $(
845             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
846         )*
847     ) => {{
848         let lhs = $lhs.load_scalar($fx);
849         let rhs = $rhs.load_scalar($fx);
850         match ($bin_op, $signed) {
851             $(
852                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
853             )*
854         }
855     }}
856 }
857
858 fn trans_bool_binop<'a, 'tcx: 'a>(
859     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
860     bin_op: BinOp,
861     lhs: CValue<'tcx>,
862     rhs: CValue<'tcx>,
863     ty: Ty<'tcx>,
864 ) -> CValue<'tcx> {
865     let res = binop_match! {
866         fx, bin_op, false, lhs, rhs, ty, "bool";
867         Add (_) bug;
868         Sub (_) bug;
869         Mul (_) bug;
870         Div (_) bug;
871         Rem (_) bug;
872         BitXor (_) bxor;
873         BitAnd (_) band;
874         BitOr (_) bor;
875         Shl (_) bug;
876         Shr (_) bug;
877
878         Eq (_) icmp(Equal);
879         Lt (_) icmp(UnsignedLessThan);
880         Le (_) icmp(UnsignedLessThanOrEqual);
881         Ne (_) icmp(NotEqual);
882         Ge (_) icmp(UnsignedGreaterThanOrEqual);
883         Gt (_) icmp(UnsignedGreaterThan);
884
885         Offset (_) bug;
886     };
887
888     res
889 }
890
891 pub fn trans_int_binop<'a, 'tcx: 'a>(
892     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
893     bin_op: BinOp,
894     lhs: CValue<'tcx>,
895     rhs: CValue<'tcx>,
896     out_ty: Ty<'tcx>,
897     signed: bool,
898 ) -> CValue<'tcx> {
899     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
900         assert_eq!(
901             lhs.layout().ty,
902             rhs.layout().ty,
903             "int binop requires lhs and rhs of same type"
904         );
905     }
906     binop_match! {
907         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
908         Add (_) iadd;
909         Sub (_) isub;
910         Mul (_) imul;
911         Div (false) udiv;
912         Div (true) sdiv;
913         Rem (false) urem;
914         Rem (true) srem;
915         BitXor (_) bxor;
916         BitAnd (_) band;
917         BitOr (_) bor;
918         Shl (_) ishl;
919         Shr (false) ushr;
920         Shr (true) sshr;
921
922         Eq (_) icmp(Equal);
923         Lt (false) icmp(UnsignedLessThan);
924         Lt (true) icmp(SignedLessThan);
925         Le (false) icmp(UnsignedLessThanOrEqual);
926         Le (true) icmp(SignedLessThanOrEqual);
927         Ne (_) icmp(NotEqual);
928         Ge (false) icmp(UnsignedGreaterThanOrEqual);
929         Ge (true) icmp(SignedGreaterThanOrEqual);
930         Gt (false) icmp(UnsignedGreaterThan);
931         Gt (true) icmp(SignedGreaterThan);
932
933         Offset (_) bug;
934     }
935 }
936
937 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
938     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
939     bin_op: BinOp,
940     in_lhs: CValue<'tcx>,
941     in_rhs: CValue<'tcx>,
942     out_ty: Ty<'tcx>,
943     signed: bool,
944 ) -> CValue<'tcx> {
945     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
946         assert_eq!(
947             in_lhs.layout().ty,
948             in_rhs.layout().ty,
949             "checked int binop requires lhs and rhs of same type"
950         );
951     }
952
953     let lhs = in_lhs.load_scalar(fx);
954     let rhs = in_rhs.load_scalar(fx);
955     let res = match bin_op {
956         BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
957         BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
958         BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
959         BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
960         BinOp::Shr => {
961             if !signed {
962                 fx.bcx.ins().ushr(lhs, rhs)
963             } else {
964                 fx.bcx.ins().sshr(lhs, rhs)
965             }
966         }
967         _ => bug!(
968             "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
969             bin_op,
970             in_lhs,
971             in_rhs
972         ),
973     };
974
975     // TODO: check for overflow
976     let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
977
978     let out_place = CPlace::new_stack_slot(fx, out_ty);
979     let out_layout = out_place.layout();
980     out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
981
982     out_place.to_cvalue(fx)
983 }
984
985 fn trans_float_binop<'a, 'tcx: 'a>(
986     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
987     bin_op: BinOp,
988     lhs: CValue<'tcx>,
989     rhs: CValue<'tcx>,
990     ty: Ty<'tcx>,
991 ) -> CValue<'tcx> {
992     let res = binop_match! {
993         fx, bin_op, false, lhs, rhs, ty, "float";
994         Add (_) fadd;
995         Sub (_) fsub;
996         Mul (_) fmul;
997         Div (_) fdiv;
998         Rem (_) custom(|| {
999             assert_eq!(lhs.layout().ty, ty);
1000             assert_eq!(rhs.layout().ty, ty);
1001             match ty.sty {
1002                 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
1003                 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
1004                 _ => bug!(),
1005             }
1006         });
1007         BitXor (_) bxor;
1008         BitAnd (_) band;
1009         BitOr (_) bor;
1010         Shl (_) bug;
1011         Shr (_) bug;
1012
1013         Eq (_) fcmp(Equal);
1014         Lt (_) fcmp(LessThan);
1015         Le (_) fcmp(LessThanOrEqual);
1016         Ne (_) fcmp(NotEqual);
1017         Ge (_) fcmp(GreaterThanOrEqual);
1018         Gt (_) fcmp(GreaterThan);
1019
1020         Offset (_) bug;
1021     };
1022
1023     res
1024 }
1025
1026 fn trans_char_binop<'a, 'tcx: 'a>(
1027     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1028     bin_op: BinOp,
1029     lhs: CValue<'tcx>,
1030     rhs: CValue<'tcx>,
1031     ty: Ty<'tcx>,
1032 ) -> CValue<'tcx> {
1033     let res = binop_match! {
1034         fx, bin_op, false, lhs, rhs, ty, "char";
1035         Add (_) bug;
1036         Sub (_) bug;
1037         Mul (_) bug;
1038         Div (_) bug;
1039         Rem (_) bug;
1040         BitXor (_) bug;
1041         BitAnd (_) bug;
1042         BitOr (_) bug;
1043         Shl (_) bug;
1044         Shr (_) bug;
1045
1046         Eq (_) icmp(Equal);
1047         Lt (_) icmp(UnsignedLessThan);
1048         Le (_) icmp(UnsignedLessThanOrEqual);
1049         Ne (_) icmp(NotEqual);
1050         Ge (_) icmp(UnsignedGreaterThanOrEqual);
1051         Gt (_) icmp(UnsignedGreaterThan);
1052
1053         Offset (_) bug;
1054     };
1055
1056     res
1057 }
1058
1059 fn trans_ptr_binop<'a, 'tcx: 'a>(
1060     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1061     bin_op: BinOp,
1062     lhs: CValue<'tcx>,
1063     rhs: CValue<'tcx>,
1064     ret_ty: Ty<'tcx>,
1065 ) -> CValue<'tcx> {
1066     let not_fat = match lhs.layout().ty.sty {
1067         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1068             ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1069         }
1070         ty::FnPtr(..) => true,
1071         _ => bug!("trans_ptr_binop on non ptr"),
1072     };
1073     if not_fat {
1074         if let BinOp::Offset = bin_op {
1075             let (base, offset) = (lhs, rhs.load_scalar(fx));
1076             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1077             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1078             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1079             let base_val = base.load_scalar(fx);
1080             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1081             return CValue::ByVal(res, base.layout());
1082         }
1083
1084         binop_match! {
1085             fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1086             Add (_) bug;
1087             Sub (_) bug;
1088             Mul (_) bug;
1089             Div (_) bug;
1090             Rem (_) bug;
1091             BitXor (_) bug;
1092             BitAnd (_) bug;
1093             BitOr (_) bug;
1094             Shl (_) bug;
1095             Shr (_) bug;
1096
1097             Eq (_) icmp(Equal);
1098             Lt (_) icmp(UnsignedLessThan);
1099             Le (_) icmp(UnsignedLessThanOrEqual);
1100             Ne (_) icmp(NotEqual);
1101             Ge (_) icmp(UnsignedGreaterThanOrEqual);
1102             Gt (_) icmp(UnsignedGreaterThan);
1103
1104             Offset (_) bug; // Handled above
1105         }
1106     } else {
1107         let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1108         let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1109         let res = match bin_op {
1110             BinOp::Eq => {
1111                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1112                 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1113                 fx.bcx.ins().band(ptr_eq, extra_eq)
1114             }
1115             BinOp::Ne => {
1116                 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1117                 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1118                 fx.bcx.ins().bor(ptr_ne, extra_ne)
1119             }
1120             _ => unimplemented!(
1121                 "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1122                 bin_op
1123             ),
1124         };
1125
1126         assert_eq!(fx.tcx.types.bool, ret_ty);
1127         let ret_layout = fx.layout_of(ret_ty);
1128         CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1129     }
1130 }
1131
1132 pub fn trans_place<'a, 'tcx: 'a>(
1133     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1134     place: &Place<'tcx>,
1135 ) -> CPlace<'tcx> {
1136     match place {
1137         Place::Base(base) => match base {
1138             PlaceBase::Local(local) => fx.get_local_place(*local),
1139             PlaceBase::Static(static_) => match static_.kind {
1140                 StaticKind::Static(def_id) => {
1141                     crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1142                 }
1143                 StaticKind::Promoted(promoted) => {
1144                     crate::constant::trans_promoted(fx, promoted, static_.ty)
1145                 }
1146             }
1147         }
1148         Place::Projection(projection) => {
1149             let base = trans_place(fx, &projection.base);
1150             match projection.elem {
1151                 ProjectionElem::Deref => base.place_deref(fx),
1152                 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1153                 ProjectionElem::Index(local) => {
1154                     let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1155                     base.place_index(fx, index)
1156                 }
1157                 ProjectionElem::ConstantIndex {
1158                     offset,
1159                     min_length: _,
1160                     from_end,
1161                 } => {
1162                     let index = if !from_end {
1163                         fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1164                     } else {
1165                         let len = codegen_array_len(fx, base);
1166                         fx.bcx.ins().iadd_imm(len, -(offset as i64))
1167                     };
1168                     base.place_index(fx, index)
1169                 }
1170                 ProjectionElem::Subslice { from, to } => {
1171                     // These indices are generated by slice patterns.
1172                     // slice[from:-to] in Python terms.
1173
1174                     match base.layout().ty.sty {
1175                         ty::Array(elem_ty, len) => {
1176                             let elem_layout = fx.layout_of(elem_ty);
1177                             let ptr = base.to_addr(fx);
1178                             let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx);
1179                             CPlace::Addr(
1180                                 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1181                                 None,
1182                                 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1183                             )
1184                         }
1185                         ty::Slice(elem_ty) => {
1186                             let elem_layout = fx.layout_of(elem_ty);
1187                             let (ptr, len) = base.to_addr_maybe_unsized(fx);
1188                             let len = len.unwrap();
1189                             CPlace::Addr(
1190                                 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1191                                 Some(fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64))),
1192                                 base.layout(),
1193                             )
1194                         }
1195                         _ => unreachable!(),
1196                     }
1197                 }
1198                 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1199             }
1200         }
1201     }
1202 }
1203
1204 pub fn trans_operand<'a, 'tcx>(
1205     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1206     operand: &Operand<'tcx>,
1207 ) -> CValue<'tcx> {
1208     match operand {
1209         Operand::Move(place) | Operand::Copy(place) => {
1210             let cplace = trans_place(fx, place);
1211             cplace.to_cvalue(fx)
1212         }
1213         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
1214     }
1215 }