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