]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Rustup to rustc 1.41.0-nightly (6d77e45f0 2019-12-04)
[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                 // TODO HACK brz/brnz for i8/i16 is not yet implemented
172                 let cond = fx.bcx.ins().uextend(types::I32, cond);
173                 let target = fx.get_ebb(*target);
174                 if *expected {
175                     fx.bcx.ins().brnz(cond, target, &[]);
176                 } else {
177                     fx.bcx.ins().brz(cond, target, &[]);
178                 };
179                 trap_panic(
180                     fx,
181                     format!(
182                         "[panic] Assert {:?} at {:?} failed.",
183                         msg,
184                         bb_data.terminator().source_info.span
185                     ),
186                 );
187             }
188
189             TerminatorKind::SwitchInt {
190                 discr,
191                 switch_ty: _,
192                 values,
193                 targets,
194             } => {
195                 let discr = trans_operand(fx, discr).load_scalar(fx);
196                 let mut switch = ::cranelift::frontend::Switch::new();
197                 for (i, value) in values.iter().enumerate() {
198                     let ebb = fx.get_ebb(targets[i]);
199                     switch.set_entry(*value as u64, ebb);
200                 }
201                 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
202                 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
203             }
204             TerminatorKind::Call {
205                 func,
206                 args,
207                 destination,
208                 cleanup: _,
209                 from_hir_call: _,
210             } => {
211                 crate::abi::codegen_terminator_call(
212                     fx,
213                     func,
214                     args,
215                     destination,
216                     bb_data.terminator().source_info.span,
217                 );
218             }
219             TerminatorKind::Resume | TerminatorKind::Abort => {
220                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
221             }
222             TerminatorKind::Unreachable => {
223                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
224             }
225             TerminatorKind::Yield { .. }
226             | TerminatorKind::FalseEdges { .. }
227             | TerminatorKind::FalseUnwind { .. }
228             | TerminatorKind::DropAndReplace { .. }
229             | TerminatorKind::GeneratorDrop => {
230                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
231             }
232             TerminatorKind::Drop {
233                 location,
234                 target,
235                 unwind: _,
236             } => {
237                 let drop_place = trans_place(fx, location);
238                 crate::abi::codegen_drop(fx, drop_place);
239
240                 let target_ebb = fx.get_ebb(*target);
241                 fx.bcx.ins().jump(target_ebb, &[]);
242             }
243         };
244     }
245
246     fx.bcx.seal_all_blocks();
247     fx.bcx.finalize();
248 }
249
250 fn trans_stmt<'tcx>(
251     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
252     cur_ebb: Ebb,
253     stmt: &Statement<'tcx>,
254 ) {
255     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
256
257     fx.set_debug_loc(stmt.source_info);
258
259     #[cfg(debug_assertions)]
260     match &stmt.kind {
261         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
262         _ => {
263             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
264             fx.add_comment(inst, format!("{:?}", stmt));
265         }
266     }
267
268     match &stmt.kind {
269         StatementKind::SetDiscriminant {
270             place,
271             variant_index,
272         } => {
273             let place = trans_place(fx, place);
274             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
275         }
276         StatementKind::Assign(to_place_and_rval) => {
277             let lval = trans_place(fx, &to_place_and_rval.0);
278             let dest_layout = lval.layout();
279             match &to_place_and_rval.1 {
280                 Rvalue::Use(operand) => {
281                     let val = trans_operand(fx, operand);
282                     lval.write_cvalue(fx, val);
283                 }
284                 Rvalue::Ref(_, _, place) => {
285                     let place = trans_place(fx, place);
286                     place.write_place_ref(fx, lval);
287                 }
288                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
289                     let lhs = trans_operand(fx, lhs);
290                     let rhs = trans_operand(fx, rhs);
291
292                     let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
293                     lval.write_cvalue(fx, res);
294                 }
295                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
296                     let lhs = trans_operand(fx, lhs);
297                     let rhs = trans_operand(fx, rhs);
298
299                     let res = if !fx.tcx.sess.overflow_checks() {
300                         let val =
301                             crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
302                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
303                         CValue::by_val_pair(val, is_overflow, lval.layout())
304                     } else {
305                         crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
306                     };
307
308                     lval.write_cvalue(fx, res);
309                 }
310                 Rvalue::UnaryOp(un_op, operand) => {
311                     let operand = trans_operand(fx, operand);
312                     let layout = operand.layout();
313                     let val = operand.load_scalar(fx);
314                     let res = match un_op {
315                         UnOp::Not => {
316                             match layout.ty.kind {
317                                 ty::Bool => {
318                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
319                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
320                                     CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
321                                 }
322                                 ty::Uint(_) | ty::Int(_) => {
323                                     CValue::by_val(fx.bcx.ins().bnot(val), layout)
324                                 }
325                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
326                             }
327                         }
328                         UnOp::Neg => match layout.ty.kind {
329                             ty::Int(_) => {
330                                 let zero = CValue::const_val(fx, layout.ty, 0);
331                                 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
332                             }
333                             ty::Float(_) => {
334                                 CValue::by_val(fx.bcx.ins().fneg(val), layout)
335                             }
336                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
337                         },
338                     };
339                     lval.write_cvalue(fx, res);
340                 }
341                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
342                     let layout = fx.layout_of(ty);
343                     match fx
344                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
345                         .kind
346                     {
347                         ty::FnDef(def_id, substs) => {
348                             let func_ref = fx.get_function_ref(
349                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
350                                     .unwrap(),
351                             );
352                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
353                             lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
354                         }
355                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
356                     }
357                 }
358                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
359                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty)
360                 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), 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.kind {
394                         // enum -> discriminant value
395                         assert!(adt_def.is_enum());
396                         match to_ty.kind {
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.kind {
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                     _ => unreachable!("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::InlineAsmInner {
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                 "" => {
538                     assert_eq!(inputs, &[Name::intern("r")]);
539                     assert!(outputs.is_empty(), "{:?}", outputs);
540
541                     // Black box
542                 }
543                 "cpuid" | "cpuid\n" => {
544                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
545
546                     assert_eq!(outputs.len(), 4);
547                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
548                         .iter()
549                         .enumerate()
550                     {
551                         assert_eq!(&outputs[i].constraint.as_str(), c);
552                         assert!(!outputs[i].is_rw);
553                         assert!(!outputs[i].is_indirect);
554                     }
555
556                     assert_eq!(clobbers, &[Name::intern("rbx")]);
557
558                     assert!(!volatile);
559                     assert!(!alignstack);
560
561                     crate::trap::trap_unimplemented(
562                         fx,
563                         "__cpuid_count arch intrinsic is not supported",
564                     );
565                 }
566                 "xgetbv" => {
567                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
568
569                     assert_eq!(outputs.len(), 2);
570                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
571                         assert_eq!(&outputs[i].constraint.as_str(), c);
572                         assert!(!outputs[i].is_rw);
573                         assert!(!outputs[i].is_indirect);
574                     }
575
576                     assert_eq!(clobbers, &[]);
577
578                     assert!(!volatile);
579                     assert!(!alignstack);
580
581                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
582                 }
583                 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
584                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
585                 }
586                 _ => unimpl!("Inline assembly is not supported"),
587             }
588         }
589     }
590 }
591
592 fn codegen_array_len<'tcx>(
593     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
594     place: CPlace<'tcx>,
595 ) -> Value {
596     match place.layout().ty.kind {
597         ty::Array(_elem_ty, len) => {
598             let len = crate::constant::force_eval_const(fx, len)
599                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
600             fx.bcx.ins().iconst(fx.pointer_type, len)
601         }
602         ty::Slice(_elem_ty) => place
603             .to_addr_maybe_unsized(fx)
604             .1
605             .expect("Length metadata for slice place"),
606         _ => bug!("Rvalue::Len({:?})", place),
607     }
608 }
609
610 pub fn trans_place<'tcx>(
611     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
612     place: &Place<'tcx>,
613 ) -> CPlace<'tcx> {
614     let mut cplace = match &place.base {
615         PlaceBase::Local(local) => fx.get_local_place(*local),
616         PlaceBase::Static(static_) => match static_.kind {
617             StaticKind::Static => {
618                 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
619             }
620             StaticKind::Promoted(promoted, substs) => {
621                 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
622                 crate::constant::trans_promoted(fx, instance, promoted, static_.ty)
623             }
624         },
625     };
626
627     for elem in &*place.projection {
628         match *elem {
629             PlaceElem::Deref => {
630                 cplace = cplace.place_deref(fx);
631             }
632             PlaceElem::Field(field, _ty) => {
633                 cplace = cplace.place_field(fx, field);
634             }
635             PlaceElem::Index(local) => {
636                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
637                 cplace = cplace.place_index(fx, index);
638             }
639             PlaceElem::ConstantIndex {
640                 offset,
641                 min_length: _,
642                 from_end,
643             } => {
644                 let index = if !from_end {
645                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
646                 } else {
647                     let len = codegen_array_len(fx, cplace);
648                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
649                 };
650                 cplace = cplace.place_index(fx, index);
651             }
652             PlaceElem::Subslice { from, to } => {
653                 // These indices are generated by slice patterns.
654                 // slice[from:-to] in Python terms.
655
656                 match cplace.layout().ty.kind {
657                     ty::Array(elem_ty, len) => {
658                         let elem_layout = fx.layout_of(elem_ty);
659                         let ptr = cplace.to_addr(fx);
660                         let len = crate::constant::force_eval_const(fx, len)
661                             .eval_usize(fx.tcx, ParamEnv::reveal_all());
662                         cplace = CPlace::for_addr(
663                             fx.bcx
664                                 .ins()
665                                 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
666                             fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
667                         );
668                     }
669                     ty::Slice(elem_ty) => {
670                         let elem_layout = fx.layout_of(elem_ty);
671                         let (ptr, len) = cplace.to_addr_maybe_unsized(fx);
672                         let len = len.unwrap();
673                         cplace = CPlace::for_addr_with_extra(
674                             fx.bcx
675                                 .ins()
676                                 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
677                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
678                             cplace.layout(),
679                         );
680                     }
681                     _ => unreachable!(),
682                 }
683             }
684             PlaceElem::Downcast(_adt_def, variant) => {
685                 cplace = cplace.downcast_variant(fx, variant);
686             }
687         }
688     }
689
690     cplace
691 }
692
693 pub fn trans_operand<'tcx>(
694     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
695     operand: &Operand<'tcx>,
696 ) -> CValue<'tcx> {
697     match operand {
698         Operand::Move(place) | Operand::Copy(place) => {
699             let cplace = trans_place(fx, place);
700             cplace.to_cvalue(fx)
701         }
702         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
703     }
704 }