1 //! Codegen of a single function
3 use rustc_ast::InlineAsmOptions;
4 use rustc_index::vec::IndexVec;
5 use rustc_middle::ty::adjustment::PointerCast;
6 use rustc_middle::ty::layout::FnAbiOf;
7 use rustc_middle::ty::print::with_no_trimmed_paths;
9 use indexmap::IndexSet;
11 use crate::constant::ConstantCx;
12 use crate::prelude::*;
13 use crate::pretty_clif::CommentWriter;
15 pub(crate) fn codegen_fn<'tcx>(
16 cx: &mut crate::CodegenCx<'tcx>,
17 module: &mut dyn Module,
18 instance: Instance<'tcx>,
23 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
24 debug_assert!(!instance.substs.needs_infer());
26 let mir = tcx.instance_mir(instance.def);
27 let _mir_guard = crate::PrintOnPanic(|| {
28 let mut buf = Vec::new();
29 rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf).unwrap();
30 String::from_utf8_lossy(&buf).into_owned()
34 let symbol_name = tcx.symbol_name(instance);
35 let sig = get_function_sig(tcx, module.isa().triple(), instance);
36 let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
38 cx.cached_context.clear();
40 // Make the FunctionBuilder
41 let mut func_ctx = FunctionBuilderContext::new();
42 let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
43 func.name = ExternalName::user(0, func_id.as_u32());
45 func.collect_debug_info();
47 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
50 let start_block = bcx.create_block();
51 let block_map: IndexVec<BasicBlock, Block> =
52 (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
55 let target_config = module.target_config();
56 let pointer_type = target_config.pointer_type();
57 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
59 let mut fx = FunctionCx {
65 constants_cx: ConstantCx::new(),
70 fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
74 local_map: IndexVec::with_capacity(mir.local_decls.len()),
75 caller_location: None, // set by `codegen_fn_prelude`
78 source_info_set: indexmap::IndexSet::new(),
82 let arg_uninhabited = fx
85 .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
87 if !crate::constant::check_constants(&mut fx) {
88 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
89 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
90 crate::trap::trap_unreachable(&mut fx, "compilation should have been aborted");
91 } else if arg_uninhabited {
92 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
93 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
94 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
96 tcx.sess.time("codegen clif ir", || {
98 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
99 codegen_fn_content(&mut fx);
103 // Recover all necessary data from fx, before accessing func will prevent future access to it.
104 let instance = fx.instance;
105 let clif_comments = fx.clif_comments;
106 let source_info_set = fx.source_info_set;
107 let local_map = fx.local_map;
109 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
111 crate::pretty_clif::write_clif_file(
121 verify_func(tcx, &clif_comments, &func);
137 cx: &mut crate::CodegenCx<'tcx>,
138 module: &mut dyn Module,
139 instance: Instance<'tcx>,
143 mut clif_comments: CommentWriter,
144 source_info_set: IndexSet<SourceInfo>,
145 local_map: IndexVec<mir::Local, CPlace<'tcx>>,
149 // Store function in context
150 let context = &mut cx.cached_context;
154 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
155 // instruction, which doesn't have an encoding.
156 context.compute_cfg();
157 context.compute_domtree();
158 context.eliminate_unreachable_code(module.isa()).unwrap();
159 context.dce(module.isa()).unwrap();
160 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
161 // invalidate it when it would change.
162 context.domtree.clear();
164 // Perform rust specific optimizations
165 tcx.sess.time("optimize clif ir", || {
166 crate::optimize::optimize_function(
176 tcx.sess.time("define function", || {
177 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
178 module.define_function(func_id, context).unwrap()
181 // Write optimized function to file for debugging
182 crate::pretty_clif::write_clif_file(
191 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
192 crate::pretty_clif::write_ir_file(
194 || format!("{}.vcode", tcx.symbol_name(instance).name),
195 |file| file.write_all(disasm.as_bytes()),
199 // Define debuginfo for function
200 let isa = module.isa();
201 let debug_context = &mut cx.debug_context;
202 let unwind_context = &mut cx.unwind_context;
203 tcx.sess.time("generate debug info", || {
204 if let Some(debug_context) = debug_context {
205 debug_context.define_function(
215 unwind_context.add_function(func_id, &context, isa);
219 pub(crate) fn verify_func(
221 writer: &crate::pretty_clif::CommentWriter,
224 tcx.sess.time("verify clif ir", || {
225 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
226 match cranelift_codegen::verify_function(&func, &flags) {
229 tcx.sess.err(&format!("{:?}", err));
230 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
232 Some(Box::new(writer)),
235 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
241 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
242 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
243 let block = fx.get_block(bb);
244 fx.bcx.switch_to_block(block);
246 if bb_data.is_cleanup {
247 // Unwinding after panicking is not supported
250 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
251 // so for cleanup blocks.
255 for stmt in &bb_data.statements {
256 fx.set_debug_loc(stmt.source_info);
257 codegen_stmt(fx, block, stmt);
260 if fx.clif_comments.enabled() {
261 let mut terminator_head = "\n".to_string();
262 with_no_trimmed_paths!({
263 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
265 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
266 fx.add_comment(inst, terminator_head);
269 let source_info = bb_data.terminator().source_info;
270 fx.set_debug_loc(source_info);
272 match &bb_data.terminator().kind {
273 TerminatorKind::Goto { target } => {
274 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
275 let mut can_immediately_return = true;
276 for stmt in &fx.mir[*target].statements {
277 if let StatementKind::StorageDead(_) = stmt.kind {
279 // FIXME Can sometimes happen, see rust-lang/rust#70531
280 can_immediately_return = false;
285 if can_immediately_return {
286 crate::abi::codegen_return(fx);
291 let block = fx.get_block(*target);
292 fx.bcx.ins().jump(block, &[]);
294 TerminatorKind::Return => {
295 crate::abi::codegen_return(fx);
297 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
298 if !fx.tcx.sess.overflow_checks() {
299 if let mir::AssertKind::OverflowNeg(_) = *msg {
300 let target = fx.get_block(*target);
301 fx.bcx.ins().jump(target, &[]);
305 let cond = codegen_operand(fx, cond).load_scalar(fx);
307 let target = fx.get_block(*target);
308 let failure = fx.bcx.create_block();
309 fx.bcx.set_cold_block(failure);
312 fx.bcx.ins().brz(cond, failure, &[]);
314 fx.bcx.ins().brnz(cond, failure, &[]);
316 fx.bcx.ins().jump(target, &[]);
318 fx.bcx.switch_to_block(failure);
322 AssertKind::BoundsCheck { ref len, ref index } => {
323 let len = codegen_operand(fx, len).load_scalar(fx);
324 let index = codegen_operand(fx, index).load_scalar(fx);
325 let location = fx.get_caller_location(source_info.span).load_scalar(fx);
329 rustc_hir::LangItem::PanicBoundsCheck,
330 &[index, len, location],
335 let msg_str = msg.description();
336 codegen_panic(fx, msg_str, source_info.span);
341 TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
342 let discr = codegen_operand(fx, discr).load_scalar(fx);
344 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
345 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
347 assert_eq!(targets.iter().count(), 1);
348 let (then_value, then_block) = targets.iter().next().unwrap();
349 let then_block = fx.get_block(then_block);
350 let else_block = fx.get_block(targets.otherwise());
351 let test_zero = match then_value {
354 _ => unreachable!("{:?}", targets),
357 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
358 let (discr, is_inverted) =
359 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
360 let test_zero = if is_inverted { !test_zero } else { test_zero };
361 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
362 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
363 &fx.bcx, discr, test_zero,
366 fx.bcx.ins().jump(then_block, &[]);
368 fx.bcx.ins().jump(else_block, &[]);
372 fx.bcx.ins().brz(discr, then_block, &[]);
373 fx.bcx.ins().jump(else_block, &[]);
375 fx.bcx.ins().brnz(discr, then_block, &[]);
376 fx.bcx.ins().jump(else_block, &[]);
380 let mut switch = ::cranelift_frontend::Switch::new();
381 for (value, block) in targets.iter() {
382 let block = fx.get_block(block);
383 switch.set_entry(value, block);
385 let otherwise_block = fx.get_block(targets.otherwise());
386 switch.emit(&mut fx.bcx, discr, otherwise_block);
389 TerminatorKind::Call {
397 fx.tcx.sess.time("codegen call", || {
398 crate::abi::codegen_terminator_call(fx, *fn_span, func, args, *destination)
401 TerminatorKind::InlineAsm {
409 if options.contains(InlineAsmOptions::MAY_UNWIND) {
410 fx.tcx.sess.span_fatal(
412 "cranelift doesn't support unwinding from inline assembly.",
416 crate::inline_asm::codegen_inline_asm(
425 Some(destination) => {
426 let destination_block = fx.get_block(destination);
427 fx.bcx.ins().jump(destination_block, &[]);
430 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
434 TerminatorKind::Resume | TerminatorKind::Abort => {
435 // FIXME implement unwinding
436 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
438 TerminatorKind::Unreachable => {
439 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
441 TerminatorKind::Yield { .. }
442 | TerminatorKind::FalseEdge { .. }
443 | TerminatorKind::FalseUnwind { .. }
444 | TerminatorKind::DropAndReplace { .. }
445 | TerminatorKind::GeneratorDrop => {
446 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
448 TerminatorKind::Drop { place, target, unwind: _ } => {
449 let drop_place = codegen_place(fx, *place);
450 crate::abi::codegen_drop(fx, source_info.span, drop_place);
452 let target_block = fx.get_block(*target);
453 fx.bcx.ins().jump(target_block, &[]);
458 fx.bcx.seal_all_blocks();
462 fn codegen_stmt<'tcx>(
463 fx: &mut FunctionCx<'_, '_, 'tcx>,
464 #[allow(unused_variables)] cur_block: Block,
465 stmt: &Statement<'tcx>,
467 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
469 fx.set_debug_loc(stmt.source_info);
473 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
475 if fx.clif_comments.enabled() {
476 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
477 fx.add_comment(inst, format!("{:?}", stmt));
483 StatementKind::SetDiscriminant { place, variant_index } => {
484 let place = codegen_place(fx, **place);
485 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
487 StatementKind::Assign(to_place_and_rval) => {
488 let lval = codegen_place(fx, to_place_and_rval.0);
489 let dest_layout = lval.layout();
490 match to_place_and_rval.1 {
491 Rvalue::Use(ref operand) => {
492 let val = codegen_operand(fx, operand);
493 lval.write_cvalue(fx, val);
495 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
496 let place = codegen_place(fx, place);
497 let ref_ = place.place_ref(fx, lval.layout());
498 lval.write_cvalue(fx, ref_);
500 Rvalue::ThreadLocalRef(def_id) => {
501 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
502 lval.write_cvalue(fx, val);
504 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
505 let lhs = codegen_operand(fx, &lhs_rhs.0);
506 let rhs = codegen_operand(fx, &lhs_rhs.1);
508 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
509 lval.write_cvalue(fx, res);
511 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
512 let lhs = codegen_operand(fx, &lhs_rhs.0);
513 let rhs = codegen_operand(fx, &lhs_rhs.1);
515 let res = if !fx.tcx.sess.overflow_checks() {
517 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
518 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
519 CValue::by_val_pair(val, is_overflow, lval.layout())
521 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
524 lval.write_cvalue(fx, res);
526 Rvalue::UnaryOp(un_op, ref operand) => {
527 let operand = codegen_operand(fx, operand);
528 let layout = operand.layout();
529 let val = operand.load_scalar(fx);
530 let res = match un_op {
531 UnOp::Not => match layout.ty.kind() {
533 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
534 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
536 ty::Uint(_) | ty::Int(_) => {
537 CValue::by_val(fx.bcx.ins().bnot(val), layout)
539 _ => unreachable!("un op Not for {:?}", layout.ty),
541 UnOp::Neg => match layout.ty.kind() {
542 ty::Int(IntTy::I128) => {
543 // FIXME remove this case once ineg.i128 works
545 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
546 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
548 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
549 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
550 _ => unreachable!("un op Neg for {:?}", layout.ty),
553 lval.write_cvalue(fx, res);
556 CastKind::Pointer(PointerCast::ReifyFnPointer),
560 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
561 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
562 match *from_ty.kind() {
563 ty::FnDef(def_id, substs) => {
564 let func_ref = fx.get_function_ref(
565 Instance::resolve_for_fn_ptr(
567 ParamEnv::reveal_all(),
572 .polymorphize(fx.tcx),
574 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
575 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
577 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
581 CastKind::Pointer(PointerCast::UnsafeFnPointer),
586 CastKind::Pointer(PointerCast::MutToConstPointer),
591 CastKind::Pointer(PointerCast::ArrayToPointer),
595 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
596 let operand = codegen_operand(fx, operand);
597 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
599 Rvalue::Cast(CastKind::Misc, ref operand, to_ty) => {
600 let operand = codegen_operand(fx, operand);
601 let from_ty = operand.layout().ty;
602 let to_ty = fx.monomorphize(to_ty);
604 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
605 ty.builtin_deref(true)
606 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
607 has_ptr_meta(fx.tcx, pointee_ty)
612 if is_fat_ptr(fx, from_ty) {
613 if is_fat_ptr(fx, to_ty) {
614 // fat-ptr -> fat-ptr
615 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
617 // fat-ptr -> thin-ptr
618 let (ptr, _extra) = operand.load_scalar_pair(fx);
619 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
621 } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
622 // enum -> discriminant value
623 assert!(adt_def.is_enum());
625 ty::Uint(_) | ty::Int(_) => {}
626 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
628 let to_clif_ty = fx.clif_type(to_ty).unwrap();
630 let discriminant = crate::discriminant::codegen_get_discriminant(
633 fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
637 let res = crate::cast::clif_intcast(
643 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
645 let to_clif_ty = fx.clif_type(to_ty).unwrap();
646 let from = operand.load_scalar(fx);
648 let res = clif_int_or_float_cast(
655 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
659 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
663 let operand = codegen_operand(fx, operand);
664 match *operand.layout().ty.kind() {
665 ty::Closure(def_id, substs) => {
666 let instance = Instance::resolve_closure(
670 ty::ClosureKind::FnOnce,
672 .polymorphize(fx.tcx);
673 let func_ref = fx.get_function_ref(instance);
674 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
675 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
677 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
680 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
681 let operand = codegen_operand(fx, operand);
682 operand.unsize_value(fx, lval);
684 Rvalue::Discriminant(place) => {
685 let place = codegen_place(fx, place);
686 let value = place.to_cvalue(fx);
688 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
689 lval.write_cvalue(fx, discr);
691 Rvalue::Repeat(ref operand, times) => {
692 let operand = codegen_operand(fx, operand);
695 .eval(fx.tcx, ParamEnv::reveal_all())
697 .try_to_bits(fx.tcx.data_layout.pointer_size)
699 if operand.layout().size.bytes() == 0 {
700 // Do nothing for ZST's
701 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
702 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
703 // FIXME use emit_small_memset where possible
704 let addr = lval.to_ptr().get_addr(fx);
705 let val = operand.load_scalar(fx);
706 fx.bcx.call_memset(fx.target_config, addr, val, times);
708 let loop_block = fx.bcx.create_block();
709 let loop_block2 = fx.bcx.create_block();
710 let done_block = fx.bcx.create_block();
711 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
712 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
713 fx.bcx.ins().jump(loop_block, &[zero]);
715 fx.bcx.switch_to_block(loop_block);
716 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
717 fx.bcx.ins().brnz(done, done_block, &[]);
718 fx.bcx.ins().jump(loop_block2, &[]);
720 fx.bcx.switch_to_block(loop_block2);
721 let to = lval.place_index(fx, index);
722 to.write_cvalue(fx, operand);
723 let index = fx.bcx.ins().iadd_imm(index, 1);
724 fx.bcx.ins().jump(loop_block, &[index]);
726 fx.bcx.switch_to_block(done_block);
730 Rvalue::Len(place) => {
731 let place = codegen_place(fx, place);
732 let usize_layout = fx.layout_of(fx.tcx.types.usize);
733 let len = codegen_array_len(fx, place);
734 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
736 Rvalue::ShallowInitBox(ref operand, content_ty) => {
737 let content_ty = fx.monomorphize(content_ty);
738 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
739 let operand = codegen_operand(fx, operand);
740 let operand = operand.load_scalar(fx);
741 lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
743 Rvalue::NullaryOp(null_op, ty) => {
747 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
749 let layout = fx.layout_of(fx.monomorphize(ty));
750 let val = match null_op {
751 NullOp::SizeOf => layout.size.bytes(),
752 NullOp::AlignOf => layout.align.abi.bytes(),
754 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
755 lval.write_cvalue(fx, val);
757 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
758 AggregateKind::Array(_ty) => {
759 for (i, operand) in operands.iter().enumerate() {
760 let operand = codegen_operand(fx, operand);
761 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
762 let to = lval.place_index(fx, index);
763 to.write_cvalue(fx, operand);
766 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
770 StatementKind::StorageLive(_)
771 | StatementKind::StorageDead(_)
773 | StatementKind::FakeRead(..)
774 | StatementKind::Retag { .. }
775 | StatementKind::AscribeUserType(..) => {}
777 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
778 StatementKind::CopyNonOverlapping(inner) => {
779 let dst = codegen_operand(fx, &inner.dst);
782 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
783 .expect("Expected pointer");
784 let dst = dst.load_scalar(fx);
785 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
786 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
787 let elem_size: u64 = pointee.size.bytes();
789 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
790 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
795 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
796 match *place.layout().ty.kind() {
797 ty::Array(_elem_ty, len) => {
798 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
799 fx.bcx.ins().iconst(fx.pointer_type, len)
801 ty::Slice(_elem_ty) => {
802 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
804 _ => bug!("Rvalue::Len({:?})", place),
808 pub(crate) fn codegen_place<'tcx>(
809 fx: &mut FunctionCx<'_, '_, 'tcx>,
812 let mut cplace = fx.get_local_place(place.local);
814 for elem in place.projection {
816 PlaceElem::Deref => {
817 if cplace.layout().ty.is_box() {
819 .place_field(fx, Field::new(0)) // Box<T> -> Unique<T>
820 .place_field(fx, Field::new(0)) // Unique<T> -> *const T
823 cplace = cplace.place_deref(fx);
826 PlaceElem::Field(field, _ty) => {
827 cplace = cplace.place_field(fx, field);
829 PlaceElem::Index(local) => {
830 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
831 cplace = cplace.place_index(fx, index);
833 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
834 let offset: u64 = offset;
835 let index = if !from_end {
836 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
838 let len = codegen_array_len(fx, cplace);
839 fx.bcx.ins().iadd_imm(len, -(offset as i64))
841 cplace = cplace.place_index(fx, index);
843 PlaceElem::Subslice { from, to, from_end } => {
844 // These indices are generated by slice patterns.
845 // slice[from:-to] in Python terms.
847 let from: u64 = from;
850 match cplace.layout().ty.kind() {
851 ty::Array(elem_ty, _len) => {
852 assert!(!from_end, "array subslices are never `from_end`");
853 let elem_layout = fx.layout_of(*elem_ty);
854 let ptr = cplace.to_ptr();
855 cplace = CPlace::for_ptr(
856 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
857 fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
860 ty::Slice(elem_ty) => {
861 assert!(from_end, "slice subslices should be `from_end`");
862 let elem_layout = fx.layout_of(*elem_ty);
863 let (ptr, len) = cplace.to_ptr_maybe_unsized();
864 let len = len.unwrap();
865 cplace = CPlace::for_ptr_with_extra(
866 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
867 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
874 PlaceElem::Downcast(_adt_def, variant) => {
875 cplace = cplace.downcast_variant(fx, variant);
883 pub(crate) fn codegen_operand<'tcx>(
884 fx: &mut FunctionCx<'_, '_, 'tcx>,
885 operand: &Operand<'tcx>,
888 Operand::Move(place) | Operand::Copy(place) => {
889 let cplace = codegen_place(fx, *place);
892 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
896 pub(crate) fn codegen_panic<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, msg_str: &str, span: Span) {
897 let location = fx.get_caller_location(span).load_scalar(fx);
899 let msg_ptr = fx.anonymous_str(msg_str);
900 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
901 let args = [msg_ptr, msg_len, location];
903 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, span);
906 pub(crate) fn codegen_panic_inner<'tcx>(
907 fx: &mut FunctionCx<'_, '_, 'tcx>,
908 lang_item: rustc_hir::LangItem,
913 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
915 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
916 let symbol_name = fx.tcx.symbol_name(instance).name;
921 AbiParam::new(fx.pointer_type),
922 AbiParam::new(fx.pointer_type),
923 AbiParam::new(fx.pointer_type),
929 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);