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