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