]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Fix foreign type handling
[rust.git] / src / base.rs
1 use rustc::ty::adjustment::PointerCast;
2
3 use crate::prelude::*;
4
5 pub fn trans_fn<'clif, 'tcx, B: Backend + 'static>(
6     cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
7     instance: Instance<'tcx>,
8     linkage: Linkage,
9 ) {
10     let tcx = cx.tcx;
11
12     let mir = tcx.instance_mir(instance.def);
13
14     // Declare function
15     let (name, sig) = get_function_name_and_sig(tcx, instance, false);
16     let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
17     let mut debug_context = cx
18         .debug_context
19         .as_mut()
20         .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
21
22     // FIXME reuse Function and FunctionBuilder between multiple trans_fn calls
23     let mut bcx = FunctionBuilder::new(Function::with_name_signature(ExternalName::user(0, 0), sig));
24
25     // Predefine ebb's
26     let start_ebb = bcx.create_ebb();
27     let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
28     for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
29         ebb_map.insert(bb, bcx.create_ebb());
30     }
31
32     // Make FunctionCx
33     let pointer_type = cx.module.target_config().pointer_type();
34     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
35
36     let mut fx = FunctionCx {
37         tcx,
38         module: cx.module,
39         pointer_type,
40
41         instance,
42         mir,
43
44         bcx,
45         ebb_map,
46         local_map: HashMap::new(),
47
48         clif_comments,
49         constants_cx: &mut cx.constants_cx,
50         caches: &mut cx.caches,
51         source_info_set: indexmap::IndexSet::new(),
52     };
53
54     with_unimpl_span(fx.mir.span, || {
55         crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
56         codegen_fn_content(&mut fx);
57     });
58
59     fx.bcx.seal_all_blocks();
60     let func = fx.bcx.finalize();
61
62     // Recover all necessary data from fx, before accessing func will prevent future access to it.
63     let instance = fx.instance;
64     let clif_comments = fx.clif_comments;
65     let source_info_set = fx.source_info_set;
66
67     #[cfg(debug_assertions)]
68     crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
69
70     // Verify function
71     verify_func(tcx, &clif_comments, &func);
72
73     // Define function
74     let context = &mut cx.caches.context;
75     context.func = func;
76     cx.module.define_function(func_id, context).unwrap();
77
78     let value_ranges = context
79         .build_value_labels_ranges(cx.module.isa())
80         .expect("value location ranges");
81
82     // Write optimized function to file for debugging
83     #[cfg(debug_assertions)]
84     crate::pretty_clif::write_clif_file(
85         cx.tcx,
86         "opt",
87         instance,
88         &context.func,
89         &clif_comments,
90         Some(&value_ranges),
91     );
92
93     // Define debuginfo for function
94     let isa = cx.module.isa();
95     debug_context
96         .as_mut()
97         .map(|x| x.define(tcx, context, isa, &source_info_set));
98
99     // Clear context to make it usable for the next function
100     context.clear();
101 }
102
103 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
104     let flags = settings::Flags::new(settings::builder());
105     match ::cranelift::codegen::verify_function(&func, &flags) {
106         Ok(_) => {}
107         Err(err) => {
108             tcx.sess.err(&format!("{:?}", err));
109             let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
110                 &func,
111                 None,
112                 Some(Box::new(writer)),
113                 err,
114             );
115             tcx.sess
116                 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
117         }
118     }
119 }
120
121 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
122     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
123         if bb_data.is_cleanup {
124             // Unwinding after panicking is not supported
125             continue;
126         }
127
128         let ebb = fx.get_ebb(bb);
129         fx.bcx.switch_to_block(ebb);
130
131         fx.bcx.ins().nop();
132         for stmt in &bb_data.statements {
133             fx.set_debug_loc(stmt.source_info);
134             trans_stmt(fx, ebb, stmt);
135         }
136
137         #[cfg(debug_assertions)]
138         {
139             let mut terminator_head = "\n".to_string();
140             bb_data
141                 .terminator()
142                 .kind
143                 .fmt_head(&mut terminator_head)
144                 .unwrap();
145             let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
146             fx.add_comment(inst, terminator_head);
147         }
148
149         fx.set_debug_loc(bb_data.terminator().source_info);
150
151         match &bb_data.terminator().kind {
152             TerminatorKind::Goto { target } => {
153                 let ebb = fx.get_ebb(*target);
154                 fx.bcx.ins().jump(ebb, &[]);
155             }
156             TerminatorKind::Return => {
157                 crate::abi::codegen_return(fx);
158             }
159             TerminatorKind::Assert {
160                 cond,
161                 expected,
162                 msg,
163                 target,
164                 cleanup: _,
165             } => {
166                 if !fx.tcx.sess.overflow_checks() {
167                     if let mir::interpret::PanicInfo::OverflowNeg = *msg {
168                         let target = fx.get_ebb(*target);
169                         fx.bcx.ins().jump(target, &[]);
170                         continue;
171                     }
172                 }
173                 let cond = trans_operand(fx, cond).load_scalar(fx);
174                 // TODO HACK brz/brnz for i8/i16 is not yet implemented
175                 let cond = fx.bcx.ins().uextend(types::I32, cond);
176                 let target = fx.get_ebb(*target);
177                 if *expected {
178                     fx.bcx.ins().brnz(cond, target, &[]);
179                 } else {
180                     fx.bcx.ins().brz(cond, target, &[]);
181                 };
182                 trap_panic(
183                     fx,
184                     format!(
185                         "[panic] Assert {:?} at {:?} failed.",
186                         msg,
187                         bb_data.terminator().source_info.span
188                     ),
189                 );
190             }
191
192             TerminatorKind::SwitchInt {
193                 discr,
194                 switch_ty: _,
195                 values,
196                 targets,
197             } => {
198                 let discr = trans_operand(fx, discr).load_scalar(fx);
199                 let mut switch = ::cranelift::frontend::Switch::new();
200                 for (i, value) in values.iter().enumerate() {
201                     let ebb = fx.get_ebb(targets[i]);
202                     switch.set_entry(*value as u64, ebb);
203                 }
204                 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
205                 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
206             }
207             TerminatorKind::Call {
208                 func,
209                 args,
210                 destination,
211                 cleanup: _,
212                 from_hir_call: _,
213             } => {
214                 crate::abi::codegen_terminator_call(fx, func, args, destination);
215             }
216             TerminatorKind::Resume | TerminatorKind::Abort => {
217                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
218             }
219             TerminatorKind::Unreachable => {
220                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
221             }
222             TerminatorKind::Yield { .. }
223             | TerminatorKind::FalseEdges { .. }
224             | TerminatorKind::FalseUnwind { .. }
225             | TerminatorKind::DropAndReplace { .. }
226             | TerminatorKind::GeneratorDrop => {
227                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
228             }
229             TerminatorKind::Drop {
230                 location,
231                 target,
232                 unwind: _,
233             } => {
234                 let drop_place = trans_place(fx, location);
235                 crate::abi::codegen_drop(fx, drop_place);
236
237                 let target_ebb = fx.get_ebb(*target);
238                 fx.bcx.ins().jump(target_ebb, &[]);
239             }
240         };
241     }
242 }
243
244 fn trans_stmt<'tcx>(
245     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
246     cur_ebb: Ebb,
247     stmt: &Statement<'tcx>,
248 ) {
249     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
250
251     fx.set_debug_loc(stmt.source_info);
252
253     #[cfg(debug_assertions)]
254     match &stmt.kind {
255         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
256         _ => {
257             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
258             fx.add_comment(inst, format!("{:?}", stmt));
259         }
260     }
261
262     match &stmt.kind {
263         StatementKind::SetDiscriminant {
264             place,
265             variant_index,
266         } => {
267             let place = trans_place(fx, place);
268             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
269         }
270         StatementKind::Assign(to_place_and_rval) => {
271             let lval = trans_place(fx, &to_place_and_rval.0);
272             let dest_layout = lval.layout();
273             match &to_place_and_rval.1 {
274                 Rvalue::Use(operand) => {
275                     let val = trans_operand(fx, operand);
276                     lval.write_cvalue(fx, val);
277                 }
278                 Rvalue::Ref(_, _, place) => {
279                     let place = trans_place(fx, place);
280                     place.write_place_ref(fx, lval);
281                 }
282                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
283                     let lhs = trans_operand(fx, lhs);
284                     let rhs = trans_operand(fx, rhs);
285
286                     let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
287                     lval.write_cvalue(fx, res);
288                 }
289                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
290                     let lhs = trans_operand(fx, lhs);
291                     let rhs = trans_operand(fx, rhs);
292
293                     let res = if !fx.tcx.sess.overflow_checks() {
294                         let val =
295                             crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
296                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
297                         CValue::by_val_pair(val, is_overflow, lval.layout())
298                     } else {
299                         crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
300                     };
301
302                     lval.write_cvalue(fx, res);
303                 }
304                 Rvalue::UnaryOp(un_op, operand) => {
305                     let operand = trans_operand(fx, operand);
306                     let layout = operand.layout();
307                     let val = operand.load_scalar(fx);
308                     let res = match un_op {
309                         UnOp::Not => {
310                             match layout.ty.sty {
311                                 ty::Bool => {
312                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
313                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
314                                     fx.bcx.ins().bint(types::I8, res)
315                                 }
316                                 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
317                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
318                             }
319                         }
320                         UnOp::Neg => match layout.ty.sty {
321                             ty::Int(_) => {
322                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
323                                 if clif_ty == types::I128 {
324                                     // FIXME implement it
325                                     crate::trap::trap_unreachable_ret_value(
326                                         fx,
327                                         layout,
328                                         "i128 neg is not yet supported",
329                                     )
330                                     .load_scalar(fx)
331                                 } else {
332                                     let zero = fx.bcx.ins().iconst(clif_ty, 0);
333                                     fx.bcx.ins().isub(zero, val)
334                                 }
335                             }
336                             ty::Float(_) => fx.bcx.ins().fneg(val),
337                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
338                         },
339                     };
340                     lval.write_cvalue(fx, CValue::by_val(res, layout));
341                 }
342                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
343                     let layout = fx.layout_of(ty);
344                     match fx
345                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
346                         .sty
347                     {
348                         ty::FnDef(def_id, substs) => {
349                             let func_ref = fx.get_function_ref(
350                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
351                                     .unwrap(),
352                             );
353                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
354                             lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
355                         }
356                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
357                     }
358                 }
359                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
360                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
361                     let operand = trans_operand(fx, operand);
362                     let layout = fx.layout_of(ty);
363                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
364                 }
365                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
366                     let operand = trans_operand(fx, operand);
367                     let from_ty = operand.layout().ty;
368                     let to_ty = fx.monomorphize(to_ty);
369
370                     fn is_fat_ptr<'tcx>(
371                         fx: &FunctionCx<'_, 'tcx, impl Backend>,
372                         ty: Ty<'tcx>,
373                     ) -> bool {
374                         ty.builtin_deref(true)
375                             .map(
376                                 |ty::TypeAndMut {
377                                      ty: pointee_ty,
378                                      mutbl: _,
379                                  }| has_ptr_meta(fx.tcx, pointee_ty),
380                             )
381                             .unwrap_or(false)
382                     }
383
384                     if is_fat_ptr(fx, from_ty) {
385                         if is_fat_ptr(fx, to_ty) {
386                             // fat-ptr -> fat-ptr
387                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
388                         } else {
389                             // fat-ptr -> thin-ptr
390                             let (ptr, _extra) = operand.load_scalar_pair(fx);
391                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
392                         }
393                     } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
394                         // enum -> discriminant value
395                         assert!(adt_def.is_enum());
396                         match to_ty.sty {
397                             ty::Uint(_) | ty::Int(_) => {}
398                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
399                         }
400
401                         let discr = crate::discriminant::codegen_get_discriminant(
402                             fx,
403                             operand,
404                             fx.layout_of(to_ty),
405                         );
406                         lval.write_cvalue(fx, discr);
407                     } else {
408                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
409                         let from = operand.load_scalar(fx);
410
411                         let res = clif_int_or_float_cast(
412                             fx,
413                             from,
414                             type_sign(from_ty),
415                             to_clif_ty,
416                             type_sign(to_ty),
417                         );
418                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
419                     }
420                 }
421                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
422                     let operand = trans_operand(fx, operand);
423                     match operand.layout().ty.sty {
424                         ty::Closure(def_id, substs) => {
425                             let instance = Instance::resolve_closure(
426                                 fx.tcx,
427                                 def_id,
428                                 substs,
429                                 ty::ClosureKind::FnOnce,
430                             );
431                             let func_ref = fx.get_function_ref(instance);
432                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
433                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
434                         }
435                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
436                     }
437                 }
438                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
439                     let operand = trans_operand(fx, operand);
440                     operand.unsize_value(fx, lval);
441                 }
442                 Rvalue::Discriminant(place) => {
443                     let place = trans_place(fx, place);
444                     let value = place.to_cvalue(fx);
445                     let discr =
446                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
447                     lval.write_cvalue(fx, discr);
448                 }
449                 Rvalue::Repeat(operand, times) => {
450                     let operand = trans_operand(fx, operand);
451                     for i in 0..*times {
452                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
453                         let to = lval.place_index(fx, index);
454                         to.write_cvalue(fx, operand);
455                     }
456                 }
457                 Rvalue::Len(place) => {
458                     let place = trans_place(fx, place);
459                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
460                     let len = codegen_array_len(fx, place);
461                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
462                 }
463                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
464                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
465
466                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
467                     let layout = fx.layout_of(content_ty);
468                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
469                     let llalign = fx
470                         .bcx
471                         .ins()
472                         .iconst(usize_type, layout.align.abi.bytes() as i64);
473                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
474
475                     // Allocate space:
476                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
477                         Ok(id) => id,
478                         Err(s) => {
479                             fx.tcx
480                                 .sess
481                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
482                         }
483                     };
484                     let instance = ty::Instance::mono(fx.tcx, def_id);
485                     let func_ref = fx.get_function_ref(instance);
486                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
487                     let ptr = fx.bcx.inst_results(call)[0];
488                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
489                 }
490                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
491                     assert!(lval
492                         .layout()
493                         .ty
494                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
495                     let ty_size = fx.layout_of(ty).size.bytes();
496                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
497                     lval.write_cvalue(fx, val);
498                 }
499                 Rvalue::Aggregate(kind, operands) => match **kind {
500                     AggregateKind::Array(_ty) => {
501                         for (i, operand) in operands.into_iter().enumerate() {
502                             let operand = trans_operand(fx, operand);
503                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
504                             let to = lval.place_index(fx, index);
505                             to.write_cvalue(fx, operand);
506                         }
507                     }
508                     _ => unimpl!("shouldn't exist at trans {:?}", to_place_and_rval.1),
509                 },
510             }
511         }
512         StatementKind::StorageLive(_)
513         | StatementKind::StorageDead(_)
514         | StatementKind::Nop
515         | StatementKind::FakeRead(..)
516         | StatementKind::Retag { .. }
517         | StatementKind::AscribeUserType(..) => {}
518
519         StatementKind::InlineAsm(asm) => {
520             use syntax::ast::Name;
521             let InlineAsm {
522                 asm,
523                 outputs: _,
524                 inputs: _,
525             } = &**asm;
526             let rustc::hir::InlineAsm {
527                 asm: asm_code, // Name
528                 outputs,       // Vec<Name>
529                 inputs,        // Vec<Name>
530                 clobbers,      // Vec<Name>
531                 volatile,      // bool
532                 alignstack,    // bool
533                 dialect: _,    // syntax::ast::AsmDialect
534                 asm_str_style: _,
535             } = asm;
536             match &*asm_code.as_str() {
537                 "cpuid" | "cpuid\n" => {
538                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
539
540                     assert_eq!(outputs.len(), 4);
541                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
542                         .iter()
543                         .enumerate()
544                     {
545                         assert_eq!(&outputs[i].constraint.as_str(), c);
546                         assert!(!outputs[i].is_rw);
547                         assert!(!outputs[i].is_indirect);
548                     }
549
550                     assert_eq!(clobbers, &[Name::intern("rbx")]);
551
552                     assert!(!volatile);
553                     assert!(!alignstack);
554
555                     crate::trap::trap_unimplemented(
556                         fx,
557                         "__cpuid_count arch intrinsic is not supported",
558                     );
559                 }
560                 "xgetbv" => {
561                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
562
563                     assert_eq!(outputs.len(), 2);
564                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
565                         assert_eq!(&outputs[i].constraint.as_str(), c);
566                         assert!(!outputs[i].is_rw);
567                         assert!(!outputs[i].is_indirect);
568                     }
569
570                     assert_eq!(clobbers, &[]);
571
572                     assert!(!volatile);
573                     assert!(!alignstack);
574
575                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
576                 }
577                 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
578                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
579                 }
580                 _ => unimpl!("Inline assembly is not supported"),
581             }
582         }
583     }
584 }
585
586 fn codegen_array_len<'tcx>(
587     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
588     place: CPlace<'tcx>,
589 ) -> Value {
590     match place.layout().ty.sty {
591         ty::Array(_elem_ty, len) => {
592             let len = crate::constant::force_eval_const(fx, len)
593                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
594             fx.bcx.ins().iconst(fx.pointer_type, len)
595         }
596         ty::Slice(_elem_ty) => place
597             .to_addr_maybe_unsized(fx)
598             .1
599             .expect("Length metadata for slice place"),
600         _ => bug!("Rvalue::Len({:?})", place),
601     }
602 }
603
604 pub fn trans_place<'tcx>(
605     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
606     place: &Place<'tcx>,
607 ) -> CPlace<'tcx> {
608     let mut cplace = match &place.base {
609         PlaceBase::Local(local) => fx.get_local_place(*local),
610         PlaceBase::Static(static_) => match static_.kind {
611             StaticKind::Static => {
612                 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
613             }
614             StaticKind::Promoted(promoted, substs) => {
615                 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
616                 crate::constant::trans_promoted(fx, instance, promoted, static_.ty)
617             }
618         },
619     };
620
621     for elem in &*place.projection {
622         match *elem {
623             PlaceElem::Deref => {
624                 cplace = cplace.place_deref(fx);
625             }
626             PlaceElem::Field(field, _ty) => {
627                 cplace = cplace.place_field(fx, field);
628             }
629             PlaceElem::Index(local) => {
630                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
631                 cplace = cplace.place_index(fx, index);
632             }
633             PlaceElem::ConstantIndex {
634                 offset,
635                 min_length: _,
636                 from_end,
637             } => {
638                 let index = if !from_end {
639                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
640                 } else {
641                     let len = codegen_array_len(fx, cplace);
642                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
643                 };
644                 cplace = cplace.place_index(fx, index);
645             }
646             PlaceElem::Subslice { from, to } => {
647                 // These indices are generated by slice patterns.
648                 // slice[from:-to] in Python terms.
649
650                 match cplace.layout().ty.sty {
651                     ty::Array(elem_ty, len) => {
652                         let elem_layout = fx.layout_of(elem_ty);
653                         let ptr = cplace.to_addr(fx);
654                         let len = crate::constant::force_eval_const(fx, len)
655                             .eval_usize(fx.tcx, ParamEnv::reveal_all());
656                         cplace = CPlace::for_addr(
657                             fx.bcx
658                                 .ins()
659                                 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
660                             fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
661                         );
662                     }
663                     ty::Slice(elem_ty) => {
664                         let elem_layout = fx.layout_of(elem_ty);
665                         let (ptr, len) = cplace.to_addr_maybe_unsized(fx);
666                         let len = len.unwrap();
667                         cplace = CPlace::for_addr_with_extra(
668                             fx.bcx
669                                 .ins()
670                                 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
671                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
672                             cplace.layout(),
673                         );
674                     }
675                     _ => unreachable!(),
676                 }
677             }
678             PlaceElem::Downcast(_adt_def, variant) => {
679                 cplace = cplace.downcast_variant(fx, variant);
680             }
681         }
682     }
683
684     cplace
685 }
686
687 pub fn trans_operand<'tcx>(
688     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
689     operand: &Operand<'tcx>,
690 ) -> CValue<'tcx> {
691     match operand {
692         Operand::Move(place) | Operand::Copy(place) => {
693             let cplace = trans_place(fx, place);
694             cplace.to_cvalue(fx)
695         }
696         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
697     }
698 }