]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Skip ZST arguments
[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::Tagged { .. } => {
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::NicheFilling {
403                     dataful_variant,
404                     ref niche_variants,
405                     niche_start,
406                     ..
407                 } => {
408                     if *variant_index != dataful_variant {
409                         let niche = place.place_field(fx, mir::Field::new(0));
410                         //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
411                         let niche_value =
412                             ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
413                                 .wrapping_add(niche_start);
414                         // FIXME(eddyb) Check the actual primitive type here.
415                         let niche_llval = if niche_value == 0 {
416                             CValue::const_val(fx, niche.layout().ty, 0)
417                         } else {
418                             CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
419                         };
420                         niche.write_cvalue(fx, niche_llval);
421                     }
422                 }
423             }
424         }
425         StatementKind::Assign(to_place, rval) => {
426             let lval = trans_place(fx, to_place);
427             let dest_layout = lval.layout();
428             match &**rval {
429                 Rvalue::Use(operand) => {
430                     let val = trans_operand(fx, operand);
431                     lval.write_cvalue(fx, val);
432                 }
433                 Rvalue::Ref(_, _, place) => {
434                     let place = trans_place(fx, place);
435                     place.write_place_ref(fx, lval);
436                 }
437                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
438                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
439                     let lhs = trans_operand(fx, lhs);
440                     let rhs = trans_operand(fx, rhs);
441
442                     let res = match ty.sty {
443                         ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
444                         ty::Uint(_) => {
445                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
446                         }
447                         ty::Int(_) => {
448                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
449                         }
450                         ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
451                         ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
452                         ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
453                         ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
454                         _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
455                     };
456                     lval.write_cvalue(fx, res);
457                 }
458                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
459                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
460                     let lhs = trans_operand(fx, lhs);
461                     let rhs = trans_operand(fx, rhs);
462
463                     let res = match ty.sty {
464                         ty::Uint(_) => {
465                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
466                         }
467                         ty::Int(_) => {
468                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
469                         }
470                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
471                     };
472                     lval.write_cvalue(fx, res);
473                 }
474                 Rvalue::UnaryOp(un_op, operand) => {
475                     let operand = trans_operand(fx, operand);
476                     let layout = operand.layout();
477                     let val = operand.load_scalar(fx);
478                     let res = match un_op {
479                         UnOp::Not => {
480                             match layout.ty.sty {
481                                 ty::Bool => {
482                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
483                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
484                                     fx.bcx.ins().bint(types::I8, res)
485                                 }
486                                 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
487                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
488                             }
489                         }
490                         UnOp::Neg => match layout.ty.sty {
491                             ty::Int(_) => {
492                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
493                                 let zero = fx.bcx.ins().iconst(clif_ty, 0);
494                                 fx.bcx.ins().isub(zero, val)
495                             }
496                             ty::Float(_) => fx.bcx.ins().fneg(val),
497                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
498                         },
499                     };
500                     lval.write_cvalue(fx, CValue::ByVal(res, layout));
501                 }
502                 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
503                     let layout = fx.layout_of(ty);
504                     match fx
505                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
506                         .sty
507                     {
508                         ty::FnDef(def_id, substs) => {
509                             let func_ref = fx.get_function_ref(
510                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
511                                     .unwrap(),
512                             );
513                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
514                             lval.write_cvalue(fx, CValue::ByVal(func_addr, layout));
515                         }
516                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
517                     }
518                 }
519                 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty)
520                 | Rvalue::Cast(CastKind::MutToConstPointer, operand, ty) => {
521                     let operand = trans_operand(fx, operand);
522                     let layout = fx.layout_of(ty);
523                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
524                 }
525                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
526                     let operand = trans_operand(fx, operand);
527                     let from_ty = operand.layout().ty;
528
529                     fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
530                         ty
531                             .builtin_deref(true)
532                             .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
533                             .unwrap_or(false)
534                     }
535
536                     if is_fat_ptr(fx, from_ty) {
537                         if is_fat_ptr(fx, to_ty) {
538                             // fat-ptr -> fat-ptr
539                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
540                         } else {
541                             // fat-ptr -> thin-ptr
542                             let (ptr, _extra) = operand.load_scalar_pair(fx);
543                             lval.write_cvalue(fx, CValue::ByVal(ptr, dest_layout))
544                         }
545                     } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
546                         // enum -> discriminant value
547                         assert!(adt_def.is_enum());
548                         match to_ty.sty {
549                             ty::Uint(_) | ty::Int(_) => {},
550                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
551                         }
552
553                         // FIXME avoid forcing to stack
554                         let place =
555                             CPlace::Addr(operand.force_stack(fx), None, operand.layout());
556                         let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
557                         lval.write_cvalue(fx, discr);
558                     } else {
559                         let from_clif_ty = fx.clif_type(from_ty).unwrap();
560                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
561                         let from = operand.load_scalar(fx);
562
563                         let signed = match from_ty.sty {
564                             ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
565                             ty::Int(..) => true,
566                             ty::Float(..) => false, // `signed` is unused for floats
567                             _ => panic!("{}", from_ty),
568                         };
569
570                         let res = if from_clif_ty.is_int() && to_clif_ty.is_int() {
571                             // int-like -> int-like
572                             crate::common::clif_intcast(
573                                 fx,
574                                 from,
575                                 to_clif_ty,
576                                 signed,
577                             )
578                         } else if from_clif_ty.is_int() && to_clif_ty.is_float() {
579                             // int-like -> float
580                             // FIXME missing encoding for fcvt_from_sint.f32.i8
581                             let from = if from_clif_ty == types::I8 || from_clif_ty == types::I16 {
582                                 fx.bcx.ins().uextend(types::I32, from)
583                             } else {
584                                 from
585                             };
586                             if signed {
587                                 fx.bcx.ins().fcvt_from_sint(to_clif_ty, from)
588                             } else {
589                                 fx.bcx.ins().fcvt_from_uint(to_clif_ty, from)
590                             }
591                         } else if from_clif_ty.is_float() && to_clif_ty.is_int() {
592                             // float -> int-like
593                             let from = operand.load_scalar(fx);
594                             if signed {
595                                 fx.bcx.ins().fcvt_to_sint_sat(to_clif_ty, from)
596                             } else {
597                                 fx.bcx.ins().fcvt_to_uint_sat(to_clif_ty, from)
598                             }
599                         } else if from_clif_ty.is_float() && to_clif_ty.is_float() {
600                             // float -> float
601                             match (from_clif_ty, to_clif_ty) {
602                                 (types::F32, types::F64) => {
603                                     fx.bcx.ins().fpromote(types::F64, from)
604                                 }
605                                 (types::F64, types::F32) => {
606                                     fx.bcx.ins().fdemote(types::F32, from)
607                                 }
608                                 _ => from,
609                             }
610                         } else {
611                             unimpl!("rval misc {:?} {:?}", from_ty, to_ty)
612                         };
613                         lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
614                     }
615                 }
616                 Rvalue::Cast(CastKind::ClosureFnPointer, operand, _ty) => {
617                     let operand = trans_operand(fx, operand);
618                     match operand.layout().ty.sty {
619                         ty::Closure(def_id, substs) => {
620                             let instance = rustc_mir::monomorphize::resolve_closure(
621                                 fx.tcx,
622                                 def_id,
623                                 substs,
624                                 ty::ClosureKind::FnOnce,
625                             );
626                             let func_ref = fx.get_function_ref(instance);
627                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
628                             lval.write_cvalue(fx, CValue::ByVal(func_addr, lval.layout()));
629                         }
630                         _ => {
631                             bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
632                         }
633                     }
634                 }
635                 Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
636                     let operand = trans_operand(fx, operand);
637                     operand.unsize_value(fx, lval);
638                 }
639                 Rvalue::Discriminant(place) => {
640                     let place = trans_place(fx, place);
641                     let discr = trans_get_discriminant(fx, place, dest_layout);
642                     lval.write_cvalue(fx, discr);
643                 }
644                 Rvalue::Repeat(operand, times) => {
645                     let operand = trans_operand(fx, operand);
646                     for i in 0..*times {
647                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
648                         let to = lval.place_index(fx, index);
649                         to.write_cvalue(fx, operand);
650                     }
651                 }
652                 Rvalue::Len(place) => {
653                     let place = trans_place(fx, place);
654                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
655                     let len = codegen_array_len(fx, place);
656                     lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
657                 }
658                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
659                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
660
661                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
662                     let layout = fx.layout_of(content_ty);
663                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
664                     let llalign = fx
665                         .bcx
666                         .ins()
667                         .iconst(usize_type, layout.align.abi.bytes() as i64);
668                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
669
670                     // Allocate space:
671                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
672                         Ok(id) => id,
673                         Err(s) => {
674                             fx.tcx
675                                 .sess
676                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
677                         }
678                     };
679                     let instance = ty::Instance::mono(fx.tcx, def_id);
680                     let func_ref = fx.get_function_ref(instance);
681                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
682                     let ptr = fx.bcx.inst_results(call)[0];
683                     lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
684                 }
685                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
686                     assert!(lval
687                         .layout()
688                         .ty
689                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
690                     let ty_size = fx.layout_of(ty).size.bytes();
691                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
692                     lval.write_cvalue(fx, val);
693                 }
694                 Rvalue::Aggregate(kind, operands) => match **kind {
695                     AggregateKind::Array(_ty) => {
696                         for (i, operand) in operands.into_iter().enumerate() {
697                             let operand = trans_operand(fx, operand);
698                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
699                             let to = lval.place_index(fx, index);
700                             to.write_cvalue(fx, operand);
701                         }
702                     }
703                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
704                 },
705             }
706         }
707         StatementKind::StorageLive(_)
708         | StatementKind::StorageDead(_)
709         | StatementKind::Nop
710         | StatementKind::FakeRead(..)
711         | StatementKind::Retag { .. }
712         | StatementKind::AscribeUserType(..) => {}
713
714         StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
715     }
716 }
717
718 fn codegen_array_len<'a, 'tcx: 'a>(
719     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
720     place: CPlace<'tcx>,
721 ) -> Value {
722     match place.layout().ty.sty {
723         ty::Array(_elem_ty, len) => {
724             let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
725             fx.bcx.ins().iconst(fx.pointer_type, len)
726         }
727         ty::Slice(_elem_ty) => place
728             .to_addr_maybe_unsized(fx)
729             .1
730             .expect("Length metadata for slice place"),
731         _ => bug!("Rvalue::Len({:?})", place),
732     }
733 }
734
735 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
736     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
737     place: CPlace<'tcx>,
738     dest_layout: TyLayout<'tcx>,
739 ) -> CValue<'tcx> {
740     let layout = place.layout();
741
742     if layout.abi == layout::Abi::Uninhabited {
743         return trap_unreachable_ret_value(fx, dest_layout);
744     }
745     match layout.variants {
746         layout::Variants::Single { index } => {
747             let discr_val = layout
748                 .ty
749                 .ty_adt_def()
750                 .map_or(index.as_u32() as u128, |def| {
751                     def.discriminant_for_variant(fx.tcx, index).val
752                 });
753             return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
754         }
755         layout::Variants::Tagged { .. } | layout::Variants::NicheFilling { .. } => {}
756     }
757
758     let discr = place.place_field(fx, mir::Field::new(0)).to_cvalue(fx);
759     let discr_ty = discr.layout().ty;
760     let lldiscr = discr.load_scalar(fx);
761     match layout.variants {
762         layout::Variants::Single { .. } => bug!(),
763         layout::Variants::Tagged { ref tag, .. } => {
764             let signed = match tag.value {
765                 layout::Int(_, signed) => signed,
766                 _ => false,
767             };
768             let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
769             return CValue::ByVal(val, dest_layout);
770         }
771         layout::Variants::NicheFilling {
772             dataful_variant,
773             ref niche_variants,
774             niche_start,
775             ..
776         } => {
777             let niche_llty = fx.clif_type(discr_ty).unwrap();
778             let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
779             if niche_variants.start() == niche_variants.end() {
780                 let b = fx
781                     .bcx
782                     .ins()
783                     .icmp_imm(IntCC::Equal, lldiscr, niche_start as u64 as i64);
784                 let if_true = fx
785                     .bcx
786                     .ins()
787                     .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
788                 let if_false = fx
789                     .bcx
790                     .ins()
791                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
792                 let val = fx.bcx.ins().select(b, if_true, if_false);
793                 return CValue::ByVal(val, dest_layout);
794             } else {
795                 // Rebase from niche values to discriminant values.
796                 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
797                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
798                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
799                 let b = fx.bcx.ins().icmp_imm(
800                     IntCC::UnsignedLessThanOrEqual,
801                     lldiscr,
802                     niche_variants.end().as_u32() as i64,
803                 );
804                 let if_true =
805                     clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
806                 let if_false = fx
807                     .bcx
808                     .ins()
809                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
810                 let val = fx.bcx.ins().select(b, if_true, if_false);
811                 return CValue::ByVal(val, dest_layout);
812             }
813         }
814     }
815 }
816
817 macro_rules! binop_match {
818     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
819         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
820     };
821     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
822         assert_eq!($fx.tcx.types.bool, $ret_ty);
823         let ret_layout = $fx.layout_of($ret_ty);
824
825         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
826         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
827     }};
828     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
829         assert_eq!($fx.tcx.types.bool, $ret_ty);
830         let ret_layout = $fx.layout_of($ret_ty);
831         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
832         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
833     }};
834     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
835         $body
836     }};
837     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
838         let ret_layout = $fx.layout_of($ret_ty);
839         CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
840     }};
841     (
842         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
843         $(
844             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
845         )*
846     ) => {{
847         let lhs = $lhs.load_scalar($fx);
848         let rhs = $rhs.load_scalar($fx);
849         match ($bin_op, $signed) {
850             $(
851                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
852             )*
853         }
854     }}
855 }
856
857 fn trans_bool_binop<'a, 'tcx: 'a>(
858     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
859     bin_op: BinOp,
860     lhs: CValue<'tcx>,
861     rhs: CValue<'tcx>,
862     ty: Ty<'tcx>,
863 ) -> CValue<'tcx> {
864     let res = binop_match! {
865         fx, bin_op, false, lhs, rhs, ty, "bool";
866         Add (_) bug;
867         Sub (_) bug;
868         Mul (_) bug;
869         Div (_) bug;
870         Rem (_) bug;
871         BitXor (_) bxor;
872         BitAnd (_) band;
873         BitOr (_) bor;
874         Shl (_) bug;
875         Shr (_) bug;
876
877         Eq (_) icmp(Equal);
878         Lt (_) icmp(UnsignedLessThan);
879         Le (_) icmp(UnsignedLessThanOrEqual);
880         Ne (_) icmp(NotEqual);
881         Ge (_) icmp(UnsignedGreaterThanOrEqual);
882         Gt (_) icmp(UnsignedGreaterThan);
883
884         Offset (_) bug;
885     };
886
887     res
888 }
889
890 pub fn trans_int_binop<'a, 'tcx: 'a>(
891     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
892     bin_op: BinOp,
893     lhs: CValue<'tcx>,
894     rhs: CValue<'tcx>,
895     out_ty: Ty<'tcx>,
896     signed: bool,
897 ) -> CValue<'tcx> {
898     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
899         assert_eq!(
900             lhs.layout().ty,
901             rhs.layout().ty,
902             "int binop requires lhs and rhs of same type"
903         );
904     }
905     binop_match! {
906         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
907         Add (_) iadd;
908         Sub (_) isub;
909         Mul (_) imul;
910         Div (false) udiv;
911         Div (true) sdiv;
912         Rem (false) urem;
913         Rem (true) srem;
914         BitXor (_) bxor;
915         BitAnd (_) band;
916         BitOr (_) bor;
917         Shl (_) ishl;
918         Shr (false) ushr;
919         Shr (true) sshr;
920
921         Eq (_) icmp(Equal);
922         Lt (false) icmp(UnsignedLessThan);
923         Lt (true) icmp(SignedLessThan);
924         Le (false) icmp(UnsignedLessThanOrEqual);
925         Le (true) icmp(SignedLessThanOrEqual);
926         Ne (_) icmp(NotEqual);
927         Ge (false) icmp(UnsignedGreaterThanOrEqual);
928         Ge (true) icmp(SignedGreaterThanOrEqual);
929         Gt (false) icmp(UnsignedGreaterThan);
930         Gt (true) icmp(SignedGreaterThan);
931
932         Offset (_) bug;
933     }
934 }
935
936 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
937     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
938     bin_op: BinOp,
939     in_lhs: CValue<'tcx>,
940     in_rhs: CValue<'tcx>,
941     out_ty: Ty<'tcx>,
942     signed: bool,
943 ) -> CValue<'tcx> {
944     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
945         assert_eq!(
946             in_lhs.layout().ty,
947             in_rhs.layout().ty,
948             "checked int binop requires lhs and rhs of same type"
949         );
950     }
951
952     let lhs = in_lhs.load_scalar(fx);
953     let rhs = in_rhs.load_scalar(fx);
954     let res = match bin_op {
955         BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
956         BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
957         BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
958         BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
959         BinOp::Shr => {
960             if !signed {
961                 fx.bcx.ins().ushr(lhs, rhs)
962             } else {
963                 fx.bcx.ins().sshr(lhs, rhs)
964             }
965         }
966         _ => bug!(
967             "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
968             bin_op,
969             in_lhs,
970             in_rhs
971         ),
972     };
973
974     // TODO: check for overflow
975     let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
976
977     let out_place = CPlace::new_stack_slot(fx, out_ty);
978     let out_layout = out_place.layout();
979     out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
980
981     out_place.to_cvalue(fx)
982 }
983
984 fn trans_float_binop<'a, 'tcx: 'a>(
985     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
986     bin_op: BinOp,
987     lhs: CValue<'tcx>,
988     rhs: CValue<'tcx>,
989     ty: Ty<'tcx>,
990 ) -> CValue<'tcx> {
991     let res = binop_match! {
992         fx, bin_op, false, lhs, rhs, ty, "float";
993         Add (_) fadd;
994         Sub (_) fsub;
995         Mul (_) fmul;
996         Div (_) fdiv;
997         Rem (_) custom(|| {
998             assert_eq!(lhs.layout().ty, ty);
999             assert_eq!(rhs.layout().ty, ty);
1000             match ty.sty {
1001                 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
1002                 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
1003                 _ => bug!(),
1004             }
1005         });
1006         BitXor (_) bxor;
1007         BitAnd (_) band;
1008         BitOr (_) bor;
1009         Shl (_) bug;
1010         Shr (_) bug;
1011
1012         Eq (_) fcmp(Equal);
1013         Lt (_) fcmp(LessThan);
1014         Le (_) fcmp(LessThanOrEqual);
1015         Ne (_) fcmp(NotEqual);
1016         Ge (_) fcmp(GreaterThanOrEqual);
1017         Gt (_) fcmp(GreaterThan);
1018
1019         Offset (_) bug;
1020     };
1021
1022     res
1023 }
1024
1025 fn trans_char_binop<'a, 'tcx: 'a>(
1026     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1027     bin_op: BinOp,
1028     lhs: CValue<'tcx>,
1029     rhs: CValue<'tcx>,
1030     ty: Ty<'tcx>,
1031 ) -> CValue<'tcx> {
1032     let res = binop_match! {
1033         fx, bin_op, false, lhs, rhs, ty, "char";
1034         Add (_) bug;
1035         Sub (_) bug;
1036         Mul (_) bug;
1037         Div (_) bug;
1038         Rem (_) bug;
1039         BitXor (_) bug;
1040         BitAnd (_) bug;
1041         BitOr (_) bug;
1042         Shl (_) bug;
1043         Shr (_) bug;
1044
1045         Eq (_) icmp(Equal);
1046         Lt (_) icmp(UnsignedLessThan);
1047         Le (_) icmp(UnsignedLessThanOrEqual);
1048         Ne (_) icmp(NotEqual);
1049         Ge (_) icmp(UnsignedGreaterThanOrEqual);
1050         Gt (_) icmp(UnsignedGreaterThan);
1051
1052         Offset (_) bug;
1053     };
1054
1055     res
1056 }
1057
1058 fn trans_ptr_binop<'a, 'tcx: 'a>(
1059     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1060     bin_op: BinOp,
1061     lhs: CValue<'tcx>,
1062     rhs: CValue<'tcx>,
1063     ret_ty: Ty<'tcx>,
1064 ) -> CValue<'tcx> {
1065     let not_fat = match lhs.layout().ty.sty {
1066         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1067             ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1068         }
1069         ty::FnPtr(..) => true,
1070         _ => bug!("trans_ptr_binop on non ptr"),
1071     };
1072     if not_fat {
1073         if let BinOp::Offset = bin_op {
1074             let (base, offset) = (lhs, rhs.load_scalar(fx));
1075             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1076             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1077             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1078             let base_val = base.load_scalar(fx);
1079             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1080             return CValue::ByVal(res, base.layout());
1081         }
1082
1083         binop_match! {
1084             fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1085             Add (_) bug;
1086             Sub (_) bug;
1087             Mul (_) bug;
1088             Div (_) bug;
1089             Rem (_) bug;
1090             BitXor (_) bug;
1091             BitAnd (_) bug;
1092             BitOr (_) bug;
1093             Shl (_) bug;
1094             Shr (_) bug;
1095
1096             Eq (_) icmp(Equal);
1097             Lt (_) icmp(UnsignedLessThan);
1098             Le (_) icmp(UnsignedLessThanOrEqual);
1099             Ne (_) icmp(NotEqual);
1100             Ge (_) icmp(UnsignedGreaterThanOrEqual);
1101             Gt (_) icmp(UnsignedGreaterThan);
1102
1103             Offset (_) bug; // Handled above
1104         }
1105     } else {
1106         let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1107         let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1108         let res = match bin_op {
1109             BinOp::Eq => {
1110                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1111                 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1112                 fx.bcx.ins().band(ptr_eq, extra_eq)
1113             }
1114             BinOp::Ne => {
1115                 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1116                 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1117                 fx.bcx.ins().bor(ptr_ne, extra_ne)
1118             }
1119             _ => unimplemented!(
1120                 "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1121                 bin_op
1122             ),
1123         };
1124
1125         assert_eq!(fx.tcx.types.bool, ret_ty);
1126         let ret_layout = fx.layout_of(ret_ty);
1127         CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1128     }
1129 }
1130
1131 pub fn trans_place<'a, 'tcx: 'a>(
1132     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1133     place: &Place<'tcx>,
1134 ) -> CPlace<'tcx> {
1135     match place {
1136         Place::Base(base) => match base {
1137             PlaceBase::Local(local) => fx.get_local_place(*local),
1138             PlaceBase::Promoted(data) => crate::constant::trans_promoted(fx, data.0, data.1),
1139             PlaceBase::Static(static_) => crate::constant::codegen_static_ref(fx, static_),
1140         }
1141         Place::Projection(projection) => {
1142             let base = trans_place(fx, &projection.base);
1143             match projection.elem {
1144                 ProjectionElem::Deref => base.place_deref(fx),
1145                 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1146                 ProjectionElem::Index(local) => {
1147                     let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1148                     base.place_index(fx, index)
1149                 }
1150                 ProjectionElem::ConstantIndex {
1151                     offset,
1152                     min_length: _,
1153                     from_end,
1154                 } => {
1155                     let index = if !from_end {
1156                         fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1157                     } else {
1158                         let len = codegen_array_len(fx, base);
1159                         fx.bcx.ins().iadd_imm(len, -(offset as i64))
1160                     };
1161                     base.place_index(fx, index)
1162                 }
1163                 ProjectionElem::Subslice { from, to } => {
1164                     // These indices are generated by slice patterns.
1165                     // slice[from:-to] in Python terms.
1166
1167                     match base.layout().ty.sty {
1168                         ty::Array(elem_ty, len) => {
1169                             let elem_layout = fx.layout_of(elem_ty);
1170                             let ptr = base.to_addr(fx);
1171                             let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx);
1172                             CPlace::Addr(
1173                                 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1174                                 None,
1175                                 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1176                             )
1177                         }
1178                         ty::Slice(elem_ty) => {
1179                             let elem_layout = fx.layout_of(elem_ty);
1180                             let (ptr, len) = base.to_addr_maybe_unsized(fx);
1181                             let len = len.unwrap();
1182                             CPlace::Addr(
1183                                 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1184                                 Some(fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64))),
1185                                 base.layout(),
1186                             )
1187                         }
1188                         _ => unreachable!(),
1189                     }
1190                 }
1191                 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1192             }
1193         }
1194     }
1195 }
1196
1197 pub fn trans_operand<'a, 'tcx>(
1198     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1199     operand: &Operand<'tcx>,
1200 ) -> CValue<'tcx> {
1201     match operand {
1202         Operand::Move(place) | Operand::Copy(place) => {
1203             let cplace = trans_place(fx, place);
1204             cplace.to_cvalue(fx)
1205         }
1206         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
1207     }
1208 }